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