Covers from MPW, Rawpixel.
[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
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_filter = ["year_of_death", "priority", "collections", "status", "gender", "nationality"]
28     search_fields = ["first_name", "last_name", "wikidata"]
29     prepopulated_fields = {"slug": ("first_name", "last_name")}
30     autocomplete_fields = ["collections"]
31
32
33 admin.site.register(models.Author, AuthorAdmin)
34
35
36 class LicenseFilter(admin.SimpleListFilter):
37     title = 'Licencja'
38     parameter_name = 'book_license'
39     license_url_field = 'document_book__dc__license'
40     license_name_field = 'document_book__dc__license_description'
41
42     def lookups(self, requesrt, model_admin):
43         return [
44             ('cc', 'CC'),
45             ('fal', 'FAL'),
46             ('pd', 'domena publiczna'),
47         ]
48
49     def queryset(self, request, queryset):
50         v = self.value()
51         if v == 'cc': 
52             return queryset.filter(**{
53                 self.license_url_field + '__icontains': 'creativecommons.org'
54             })
55         elif v == 'fal':
56             return queryset.filter(**{
57                 self.license_url_field + '__icontains': 'artlibre.org'
58             })
59         elif v == 'pd':
60             return queryset.filter(**{
61                 self.license_name_field + '__icontains': 'domena publiczna'
62             })
63         else:
64             return queryset
65
66
67 class CoverLicenseFilter(LicenseFilter):
68     title = 'Licencja okładki'
69     parameter_name = 'cover_license'
70     license_url_field = 'document_book__dc_cover_image__license_url'
71     license_name_field = 'document_book__dc_cover_image__license_name'
72
73
74 class BookAdmin(WikidataAdminMixin, NumericFilterModelAdmin):
75     list_display = [
76         "smart_title",
77         "authors_str",
78         "translators_str",
79         "language",
80         "pd_year",
81         "priority",
82         "wikidata_link",
83     ]
84     search_fields = [
85         "title", "wikidata",
86         "authors__first_name", "authors__last_name",
87         "translators__first_name", "translators__last_name",
88         "scans_source", "text_source", "notes", "estimate_source",
89     ]
90     autocomplete_fields = ["authors", "translators", "based_on", "collections", "epochs", "genres", "kinds"]
91     prepopulated_fields = {"slug": ("title",)}
92     list_filter = [
93         "language",
94         "based_on__language",
95         ("pd_year", RangeNumericFilter),
96         "collections",
97         "collections__category",
98         "epochs", "kinds", "genres",
99         "priority",
100         "authors__gender", "authors__nationality",
101         "translators__gender", "translators__nationality",
102         "document_book__chunk__stage",
103         "document_book__chunk__user",
104
105         LicenseFilter,
106         CoverLicenseFilter,
107     ]
108     readonly_fields = ["wikidata_link", "estimated_costs", "documents_book_link"]
109     actions = [export_as_csv_action()]
110     fieldsets = [
111         (None, {"fields": [("wikidata", "wikidata_link")]}),
112         (
113             _("Identification"),
114             {
115                 "fields": [
116                     "title",
117                     ("slug", 'documents_book_link'),
118                     "authors",
119                     "translators",
120                     "language",
121                     "based_on",
122                     "pd_year",
123                 ]
124             },
125         ),
126         (
127             _("Features"),
128             {
129                 "fields": [
130                     "epochs",
131                     "genres",
132                     "kinds",
133                 ]
134             },
135         ),
136         (
137             _("Plan"),
138             {
139                 "fields": [
140                     "scans_source",
141                     "text_source",
142                     "priority",
143                     "collections",
144                     "notes",
145                     ("estimated_chars", "estimated_verses", "estimate_source"),
146                     "estimated_costs",
147                 ]
148             },
149         ),
150     ]
151
152     def get_queryset(self, request):
153         qs = super().get_queryset(request)
154         if request.resolver_match.view_name.endswith("changelist"):
155             qs = qs.prefetch_related("authors", "translators")
156         return qs
157
158     def estimated_costs(self, obj):
159         return "\n".join(
160             "{}: {} zł".format(
161                 work_type.name,
162                 cost or '—'
163             )
164             for work_type, cost in obj.get_estimated_costs().items()
165         )
166
167     def smart_title(self, obj):
168         if obj.title:
169             return obj.title
170         if obj.notes:
171             n = obj.notes
172             if len(n) > 100:
173                 n = n[:100] + '…'
174             return mark_safe(
175                 '<em><small>' + escape(n) + '</small></em>'
176             )
177         return '---'
178     smart_title.short_description = _('Title')
179     smart_title.admin_order_field = 'title'
180
181     def documents_book_link(self, obj):
182         for book in obj.document_books.all():
183             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))
184     documents_book_link.short_description = _('Book')
185
186
187 admin.site.register(models.Book, BookAdmin)
188
189
190 admin.site.register(models.CollectionCategory)
191
192
193 class AuthorInline(admin.TabularInline):
194     model = models.Author.collections.through
195     autocomplete_fields = ["author"]
196
197
198 class BookInline(admin.TabularInline):
199     model = models.Book.collections.through
200     autocomplete_fields = ["book"]
201
202
203 class CollectionAdmin(admin.ModelAdmin):
204     list_display = ["name"]
205     autocomplete_fields = []
206     prepopulated_fields = {"slug": ("name",)}
207     search_fields = ["name"]
208     fields = ['name', 'slug', 'category', 'notes', 'estimated_costs']
209     readonly_fields = ['estimated_costs']
210     inlines = [AuthorInline, BookInline]
211
212     def estimated_costs(self, obj):
213         return "\n".join(
214             "{}: {} zł".format(
215                 work_type.name,
216                 cost or '—'
217             )
218             for work_type, cost in obj.get_estimated_costs().items()
219         )
220
221
222 admin.site.register(models.Collection, CollectionAdmin)
223
224
225
226 class CategoryAdmin(admin.ModelAdmin):
227     search_fields = ["name"]
228
229 admin.site.register(models.Epoch, CategoryAdmin)
230 admin.site.register(models.Genre, CategoryAdmin)
231 admin.site.register(models.Kind, CategoryAdmin)
232
233
234
235 class WorkRateInline(admin.TabularInline):
236     model = models.WorkRate
237     autocomplete_fields = ['kinds', 'genres', 'epochs', 'collections']
238
239
240 class WorkTypeAdmin(admin.ModelAdmin):
241     inlines = [WorkRateInline]
242
243 admin.site.register(models.WorkType, WorkTypeAdmin)
244