views.py 10.2 KB
Newer Older
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
"""
	Vues de l'application Sights
"""

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
from ..forms import (
    SessionChangePlaceForm,
    SessionForm,
    DeviceForm,
)
from ..mixins import (
    SessionEditAuthMixin,
    SessionViewAuthMixin,
    SightingEditAuthMixin,
)
from ..models import (
    Session,
    Device,
    Sighting,
)
from ..tables import (
    SessionTable,
    SessionDeviceTable,
    SessionSightingTable,
)

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
54
55
56
57
58
59
    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

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
    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

91
    # Improve workflow - Go to observation
Rémy Lebrun's avatar
Rémy Lebrun committed
92
    def get_success_url(self):
93
        id_session = self.object.id_session
Rémy Lebrun's avatar
Rémy Lebrun committed
94
        if self.request.method == "POST" and "gotoObs" in self.request.POST:
95
            return reverse_lazy("sights:sighting_create", kwargs={"pk": id_session})
96
        return reverse_lazy("sights:session_detail", kwargs={"pk": id_session})
Rémy Lebrun's avatar
Rémy Lebrun committed
97

98
99
100
101
102
103
104
105
106
107
108

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
109
110
111
112
113
114
    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

115
116
    def get_context_data(self, **kwargs):
        context = super(SessionUpdate, self).get_context_data(**kwargs)
Rémy Lebrun's avatar
Rémy Lebrun committed
117
        context["icon"] = "far fa-calendar-alt"
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
        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):
134
        context = super(SessionChangePlaceUpdate, self).get_context_data(**kwargs)
135
136
137
138
139
140
141
142
143
144
145
146
147
148
        context["icon"] = "fa fa-fw fa-exclamation-triangle"
        context["title"] = _("Changer la localité de la session")
        context[
            "js"
        ] = """      
        """
        return context


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

    def get_success_url(self):
149
        return reverse_lazy("sights:place_detail", kwargs={"pk": self.object.place_id})
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168

    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")
        context["message_alert"] = _(
            "Êtes-vous certain de vouloir supprimer la session"
        )
        return context


class SessionDetail(SessionViewAuthMixin, DetailView):
    model = Session
    template_name = "sights/session_detail.html"

    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
169
        context["icon"] = "far fa-calendar-alt"
170
171
172
173
174
175
176
177
178
179
180
181
        context["title"] = _("Détails de la session d'inventaire")
        context[
            "js"
        ] = """      
        """
        # Rendu des observations
        context["sightingicon"] = "fa fa-eye fa-fw"
        context["sightingtitle"] = _("Observations")
        context["sightingcount"] = (
            Sighting.objects.filter(session=pk).distinct().count()
        )
        context["sightingtable"] = SessionSightingTable(
182
            Sighting.objects.filter(session=pk).distinct().order_by("-timestamp_update")
183
184
185
186
187
        )
        # Rendu des dispositifs
        context["deviceicon"] = "fi-target"
        context["devicetitle"] = _("Dispositifs d'échantillonnage")
        context["devicecount"] = Device.objects.filter(session=pk).count()
188
        context["devicetable"] = SessionDeviceTable(Device.objects.filter(session=pk))
189
190
191
192
193
194
195
196
197
198
199
        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
200
        context["icon"] = "far fa-calendar-alt"
201
202
203
204
205
206
207
208
209
210
211
212
        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)
            )
213
214
            .distinct()
            .count()
215
216
217
218
219
220
221
222
223
224
225
        )
        return context

    def get_queryset(self):
        loggeduser = self.request.user
        return (
            Session.objects.filter(
                Q(created_by=loggeduser)
                | Q(main_observer=loggeduser)
                | Q(other_observer__username__contains=loggeduser.username)
            )
226
227
            .distinct()
            .order_by("-timestamp_update")
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
        )


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")
244
        kwargs["contact"] = Session.objects.get(id_session=session_id).contact.code
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
        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"
        ] = """      
        """
        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
271
        kwargs["contact"] = Session.objects.get(id_session=session_id).contact.code
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
        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"
        ] = """      
        """
        return context


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