Web   ·   Wiki   ·   Activities   ·   Blog   ·   Lists   ·   Chat   ·   Meeting   ·   Bugs   ·   Git   ·   Translate   ·   Archive   ·   People   ·   Donate
summaryrefslogtreecommitdiffstats
path: root/webapp/polls/views.py
blob: 526cabcfe437bee0be3d3b403e7e4a1658744148 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
# pylint: disable=C0111
# -*- encoding: utf-8 -*-
import os
import warnings
from importlib import import_module

from datetime import datetime

from pymongo import ASCENDING

from django.views.generic.base import TemplateView
from django.views.generic.list import ListView
from django.utils.datastructures import DotExpandedDict
from django.utils.safestring import SafeUnicode
from django.http import HttpResponse, HttpResponseRedirect, Http404
from django.core.urlresolvers import reverse
from django.views.generic.edit import FormView
from django.contrib import messages
from django.shortcuts import render_to_response
from django.conf import settings

from utils.forms import BadFormValidation
from utils.data_structure import dict_merge

from polls.models import (WIDGET_TYPES, Structure, Poll, PollResultFile)
from polls.models import is_image_file
from polls.forms import PollForm


module_path = settings.CLOCK_CLASS.split('.')[:-1]
module_path = ".".join(module_path)
module = import_module(module_path)
class_name = settings.CLOCK_CLASS.split('.')[-1:][0]
Clock = getattr(module, class_name)


__all__ = [
    'StructureFormView',
    'PollFormView',
    'PollListView',
    'UnploadPollResultFormView'
]


def clean_data(value):

    if isinstance(value, dict):
        for key_, value_ in value.iteritems():
            value[key_] = clean_data(value_)
        return value

    if isinstance(value, list):
        if len(value) == 1:
            value = clean_data(value.pop())
        else:
            value = [clean_data(value_) for value_ in value]
        return value

    if not is_image_file(value):
        value = value.strip(' ')

    if value == '':
        value = None
    if value == 'True' or value in [u'on']:
        value = True
    if value == 'False':
        value = False

    if isinstance(value, unicode):
        return SafeUnicode(value)
    else:
        return value


class PollFormView(FormView):

    template_name = "poll-form.html"
    form_class = PollForm

    def get_context_data(self, **kwargs):
        context = super(PollFormView, self).get_context_data(**kwargs)
        form = context['form']

        # If id and Wrong id or poll is not open => 404
        _id = self.kwargs.get('id', None)
        poll = Poll.get(id=_id) if _id else Poll()
        if _id and not poll:
            raise Http404()
        if poll and not poll.is_open():
            if not self.request.user.is_superuser:
                raise Http404()

        poll = Poll(data=form.data) if form.is_bound else poll
        context.update({
            "poll": poll,
            "pollsters_id": map(lambda p: str(p.id), poll.get_pollsters()),
            "STATUS_CHOICES": Poll.status_choices(),
            "POLLSTER_CHOICES": form.fields['pollsters'].choices,
        })
        return context

    def form_valid(self, form):
        try:
            poll = form.save()
        except BadFormValidation:
            msg = u'Ocurrió un error, no se guardó la encuesta.'
            messages.add_message(self.request, messages.ERROR, msg)
            return self.render_to_response(self.get_context_data(form=form))
            # TODO: Logear
        except Exception:
            pass
            # TODO: Logear
        else:
            msg = u'La encuesta: "%s" fué guardada correctamente.' % poll.name
            messages.add_message(self.request, messages.SUCCESS, msg)

            if not self.request.user.is_superuser:
                return HttpResponseRedirect(reverse('index'))

            if poll.is_open() and self.request.GET.get('continue', None):
                return HttpResponseRedirect(
                    reverse(
                        'sociologist:structure.builder',
                        kwargs={'poll_id': str(poll.id)}
                    )
                )
            else:
                return HttpResponseRedirect(
                    reverse(
                        'sociologist:poll_edit',
                        kwargs={'id': str(poll.id)}
                    )
                )

        return self.form_invalid(form)


