mark books final by form
[redakcja.git] / apps / catalogue / forms.py
1 # -*- coding: utf-8 -*-
2 #
3 # This file is part of FNP-Redakcja, licensed under GNU Affero GPLv3 or later.
4 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
5 #
6 from catalogue.models import User
7 from django.db.models import Count
8 from django import forms
9 from django.utils.translation import ugettext_lazy as _
10
11 from catalogue.constants import MASTERS
12 from catalogue.models import Book, Chunk, Image
13
14 class DocumentCreateForm(forms.ModelForm):
15     """
16         Form used for creating new documents.
17     """
18     file = forms.FileField(required=False)
19     text = forms.CharField(required=False, widget=forms.Textarea)
20
21     class Meta:
22         model = Book
23         exclude = ['parent', 'parent_number', 'project']
24
25     def __init__(self, *args, **kwargs):
26         super(DocumentCreateForm, self).__init__(*args, **kwargs)
27         self.fields['slug'].widget.attrs={'class': 'autoslug'}
28         self.fields['gallery'].widget.attrs={'class': 'autoslug'}
29         self.fields['title'].widget.attrs={'class': 'autoslug-source'}
30
31     def clean(self):
32         super(DocumentCreateForm, self).clean()
33         file = self.cleaned_data['file']
34
35         if file is not None:
36             try:
37                 self.cleaned_data['text'] = file.read().decode('utf-8')
38             except UnicodeDecodeError:
39                 raise forms.ValidationError(_("Text file must be UTF-8 encoded."))
40
41         if not self.cleaned_data["text"]:
42             self._errors["file"] = self.error_class([_("You must either enter text or upload a file")])
43
44         return self.cleaned_data
45
46
47 class DocumentsUploadForm(forms.Form):
48     """
49         Form used for uploading new documents.
50     """
51     file = forms.FileField(required=True, label=_('ZIP file'))
52     dirs = forms.BooleanField(label=_('Directories are documents in chunks'),
53             widget = forms.CheckboxInput(attrs={'disabled':'disabled'}))
54
55     def clean(self):
56         file = self.cleaned_data['file']
57
58         import zipfile
59         try:
60             z = self.cleaned_data['zip'] = zipfile.ZipFile(file)
61         except zipfile.BadZipfile:
62             raise forms.ValidationError("Should be a ZIP file.")
63         if z.testzip():
64             raise forms.ValidationError("ZIP file corrupt.")
65
66         return self.cleaned_data
67
68
69 class ChunkForm(forms.ModelForm):
70     """
71         Form used for editing a chunk.
72     """
73     user = forms.ModelChoiceField(queryset=
74         User.objects.annotate(count=Count('chunk')).
75         order_by('last_name', 'first_name'), required=False,
76         label=_('Assigned to')) 
77
78     class Meta:
79         model = Chunk
80         fields = ['title', 'slug', 'gallery_start', 'user', 'stage']
81         exclude = ['number']
82
83     def __init__(self, *args, **kwargs):
84         super(ChunkForm, self).__init__(*args, **kwargs)
85         self.fields['gallery_start'].widget.attrs={'class': 'number-input'}
86         self.fields['slug'].widget.attrs={'class': 'autoslug'}
87         self.fields['title'].widget.attrs={'class': 'autoslug-source'}
88
89     def clean_slug(self):
90         slug = self.cleaned_data['slug']
91         try:
92             chunk = Chunk.objects.get(book=self.instance.book, slug=slug)
93         except Chunk.DoesNotExist:
94             return slug
95         if chunk == self.instance:
96             return slug
97         raise forms.ValidationError(_('Chunk with this slug already exists'))
98
99
100 class ChunkAddForm(ChunkForm):
101     """
102         Form used for adding a chunk to a document.
103     """
104
105     def clean_slug(self):
106         slug = self.cleaned_data['slug']
107         try:
108             user = Chunk.objects.get(book=self.instance.book, slug=slug)
109         except Chunk.DoesNotExist:
110             return slug
111         raise forms.ValidationError(_('Chunk with this slug already exists'))
112
113
114 class BookAppendForm(forms.Form):
115     """
116         Form for appending a book to another book.
117         It means moving all chunks from book A to book B and deleting A.
118     """
119     append_to = forms.ModelChoiceField(queryset=Book.objects.all(),
120             label=_("Append to"))
121
122     def __init__(self, book, *args, **kwargs):
123         ret =  super(BookAppendForm, self).__init__(*args, **kwargs)
124         self.fields['append_to'].queryset = Book.objects.exclude(pk=book.pk)
125         return ret
126
127
128 class BookForm(forms.ModelForm):
129     """Form used for editing a Book."""
130
131     class Meta:
132         model = Book
133         exclude = ['project']
134
135     def __init__(self, *args, **kwargs):
136         ret = super(BookForm, self).__init__(*args, **kwargs)
137         self.fields['slug'].widget.attrs.update({"class": "autoslug"})
138         self.fields['title'].widget.attrs.update({"class": "autoslug-source"})
139         return ret
140
141     def save(self, **kwargs):
142         orig_instance = Book.objects.get(pk=self.instance.pk)
143         old_gallery = orig_instance.gallery
144         new_gallery = self.cleaned_data['gallery']
145         if new_gallery != old_gallery:
146             import shutil
147             import os.path
148             from django.conf import settings
149             shutil.move(orig_instance.gallery_path(),
150                         os.path.join(settings.MEDIA_ROOT, settings.IMAGE_DIR, new_gallery))
151         super(BookForm, self).save(**kwargs)
152
153
154 class ReadonlyBookForm(BookForm):
155     """Form used for not editing a Book."""
156
157     def __init__(self, *args, **kwargs):
158         ret = super(ReadonlyBookForm, self).__init__(*args, **kwargs)
159         for field in self.fields.values():
160             field.widget.attrs.update({"disabled": "disabled"})
161         return ret
162
163
164 class ChooseMasterForm(forms.Form):
165     """
166         Form used for fixing the chunks in a book.
167     """
168
169     master = forms.ChoiceField(choices=((m, m) for m in MASTERS))
170
171
172 class ImageForm(forms.ModelForm):
173     """Form used for editing an Image."""
174     user = forms.ModelChoiceField(queryset=
175         User.objects.annotate(count=Count('chunk')).
176         order_by('-count', 'last_name', 'first_name'), required=False,
177         label=_('Assigned to')) 
178
179     class Meta:
180         model = Image
181         fields = ['title', 'slug', 'user', 'stage']
182
183     def __init__(self, *args, **kwargs):
184         super(ImageForm, self).__init__(*args, **kwargs)
185         self.fields['slug'].widget.attrs={'class': 'autoslug'}
186         self.fields['title'].widget.attrs={'class': 'autoslug-source'}
187
188
189 class ReadonlyImageForm(ImageForm):
190     """Form used for not editing an Image."""
191
192     def __init__(self, *args, **kwargs):
193         super(ReadonlyImageForm, self).__init__(*args, **kwargs)
194         for field in self.fields.values():
195             field.widget.attrs.update({"disabled": "disabled"})
196
197
198 class MarkFinalForm(forms.Form):
199     username = forms.CharField(initial='lipszyc')
200     comment = forms.CharField(initial=u'Ostateczna akceptacja merytoryczna przez kierownika literackiego.')
201     books = forms.CharField(widget=forms.Textarea, help_text=u'linki do książek w redakcji, po jednym na wiersz')
202
203     def clean_books(self):
204         books_value = self.cleaned_data['books']
205         slugs = [line.split('/')[-2] for line in books_value.split('\n') if line.strip()]
206         books = Book.objects.filter(slug__in=slugs)
207         if len(books) != len(slugs):
208             raise forms.ValidationError(
209                 'Incorrect slug(s): %s' % ' '.join(slug for slug in slugs if not Book.objects.filter(slug=slug)))
210         return books
211
212     def clean_username(self):
213         username = self.cleaned_data['username']
214         if not User.objects.filter(username=username):
215             raise forms.ValidationError('Invalid username')
216         return username
217
218     def save(self):
219         for book in self.cleaned_data['books']:
220             for chunk in book.chunk_set.all():
221                 src = chunk.head.materialize()
222                 chunk.commit(
223                     text=src,
224                     author=User.objects.get(username=self.cleaned_data['username']),
225                     description=self.cleaned_data['comment'],
226                     tags=[Chunk.tag_model.objects.get(slug='editor-proofreading')],
227                     publishable=True
228                 )