views.py 9.59 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
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
"""
	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

    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


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)

    def get_context_data(self, **kwargs):
        context = super(SessionUpdate, self).get_context_data(**kwargs)
        context["icon"] = "fi-calendar"
        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):
        context = super(SessionChangePlaceUpdate, self).get_context_data(
            **kwargs
        )
        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):
        return reverse_lazy(
            "sights:place_detail", kwargs={"pk": self.object.place_id}
        )

    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
        context["icon"] = "fi-calendar"
        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(
            Sighting.objects.filter(session=pk)
                .distinct()
                .order_by("-timestamp_update")
        )
        # Rendu des dispositifs
        context["deviceicon"] = "fi-target"
        context["devicetitle"] = _("Dispositifs d'échantillonnage")
        context["devicecount"] = Device.objects.filter(session=pk).count()
        context["devicetable"] = SessionDeviceTable(
            Device.objects.filter(session=pk)
        )
        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
        context["icon"] = "fi-calendar"
        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)
            )
                .distinct()
                .count()
        )
        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)
            )
                .distinct()
                .order_by("-timestamp_update")
        )


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