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