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