class PollListView(ListView):

    template_name = "poll-list.html"
    context_object_name = "polls"

    def get_queryset(self, *args, **kwargs):
        user = self.request.user
        assigned_to = lambda poll: ", ".join(
            map(lambda p: p.username, poll.get_pollsters()))
        return [
            {
                'name': poll.name.capitalize(),
                'status': poll.status,
                'is_open': poll.is_open(),
                'assigned_to': assigned_to(poll) if assigned_to(poll) else "-",
                'action_result_view': {
                    'disabled': "disabled" if not poll.has_result() else "",
                    'url': reverse(
                        'sociologist:poll_result_detail',
                        kwargs={'poll_id': str(poll.id)}
                    ),
                },
                'action_edit': {
                    'disabled': "disabled" if not poll.is_open() and (
                        not poll.is_open() and not user.is_superuser) else "",
                    'url': reverse(
                        'sociologist:poll_edit', kwargs={'id': str(poll.id)}
                    ),
                },
                'action_structure_builder': {
                    'disabled': ("disabled" if
                                 poll.structure.is_read_only() else ""),
                    'url': reverse(
                        'sociologist:structure.builder',
                        kwargs={'poll_id': str(poll.id)}
                    )
                },
                'action_download': {
                    'disabled': "",
                    'url': reverse(
                        'sociologist:poll_download',
                        kwargs={'poll_id': str(poll.id)}
                    ),
                },
                'action_clone': {
                    'disabled': "",
                    'url': reverse(
                        'sociologist:poll_clone', kwargs={'id': str(poll.id)}
                    ),
                },
                'background_color': "#f2dede" if poll.is_open() else "#e8f4db"
            } for poll in Poll.all(
                sort=[('status', ASCENDING), ('name', ASCENDING)])
        ]


class StructureFormView(TemplateView):

    template_name = "poll-structure-form.html"

    def get(self, request, *args, **kwargs):
        context = self.get_context_data()
        structure = self.poll.structure

        read_only = Structure.READ_ONLY_MSG
        msg = read_only if structure.is_read_only() else ''
        messages.add_message(self.request, messages.WARNING, msg)

        context.update({'structure': structure})
        return self.render_to_response(context)

    def get_context_data(self, **kwargs):
        context = super(StructureFormView, self).get_context_data(**kwargs)

        # If id and Wrong id or poll is not open => 404
        _id = _id = self.kwargs.get('poll_id', None)
        self.poll = Poll.get(id=_id) if _id else None
        if _id and not self.poll:
            raise Http404()
        if self.poll and not self.poll.is_open():
            raise Http404()

        context.update({'WIDGET_TYPES': WIDGET_TYPES, 'poll': self.poll})
        return context

    def post(self, request, *args, **kwargs):
        context = self.get_context_data()
        data = {}

        data_post = DotExpandedDict(dict(request.POST.lists()))
        data_files = DotExpandedDict(dict(request.FILES.lists()))

        data = dict_merge(data_post, data_files)

        for key, value in data.items():
            data[key] = clean_data(value)

        _id = data.get('id', None)
        structure = Structure(
            data={"groups": data.get('groups', {}), 'id': _id},
            poll=self.poll
        )

        if structure.is_valid(new_data=data):
            try:
                structure.save_image_options(tmp=False)
                structure.save_image_fields()
                structure.save()
            except Exception:
                msg = u'Ocurrió un error, no se guardó la estructura.'
                messages.add_message(self.request, messages.ERROR, msg)

                # Rollback img options to tmp directory
                if not structure.id:
                    structure.image_rollback()
            else:
                messages.add_message(
                    self.request,
                    messages.SUCCESS,
                    u'La estructura de la encuesta "%s" fué'
                    ' guardada correctamente.' % self.poll.name
                )

                return HttpResponseRedirect(
                    reverse(
                        'sociologist:structure.builder',
                        kwargs={"poll_id": str(self.poll.id)}
                    )
                )
        else:
            structure.save_image_options(tmp=True)
            structure.save_image_fields()
            context.update({'errors': structure.errors})
            messages.add_message(
                self.request,
                messages.ERROR,
                u'Hubo errores de validación, '
                'para guardar asegurese de corregirlos.'
            )

        context.update({'structure': structure})
        return self.render_to_response(context)


