-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathmodels.py
More file actions
executable file
·3516 lines (3083 loc) · 115 KB
/
models.py
File metadata and controls
executable file
·3516 lines (3083 loc) · 115 KB
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
import logging
import os
import sys
import traceback
from datetime import datetime
from functools import cached_property
from django.core.files.base import ContentFile
from django.db import IntegrityError, models
from django.db.models import Q, Count, Min
from django.db.utils import DataError
from django.utils import timezone
from django.utils.translation import gettext_lazy as _
from django_prometheus.models import ExportModelOperationsMixin
from legendarium.formatter import descriptive_format
from modelcluster.fields import ParentalKey
from modelcluster.models import ClusterableModel
from packtools.sps.formats import crossref, pmc, pubmed
from packtools.sps.pid_provider.xml_sps_lib import XMLWithPre, generate_finger_print
from wagtail.admin.panels import FieldPanel, InlinePanel, ObjectList, TabbedInterface
from wagtail.models import Orderable
from wagtailautocomplete.edit_handlers import AutocompletePanel
from packtools.sps.libs.requester import NonRetryableError
from article import choices
from article.utils.url_builder import ArticleURLBuilder
from collection.models import Collection
from core.forms import CoreAdminModelForm
from core.models import CommonControlField # Ajuste o import conforme sua estrutura
from core.models import (
BaseExporter,
BaseLegacyRecord,
FlexibleDate,
Language,
License,
LicenseStatement,
TextLanguageMixin,
CharFieldLangMixin,
)
from core.utils.utils import NonRetryableError, fetch_data
from doi.models import DOI
from doi_manager.models import CrossRefConfiguration
from institution.models import Publisher, Sponsor
from issue.models import Issue, TableOfContents
from journal.models import Journal, SciELOJournal
from pid_provider.choices import PPXML_STATUS_DONE
from pid_provider.models import PidProviderXML
from pid_provider.provider import PidProvider
from location.models import Location
from organization.models import Organization, NormAffiliation
from researcher.models import AffiliationMixin, CollabMixin, ResearchNameMixin
from tracker.models import BaseEvent, EventSaveError, UnexpectedEvent
from vocabulary.models import Keyword
class RequestXMLException(Exception):
"""Exceção personalizada para erros na requisição de XML"""
pass
class XMLException(Exception):
"""Exceção personalizada para erros na requisição de XML"""
pass
class UnableToRegisterPIDError(Exception):
"""Exceção personalizada para erros ao registrar PID"""
pass
class AMArticle(BaseLegacyRecord):
"""
Modelo que representa a coleta de dados de Issue na API Article Meta.
from:
https://articlemeta.scielo.org/api/v1/issue/?collection={collection}&code={code}"
"""
pid = models.CharField(
_("PID"),
max_length=23,
blank=True,
null=True,
)
new_record = models.ForeignKey(
"Article",
on_delete=models.SET_NULL,
null=True,
blank=True,
related_name="legacy_article",
)
panels = [
AutocompletePanel("collection"),
FieldPanel("new_record"),
FieldPanel("pid"),
FieldPanel("status"),
FieldPanel("processing_date"),
FieldPanel("url"),
FieldPanel("data", read_only=True),
]
class Meta:
verbose_name = _("Legacy article")
verbose_name_plural = _("Legacy articles")
indexes = [
models.Index(
fields=[
"pid",
]
),
]
class Article(
ExportModelOperationsMixin("article"), CommonControlField, ClusterableModel
):
pp_xml = models.ForeignKey(
PidProviderXML,
null=True,
blank=True,
on_delete=models.SET_NULL,
)
data_status = models.CharField(
_("Data status"),
max_length=15,
null=True,
blank=True,
choices=choices.DATA_STATUS,
default=choices.DATA_STATUS_UNDEF,
)
pid_v2 = models.CharField(_("PID V2"), max_length=23, null=True, blank=True)
pid_v3 = models.CharField(
_("PID V3"), max_length=23, null=True, blank=True, unique=True
)
sps_pkg_name = models.CharField(
_("Package name"), max_length=64, null=True, blank=True
)
journal = models.ForeignKey(
Journal,
verbose_name=_("Journal"),
null=True,
blank=True,
on_delete=models.SET_NULL,
)
doi = models.ManyToManyField(DOI, blank=True)
pub_date_day = models.CharField(
_("pub date day"),
max_length=10,
null=True,
blank=True,
help_text=_("Dia de publicação no site."),
)
pub_date_month = models.CharField(
_("pub date month"),
max_length=10,
null=True,
blank=True,
help_text=_("Mês de publicação no site."),
)
pub_date_year = models.CharField(
max_length=4, null=True, blank=True, help_text=_("Ano de publicação no site.")
)
fundings = models.ManyToManyField(
"ArticleFunding", verbose_name=_("Fundings"), blank=True
)
languages = models.ManyToManyField(Language, blank=True)
titles = models.ManyToManyField("DocumentTitle", blank=True)
# researchers field replaced by contrib_persons (ContribPerson model)
# researchers = models.ManyToManyField(Researcher, blank=True)
article_type = models.CharField(max_length=50, null=True, blank=True)
# abstracts = models.ManyToManyField("DocumentAbstract", blank=True)
sections = models.ManyToManyField(TableOfContents, blank=True)
license_statements = models.ManyToManyField(LicenseStatement, blank=True)
license = models.ForeignKey(
License, on_delete=models.SET_NULL, null=True, blank=True
)
issue = models.ForeignKey(Issue, on_delete=models.SET_NULL, null=True, blank=True)
first_page = models.CharField(max_length=20, null=True, blank=True)
last_page = models.CharField(max_length=20, null=True, blank=True)
elocation_id = models.CharField(max_length=64, null=True, blank=True)
keywords = models.ManyToManyField(Keyword, blank=True)
valid = models.BooleanField(default=False, blank=True, null=True)
errors = models.JSONField(default=None, blank=True, null=True)
is_public = models.BooleanField(default=False, blank=True, null=True)
is_classic_public = models.BooleanField(default=False, blank=True, null=True)
is_new_public = models.BooleanField(default=False, blank=True, null=True)
data_availability_status = models.CharField(
_("Data Availability Status"),
max_length=30,
null=True,
blank=True,
choices=choices.DATA_AVAILABILITY_STATUS,
default=choices.DATA_AVAILABILITY_STATUS_NOT_PROCESSED,
)
invalid_data_availability_status = models.CharField(
_("Invalid data availability status from XML"),
max_length=255,
null=True,
blank=True,
help_text=_("Armazena valores inválidos recebidos do XML")
)
peer_review_stats = models.JSONField(
_("Peer review statistics"),
default=dict,
blank=True,
help_text=_("Todas as datas e intervalos do processo de revisão por pares"),
)
preprint_dateiso = models.CharField(
_("Preprint Date (ISO)"),
max_length=10,
null=True,
blank=True,
help_text=_("Preprint publication date in ISO format (YYYY-MM-DD)")
)
received_dateiso = models.CharField(
_("Received Date (ISO)"),
max_length=10,
null=True,
blank=True,
help_text=_("Date the article was received, in ISO format (YYYY-MM-DD)")
)
accepted_dateiso = models.CharField(
_("Accepted Date (ISO)"),
max_length=10,
null=True,
blank=True,
help_text=_("Date the article was accepted, in ISO format (YYYY-MM-DD)")
)
days_preprint_to_received = models.IntegerField(null=True, blank=True)
days_received_to_accepted = models.IntegerField(null=True, blank=True)
days_accepted_to_published = models.IntegerField(null=True, blank=True)
days_preprint_to_published = models.IntegerField(null=True, blank=True)
days_receive_to_published = models.IntegerField(null=True, blank=True)
days_preprint_to_received_estimated = models.BooleanField(null=True, blank=True)
days_received_to_accepted_estimated = models.BooleanField(null=True, blank=True)
days_accepted_to_published_estimated = models.BooleanField(null=True, blank=True)
days_preprint_to_published_estimated = models.BooleanField(null=True, blank=True)
days_receive_to_published_estimated = models.BooleanField(null=True, blank=True)
base_form_class = CoreAdminModelForm
# Metadados principais do artigo
panels_identification = [
FieldPanel("pid_v2", read_only=True),
FieldPanel("pid_v3", read_only=True),
AutocompletePanel("doi", read_only=True),
FieldPanel("article_type", read_only=True),
AutocompletePanel("sections", read_only=True),
AutocompletePanel("titles", read_only=True),
]
# Informações de publicação
panels_publication = [
AutocompletePanel("journal", read_only=True),
AutocompletePanel("issue", read_only=True),
FieldPanel("pub_date_year", read_only=True),
FieldPanel("pub_date_month", read_only=True),
FieldPanel("pub_date_day", read_only=True),
FieldPanel("first_page", read_only=True),
FieldPanel("last_page", read_only=True),
FieldPanel("elocation_id", read_only=True),
]
panels_open_science = [
InlinePanel("related_articles", label=_("Related Articles")),
AutocompletePanel("license", read_only=True),
FieldPanel("data_availability_status", read_only=True),
InlinePanel(
"data_availability_statements", label=_("Data Availability Statements")
),
]
# Conteúdo e classificação
panels_content = [
AutocompletePanel("languages", read_only=True),
InlinePanel("abstracts", label=_("Abstract")),
AutocompletePanel("keywords", read_only=True),
]
# Autoria e colaboração
panels_authorship = [
InlinePanel("contrib_persons", label=_("Contributors")),
InlinePanel("contrib_collabs", label=_("Collaborations")),
]
# Licenciamento e financiamento
panels_rights_funding = [
AutocompletePanel("fundings", read_only=True),
]
panels_processing = [
FieldPanel("is_public", read_only=True),
FieldPanel("is_classic_public", read_only=True),
FieldPanel("is_new_public", read_only=True),
FieldPanel("data_status", read_only=True),
FieldPanel("valid", read_only=True),
]
panels_errors = [
FieldPanel("errors", read_only=True),
InlinePanel("events", label=_("Events")),
]
edit_handler = TabbedInterface(
[
ObjectList(panels_identification, heading=_("Identification")),
ObjectList(panels_publication, heading=_("Publication Details")),
ObjectList(panels_content, heading=_("Content & Classification")),
ObjectList(panels_authorship, heading=_("Authors & Collaborators")),
ObjectList(panels_open_science, heading=_("Open Science")),
ObjectList(panels_rights_funding, heading=_("Funding")),
ObjectList(panels_errors, heading=_("Errors")),
ObjectList(panels_processing, heading=_("Processing")),
]
)
class Meta:
ordering = ["-updated", "-created", "sps_pkg_name"]
indexes = [
models.Index(
fields=[
"id",
]
),
models.Index(
fields=[
"valid",
]
),
models.Index(
fields=[
"data_status",
]
),
models.Index(
fields=[
"sps_pkg_name",
]
),
models.Index(
fields=[
"pid_v3",
]
),
models.Index(
fields=[
"pub_date_year",
]
),
models.Index(fields=["pid_v2"]),
models.Index(fields=["is_classic_public"]),
models.Index(fields=["is_new_public"]),
models.Index(fields=["pp_xml"]),
models.Index(fields=["data_availability_status"]),
models.Index(fields=["article_type"]),
models.Index(fields=["days_preprint_to_received"]),
models.Index(fields=["days_received_to_accepted"]),
models.Index(fields=["days_accepted_to_published"]),
models.Index(fields=["days_preprint_to_published"]),
models.Index(fields=["days_receive_to_published"]),
models.Index(fields=["days_receive_to_published_estimated"]),
]
def __unicode__(self):
return self.sps_pkg_name or self.pid_v3 or f"{self.doi.first()}" or self.title
def __str__(self):
return self.sps_pkg_name or self.pid_v3 or f"{self.doi.first()}" or self.title
@cached_property
def xml_with_pre(self):
try:
return self.pp_xml.xml_with_pre
except AttributeError:
return PidProviderXML.get_xml_with_pre(self.pid_v3)
@property
def xmltree(self):
try:
return self.xml_with_pre.xmltree
except AttributeError:
return PidProvider.get_xmltree(self.pid_v3)
@cached_property
def collections(self):
"""
Returns the collections associated with this article.
First tries to get collections from legacy_article relationships,
then falls back to journal relationships if no legacy articles exist.
Returns:
list: List of Collection objects
"""
if self.legacy_article.exists():
return [
item.collection
for item in self.legacy_article.select_related("collection").all()
]
if self.journal:
return [
item.collection
for item in self.journal.scielojournal_set.select_related(
"collection"
).all()
]
return []
@classmethod
def last_created_date(cls):
try:
last_created = cls.objects.filter(
pid_v3__isnull=False,
).latest("created")
return last_created.created
except (AttributeError, cls.DoesNotExist):
return datetime(1, 1, 1)
@property
def data(self):
_data = {
"article__pid_v2": self.pid_v2,
"article__pid_v3": self.pid_v3,
}
return _data
@property
def source(self):
"""
Return the format: Acta Cirúrgica Brasileira, Volume: 37, Issue: 7, Article number: e370704, Published: 10 OCT 2022
"""
if not self.journal:
return ""
if not self.issue:
return ""
leg_dict = {
"title": self.journal.title,
"pubdate": self.issue.year,
"volume": self.issue.volume,
"number": self.issue.number,
"suppl": self.issue.supplement,
"fpage": self.first_page,
"lpage": self.last_page,
"elocation": self.elocation_id,
}
try:
return descriptive_format(**leg_dict)
except Exception as ex:
logging.exception("Erro on article %s, error: %s" % (self.pid_v2, ex))
return ""
@property
def pub_date(self):
year = self.pub_date_year or ""
month = self.pub_date_month or ""
day = self.pub_date_day or ""
if year and month and day:
return f"{year}-{month.zfill(2)}-{day.zfill(2)}"
elif year and month:
return f"{year}-{month.zfill(2)}"
else:
return year
@classmethod
def get_by_pid_v3_or_by_sps_pkg_name(
cls,
pid_v3=None,
sps_pkg_name=None,
):
if not pid_v3 and not sps_pkg_name:
raise ValueError("Article requires params: pid_v3 or sps_pkg_name")
q = Q()
if pid_v3:
q |= Q(pid_v3=pid_v3)
if sps_pkg_name:
q |= Q(sps_pkg_name=sps_pkg_name)
return cls.objects.filter(q).order_by("-updated").distinct()
@classmethod
def get(
cls,
pid_v3=None,
sps_pkg_name=None,
handle_multiple=False,
):
if not pid_v3 and not sps_pkg_name:
raise ValueError("Article requires params: pid_v3 or sps_pkg_name")
try:
return cls.objects.get(sps_pkg_name=sps_pkg_name, pid_v3=pid_v3)
except cls.DoesNotExist:
pass
except cls.MultipleObjectsReturned:
pass
except Exception as e:
raise e
items = cls.get_by_pid_v3_or_by_sps_pkg_name(
pid_v3=pid_v3,
sps_pkg_name=sps_pkg_name,
)
if not items.exists():
raise cls.DoesNotExist(
"Article not found for pid_v3: {pid_v3} or sps_pkg_name: {sps_pkg_name}"
)
public = items.filter(is_classic_public=True)
public_items = list(public)
if len(public_items) == 1:
return public_items[0]
items = list(items)
if len(public_items) == 0 and len(items) == 1:
return items[0]
if handle_multiple:
return public_items[0] or items[0]
raise cls.MultipleObjectsReturned(
f"Multiple Article found for pid_v3: {pid_v3} or sps_pkg_name: {sps_pkg_name}"
)
@classmethod
def create(
cls,
user,
pid_v3=None,
sps_pkg_name=None,
handle_multiple=True,
):
try:
logging.info(f"create: {pid_v3} {sps_pkg_name}")
obj = cls()
obj.pid_v3 = pid_v3
obj.sps_pkg_name = sps_pkg_name
obj.creator = user
obj.save()
return obj
except IntegrityError:
return cls.get(
pid_v3=pid_v3,
sps_pkg_name=sps_pkg_name,
handle_multiple=handle_multiple,
)
@classmethod
def create_or_update(
cls,
user,
pid_v3=None,
sps_pkg_name=None,
handle_multiple=False,
):
logging.info(f"Article.get_or_create: {user} {pid_v3} {sps_pkg_name}")
try:
return cls.get(
pid_v3=pid_v3,
sps_pkg_name=sps_pkg_name,
handle_multiple=handle_multiple,
)
except cls.DoesNotExist:
return cls.create(user=user, pid_v3=pid_v3, sps_pkg_name=sps_pkg_name)
@classmethod
def get_or_create(
cls,
pid_v3=None,
user=None,
sps_pkg_name=None,
):
return cls.create_or_update(user=user, pid_v3=pid_v3, sps_pkg_name=sps_pkg_name)
def mark_as_completed(self, user=None):
self.valid = True
self.data_status = choices.DATA_STATUS_COMPLETED
self.save() # Salvar estado final
self.pp_xml.mark_as_done()
def set_date_pub(self, dates, save=True):
if dates:
self.pub_date_day = dates.get("day")
self.pub_date_month = dates.get("month")
self.pub_date_year = dates.get("year")
if save:
self.save()
def set_pids(self, pids, save=True):
self.pid_v2 = pids.get("v2")
self.pid_v3 = pids.get("v3")
if save:
self.save()
def is_indexed_at(self, db_acronym):
return bool(self.journal) and self.journal.is_indexed_at(db_acronym)
def create_legacy_keys(self, user=None, force_update=False):
if not force_update:
if self.legacy_article.count() == self.journal.scielojournal_set.count():
return
# garante que a issue tenha suas chaves legadas criadas
self.issue.create_legacy_keys(user, force_update)
for issue_key in self.issue.get_legacy_keys():
collection = issue_key["collection"]
issue_pid = issue_key["pid"]
if not self.pid_v2:
# este valor deve vir pela importação do AM ou
# pelo upload (migração ou alimentação direta)
# via solicitação de pid para o pid provider
continue
if self.pid_v2 and issue_pid in self.pid_v2:
am_article = AMArticle.create_or_update(
self.pid_v2, collection, None, user, status="done"
)
self.legacy_article.add(am_article)
def get_legacy_keys(self, collection_acron_list=None, is_active=None):
params = {}
if collection_acron_list:
params["collection__acron3__in"] = collection_acron_list
if is_active:
params["collection__is_active"] = bool(is_active)
data = {}
for item in self.legacy_article.filter(**params):
data[item.collection.acron3] = item.legacy_keys
if not data:
UnexpectedEvent.create(
exception=ValueError("No legacy keys found for article"),
detail={
"operation": "Article.get_legacy_keys",
"article": str(self),
"collection_acron_list": collection_acron_list,
"is_active": is_active,
"params": params,
"legacy_article_count": self.legacy_article.count(),
},
)
return list(data.values())
def select_collections(self, collection_acron_list=None, is_activate=None):
if not self.journal:
raise ValueError(f"{self} has no journal")
return self.journal.select_collections(collection_acron_list, is_activate)
def select_journals(self, collection_acron_list=None):
if not self.journal:
raise ValueError(f"{self} has no journal")
return self.journal.select_items(collection_acron_list)
@classmethod
def select_items(
cls,
collection_acron_list=None,
journal_acron_list=None,
from_pub_year=None,
until_pub_year=None,
volume=None,
number=None,
supplement=None,
from_updated_date=None,
until_updated_date=None,
data_status_list=None,
valid=None,
pp_xml__isnull=None,
sps_pkg_name__isnull=None,
article_license__isnull=None,
params=None,
):
params = params or {}
if collection_acron_list:
params["journal__scielojournal__collection__acron3__in"] = (
collection_acron_list
)
if journal_acron_list:
params["journal__scielojournal__journal_acron__in"] = journal_acron_list
if from_pub_year:
params["issue__year__gte"] = from_pub_year
if until_pub_year:
params["issue__year__lte"] = until_pub_year
if from_updated_date:
params["updated_date__gte"] = from_updated_date
if until_updated_date:
params["updated_date__lte"] = until_updated_date
if data_status_list:
params["data_status__in"] = data_status_list
if volume:
params["issue__volume"] = volume
if number:
params["issue__number"] = number
if supplement:
params["issue__supplement"] = supplement
q = Q()
if valid is not None:
q |= Q(valid=valid)
if pp_xml__isnull is not None:
q |= Q(pp_xml__isnull=pp_xml__isnull)
if sps_pkg_name__isnull is not None:
q |= Q(sps_pkg_name__isnull=sps_pkg_name__isnull)
if article_license__isnull is not None:
q |= Q(article_license__isnull=article_license__isnull)
return cls.objects.filter(q, **params).distinct()
@classmethod
def select_journal_articles(cls, journal=None, journal_id=None, issns=None):
if not issns and not journal and not journal_id:
raise ValueError(
"Article.select_journal_articles requires issns, journal or journal_id param"
)
if journal:
return cls.objects.filter(journal=journal)
if journal_id:
return cls.objects.filter(journal_id=journal_id)
return cls.objects.filter(
Q(journal__official__issn_print__in=issns)
| Q(journal__official__issn_electronic__in=issns)
)
@cached_property
def langs(self):
return [lang.code2 for lang in self.languages.all()]
@property
def urls_data(self):
urls = []
for sj in self.journal.scielojournal_set.select_related("collection").all():
try:
pid_v2 = (
self.legacy_article.filter(collection=sj.collection).first().pid
)
except AttributeError:
pid_v2 = None
if not pid_v2:
continue
url_builder = ArticleURLBuilder(
sj.collection.base_url,
sj.journal_acron,
pid_v2,
self.pid_v3,
)
for item in url_builder.get_urls(self.langs):
item["collection"] = sj.collection
urls.append(item)
return urls
def get_availability(
self, collection_acron_list=None, collection=None, fmt=None, params=None
):
params = params or {}
if fmt:
params["fmt"] = fmt
if collection:
params["collection"] = collection
if collection_acron_list:
params["collection__acron3__in"] = collection_acron_list
logging.info(f"get_availability {params}")
return self.article_availability.filter(available=True, **params)
def check_availability(self, user, force_update=False):
try:
if not self.is_pp_xml_valid():
return False
if not force_update and self.is_available():
return True
event = None
urls = []
for item in self.article_availability.all():
urls.append(item.url)
event = self.add_event(user, _("register urls"))
for item in self.urls_data:
if item["url"] in urls:
urls.remove(item["url"])
ArticleAvailability.create_or_update(
user,
self,
collection=item["collection"],
url=item["url"],
fmt=item["format"],
lang=item.get("lang"),
)
if urls:
self.article_availability.filter(url__in=urls).delete()
return self.mark_as_available()
except Exception as e:
exc_type, exc_value, exc_traceback = sys.exc_info()
if event:
event.finish(completed=False, exceptions=traceback.format_exc())
else:
UnexpectedEvent.create(
item=str(self),
exception=e,
exc_traceback=exc_traceback,
detail=dict(
function="article.models.Article.check_availability",
),
)
def mark_as_available(self):
save = False
public = self.classic_available().exists()
if self.is_classic_public != public:
self.is_classic_public = public
save = True
public = self.new_available().exists()
if self.is_new_public != public:
self.is_new_public = public
save = True
if self.is_classic_public or self.is_new_public:
if self.data_status != choices.DATA_STATUS_PUBLIC:
self.data_status = choices.DATA_STATUS_PUBLIC
save = True
if not self.is_public:
self.is_public = True
save = True
if save:
self.save()
return self.is_public
def is_available(self, collection_acron_list=None, fmt=None):
return self.get_availability(
fmt=fmt, collection_acron_list=collection_acron_list
).exists()
def new_available(self, collection_acron_list=None):
return self.get_availability(
fmt="xml", collection_acron_list=collection_acron_list
)
def classic_available(self, collection_acron_list=None):
params = {"url__contains": "/scielo.php"}
return self.get_availability(
fmt="html", collection_acron_list=collection_acron_list, params=params
)
def get_text_langs(self, collection_acron_list=None, fmt=None):
by_collection = {}
params = {}
if fmt:
params["fmt"] = fmt
else:
params["fmt__in"] = ["html", "pdf"]
if collection_acron_list:
params["collection__acron3__in"] = collection_acron_list
for item in self.article_availability.filter(lang__isnull=False, **params).select_related('collection', 'lang').distinct():
acron3 = item.collection.acron3
code2 = item.lang.code2
fmt = item.fmt
by_collection.setdefault(acron3, {})
by_collection[acron3].setdefault(fmt, [])
if code2 not in by_collection[acron3][fmt]:
by_collection[acron3][fmt].append(code2)
return by_collection
def add_event(self, user, name):
return ArticleEvent.create(user, self, name)
def add_related_article(self, user, href, ext_link_type, related_type, related_article=None):
return RelatedArticle.create_or_update(
user,
self,
href,
ext_link_type,
related_type,
related_article=related_article,
)
@classmethod
def mark_items_as_public(
cls, journal=None, journal_id=None, force_update=False, user=None
):
# DATA_STATUS_DELETED, DATA_STATUS_MOVED, DATA_STATUS_INVALID, DATA_STATUS_DUPLICATED,
if force_update:
exclusion_list = []
else:
exclusion_list = choices.DATA_STATUS_EXCLUSION_LIST + [
choices.DATA_STATUS_PUBLIC
]
for item in (
cls.select_journal_articles(journal=journal, journal_id=journal_id)
.exclude(
data_status__in=exclusion_list,
)
.iterator()
):
item.check_availability(user)
@classmethod
def mark_items_as_invalid(cls, journal=None, journal_id=None):
qs = cls.select_journal_articles(journal=journal, journal_id=journal_id)
if qs.count() == 0:
return
for item in qs.iterator():
item.is_pp_xml_valid()
def is_pp_xml_valid(self):
if not self.pp_xml:
try:
self.pp_xml = PidProviderXML.get_by_pid_v3(pid_v3=self.pid_v3)
except PidProviderXML.DoesNotExist:
self.pp_xml = None
if not self.pp_xml or not self.pp_xml.xml_with_pre:
if self.data_status != choices.DATA_STATUS_INVALID:
self.data_status = choices.DATA_STATUS_INVALID
self.save()
return None
return self.id
@classmethod
def find_duplicated_pkg_names(cls, journal=None, journal_id=None):
# Busca em ambos os campos de ISSN
params = {}
if journal:
params["journal"] = journal
if journal_id:
params["journal__id"] = journal_id
return (
cls.objects.filter(**params)
.exclude(sps_pkg_name__isnull=True)
.exclude(sps_pkg_name="")
.exclude(data_status=choices.DATA_STATUS_DUPLICATED)
.values("sps_pkg_name")
.annotate(count=Count("id"))
.filter(count__gt=1)
.values_list("sps_pkg_name", flat=True)
)
@classmethod
def find_duplicated_pid_v2(cls, journal=None, journal_id=None):
# Busca em ambos os campos de ISSN
params = {}
if journal:
params["journal"] = journal
if journal_id:
params["journal__id"] = journal_id
return (
cls.objects.filter(**params)
.exclude(pid_v2__isnull=True)
.exclude(pid_v2="")
.exclude(data_status=choices.DATA_STATUS_DUPLICATED)
.values("pid_v2")
.annotate(count=Count("id"))
.filter(count__gt=1)
.values_list("pid_v2", flat=True)
)
@classmethod
def deduplicate_items(cls, user, journal=None, journal_id=None, mark_as_duplicated=False, deduplicate=False):
"""
Corrige todos os artigos marcados como DATA_STATUS_DUPLICATED com base nos ISSNs fornecidos.
Args:
issns: Lista de ISSNs para verificar duplicatas.
user: Usuário que está executando a operação.
"""
article_duplicated_pid_v2 = cls.find_duplicated_pid_v2(
journal, journal_id
)
if article_duplicated_pid_v2.exists():
if mark_as_duplicated:
cls.objects.filter(pid_v2__in=article_duplicated_pid_v2).exclude(
data_status=choices.DATA_STATUS_DUPLICATED
).update(
data_status=choices.DATA_STATUS_DUPLICATED,
)
if deduplicate:
for pid_v2 in article_duplicated_pid_v2:
cls.fix_duplicated_items(user, None, pid_v2)
article_duplicated_pkg_names = cls.find_duplicated_pkg_names(
journal, journal_id
)
if article_duplicated_pkg_names.exists():
if mark_as_duplicated:
cls.objects.filter(sps_pkg_name__in=article_duplicated_pkg_names).exclude(
data_status=choices.DATA_STATUS_DUPLICATED
).update(
data_status=choices.DATA_STATUS_DUPLICATED,
)
if deduplicate:
for pkg_name in article_duplicated_pkg_names:
cls.fix_duplicated_items(user, pkg_name, None)
return article_duplicated_pkg_names
@classmethod
def fix_duplicated_items(cls, user, pkg_name, pid_v2):
"""
Corrige artigos marcados como DATA_STATUS_DUPLICATED com base no pkg_name fornecido.