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