-
Notifications
You must be signed in to change notification settings - Fork 11
/
models.py
1627 lines (1313 loc) · 61.1 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
# -*- encoding: utf-8 -*-
import urllib
import hashlib
import logging
import choices
from pytz import all_timezones
from scielomanager import tools
import datetime
from uuid import uuid4
try:
from collections import OrderedDict
except ImportError:
from ordereddict import OrderedDict
from django.db import (
models,
IntegrityError,
DatabaseError,
)
from django.db.models import Q
from django.core.exceptions import ObjectDoesNotExist, ImproperlyConfigured
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic
from django.contrib.auth.models import User
from django.utils.translation import ugettext_lazy as _
from django.utils.translation import ugettext as __
from django.conf import settings
from django.db.models.signals import post_save, pre_save
from django.dispatch import receiver
from django.template.defaultfilters import slugify
from scielo_extensions import modelfields
from tastypie.models import create_api_key
import celery
from PIL import Image
from scielomanager.utils import base28
from scielomanager.custom_fields import (
ContentTypeRestrictedFileField,
XMLSPSField,
)
from . import modelmanagers
logger = logging.getLogger(__name__)
LINKABLE_ARTICLE_TYPES = ['correction', ]
EVENT_TYPES = [(ev_type, ev_type) for ev_type in ['added', 'deleted', 'updated']]
ISSUE_DEFAULT_LICENSE_HELP_TEXT = _(u"If not defined, will be applied the related journal's use license. \
The SciELO default use license is BY-NC. Please visit: http://ref.scielo.org/jf5ndd (5.2.11. Política de direitos autorais) for more details.")
def get_user_collections(user_id):
"""
Return all the collections of a given user, The returned collections are the collections where the
user could have access by the collections bar.
"""
user_collections = User.objects.get(pk=user_id).usercollections_set.all().order_by(
'collection__name')
return user_collections
def get_journals_default_use_license():
"""
Returns the default use license for all new Journals.
This callable is passed as the default value on Journal.use_license field.
The default use license is the one defined on SciELO criteria, and at
the time is BY-NC. See http://ref.scielo.org/jf5ndd for more information.
"""
try:
return UseLicense.objects.get(is_default=True)
except UseLicense.DoesNotExist:
raise ImproperlyConfigured("There is no UseLicense set as default")
class AppCustomManager(models.Manager):
"""
Domain specific model managers.
"""
def available(self, is_available=True):
"""
Filter the queryset based on its availability.
"""
data_queryset = self.get_query_set()
if not isinstance(is_available, bool):
try:
if int(is_available) == 0:
is_available = False
else:
is_available = True
except (ValueError, TypeError):
is_available = True
data_queryset = data_queryset.filter(is_trashed=not is_available)
return data_queryset
class JournalCustomManager(AppCustomManager):
def all_by_user(self, user, is_available=True, pub_status=None):
"""
Retrieves all the user's journals, contextualized by
their default collection.
"""
objects_all = Journal.userobjects.all()
if is_available:
objects_all = objects_all.available().distinct()
else:
objects_all = objects_all.unavailable().distinct()
if pub_status:
if pub_status in [stat[0] for stat in choices.JOURNAL_PUBLICATION_STATUS]:
objects_all = objects_all.filter(pub_status=pub_status)
return objects_all
def recents_by_user(self, user):
"""
Retrieves the recently modified objects related to the given user.
"""
default_collection = Collection.userobjects.active()
recents = self.filter(
collections=default_collection).distinct().order_by('-updated')[:5]
return recents
def all_by_collection(self, collection, is_available=True):
objects_all = self.available(is_available).filter(
collections=collection)
return objects_all
def by_issn(self, issn):
"""
Get the journal assigned to `issn`, being electronic or print.
In some cases more than one instance of the same journal will be
returned due to the fact that journals present in more than one
collection is handled separately.
"""
if issn == '':
return Journal.objects.none()
journals = Journal.objects.filter(
models.Q(print_issn=issn) | models.Q(eletronic_issn=issn)
)
return journals
class SectionCustomManager(AppCustomManager):
def all_by_user(self, user, is_available=True):
default_collection = Collection.objects.get_default_by_user(user)
objects_all = self.available(is_available).filter(
journal__collections=default_collection).distinct()
return objects_all
class IssueCustomManager(AppCustomManager):
def all_by_collection(self, collection, is_available=True):
objects_all = self.available(is_available).filter(
journal__collections=collection)
return objects_all
class InstitutionCustomManager(AppCustomManager):
"""
Add capabilities to Institution subclasses to retrieve querysets
based on user's collections.
"""
def all_by_user(self, user, is_available=True):
default_collection = Collection.objects.get_default_by_user(user)
objects_all = self.available(is_available).filter(
collections__in=[default_collection]).distinct()
return objects_all
class CollectionCustomManager(AppCustomManager):
def all_by_user(self, user):
"""
Returns all the Collections related to the given
user.
"""
collections = self.filter(usercollections__user=user).order_by(
'name')
return collections
def get_default_by_user(self, user):
"""
Returns the Collection marked as default by the given user.
If none satisfies this condition, the first
instance is then returned.
Like any manager method that does not return Querysets,
`get_default_by_user` raises DoesNotExist if there is no
result for the given parameter.
"""
collections = self.filter(
usercollections__user=user,
usercollections__is_default=True).order_by('name')
if not collections.count():
try:
collection = self.all_by_user(user)[0]
except IndexError:
raise Collection.DoesNotExist()
else:
collection.make_default_to_user(user)
return collection
return collections[0]
def get_managed_by_user(self, user):
"""
Returns all collections managed by a given user.
"""
collections = self.filter(
usercollections__user=user,
usercollections__is_manager=True).order_by('name')
return collections
class RegularPressReleaseCustomManager(models.Manager):
def by_journal_pid(self, journal_pid):
"""
Returns all PressReleases related to a Journal, given its
PID.
"""
journals = Journal.objects.filter(
models.Q(print_issn=journal_pid) | models.Q(eletronic_issn=journal_pid))
preleases = self.filter(issue__journal__in=journals.values('id')).select_related('translations')
return preleases
def all_by_journal(self, journal):
"""
Returns all PressReleases related to a Journal
"""
preleases = self.filter(issue__journal=journal)
return preleases
def by_issue_pid(self, issue_pid):
"""
Returns all PressReleases related to an Issue, given its
PID.
"""
issn_slice = slice(0, 9)
year_slice = slice(9, 13)
order_slice = slice(13, None)
issn = issue_pid[issn_slice]
year = issue_pid[year_slice]
order = int(issue_pid[order_slice])
preleases_qset = self.by_journal_pid(issn)
return preleases_qset.filter(issue__publication_year=year).filter(issue__order=order)
class AheadPressReleaseCustomManager(models.Manager):
def by_journal_pid(self, journal_pid):
"""
Returns all PressReleases related to a Journal, given its
PID.
"""
preleases = self.filter(models.Q(journal__print_issn=journal_pid) | models.Q(journal__eletronic_issn=journal_pid))
return preleases
class Language(models.Model):
"""
Represents ISO 639-1 Language Code and its language name in English. Django
automaticaly translates language names, if you write them right.
http://en.wikipedia.org/wiki/ISO_639-1_language_matrix
"""
iso_code = models.CharField(_('ISO 639-1 Language Code'), max_length=2)
name = models.CharField(_('Language Name (in English)'), max_length=64)
def __unicode__(self):
return __(self.name)
class Meta:
ordering = ['name']
PROFILE_TIMEZONES_CHOICES = zip(all_timezones, all_timezones)
class UserProfile(models.Model):
user = models.OneToOneField(User)
email_notifications = models.BooleanField("Want to receive email notifications?", default=True)
tz = models.CharField("Time Zone", max_length=150, choices=PROFILE_TIMEZONES_CHOICES, default=settings.TIME_ZONE)
@property
def is_editor(self):
return self.user.groups.filter(name__iexact='Editors').exists()
@property
def is_librarian(self):
return self.user.groups.filter(name__iexact='Librarian').exists()
@property
def is_trainee(self):
return self.user.groups.filter(name__iexact='Trainee').exists()
@property
def gravatar_id(self):
return hashlib.md5(self.user.email.lower().strip()).hexdigest()
@property
def avatar_url(self):
params = urllib.urlencode({'s': 18, 'd': 'mm'})
return '{0}/avatar/{1}?{2}'.format(getattr(settings, 'GRAVATAR_BASE_URL', 'https://secure.gravatar.com'), self.gravatar_id, params)
@property
def get_default_collection(self):
"""
Return the default collection for this user
"""
uc = UserCollections.objects.get(user=self.user, is_default=True)
return uc.collection
class Collection(models.Model):
objects = models.Manager() # The default manager.
userobjects = modelmanagers.CollectionManager() # Custom manager
collection = models.ManyToManyField(User, related_name='user_collection', through='UserCollections', null=True, blank=True, )
name = models.CharField(_('Collection Name'), max_length=128, db_index=True, )
name_slug = models.SlugField(unique=True, db_index=True, blank=True, null=True)
url = models.URLField(_('Instance URL'), )
logo = models.ImageField(_('Logo'), upload_to='img/collections_logos', null=True, blank=True, )
acronym = models.CharField(_('Sigla'), max_length=16, db_index=True, blank=True, )
country = models.CharField(_('Country'), max_length=32,)
state = models.CharField(_('State'), max_length=32, null=False, blank=True,)
city = models.CharField(_('City'), max_length=32, null=False, blank=True,)
address = models.TextField(_('Address'),)
address_number = models.CharField(_('Number'), max_length=8,)
address_complement = models.CharField(_('Complement'), max_length=128, null=False, blank=True,)
zip_code = models.CharField(_('Zip Code'), max_length=16, null=True, blank=True, )
phone = models.CharField(_('Phone Number'), max_length=16, null=False, blank=True, )
fax = models.CharField(_('Fax Number'), max_length=16, null=False, blank=True, )
email = models.EmailField(_('Email'), )
def __unicode__(self):
return unicode(self.name)
class Meta:
ordering = ['name']
permissions = (("list_collection", "Can list Collections"),)
def save(self, *args, **kwargs):
self.name_slug = slugify(self.name)
super(Collection, self).save(*args, **kwargs)
def add_user(self, user, is_manager=False):
"""
Add the user to the current collection.
If user have not a default collection, then ``self``
will be the default one
"""
UserCollections.objects.create(collection=self,
user=user,
is_default=False,
is_manager=is_manager)
# if user do not have a default collections, make this the default one
user_has_default_collection = UserCollections.objects.filter(is_default=True, user=user).exists()
if not user_has_default_collection:
self.make_default_to_user(user)
def remove_user(self, user):
"""
Removes the user from the current collection.
If the user isn't already related to the given collection,
it will do nothing, silently.
"""
try:
uc = UserCollections.objects.get(collection=self, user=user)
except UserCollections.DoesNotExist:
return None
else:
uc.delete()
def make_default_to_user(self, user):
"""
Makes the current collection, the user's default.
"""
UserCollections.objects.filter(user=user).update(is_default=False)
uc, created = UserCollections.objects.get_or_create(
collection=self, user=user)
uc.is_default = True
uc.save()
def is_default_to_user(self, user):
"""
Returns a boolean value depending if the current collection
is set as default to the given user.
"""
try:
uc = UserCollections.objects.get(collection=self, user=user)
return uc.is_default
except UserCollections.DoesNotExist:
return False
def is_managed_by_user(self, user):
"""
Returns a boolean value depending if the current collection
is managed by the given user.
"""
try:
uc = UserCollections.objects.get(collection=self, user=user)
return uc.is_manager
except UserCollections.DoesNotExist:
return False
class UserCollections(models.Model):
objects = models.Manager() # The default manager.
userobjects = modelmanagers.UserCollectionsManager() # Custom manager
user = models.ForeignKey(User)
collection = models.ForeignKey(Collection)
is_default = models.BooleanField(_('Is default'), default=False, null=False, blank=False)
is_manager = models.BooleanField(_('Is manager of the collection?'), default=False, null=False, blank=False)
class Meta:
unique_together = ("user", "collection", )
class Institution(models.Model):
objects = models.Manager() # The default manager.
userobjects = modelmanagers.InstitutionManager() # Custom manager
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
name = models.CharField(_('Institution Name'), max_length=256, db_index=True)
complement = models.TextField(_('Institution Complements'), blank=True, default="")
acronym = models.CharField(_('Sigla'), max_length=16, db_index=True, blank=True)
country = models.CharField(_('Country'), max_length=32)
state = models.CharField(_('State'), max_length=32, null=False, blank=True)
city = models.CharField(_('City'), max_length=32, null=False, blank=True)
address = models.TextField(_('Address'))
address_number = models.CharField(_('Number'), max_length=8)
address_complement = models.CharField(_('Address Complement'), max_length=128, null=False, blank=True)
zip_code = models.CharField(_('Zip Code'), max_length=16, null=True, blank=True)
phone = models.CharField(_('Phone Number'), max_length=16, null=False, blank=True)
fax = models.CharField(_('Fax Number'), max_length=16, null=False, blank=True)
cel = models.CharField(_('Cel Number'), max_length=16, null=False, blank=True)
email = models.EmailField(_('E-mail'))
is_trashed = models.BooleanField(_('Is trashed?'), default=False, db_index=True)
def __unicode__(self):
return u'%s' % (self.name)
class Meta:
ordering = ['name']
class Sponsor(Institution):
objects = models.Manager() # The default manager.
userobjects = modelmanagers.SponsorManager() # Custom manager
collections = models.ManyToManyField(Collection)
class Meta:
permissions = (("list_sponsor", "Can list Sponsors"),)
class SubjectCategory(models.Model):
objects = JournalCustomManager() # Custom manager
term = models.CharField(_('Term'), max_length=256, db_index=True)
def __unicode__(self):
return self.term
class StudyArea(models.Model):
study_area = models.CharField(_('Study Area'), max_length=256,
choices=sorted(choices.SUBJECTS, key=lambda SUBJECTS: SUBJECTS[1]))
def __unicode__(self):
return self.study_area
class Journal(models.Model):
"""
Represents a Journal that is managed by one SciELO Collection.
`editor_address` references the institution who operates the
process.
`publisher_address` references the institution who is responsible
for the Journal.
"""
# Custom manager
objects = JournalCustomManager()
userobjects = modelmanagers.JournalManager()
# Relation fields
editor = models.ForeignKey(User, verbose_name=_('Editor'),
related_name='editor_journal', null=True, blank=True)
creator = models.ForeignKey(User, related_name='enjoy_creator',
editable=False)
sponsor = models.ManyToManyField('Sponsor', verbose_name=_('Sponsor'),
related_name='journal_sponsor', null=True, blank=True)
previous_title = models.ForeignKey('Journal', verbose_name=_('Previous title'),
related_name='prev_title', null=True, blank=True)
# licença de uso padrão definida pelo editor da revista
use_license = models.ForeignKey('UseLicense', verbose_name=_('Use license'),
default=get_journals_default_use_license)
collections = models.ManyToManyField('Collection', through='Membership')
# os idiomas que a revista publica conteúdo
languages = models.ManyToManyField('Language')
ccn_code = models.CharField(_("CCN Code"), max_length=64, default='',
blank=True, help_text=_("The code of the journal at the CCN database."))
# os idiomas que os artigos da revista apresentam as palavras-chave
abstract_keyword_languages = models.ManyToManyField('Language',
related_name="abstract_keyword_languages")
subject_categories = models.ManyToManyField(SubjectCategory,
verbose_name=_("Subject Categories"), related_name="journals",
null=True)
study_areas = models.ManyToManyField(StudyArea, verbose_name=_("Study Area"),
related_name="journals_migration_tmp", null=True)
# Fields
current_ahead_documents = models.IntegerField(
_('Total of ahead of print documents for the current year'),
max_length=3, default=0, blank=True)
previous_ahead_documents = models.IntegerField(
_('Total of ahead of print documents for the previous year'),
max_length=3, default=0, blank=True)
twitter_user = models.CharField(_('Twitter User'), max_length=128,
default='', blank=True)
title = models.CharField(_('Journal Title'), max_length=256, db_index=True)
title_iso = models.CharField(_('ISO abbreviated title'), max_length=256,
db_index=True)
short_title = models.CharField(_('Short Title'), max_length=256,
db_index=True, default='')
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
acronym = models.CharField(_('Acronym'), max_length=16, blank=False)
scielo_issn = models.CharField(_('The ISSN used to build the Journal PID.'),
max_length=16, choices=sorted(
choices.SCIELO_ISSN, key=lambda SCIELO_ISSN: SCIELO_ISSN[1]))
print_issn = models.CharField(_('Print ISSN'), max_length=9, db_index=True)
eletronic_issn = models.CharField(_('Electronic ISSN'), max_length=9,
db_index=True)
subject_descriptors = models.CharField(_('Subject / Descriptors'),
max_length=1024)
init_year = models.CharField(_('Initial Year'), max_length=4)
init_vol = models.CharField(_('Initial Volume'), max_length=16, default='',
blank=True)
init_num = models.CharField(_('Initial Number'), max_length=16, default='',
blank=True)
final_year = models.CharField(_('Final Year'), max_length=4, default='',
blank=True)
final_vol = models.CharField(_('Final Volume'), max_length=16, default='',
blank=True)
final_num = models.CharField(_('Final Number'), max_length=16, default='',
blank=True)
medline_title = models.CharField(_('Medline Title'), max_length=256,
default='', blank=True)
medline_code = models.CharField(_('Medline Code'), max_length=64,
default='', blank=True)
frequency = models.CharField(_('Frequency'), max_length=16,
choices=sorted(
choices.FREQUENCY, key=lambda FREQUENCY: FREQUENCY[1]))
editorial_standard = models.CharField(_('Editorial Standard'), max_length=64,
choices=sorted(choices.STANDARD, key=lambda STANDARD: STANDARD[1]))
ctrl_vocabulary = models.CharField(_('Controlled Vocabulary'), max_length=64,
choices=choices.CTRL_VOCABULARY)
pub_level = models.CharField(_('Publication Level'), max_length=64,
choices=sorted(
choices.PUBLICATION_LEVEL, key=lambda PUBLICATION_LEVEL: PUBLICATION_LEVEL[1]))
secs_code = models.CharField(_('SECS Code'), max_length=64, default='',
blank=True)
# detentor dos direitos de uso
copyrighter = models.CharField(_('Copyrighter'), max_length=254)
url_online_submission = models.CharField(_('URL of online submission'),
max_length=128, default='', blank=True)
url_journal = models.CharField(_('URL of the journal'), max_length=128,
default='', blank=True)
notes = models.TextField(_('Notes'), max_length=254, default='', blank=True)
index_coverage = models.TextField(_('Index Coverage'), default='',
blank=True)
cover = ContentTypeRestrictedFileField(_('Journal Cover'),
upload_to='img/journal_cover/', null=True, blank=True,
content_types=settings.IMAGE_CONTENT_TYPE,
max_upload_size=settings.JOURNAL_COVER_MAX_SIZE)
logo = ContentTypeRestrictedFileField(_('Journal Logo'),
upload_to='img/journals_logos', null=True, blank=True,
content_types=settings.IMAGE_CONTENT_TYPE,
max_upload_size=settings.JOURNAL_LOGO_MAX_SIZE)
is_trashed = models.BooleanField(_('Is trashed?'), default=False,
db_index=True)
other_previous_title = models.CharField(_('Other Previous Title'),
max_length=255, default='', blank=True)
editor_name = models.CharField(_('Editor Names'), max_length=512)
editor_address = models.CharField(_('Editor Address'), max_length=512)
editor_address_city = models.CharField(_('Editor City'), max_length=256)
editor_address_state = models.CharField(_('Editor State/Province/Region'),
max_length=128)
editor_address_zip = models.CharField(_('Editor Zip/Postal Code'),
max_length=64)
editor_address_country = modelfields.CountryField(_('Editor Country'))
editor_phone1 = models.CharField(_('Editor Phone 1'), max_length=32)
editor_phone2 = models.CharField(_('Editor Phone 2'), null=True, blank=True,
max_length=32)
editor_email = models.EmailField(_('Editor E-mail'))
publisher_name = models.CharField(_('Publisher Name'), max_length=512)
publisher_country = modelfields.CountryField(_('Publisher Country'))
publisher_state = models.CharField(_('Publisher State/Province/Region'),
max_length=64)
publication_city = models.CharField(_('Publication City'), max_length=64)
is_indexed_scie = models.BooleanField(_('SCIE'), default=False)
is_indexed_ssci = models.BooleanField(_('SSCI'), default=False)
is_indexed_aehci = models.BooleanField(_('A&HCI'), default=False)
def __repr__(self):
return u'<%s pk="%s" acronym="%s">' % (self.__class__.__name__, self.pk,
self.acronym)
def __unicode__(self):
return self.title
class Meta:
ordering = ('title', 'id')
permissions = (("list_journal", "Can list Journals"),
("list_editor_journal", "Can list editor Journal"),
("change_editor", "Can change editor of the journal"))
def get_last_issue(self):
"""
Return the latest issue based on descending ordering of parameters:
``publication_year``, ``volume`` and ``number``
Return a issue instance otherwise ``None``
"""
try:
return self.issue_set.order_by('-publication_year', '-volume', '-number')[0]
except IndexError:
return None
def issues_as_grid(self, is_available=True):
objects_all = self.issue_set.available(is_available).order_by(
'-publication_year', '-volume')
grid = OrderedDict()
for issue in objects_all:
year_node = grid.setdefault(issue.publication_year, OrderedDict())
volume_node = year_node.setdefault(issue.volume, [])
volume_node.append(issue)
for year, volume in grid.items():
for vol, issues in volume.items():
issues.sort(key=lambda x: x.order)
return grid
@property
def succeeding_title(self):
try:
return self.prev_title.get()
except ObjectDoesNotExist:
return None
def has_issues(self, issues):
"""
Returns ``True`` if all the given issues are bound to the journal.
``issues`` is a list of Issue pk.
"""
issues_to_test = set(int(issue) for issue in issues)
bound_issues = set(issue.pk for issue in self.issue_set.all())
return issues_to_test.issubset(bound_issues)
@property
def scielo_pid(self):
"""
Returns the ISSN used as PID on SciELO public catalogs.
"""
attr = u'print_issn' if self.scielo_issn == u'print' else u'eletronic_issn'
return getattr(self, attr)
def join(self, collection, responsible):
"""Make this journal part of the collection.
"""
Membership.objects.create(journal=self,
collection=collection,
created_by=responsible,
status='inprogress')
def membership_info(self, collection, attribute=None):
"""Retrieve info about the relation of this journal with a
given collection.
"""
rel = self.membership_set.get(collection=collection)
if attribute:
return getattr(rel, attribute)
else:
return rel
def is_member(self, collection):
"""
Returns a boolean indicating whether or not a member of a specific collection
"""
return self.membership_set.filter(collection=collection).exists()
def change_status(self, collection, new_status, reason, responsible):
rel = self.membership_info(collection)
rel.status = new_status
rel.reason = reason
rel.created_by = responsible
rel.save()
class Membership(models.Model):
"""
Represents the many-to-many relation
between Journal and Collection.
"""
journal = models.ForeignKey('Journal')
collection = models.ForeignKey('Collection')
status = models.CharField(max_length=16, default="inprogress",
choices=choices.JOURNAL_PUBLICATION_STATUS)
since = models.DateTimeField(auto_now=True)
reason = models.TextField(_('Why are you changing the publication status?'),
blank=True, default="")
created_by = models.ForeignKey(User, editable=False)
def save(self, *args, **kwargs):
"""
Always save a copy at JournalTimeline
"""
super(Membership, self).save(*args, **kwargs)
JournalTimeline.objects.create(journal=self.journal,
collection=self.collection,
status=self.status,
reason=self.reason,
created_by=self.created_by,
since=self.since)
class Meta():
unique_together = ("journal", "collection")
class JournalTimeline(models.Model):
"""
Represents the status history of a journal.
"""
journal = models.ForeignKey('Journal', related_name='statuses')
collection = models.ForeignKey('Collection')
status = models.CharField(max_length=16,
choices=choices.JOURNAL_PUBLICATION_STATUS)
since = models.DateTimeField()
reason = models.TextField(_('Reason'), default="")
created_by = models.ForeignKey(User)
class JournalTitle(models.Model):
journal = models.ForeignKey(Journal, related_name='other_titles')
title = models.CharField(_('Title'), null=False, max_length=128)
category = models.CharField(_('Title Category'), null=False, max_length=128, choices=sorted(choices.TITLE_CATEGORY, key=lambda TITLE_CATEGORY: TITLE_CATEGORY[1]))
class JournalMission(models.Model):
journal = models.ForeignKey(Journal, related_name='missions')
description = models.TextField(_('Mission'))
language = models.ForeignKey('Language', blank=False, null=True)
class UseLicense(models.Model):
license_code = models.CharField(_('License Code'), unique=True, null=False, blank=False, max_length=64)
reference_url = models.URLField(_('License Reference URL'), null=True, blank=True)
disclaimer = models.TextField(_('Disclaimer'), null=True, blank=True, max_length=512)
is_default = models.BooleanField(_('Is Default?'), default=False)
def __unicode__(self):
return self.license_code
class Meta:
ordering = ['license_code']
def save(self, *args, **kwargs):
"""
Only one UseLicense must be the default (is_default==True).
If already have one, these will be unset as default (is_default==False)
If None is already setted, this instance been saved, will be the default.
If the only one is unsetted as default, then will be foreced to be the default anyway,
to allways get one license setted as default
"""
qs = UseLicense.objects.filter(is_default=True)
if (qs.count() == 0 ) or (self in qs):
# no other was default, or ``self`` is the current default one,
# so ``self`` will be set as default
self.is_default = True
if self.is_default:
if self.pk:
qs = qs.exclude(pk=self.pk)
if qs.count() != 0:
qs.update(is_default=False)
super(UseLicense, self).save(*args, **kwargs)
class TranslatedData(models.Model):
translation = models.CharField(_('Translation'), null=True, blank=True, max_length=512)
language = models.CharField(_('Language'), choices=sorted(choices.LANGUAGE, key=lambda LANGUAGE: LANGUAGE[1]), null=False, blank=False, max_length=32)
model = models.CharField(_('Model'), null=False, blank=False, max_length=32)
field = models.CharField(_('Field'), null=False, blank=False, max_length=32)
def __unicode__(self):
return self.translation if self.translation is not None else 'Missing trans: {0}.{1}'.format(self.model, self.field)
class SectionTitle(models.Model):
section = models.ForeignKey('Section', related_name='titles')
title = models.CharField(_('Title'), max_length=256, null=False)
language = models.ForeignKey('Language')
class Meta:
ordering = ['title']
class Section(models.Model):
"""
Represents a multilingual section of one/many Issues of
a given Journal.
``legacy_code`` contains the section code used by the old
title manager. We've decided to store this value just by
historical reasons, and we don't know if it will last forever.
"""
# Custom manager
objects = SectionCustomManager()
userobjects = modelmanagers.SectionManager()
journal = models.ForeignKey(Journal)
code = models.CharField(_('Legacy code'), unique=True, max_length=21, blank=True)
legacy_code = models.CharField(null=True, blank=True, max_length=16)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
is_trashed = models.BooleanField(_('Is trashed?'), default=False, db_index=True)
def __unicode__(self):
return ' | '.join([sec_title.title for sec_title in self.titles.all().order_by('language')])
@property
def actual_code(self):
if not self.pk or not self.code:
raise AttributeError('section must be saved in order to have a code')
return self.code
def is_used(self):
try:
return True if self.issue_set.all().count() else False
except ValueError: # raised when the object is not yet saved
return False
def add_title(self, title, language):
"""
Adds a section title in the given language.
A Language instance must be passed as the language argument.
"""
SectionTitle.objects.create(section=self, title=title, language=language)
def _suggest_code(self, rand_generator=base28.genbase):
"""
Suggests a code for the section instance.
The code is formed by the journal acronym + 4 pseudo-random
base 28 chars.
``rand_generator`` is the callable responsible for the pseudo-random
chars sequence. It may accept the number of chars as argument.
"""
num_chars = getattr(settings, 'SECTION_CODE_TOTAL_RANDOM_CHARS', 4)
fmt = u'{0}-{1}'.format(self.journal.acronym, rand_generator(num_chars))
return fmt
def _create_code(self, *args, **kwargs):
if not self.code:
tries = kwargs.pop('max_tries', 5)
while tries > 0:
self.code = self._suggest_code()
try:
super(Section, self).save(*args, **kwargs)
except IntegrityError:
tries -= 1
logger.warning('conflict while trying to generate a section code. %i tries remaining.' % tries)
continue
else:
logger.info('code created successfully for %s' % unicode(self))
break
else:
msg = 'max_tries reached while trying to generate a code for the section %s.' % unicode(self)
logger.error(msg)
raise DatabaseError(msg)
class Meta:
ordering = ('id',)
permissions = (("list_section", "Can list Sections"),)
def save(self, *args, **kwargs):
"""
If ``code`` already exists, the section is saved. Else,
the ``code`` will be generated before the save process is
performed.
"""
if self.code:
super(Section, self).save(*args, **kwargs)
else:
# the call to super().save is delegated to _create_code
# because there are needs to control saving max tries.
self._create_code(*args, **kwargs)
class Issue(models.Model):
# Custom manager
objects = IssueCustomManager()
userobjects = modelmanagers.IssueManager()
section = models.ManyToManyField(Section, verbose_name=_("Section"), blank=True)
journal = models.ForeignKey(Journal)
volume = models.CharField(_('Volume'), blank=True, max_length=16)
number = models.CharField(_('Number'), blank=True, max_length=16)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
publication_start_month = models.IntegerField(_('Start Month'), blank=True, null=True, choices=choices.MONTHS)
publication_end_month = models.IntegerField(_('End Month'), blank=True, null=True, choices=choices.MONTHS)
publication_year = models.IntegerField(_('Year'))
is_marked_up = models.BooleanField(_('Is Marked Up?'), default=False, null=False, blank=True)
use_license = models.ForeignKey(UseLicense, verbose_name=_("Use License"), null=True, help_text=ISSUE_DEFAULT_LICENSE_HELP_TEXT)
total_documents = models.IntegerField(_('Total of Documents'), default=0)
ctrl_vocabulary = models.CharField(_('Controlled Vocabulary'), max_length=64,
choices=sorted(choices.CTRL_VOCABULARY, key=lambda CTRL_VOCABULARY: CTRL_VOCABULARY[1]), null=False, blank=True)
editorial_standard = models.CharField(_('Editorial Standard'), max_length=64,
choices=sorted(choices.STANDARD, key=lambda STANDARD: STANDARD[1]))
cover = models.ImageField(_('Issue Cover'), upload_to='img/issue_cover/', null=True, blank=True)
is_trashed = models.BooleanField(_('Is trashed?'), default=False, db_index=True)
label = models.CharField(db_index=True, blank=True, null=True, max_length=64)
order = models.IntegerField(_('Issue Order'), blank=True)
type = models.CharField(_('Type'), max_length=15, choices=choices.ISSUE_TYPES, default='regular', editable=False)
suppl_text = models.CharField(_('Suppl Text'), max_length=15, null=True, blank=True)
spe_text = models.CharField(_('Special Text'), max_length=15, null=True, blank=True)
class Meta:
ordering = ('created', 'id')
permissions = (("list_issue", "Can list Issues"), )
@property
def scielo_pid(self):
"""
Returns the PID used on SciELO public catalogs, in the form:
``journal_issn + year + order``
"""
jissn = self.journal.scielo_pid
return ''.join(
[
jissn,
unicode(self.publication_year),
u'%04d' % self.order,
]
)
@property
def identification(self):
values = [self.number]
if self.type == 'supplement':
values.append('suppl.%s' % self.suppl_text)
if self.type == 'special':
_spe_text = 'spe' + self.spe_text if self.spe_text else 'spe'