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