af77e26f3e469d75d382aaf32685450b43d49b5c
[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 from django.contrib import admin
5 from django.utils.html import escape, format_html
6 from django.utils.safestring import mark_safe
7 from django.utils.translation import gettext_lazy as _
8 from admin_numeric_filter.admin import RangeNumericFilter, NumericFilterModelAdmin
9 from admin_ordering.admin import OrderableAdmin
10 from fnpdjango.actions import export_as_csv_action
11 from modeltranslation.admin import TabbedTranslationAdmin
12 from . import models
13 import documents.models
14 from .wikidata import WikidataAdminMixin
15
16
17 class NotableBookInline(OrderableAdmin, admin.TabularInline):
18     model = models.NotableBook
19     autocomplete_fields = ['book']
20     ordering_field_hide_input = True
21
22
23 class AuthorAdmin(WikidataAdminMixin, TabbedTranslationAdmin):
24     list_display = [
25         "first_name",
26         "last_name",
27         "status",
28         "year_of_death",
29         "gender",
30         "nationality",
31         "priority",
32         "wikidata_link",
33         "slug",
34     ]
35     list_display_links = [
36         "first_name", "last_name"
37     ]
38     list_filter = [
39         ("year_of_death", RangeNumericFilter),
40         "priority",
41         "collections",
42         "status",
43         "gender",
44         "nationality",
45         ("genitive", admin.EmptyFieldListFilter)
46     ]
47     list_per_page = 10000000
48     search_fields = ["first_name", "last_name", "wikidata"]
49     readonly_fields = ["wikidata_link", "description_preview"]
50
51     fieldsets = [
52         (None, {"fields": [("wikidata", "wikidata_link")]}),
53         (
54             _("Identification"),
55             {
56                 "fields": [
57                     ("first_name", "last_name"),
58                     "slug",
59                     "genitive",
60                     "gender",
61                     "nationality",
62                     ("date_of_birth", "year_of_birth", "year_of_birth_inexact", "year_of_birth_range", "place_of_birth"),
63                     ("date_of_death", "year_of_death", "year_of_death_inexact", "year_of_death_range", "place_of_death"),
64                     ("description", "description_preview"),
65                     "status",
66                     "collections",
67                     "priority",
68                     
69                     "notes",
70                     "gazeta_link",
71                     "culturepl_link",
72                     "plwiki",
73                     "photo", "photo_source", "photo_attribution",
74                 ]
75             },
76         ),
77     ]
78     
79     prepopulated_fields = {"slug": ("first_name", "last_name")}
80     autocomplete_fields = ["collections", "place_of_birth", "place_of_death"]
81     inlines = [
82         NotableBookInline,
83     ]
84
85     def description_preview(self, obj):
86         return obj.generate_description()
87
88
89 admin.site.register(models.Author, AuthorAdmin)
90
91
92 class LicenseFilter(admin.SimpleListFilter):
93     title = 'Licencja'
94     parameter_name = 'book_license'
95     license_url_field = 'document_book__dc__license'
96     license_name_field = 'document_book__dc__license_description'
97
98     def lookups(self, requesrt, model_admin):
99         return [
100             ('cc', 'CC'),
101             ('fal', 'FAL'),
102             ('pd', 'domena publiczna'),
103         ]
104
105     def queryset(self, request, queryset):
106         v = self.value()
107         if v == 'cc': 
108             return queryset.filter(**{
109                 self.license_url_field + '__icontains': 'creativecommons.org'
110             })
111         elif v == 'fal':
112             return queryset.filter(**{
113                 self.license_url_field + '__icontains': 'artlibre.org'
114             })
115         elif v == 'pd':
116             return queryset.filter(**{
117                 self.license_name_field + '__icontains': 'domena publiczna'
118             })
119         else:
120             return queryset
121
122
123 class CoverLicenseFilter(LicenseFilter):
124     title = 'Licencja okładki'
125     parameter_name = 'cover_license'
126     license_url_field = 'document_book__dc_cover_image__license_url'
127     license_name_field = 'document_book__dc_cover_image__license_name'
128
129
130 def add_title(base_class, suffix):
131     class TitledCategoryFilter(base_class):
132         def __init__(self, *args, **kwargs):
133             super().__init__(*args, **kwargs)
134             self.title += suffix
135     return TitledCategoryFilter
136
137
138
139 class BookAdmin(WikidataAdminMixin, NumericFilterModelAdmin):
140     list_display = [
141         "smart_title",
142         "authors_str",
143         "translators_str",
144         "language",
145         "pd_year",
146         "priority",
147         "wikidata_link",
148     ]
149     search_fields = [
150         "title", "wikidata",
151         "authors__first_name", "authors__last_name",
152         "translators__first_name", "translators__last_name",
153         "scans_source", "text_source", "notes", "estimate_source",
154     ]
155     autocomplete_fields = ["authors", "translators", "based_on", "collections", "epochs", "genres", "kinds"]
156     prepopulated_fields = {"slug": ("title",)}
157     list_filter = [
158         "language",
159         "based_on__language",
160         ("pd_year", RangeNumericFilter),
161         "collections",
162         "collections__category",
163         ("authors__collections", add_title(admin.RelatedFieldListFilter, ' autora')),
164         ("authors__collections__category", add_title(admin.RelatedFieldListFilter, ' autora')),
165         ("translators__collections", add_title(admin.RelatedFieldListFilter, ' tłumacza')), 
166         ("translators__collections__category", add_title(admin.RelatedFieldListFilter, ' tłumacza')),
167         "epochs", "kinds", "genres",
168         "priority",
169         "authors__gender", "authors__nationality",
170         "translators__gender", "translators__nationality",
171         "document_book__chunk__stage",
172
173         LicenseFilter,
174         CoverLicenseFilter,
175         'free_license',
176         'polona_missing',
177     ]
178     list_per_page = 1000000
179
180     readonly_fields = [
181         "wikidata_link",
182         "estimated_costs",
183         "documents_book_link",
184         "scans_source_link",
185     ]
186     actions = [export_as_csv_action(
187         fields=[
188             "id",
189             "wikidata",
190             "slug",
191             "title",
192             "authors_first_names",
193             "authors_last_names",
194             "translators_first_names",
195             "translators_last_names",
196             "language",
197             "based_on",
198             "scans_source",
199             "text_source",
200             "notes",
201             "priority",
202             "pd_year",
203             "gazeta_link",
204             "estimated_chars",
205             "estimated_verses",
206             "estimate_source"
207         ]
208     )]
209     fieldsets = [
210         (None, {"fields": [("wikidata", "wikidata_link")]}),
211         (
212             _("Identification"),
213             {
214                 "fields": [
215                     "title",
216                     ("slug", 'documents_book_link'),
217                     "authors",
218                     "translators",
219                     "language",
220                     "based_on",
221                     "original_year",
222                     "pd_year",
223                 ]
224             },
225         ),
226         (
227             _("Features"),
228             {
229                 "fields": [
230                     "epochs",
231                     "genres",
232                     "kinds",
233                 ]
234             },
235         ),
236         (
237             _("Plan"),
238             {
239                 "fields": [
240                     ("free_license", "polona_missing"),
241                     ("scans_source", "scans_source_link"),
242                     "text_source",
243                     "priority",
244                     "collections",
245                     "notes",
246                     ("estimated_chars", "estimated_verses", "estimate_source"),
247                     "estimated_costs",
248                 ]
249             },
250         ),
251     ]
252
253     def get_queryset(self, request):
254         qs = super().get_queryset(request)
255         if request.resolver_match.view_name.endswith("changelist"):
256             qs = qs.prefetch_related("authors", "translators")
257         return qs
258
259     def estimated_costs(self, obj):
260         return "\n".join(
261             "{}: {} zł".format(
262                 work_type.name,
263                 cost or '—'
264             )
265             for work_type, cost in obj.get_estimated_costs().items()
266         )
267
268     def smart_title(self, obj):
269         if obj.title:
270             return obj.title
271         if obj.notes:
272             n = obj.notes
273             if len(n) > 100:
274                 n = n[:100] + '…'
275             return mark_safe(
276                 '<em><small>' + escape(n) + '</small></em>'
277             )
278         return '---'
279     smart_title.short_description = _('Title')
280     smart_title.admin_order_field = 'title'
281
282     def documents_book_link(self, obj):
283         for book in obj.document_books.all():
284             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))
285     documents_book_link.short_description = _('Book')
286
287     def scans_source_link(self, obj):
288         if obj.scans_source:
289             return format_html(
290                 '<a href="{url}" target="_blank">{url}</a>',
291                 url=obj.scans_source,
292             )
293         else:
294             return ""
295     scans_source_link.short_description = _('scans source')
296
297
298 admin.site.register(models.Book, BookAdmin)
299
300
301 admin.site.register(models.CollectionCategory)
302
303
304 class AuthorInline(admin.TabularInline):
305     model = models.Author.collections.through
306     autocomplete_fields = ["author"]
307
308
309 class BookInline(admin.TabularInline):
310     model = models.Book.collections.through
311     autocomplete_fields = ["book"]
312
313
314 class CollectionAdmin(admin.ModelAdmin):
315     list_display = ["name"]
316     autocomplete_fields = []
317     prepopulated_fields = {"slug": ("name",)}
318     search_fields = ["name"]
319     fields = ['name', 'slug', 'category', 'description', 'notes', 'estimated_costs']
320     readonly_fields = ['estimated_costs']
321     inlines = [AuthorInline, BookInline]
322
323     def estimated_costs(self, obj):
324         return "\n".join(
325             "{}: {} zł".format(
326                 work_type.name,
327                 cost or '—'
328             )
329             for work_type, cost in obj.get_estimated_costs().items()
330         )
331
332
333 admin.site.register(models.Collection, CollectionAdmin)
334
335
336
337 class CategoryAdmin(admin.ModelAdmin):
338     search_fields = ["name"]
339
340
341 @admin.register(models.Epoch)
342 class EpochAdmin(CategoryAdmin):
343     list_display = ['name', 'adjective_feminine_singular', 'adjective_nonmasculine_plural']
344
345
346 @admin.register(models.Genre)
347 class GenreAdmin(CategoryAdmin):
348     list_display = ['name', 'plural', 'is_epoch_specific']
349
350
351 @admin.register(models.Kind)
352 class KindAdmin(CategoryAdmin):
353     list_display = ['name', 'collective_noun']
354
355
356
357 class WorkRateInline(admin.TabularInline):
358     model = models.WorkRate
359     autocomplete_fields = ['kinds', 'genres', 'epochs', 'collections']
360
361
362 class WorkTypeAdmin(admin.ModelAdmin):
363     inlines = [WorkRateInline]
364
365 admin.site.register(models.WorkType, WorkTypeAdmin)
366
367
368
369 @admin.register(models.Place)
370 class PlaceAdmin(WikidataAdminMixin, TabbedTranslationAdmin):
371     search_fields = ['name']