Fix.
[redakcja.git] / src / catalogue / admin.py
1 # This file is part of FNP-Redakcja, licensed under GNU Affero GPLv3 or later.
2 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
3 #
4 import json
5 from django.contrib import admin
6 from django.db.models import Min
7 from django import forms
8 from django.urls import reverse
9 from django.utils.html import escape, format_html
10 from django.utils.safestring import mark_safe
11 from django.utils.translation import gettext_lazy as _
12 from admin_numeric_filter.admin import RangeNumericFilter, NumericFilterModelAdmin, RangeNumericForm
13 from admin_ordering.admin import OrderableAdmin
14 from fnpdjango.actions import export_as_csv_action
15 from modeltranslation.admin import TabbedTranslationAdmin
16 from reversion.admin import VersionAdmin
17 from . import models
18 import documents.models
19 import sources.models
20 from .wikidata import WikidataAdminMixin
21
22
23 class NotableBookInline(OrderableAdmin, admin.TabularInline):
24     model = models.NotableBook
25     autocomplete_fields = ['book']
26     ordering_field_hide_input = True
27
28
29 class WoblinkCatalogueWidget(forms.Select):
30     class Media:
31         js = (
32             "admin/js/vendor/jquery/jquery.min.js",
33             "admin/js/vendor/select2/select2.full.min.js",
34             "admin/js/vendor/select2/i18n/pl.js",
35             "catalogue/woblink_admin.js",
36             "admin/js/jquery.init.js",
37             "admin/js/autocomplete.js",
38         )
39         css = {
40             "screen": (
41                 "admin/css/vendor/select2/select2.min.css",
42                 "admin/css/autocomplete.css",
43             ),
44         }
45
46     def __init__(self):
47         self.attrs = {}
48         self.choices = []
49         self.field = None
50
51     def get_url(self):
52         return reverse('catalogue_woblink_autocomplete', args=[self.category])
53
54     def build_attrs(self, base_attrs, extra_attrs=None):
55         attrs = super().build_attrs(base_attrs, extra_attrs=extra_attrs)
56         attrs.setdefault("class", "")
57         attrs.update(
58             {
59                 "data-ajax--cache": "true",
60                 "data-ajax--delay": 250,
61                 "data-ajax--type": "GET",
62                 "data-ajax--url": self.get_url(),
63                 "data-app-label": '',
64                 "data-model-name": '',
65                 "data-field-name": '',
66                 "data-theme": "admin-autocomplete",
67                 "data-allow-clear": json.dumps(not self.is_required),
68
69                 "data-placeholder": "", # Chyba że znaleziony?
70                 "lang": "pl",
71                 "class": attrs["class"]
72                 + (" " if attrs["class"] else "")
73                 + "admin-autocomplete admin-woblink",
74             }
75         )
76         return attrs
77
78     def optgroups(self, name, value, attrs=None):
79         """ Add synthetic option for keeping the current value. """
80         return [(None, [
81             self.create_option(
82                 name,
83                 v,
84                 '(bez zmian)',
85                 selected=True,
86                 index=index,
87                 attrs=attrs,
88             )
89             for index, v in enumerate(value)
90         ], 0)]
91
92 class WoblinkAuthorWidget(WoblinkCatalogueWidget):
93     category = 'author'
94
95 class AuthorForm(forms.ModelForm):
96     class Meta:
97         model = models.Author
98         fields = '__all__'
99         widgets = {
100             'woblink': WoblinkAuthorWidget,
101         }
102
103 class AuthorAdmin(WikidataAdminMixin, TabbedTranslationAdmin, VersionAdmin):
104     form = AuthorForm
105     list_display = [
106         "first_name",
107         "last_name",
108         "status",
109         "year_of_death",
110         "gender",
111         "nationality",
112         "priority",
113         "wikidata_link",
114         "woblink_link",
115         "slug",
116     ]
117     list_display_links = [
118         "first_name", "last_name"
119     ]
120     list_filter = [
121         ("year_of_death", RangeNumericFilter),
122         "priority",
123         "collections",
124         "status",
125         "gender",
126         "nationality",
127         "place_of_birth",
128         "place_of_death",
129         ("genitive", admin.EmptyFieldListFilter)
130     ]
131     list_per_page = 10000000
132     search_fields = ["first_name", "last_name", "wikidata"]
133     readonly_fields = ["wikidata_link", "description_preview", "woblink_link"]
134     prepopulated_fields = {"slug": ("first_name", "last_name")}
135     autocomplete_fields = ["collections", "place_of_birth", "place_of_death"]
136     inlines = [
137         NotableBookInline,
138     ]
139
140     fieldsets = [
141         (None, {
142             "fields": [
143                 ("wikidata", "wikidata_link"),
144                 ("woblink", "woblink_link"),
145             ]
146         }),
147         (
148             _("Identification"),
149             {
150                 "fields": [
151                     ("first_name", "last_name"),
152                     "slug",
153                     "genitive",
154                     "gender",
155                     "nationality",
156                     (
157                         "date_of_birth",
158                         "year_of_birth",
159                         "year_of_birth_inexact",
160                         "year_of_birth_range",
161                         "century_of_birth",
162                         "place_of_birth"
163                     ),
164                     (
165                         "date_of_death",
166                         "year_of_death",
167                         "year_of_death_inexact",
168                         "year_of_death_range",
169                         "century_of_death",
170                         "place_of_death"
171                     ),
172                     ("description", "description_preview"),
173                     "status",
174                     "collections",
175                     "priority",
176                     
177                     "notes",
178                     "gazeta_link",
179                     "culturepl_link",
180                     "plwiki",
181                     "photo", "photo_source", "photo_attribution",
182                 ]
183             },
184         ),
185     ]
186
187     def description_preview(self, obj):
188         return obj.generate_description()
189
190     def woblink_link(self, obj):
191         if obj.woblink:
192             return format_html(
193                 '<a href="https://woblink.com/autor/{slug}-{w}" target="_blank">{w}</a>',
194                 w=obj.woblink,
195                 slug=obj.slug,
196             )
197         else:
198             return ""
199     woblink_link.admin_order_field = "woblink"
200
201
202 admin.site.register(models.Author, AuthorAdmin)
203
204
205 class LicenseFilter(admin.SimpleListFilter):
206     title = 'Licencja'
207     parameter_name = 'book_license'
208     license_url_field = 'document_book__dc__license'
209     license_name_field = 'document_book__dc__license_description'
210
211     def lookups(self, requesrt, model_admin):
212         return [
213             ('cc', 'CC'),
214             ('fal', 'FAL'),
215             ('pd', 'domena publiczna'),
216         ]
217
218     def queryset(self, request, queryset):
219         v = self.value()
220         if v == 'cc': 
221             return queryset.filter(**{
222                 self.license_url_field + '__icontains': 'creativecommons.org'
223             })
224         elif v == 'fal':
225             return queryset.filter(**{
226                 self.license_url_field + '__icontains': 'artlibre.org'
227             })
228         elif v == 'pd':
229             return queryset.filter(**{
230                 self.license_name_field + '__icontains': 'domena publiczna'
231             })
232         else:
233             return queryset
234
235
236 class CoverLicenseFilter(LicenseFilter):
237     title = 'Licencja okładki'
238     parameter_name = 'cover_license'
239     license_url_field = 'document_book__dc_cover_image__license_url'
240     license_name_field = 'document_book__dc_cover_image__license_name'
241
242
243 class ChildrenFilter(admin.SimpleListFilter):
244     title = 'Status utworu podrzędnego'
245     parameter_name = 'book_children'
246
247     def lookups(self, requesrt, model_admin):
248         return [
249             ('no', 'bez podrzędnych'),
250             ('only', 'tylko podrzędne'),
251         ]
252
253     def queryset(self, request, queryset):
254         v = self.value()
255         if v == 'no':
256             return queryset.filter(parent=None)
257         elif v == 'only':
258             return queryset.exclude(parent=None)
259         else:
260             return queryset
261
262
263 def add_title(base_class, suffix):
264     class TitledCategoryFilter(base_class):
265         def __init__(self, *args, **kwargs):
266             super().__init__(*args, **kwargs)
267             self.title += suffix
268     return TitledCategoryFilter
269
270
271 class FirstPublicationYearFilter(admin.ListFilter):
272     title = 'Rok pierwszej publikacji'
273     parameter_name = 'first_publication_year'
274     template = 'admin/filter_numeric_range.html'
275
276     def __init__(self, request, params, *args, **kwargs):
277         super().__init__(request, params, *args, **kwargs)
278
279         self.request = request
280
281         if self.parameter_name + '_from' in params:
282             value = params.pop(self.parameter_name + '_from')
283             self.used_parameters[self.parameter_name + '_from'] = value
284
285         if self.parameter_name + '_to' in params:
286             value = params.pop(self.parameter_name + '_to')
287             self.used_parameters[self.parameter_name + '_to'] = value
288
289     def has_output(self):
290         return True
291
292     def queryset(self, request, queryset):
293         filters = {}
294
295         value_from = self.used_parameters.get(self.parameter_name + '_from', None)
296         if value_from is not None and value_from != '':
297             filters.update({
298                 self.parameter_name + '__gte': self.used_parameters.get(self.parameter_name + '_from', None),
299             })
300
301         value_to = self.used_parameters.get(self.parameter_name + '_to', None)
302         if value_to is not None and value_to != '':
303             filters.update({
304                 self.parameter_name + '__lte': self.used_parameters.get(self.parameter_name + '_to', None),
305             })
306
307         return queryset.filter(**filters)
308
309     def choices(self, changelist):
310         return ({
311             'request': self.request,
312             'parameter_name': self.parameter_name,
313             'form': RangeNumericForm(name=self.parameter_name, data={
314                 self.parameter_name + '_from': self.used_parameters.get(self.parameter_name + '_from', None),
315                 self.parameter_name + '_to': self.used_parameters.get(self.parameter_name + '_to', None),
316             }),
317         }, )
318
319     def expected_parameters(self):
320         return [
321             '{}_from'.format(self.parameter_name),
322             '{}_to'.format(self.parameter_name),
323         ]
324
325
326 class SourcesInline(admin.TabularInline):
327     model = sources.models.BookSource
328     extra = 1
329
330
331 class EditorNoteInline(admin.TabularInline):
332     model = models.EditorNote
333     extra = 1
334
335
336 class BookAdmin(WikidataAdminMixin, NumericFilterModelAdmin, VersionAdmin):
337     inlines = [EditorNoteInline, SourcesInline]
338     list_display = [
339         "smart_title",
340         "authors_str",
341         "translators_str",
342         "language",
343         "pd_year",
344         "priority",
345         "wikidata_link",
346     ]
347     search_fields = [
348         "title", "wikidata",
349         "authors__first_name", "authors__last_name",
350         "translators__first_name", "translators__last_name",
351         "scans_source", "text_source", "notes", "estimate_source",
352     ]
353     autocomplete_fields = ["parent", "authors", "translators", "based_on", "epochs", "genres", "kinds"]
354     filter_horizontal = ['collections']
355     prepopulated_fields = {"slug": ("title",)}
356     list_filter = [
357         ChildrenFilter,
358         "language",
359         "based_on__language",
360         ("pd_year", RangeNumericFilter),
361         "collections",
362         "collections__category",
363         ("authors__collections", add_title(admin.RelatedFieldListFilter, ' autora')),
364         ("authors__collections__category", add_title(admin.RelatedFieldListFilter, ' autora')),
365         ("translators__collections", add_title(admin.RelatedFieldListFilter, ' tłumacza')), 
366         ("translators__collections__category", add_title(admin.RelatedFieldListFilter, ' tłumacza')),
367         "epochs", "kinds", "genres",
368         "priority",
369         "authors__gender", "authors__nationality",
370         "translators__gender", "translators__nationality",
371
372         ("authors__place_of_birth", add_title(admin.RelatedFieldListFilter, ' autora')),
373         ("authors__place_of_death", add_title(admin.RelatedFieldListFilter, ' autora')),
374         ("translators__place_of_birth", add_title(admin.RelatedFieldListFilter, ' tłumacza')),
375         ("translators__place_of_death", add_title(admin.RelatedFieldListFilter, ' tłumacza')),
376
377         "document_book__chunk__stage",
378
379         LicenseFilter,
380         CoverLicenseFilter,
381         'free_license',
382         'polona_missing',
383
384         FirstPublicationYearFilter,
385     ]
386     list_per_page = 1000000
387
388     readonly_fields = [
389         "wikidata_link",
390         "estimated_costs",
391         "documents_book_link",
392         "scans_source_link",
393         "monthly_views_page",
394         "monthly_views_reader",
395     ]
396     actions = [export_as_csv_action(
397         fields=[
398             "id",
399             "wikidata",
400             "slug",
401             "title",
402             "authors_first_names",
403             "authors_last_names",
404             "translators_first_names",
405             "translators_last_names",
406             "language",
407             "based_on",
408             "scans_source",
409             "text_source",
410             "notes",
411             "priority",
412             "pd_year",
413             "gazeta_link",
414             "estimated_chars",
415             "estimated_verses",
416             "estimate_source",
417
418             "document_book__project",
419             "audience",
420             "first_publication_year",
421
422             "monthly_views_page",
423             "monthly_views_reader",
424
425             # content stats
426             "chars",
427             "chars_with_fn",
428             "words",
429             "words_with_fn",
430             "verses",
431             "chars_out_verse",
432             "verses_with_fn",
433             "chars_out_verse_with_fn",
434         ]
435     )]
436     fieldsets = [
437         (None, {"fields": [("wikidata", "wikidata_link")]}),
438         (
439             _("Identification"),
440             {
441                 "fields": [
442                     "title",
443                     ("parent", "parent_number"),
444                     ("slug", 'documents_book_link'),
445                     "authors",
446                     "translators",
447                     "language",
448                     "based_on",
449                     "original_year",
450                     "pd_year",
451                     "plwiki",
452                 ]
453             },
454         ),
455         (
456             _("Features"),
457             {
458                 "fields": [
459                     "epochs",
460                     "genres",
461                     "kinds",
462                 ]
463             },
464         ),
465         (
466             _("Plan"),
467             {
468                 "fields": [
469                     ("free_license", "polona_missing"),
470                     ("scans_source", "scans_source_link"),
471                     "text_source",
472                     "priority",
473                     "collections",
474                     "notes",
475                     ("estimated_chars", "estimated_verses", "estimate_source"),
476                     "estimated_costs",
477                     ("monthly_views_page", "monthly_views_reader"),
478                 ]
479             },
480         ),
481     ]
482
483     def get_queryset(self, request):
484         qs = super().get_queryset(request)
485         if request.resolver_match.view_name.endswith("changelist"):
486             qs = qs.prefetch_related("authors", "translators")
487             qs = qs.annotate(first_publication_year=Min('document_book__publish_log__timestamp__year'))
488         return qs
489
490     def estimated_costs(self, obj):
491         return "\n".join(
492             "{}: {} zł".format(
493                 work_type.name,
494                 cost or '—'
495             )
496             for work_type, cost in obj.get_estimated_costs().items()
497         )
498
499     def smart_title(self, obj):
500         if obj.title:
501             return obj.title
502         if obj.notes:
503             n = obj.notes
504             if len(n) > 100:
505                 n = n[:100] + '…'
506             return mark_safe(
507                 '<em><small>' + escape(n) + '</small></em>'
508             )
509         return '---'
510     smart_title.short_description = _('Title')
511     smart_title.admin_order_field = 'title'
512
513     def documents_book_link(self, obj):
514         for book in obj.document_books.all():
515             return mark_safe('<a style="position: absolute" href="{}"><img height="100" width="70" src="/cover/preview/{}/?height=100&width=70"></a>'.format(book.get_absolute_url(), book.slug))
516     documents_book_link.short_description = _('Book')
517
518     def scans_source_link(self, obj):
519         if obj.scans_source:
520             return format_html(
521                 '<a href="{url}" target="_blank">{url}</a>',
522                 url=obj.scans_source,
523             )
524         else:
525             return ""
526     scans_source_link.short_description = _('scans source')
527
528
529 admin.site.register(models.Book, BookAdmin)
530
531
532 admin.site.register(models.CollectionCategory, VersionAdmin)
533
534
535 class AuthorInline(admin.TabularInline):
536     model = models.Author.collections.through
537     autocomplete_fields = ["author"]
538
539
540 class BookInline(admin.TabularInline):
541     model = models.Book.collections.through
542     autocomplete_fields = ["book"]
543
544
545 class CollectionAdmin(VersionAdmin):
546     list_display = ["name"]
547     autocomplete_fields = []
548     prepopulated_fields = {"slug": ("name",)}
549     search_fields = ["name"]
550     fields = ['name', 'slug', 'category', 'description', 'notes', 'estimated_costs']
551     readonly_fields = ['estimated_costs']
552     inlines = [AuthorInline, BookInline]
553
554     def estimated_costs(self, obj):
555         return "\n".join(
556             "{}: {} zł".format(
557                 work_type.name,
558                 cost or '—'
559             )
560             for work_type, cost in obj.get_estimated_costs().items()
561         )
562
563
564 admin.site.register(models.Collection, CollectionAdmin)
565
566
567
568 class CategoryAdmin(VersionAdmin):
569     search_fields = ["name"]
570
571     def has_description(self, obj):
572         return bool(obj.description)
573     has_description.boolean = True
574     has_description.short_description = 'opis'
575
576
577 @admin.register(models.Epoch)
578 class EpochAdmin(CategoryAdmin):
579     list_display = [
580         'name',
581         'adjective_feminine_singular',
582         'adjective_nonmasculine_plural',
583         'has_description',
584     ]
585
586
587 @admin.register(models.Genre)
588 class GenreAdmin(CategoryAdmin):
589     list_display = [
590         'name',
591         'plural',
592         'is_epoch_specific',
593         'has_description',
594         'thema',
595     ]
596     fields = [
597         'wikidata',
598         'name',
599         'plural',
600         'slug',
601         'is_epoch_specific',
602         'thema',
603         'description',
604     ]
605
606
607 @admin.register(models.Kind)
608 class KindAdmin(CategoryAdmin):
609     list_display = [
610         'name',
611         'collective_noun',
612         'has_description',
613     ]
614
615
616
617 class WorkRateInline(admin.TabularInline):
618     model = models.WorkRate
619     autocomplete_fields = ['kinds', 'genres', 'epochs', 'collections']
620
621
622 class WorkTypeAdmin(VersionAdmin):
623     inlines = [WorkRateInline]
624
625 admin.site.register(models.WorkType, WorkTypeAdmin)
626
627
628
629 @admin.register(models.Place)
630 class PlaceAdmin(WikidataAdminMixin, TabbedTranslationAdmin, VersionAdmin):
631     search_fields = ['name']
632
633
634 @admin.register(models.Thema)
635 class ThemaAdmin(VersionAdmin):
636     list_display = ['code', 'name', 'usable', 'hidden', 'woblink_category']
637     list_filter = ['usable', 'usable_as_main', 'hidden']
638     search_fields = ['code', 'name', 'description', 'public_description']
639     prepopulated_fields = {"slug": ["name"]}
640
641
642
643 class WoblinkSeriesWidget(WoblinkCatalogueWidget):
644     category = 'series'
645
646 class AudienceForm(forms.ModelForm):
647     class Meta:
648         model = models.Audience
649         fields = '__all__'
650         widgets = {
651             'woblink': WoblinkSeriesWidget,
652         }
653
654 @admin.register(models.Audience)
655 class AudienceAdmin(VersionAdmin):
656     form = AudienceForm
657     list_display = ['code', 'name', 'thema', 'woblink']
658     search_fields = ['code', 'name', 'description', 'thema', 'woblink']
659     prepopulated_fields = {"slug": ["name"]}
660     fields = ['code', 'name', 'slug', 'description', 'thema', ('woblink', 'woblink_id')]
661     readonly_fields = ['woblink_id']
662
663     def woblink_id(self, obj):
664         return obj.woblink or ''