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