views.py 12.9 KB
Newer Older
1
"""
Hypsug0's avatar
Hypsug0 committed
2
    Vues de l'application Sights
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
"""

from django.contrib import messages
from django.contrib.auth.mixins import LoginRequiredMixin
from django.core.files.storage import FileSystemStorage
from django.db import IntegrityError
from django.db.models import Q
from django.http import HttpResponseRedirect
from django.urls import reverse_lazy
from django.utils.translation import ugettext_lazy as _
from django.views.generic import DetailView
from django.views.generic.edit import CreateView, DeleteView, UpdateView
from django_tables2 import SingleTableView

from core import js
Hypsug0's avatar
Hypsug0 committed
18
19
20
21
22

from ..forms import DeviceForm, SessionChangePlaceForm, SessionForm, SessionLinkForm
from ..mixins import SessionEditAuthMixin, SessionViewAuthMixin, SightingEditAuthMixin
from ..models import Device, Session, SessionLink, Sighting
from ..tables import SessionDeviceTable, SessionSightingTable, SessionTable
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38

IMAGE_FILE_TYPES = ["png", "jpg", "jpeg"]
DOCUMENT_FILE_TYPES = ["doc", "docx", "odt", "pdf"]


class SessionCreate(LoginRequiredMixin, CreateView):
    model = Session
    form_class = SessionForm
    template_name = "normal_form.html"

    def get_initial(self):
        initial = super(SessionCreate, self).get_initial()
        initial = initial.copy()
        initial["main_observer"] = self.request.user
        return initial

Rémy Lebrun's avatar
Rémy Lebrun committed
39
40
41
42
43
44
    def get_form_kwargs(self):
        kwargs = super(SessionCreate, self).get_form_kwargs()
        place_id = self.kwargs.get("pk")
        kwargs["place_id"] = place_id
        return kwargs

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
    def form_valid(self, form):
        form.instance.created_by = self.request.user
        form.instance.place_id = self.kwargs.get("pk")
        try:
            return super(SessionCreate, self).form_valid(form)
        except IntegrityError as e:
            messages.error(self.request, e.__cause__)
            return HttpResponseRedirect(self.request.path)
        # except IntegrityError as e:
        # # messages.error(self.request, e.__cause__)
        # messages.error(self.request, _('Cette session existe déjà'))
        # return HttpResponseRedirect(self.request.path)
        return super(SessionCreate, self).form_valid(form)

    def get_context_data(self, **kwargs):
        context = super(SessionCreate, self).get_context_data(**kwargs)
        context["icon"] = "fa fa-fw fa-map"
        context["title"] = _("Ajout d'une session")
        # context['js'] = """
        # $(function () {
        #     $('.dateinput').fdatepicker({
        #         format: 'dd/mm/yyyy',
        #         disableDblClickSelection: true,
        #         leftArrow: '<i class="fa fa-fw fa-chevron-left"></i>',
        #         rightArrow: '<i class="fa fa-fw fa-chevron-right"></i>',
        #     });
        # });
        # """
        context["js"] = js.DateAndTimeInput
        return context

76
    # Improve workflow - Go to observation
Rémy Lebrun's avatar
Rémy Lebrun committed
77
    def get_success_url(self):
78
        id_session = self.object.id_session
Rémy Lebrun's avatar
Rémy Lebrun committed
79
        if self.request.method == "POST" and "gotoObs" in self.request.POST:
80
            return reverse_lazy("sights:sighting_create", kwargs={"pk": id_session})
81
        return reverse_lazy("sights:session_detail", kwargs={"pk": id_session})
Rémy Lebrun's avatar
Rémy Lebrun committed
82

83
84
85
86
87
88
89
90
91
92
93

class SessionUpdate(SessionEditAuthMixin, UpdateView):
    model = Session
    form_class = SessionForm
    file_storage = FileSystemStorage()
    template_name = "normal_form.html"

    def form_valid(self, form):
        form.instance.updated_by = self.request.user
        return super(SessionUpdate, self).form_valid(form)

Rémy Lebrun's avatar
Rémy Lebrun committed
94
95
96
97
98
99
    def get_form_kwargs(self):
        kwargs = super(SessionUpdate, self).get_form_kwargs()
        place_id = self.kwargs.get("pk")
        kwargs["place_id"] = place_id
        return kwargs

100
101
    def get_context_data(self, **kwargs):
        context = super(SessionUpdate, self).get_context_data(**kwargs)
Rémy Lebrun's avatar
Rémy Lebrun committed
102
        context["icon"] = "far fa-calendar-alt"
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
        context["title"] = _("Ajout d'une session")
        context["js"] = js.DateAndTimeInput
        return context


class SessionChangePlaceUpdate(SessionEditAuthMixin, UpdateView):
    model = Session
    form_class = SessionChangePlaceForm
    file_storage = FileSystemStorage()
    template_name = "normal_form.html"

    def form_valid(self, form):
        form.instance.updated_by = self.request.user
        return super(SessionChangePlaceUpdate, self).form_valid(form)

    def get_context_data(self, **kwargs):
