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