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