119
        context = super(SessionChangePlaceUpdate, self).get_context_data(**kwargs)
120
121
122
123
        context["icon"] = "fa fa-fw fa-exclamation-triangle"
        context["title"] = _("Changer la localité de la session")
        context[
            "js"
Hypsug0's avatar
Hypsug0 committed
124
        ] = """
125
126
127
128
129
130
131
132
133
        """
        return context


class SessionDelete(SessionEditAuthMixin, DeleteView):
    model = Session
    template_name = "confirm_delete.html"

    def get_success_url(self):
134
        return reverse_lazy("sights:place_detail", kwargs={"pk": self.object.place_id})
135
136
137
138
139

    def get_context_data(self, **kwargs):
        context = super(SessionDelete, self).get_context_data(**kwargs)
        context["icon"] = "fa fa-fw fa-trash"
        context["title"] = _("Suppression d'une session")
Hypsug0's avatar
Hypsug0 committed
140
        context["message_alert"] = _("Êtes-vous certain de vouloir supprimer la session")
141
142
143
144
145
        return context


class SessionDetail(SessionViewAuthMixin, DetailView):
    model = Session
146
    template_name = "session_detail.html"
147
148
149
150
151

    def get_context_data(self, **kwargs):
        context = super(SessionDetail, self).get_context_data(**kwargs)
        pk = self.kwargs.get("pk")
        # Rendu des sessions
Rémy Lebrun's avatar
Rémy Lebrun committed
152
        context["icon"] = "far fa-calendar-alt"
153
154
155
        context["title"] = _("Détails de la session d'inventaire")
        context[
            "js"
Hypsug0's avatar
Hypsug0 committed
156
        ] = """
157
158
159
160
        """
        # Rendu des observations
        context["sightingicon"] = "fa fa-eye fa-fw"
        context["sightingtitle"] = _("Observations")
Hypsug0's avatar
Hypsug0 committed
161
        context["sightingcount"] = Sighting.objects.filter(session=pk).distinct().count()
162
        context["sightingtable"] = SessionSightingTable(
163
            Sighting.objects.filter(session=pk).distinct().order_by("-timestamp_update")
164
165
166
167
168
        )
        # Rendu des dispositifs
        context["deviceicon"] = "fi-target"
        context["devicetitle"] = _("Dispositifs d'échantillonnage")
        context["devicecount"] = Device.objects.filter(session=pk).count()
169
        context["devicetable"] = SessionDeviceTable(Device.objects.filter(session=pk))
170
171
172
173
174
175
176
177
178
179
180
        return context


class SessionMyList(LoginRequiredMixin, SingleTableView):
    table_class = SessionTable
    template_name = "table.html"
    table_pagination = {"per_page": 25}

    def get_context_data(self, **kwargs):
        context = super(SessionMyList, self).get_context_data(**kwargs)
        loggeduser = self.request.user
Rémy Lebrun's avatar
Rémy Lebrun committed
181
        context["icon"] = "far fa-calendar-alt"
182
183
184
185
186
187
188
189
190
191
192
193
        context["title"] = _("Mes sessions")
        context[
            "js"
        ] = """
        """
        context["counttitle"] = _("Nombre de sessions")
        context["count"] = (
            Session.objects.filter(
                Q(created_by=loggeduser)
                | Q(main_observer=loggeduser)
                | Q(other_observer__username__contains=loggeduser.username)
            )
194
195
            .distinct()
            .count()
196
197
198
199
200
        )
        return context

    def get_queryset(self):
        loggeduser = self.request.user
hypsug0's avatar
hypsug0 committed
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
        queryset = (
            Session.objects.select_related("created_by")
            .select_related("main_observer")
            .prefetch_related("other_observer")
            .select_related("place")
            .select_related("contact")
            .select_related("study")
            .prefetch_related("observations")
            .prefetch_related("observations__codesp")
            .prefetch_related("place__municipality")
            .prefetch_related("place__territory")
            .prefetch_related("place__type")
            .prefetch_related("place__type")
        )
        queryset = (
            queryset.filter(
217
218
219
220
                Q(created_by=loggeduser)
                | Q(main_observer=loggeduser)
                | Q(other_observer__username__contains=loggeduser.username)
            )
221
222
            .distinct()
            .order_by("-timestamp_update")
223
        )
hypsug0's avatar
hypsug0 committed
224
        return queryset
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239


class DeviceCreate(LoginRequiredMixin, CreateView):
    model = Device
    form_class = DeviceForm
    template_name = "normal_form.html"

    # def get(self, request, *args, **kwargs):
    #     session = Session.objects.get(id_session=self.kwargs.get('pk'))
    #     self.form.fields['type'].queryset = TypeDevice.objects.filter(contact=session.contact.code)
    #     return super(DeviceCreate, self).get(request, *args, **kwargs)

    def get_form_kwargs(self):
        kwargs = super(DeviceCreate, self).get_form_kwargs()
        session_id = self.kwargs.get("pk")