def download_poll(request, poll_id=None):

    # Wrong id => 404
    _id = poll_id
    poll = Poll.get(id=_id)
    if not _id or not poll:
        raise Http404()

    if request.user.is_pollster:
        # In here, somebody is downloading a poll, but is not a pollster.
        if poll and poll.is_open():
            raise Http404()

    file_name = datetime.now().strftime("%d_%m_%Y_%H_%M_%S")

    poll_template = None
    pollster = getattr(request.user, "pollster", None)
    with warnings.catch_warnings(record=True) as w:
        poll_template = poll.get_template(pollster=pollster)

        if len(w) == 1:
            # In here, A logged user that is pollster is trying download
            # a poll that is not assigned to him.
            pass

    if poll_template:
        # Download json file
        response = HttpResponse(
            poll_template, content_type='application/json')
        response['Content-Disposition'] = (
            'attachment; filename=%s.json' % file_name)
        return response
    else:
        msg = "No se pudo descargar la encuesta."
        messages.add_message(request, messages.ERROR, msg)
        return HttpResponseRedirect(request.meta['HTTP_REFERER'])


def opt_thumb(request, poll_id, img_name):

    tmp_path = settings.IMAGE_OPTIONS_ROOT + '/%s/tmp/%s' % (
        poll_id, img_name)
    path = settings.IMAGE_OPTIONS_ROOT + '/%s/%s' % (
        poll_id, img_name)

    src = ''

    if os.path.exists(tmp_path):
        src = tmp_path
        media_url = settings.IMAGE_OPTIONS_MEDIA_URL + '/%s/tmp/%s' % (
            poll_id, img_name)
    elif os.path.exists(path):
        src = path
        media_url = settings.IMAGE_OPTIONS_MEDIA_URL + '/%s/%s' % (
            poll_id, img_name)

    return render_to_response(
        'image_option_thumbnail.html',
        {"img": open(src), "img_src": media_url}
    )


def csv_download(request, poll_id):
    csv = Poll.get(poll_id).get_result().to_csv()

    response = HttpResponse(csv, content_type='text/csv;')
    response['Content-Disposition'] = (
        'attachment; filename="%s_result.csv"' % poll_id)
    return response


class UnploadPollResultFormView(TemplateView):

    template_name = "poll-result-form.html"

    def post(self, request, *args, **kwargs):  # pylint: disable=W0613
        context = self.get_context_data()
        user = request.user

        files = dict(request.FILES.lists()).get('result', [])

        if not len(files):
            msg = u'Necesita seleccionar un archivo.'
            messages.add_message(self.request, messages.INFO, msg)

        processed_files = []
        existing = []
        not_authored_by_user = []
        poll_not_assigned_to_user = []

        date_time_string = Clock.get_time_string()
        for file_ in files:
            file_name = file_.name
            tmp_file_path = file_.temporary_file_path()
            try:
                prf = PollResultFile(tmp_file_path)
                if prf.exists():
                    existing.append(file_name)
                elif not prf.is_authored_by(user):
                    not_authored_by_user.append(file_name)
                elif not prf.poll_is_assigned_to(user):
                    poll_not_assigned_to_user.append(file_name)
                else:
                    prf.name = file_name
                    prf.set_upload_timestamp(date_time_string)
                    prf.save()
                    processed_files.append(file_name)
            except ValueError:
                fname = file_.name
                msg = u'{0}: No es un .poll_result válido.'.format(fname)
                messages.add_message(self.request, messages.ERROR, msg)

        if len(existing):
            msg = u'Los siguientes resultados ya se encuentran \
                publicados: %s y no serán procesados.' % (", ".join(existing))
            messages.add_message(self.request, messages.INFO, msg)

        if len(not_authored_by_user):
            msg = u'El sistema cree que estos archivos no pertencen a una \
                    encuesta realizada por usted: {0}'.format(
                ", ".join(not_authored_by_user)
            )
            messages.add_message(request, messages.ERROR, msg)

        if len(poll_not_assigned_to_user):
            msg = u'Estos son resultados de una encuesta \
                    que no le fué asignada. {0}'.format(
                ", ".join(poll_not_assigned_to_user)
            )
            messages.add_message(self.request, messages.ERROR, msg)

        if len(processed_files):
            messages.add_message(
                self.request,
                messages.SUCCESS,
                u'Los resultados se guardaron con éxito.\
                Los siguientes archivos fueron procesados: \
                %s' % ", ".join(processed_files)
            )

        return self.render_to_response(context)