genre-thema mapping
[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 def add_title(base_class, suffix):
244     class TitledCategoryFilter(base_class):
245         def __init__(self, *args, **kwargs):
246             super().__init__(*args, **kwargs)
247             self.title += suffix
248     return TitledCategoryFilter
249
250
251 class FirstPublicationYearFilter(admin.ListFilter):
252     title = 'Rok pierwszej publikacji'
253     parameter_name = 'first_publication_year'
254     template = 'admin/filter_numeric_range.html'
255
256     def __init__(self, request, params, *args, **kwargs):
257         super().__init__(request, params, *args, **kwargs)
258
259         self.request = request
260
261         if self.parameter_name + '_from' in params:
262             value = params.pop(self.parameter_name + '_from')
263             self.used_parameters[self.parameter_name + '_from'] = value
264
265         if self.parameter_name + '_to' in params:
266             value = params.pop(self.parameter_name + '_to')
267             self.used_parameters[self.parameter_name + '_to'] = value
268
269     def has_output(self):
270         return True
271
272     def queryset(self, request, queryset):
273         filters = {}
274
275         value_from = self.used_parameters.get(self.parameter_name + '_from', None)
276         if value_from is not None and value_from != '':
277             filters.update({
278                 self.parameter_name + '__gte': self.used_parameters.get(self.parameter_name + '_from', None),
279             })
280
281         value_to = self.used_parameters.get(self.parameter_name + '_to', None)
282         if value_to is not None and value_to != '':
283             filters.update({
284                 self.parameter_name + '__lte': self.used_parameters.get(self.parameter_name + '_to', None),
285             })
286
287         return queryset.filter(**filters)
288
289     def choices(self, changelist):
290         return ({
291             'request': self.request,
292             'parameter_name': self.parameter_name,
293             'form': RangeNumericForm(name=self.parameter_name, data={
294                 self.parameter_name + '_from': self.used_parameters.get(self.parameter_name + '_from', None),
295                 self.parameter_name + '_to': self.used_parameters.get(self.parameter_name + '_to', None),
296             }),
297         }, )
298
299     def expected_parameters(self):
300         return [
301             '{}_from'.format(self.parameter_name),
302             '{}_to'.format(self.parameter_name),
303         ]
304
305
306 class SourcesInline(admin.TabularInline):
307     model = sources.models.BookSource
308     extra = 1
309
310
311 class BookAdmin(WikidataAdminMixin, NumericFilterModelAdmin, VersionAdmin):
312     inlines = [SourcesInline]
313     list_display = [
314         "smart_title",
315         "authors_str",
316         "translators_str",
317         "language",
318         "pd_year",
319         "priority",
320         "wikidata_link",
321     ]
322     search_fields = [
323         "title", "wikidata",
324         "authors__first_name", "authors__last_name",
325         "translators__first_name", "translators__last_name",
326         "scans_source", "text_source", "notes", "estimate_source",
327     ]
328     autocomplete_fields = ["authors", "translators", "based_on", "epochs", "genres", "kinds"]
329     filter_horizontal = ['collections']
330     prepopulated_fields = {"slug": ("title",)}
331     list_filter = [
332         "language",
333         "based_on__language",
334         ("pd_year", RangeNumericFilter),
335         "collections",
336         "collections__category",
337         ("authors__collections", add_title(admin.RelatedFieldListFilter, ' autora')),
338         ("authors__collections__category", add_title(admin.RelatedFieldListFilter, ' autora')),
339         ("translators__collections", add_title(admin.RelatedFieldListFilter, ' tłumacza')), 
340         ("translators__collections__category", add_title(admin.RelatedFieldListFilter, ' tłumacza')),
341         "epochs", "kinds", "genres",
342         "priority",
343         "authors__gender", "authors__nationality",
344         "translators__gender", "translators__nationality",
345
346         ("authors__place_of_birth", add_title(admin.RelatedFieldListFilter, ' autora')),
347         ("authors__place_of_death", add_title(admin.RelatedFieldListFilter, ' autora')),
348         ("translators__place_of_birth", add_title(admin.RelatedFieldListFilter, ' tłumacza')),
349         ("translators__place_of_death", add_title(admin.RelatedFieldListFilter, ' tłumacza')),
350
351         "document_book__chunk__stage",
352
353         LicenseFilter,
354         CoverLicenseFilter,
355         'free_license',
356         'polona_missing',
357
358         FirstPublicationYearFilter,
359     ]
360     list_per_page = 1000000
361
362     readonly_fields = [
363         "wikidata_link",
364         "estimated_costs",
365         "documents_book_link",
366         "scans_source_link",
367         "monthly_views_page",
368         "monthly_views_reader",
369     ]
370     actions = [export_as_csv_action(
371         fields=[
372             "id",
373             "wikidata",
374             "slug",
375             "title",
376             "authors_first_names",
377             "authors_last_names",
378             "translators_first_names",
379             "translators_last_names",
380             "language",
381             "based_on",
382             "scans_source",
383             "text_source",
384             "notes",
385             "priority",
386             "pd_year",
387             "gazeta_link",
388             "estimated_chars",
389             "estimated_verses",
390             "estimate_source",
391
392             "document_book__project",
393             "audience",
394             "first_publication_year",
395
396             "monthly_views_page",
397             "monthly_views_reader",
398
399             # content stats
400             "chars",
401             "chars_with_fn",
402             "words",
403             "words_with_fn",
404             "verses",
405             "chars_out_verse",
406             "verses_with_fn",
407             "chars_out_verse_with_fn",
408         ]
409     )]
410     fieldsets = [
411         (None, {"fields": [("wikidata", "wikidata_link")]}),
412         (
413             _("Identification"),
414             {
415                 "fields": [
416                     "title",
417                     ("slug", 'documents_book_link'),
418                     "authors",
419                     "translators",
420                     "language",
421                     "based_on",
422                     "original_year",
423                     "pd_year",
424                     "plwiki",
425                 ]
426             },
427         ),
428         (
429             _("Features"),
430             {
431                 "fields": [
432                     "epochs",
433                     "genres",
434                     "kinds",
435                 ]
436             },
437         ),
438         (
439             _("Plan"),
440             {
441                 "fields": [
442                     ("free_license", "polona_missing"),
443                     ("scans_source", "scans_source_link"),
444                     "text_source",
445                     "priority",
446                     "collections",
447                     "notes",
448                     ("estimated_chars", "estimated_verses", "estimate_source"),
449                     "estimated_costs",
450                     ("monthly_views_page", "monthly_views_reader"),
451                 ]
452             },
453         ),
454     ]
455
456     def get_queryset(self, request):
457         qs = super().get_queryset(request)
458         if request.resolver_match.view_name.endswith("changelist"):
459             qs = qs.prefetch_related("authors", "translators")
460             qs = qs.annotate(first_publication_year=Min('document_book__publish_log__timestamp__year'))
461         return qs
462
463     def estimated_costs(self, obj):
464         return "\n".join(
465             "{}: {} zł".format(
466                 work_type.name,
467                 cost or '—'
468             )
469             for work_type, cost in obj.get_estimated_costs().items()
470         )
471
472     def smart_title(self, obj):
473         if obj.title:
474             return obj.title
475         if obj.notes:
476             n = obj.notes
477             if len(n) > 100:
478                 n = n[:100] + '…'
479             return mark_safe(
480                 '<em><small>' + escape(n) + '</small></em>'
481             )
482         return '---'
483     smart_title.short_description = _('Title')
484     smart_title.admin_order_field = 'title'
485
486     def documents_book_link(self, obj):
487         for book in obj.document_books.all():
488             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))
489     documents_book_link.short_description = _('Book')
490
491     def scans_source_link(self, obj):
492         if obj.scans_source:
493             return format_html(
494                 '<a href="{url}" target="_blank">{url}</a>',
495                 url=obj.scans_source,
496             )
497         else:
498             return ""
499     scans_source_link.short_description = _('scans source')
500
501
502 admin.site.register(models.Book, BookAdmin)
503
504
505 admin.site.register(models.CollectionCategory, VersionAdmin)
506
507
508 class AuthorInline(admin.TabularInline):
509     model = models.Author.collections.through
510     autocomplete_fields = ["author"]
511
512
513 class BookInline(admin.TabularInline):
514     model = models.Book.collections.through
515     autocomplete_fields = ["book"]
516
517
518 class CollectionAdmin(VersionAdmin):
519     list_display = ["name"]
520     autocomplete_fields = []
521     prepopulated_fields = {"slug": ("name",)}
522     search_fields = ["name"]
523     fields = ['name', 'slug', 'category', 'description', 'notes', 'estimated_costs']
524     readonly_fields = ['estimated_costs']
525     inlines = [AuthorInline, BookInline]
526
527     def estimated_costs(self, obj):
528         return "\n".join(
529             "{}: {} zł".format(
530                 work_type.name,
531                 cost or '—'
532             )
533             for work_type, cost in obj.get_estimated_costs().items()
534         )
535
536
537 admin.site.register(models.Collection, CollectionAdmin)
538
539
540
541 class CategoryAdmin(VersionAdmin):
542     search_fields = ["name"]
543
544     def has_description(self, obj):
545         return bool(obj.description)
546     has_description.boolean = True
547     has_description.short_description = 'opis'
548
549
550 @admin.register(models.Epoch)
551 class EpochAdmin(CategoryAdmin):
552     list_display = [
553         'name',
554         'adjective_feminine_singular',
555         'adjective_nonmasculine_plural',
556         'has_description',
557     ]
558
559
560 @admin.register(models.Genre)
561 class GenreAdmin(CategoryAdmin):
562     list_display = [
563         'name',
564         'plural',
565         'is_epoch_specific',
566         'has_description',
567     ]
568
569
570 @admin.register(models.Kind)
571 class KindAdmin(CategoryAdmin):
572     list_display = [
573         'name',
574         'collective_noun',
575         'has_description',
576     ]
577
578
579
580 class WorkRateInline(admin.TabularInline):
581     model = models.WorkRate
582     autocomplete_fields = ['kinds', 'genres', 'epochs', 'collections']
583
584
585 class WorkTypeAdmin(VersionAdmin):
586     inlines = [WorkRateInline]
587
588 admin.site.register(models.WorkType, WorkTypeAdmin)
589
590
591
592 @admin.register(models.Place)
593 class PlaceAdmin(WikidataAdminMixin, TabbedTranslationAdmin, VersionAdmin):
594     search_fields = ['name']
595
596
597 @admin.register(models.Thema)
598 class ThemaAdmin(VersionAdmin):
599     list_display = ['code', 'name', 'usable', 'hidden', 'woblink_category']
600     list_filter = ['usable', 'usable_as_main', 'hidden']
601     search_fields = ['code', 'name', 'description', 'public_description']
602     prepopulated_fields = {"slug": ["name"]}
603
604
605
606 class WoblinkSeriesWidget(WoblinkCatalogueWidget):
607     category = 'series'
608
609 class AudienceForm(forms.ModelForm):
610     class Meta:
611         model = models.Audience
612         fields = '__all__'
613         widgets = {
614             'woblink': WoblinkSeriesWidget,
615         }
616
617 @admin.register(models.Audience)
618 class AudienceAdmin(VersionAdmin):
619     form = AudienceForm
620     list_display = ['code', 'name', 'thema', 'woblink']
621     search_fields = ['code', 'name', 'description', 'thema', 'woblink']
622     prepopulated_fields = {"slug": ["name"]}
623     fields = ['code', 'name', 'slug', 'description', 'thema', ('woblink', 'woblink_id')]
624     readonly_fields = ['woblink_id']
625
626     def woblink_id(self, obj):
627         return obj.woblink or ''