240
        kwargs["contact"] = Session.objects.get(id_session=session_id).contact.code
241
242
243
244
245
246
247
248
249
250
251
252
253
        return kwargs

    def form_valid(self, form):
        form.instance.created_by = self.request.user
        form.instance.session_id = self.kwargs.get("pk")
        return super(DeviceCreate, self).form_valid(form)

    def get_context_data(self, **kwargs):
        context = super(DeviceCreate, self).get_context_data(**kwargs)
        context["icon"] = "fi-target-two"
        context["title"] = _("Ajout d'un dispositif")
        context[
            "js"
Hypsug0's avatar
Hypsug0 committed
254
        ] = """
255
256
257
258
259
260
261
262
263
264
265
266
        """
        return context


class DeviceUpdate(SightingEditAuthMixin, UpdateView):
    model = Device
    form_class = DeviceForm
    template_name = "normal_form.html"

    def get_form_kwargs(self):
        kwargs = super(DeviceUpdate, self).get_form_kwargs()
        session_id = self.object.session_id
267
        kwargs["contact"] = Session.objects.get(id_session=session_id).contact.code
268
269
270
271
272
273
274
275
276
277
278
279
        return kwargs

    def form_valid(self, form):
        form.instance.updated_by = self.request.user
        return super(DeviceUpdate, self).form_valid(form)

    def get_context_data(self, **kwargs):
        context = super(DeviceUpdate, self).get_context_data(**kwargs)
        context["icon"] = "fi-target-two"
        context["title"] = _("Modification d'un dispositif")
        context[
            "js"
Hypsug0's avatar
Hypsug0 committed
280
        ] = """
281
282
283
284
285
286
287
288
289
        """
        return context


class DeviceDelete(SightingEditAuthMixin, DeleteView):
    model = Device
    template_name = "confirm_delete.html"

    def get_success_url(self):
Hypsug0's avatar
Hypsug0 committed
290
        return reverse_lazy("sights:session_detail", kwargs={"pk": self.object.session_id})
291
292
293
294
295

    def get_context_data(self, **kwargs):
        context = super(DeviceDelete, self).get_context_data(**kwargs)
        context["icon"] = "fa fa-fw fa-trash"
        context["title"] = _("Suppression d'une dispositif d'échantillonage")
Hypsug0's avatar
Hypsug0 committed
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
        context["message_alert"] = _("Êtes-vous certain de vouloir supprimer le dispositif")
        return context


class SessionLinkCreate(LoginRequiredMixin, CreateView):
    model = SessionLink
    form_class = SessionLinkForm
    template_name = "normal_form.html"

    # def get(self, request, *args, **kwargs):
    #     session = Session.objects.get(id_session=self.kwargs.get('pk'))
    #     self.form.fields['type'].queryset = TypeDevice.objects.filter(contact=session.contact.code)
    #     return super(DeviceCreate, self).get(request, *args, **kwargs)

    def get_form_kwargs(self):
        kwargs = super(SessionLinkCreate, self).get_form_kwargs()
        return kwargs

    def form_valid(self, form):
        form.instance.created_by = self.request.user
        form.instance.session_id = self.kwargs.get("pk")
        return super(SessionLinkCreate, self).form_valid(form)

    def get_context_data(self, **kwargs):
        context = super(SessionLinkCreate, self).get_context_data(**kwargs)
        context["icon"] = "fi-link"
        context["title"] = _("Ajout d'un lien")
        context["js"] = ""
        return context


class SessionLinkUpdate(SightingEditAuthMixin, UpdateView):
    model = SessionLink
    form_class = SessionLinkForm
    template_name = "normal_form.html"

    def get_form_kwargs(self):
        kwargs = super(SessionLinkUpdate, self).get_form_kwargs()
        return kwargs

    def form_valid(self, form):
        form.instance.updated_by = self.request.user
        return super(SessionLinkUpdate, self).form_valid(form)

    def get_context_data(self, **kwargs):
        context = super(SessionLinkUpdate, self).get_context_data(**kwargs)
        context["icon"] = "fi-link"
        context["title"] = _("Modification d'un lien")
        context["js"] = ""
        return context


class SessionLinkDelete(SightingEditAuthMixin, DeleteView):
    model = SessionLink
    template_name = "confirm_delete.html"

    def get_success_url(self):
        return reverse_lazy("sights:session_detail", kwargs={"pk": self.object.session_id})

    def get_context_data(self, **kwargs):
        context = super(SessionLinkDelete, self).get_context_data(**kwargs)
        context["icon"] = "fa fa-fw fa-trash"
        context["title"] = _("Suppression d'une lien")
        context["message_alert"] = _("Êtes-vous certain de vouloir supprimer le lien")
360
        return context