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