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