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