Blame view

src/core/pyros_django/routine_manager/views.py 29.1 KB
1cffbf1c   Etienne Pallier   moved pyros_djang...
1
2
from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_exempt
3b81a22b   Alexis Koralewski   Rework on Request...
3
from django.shortcuts import get_object_or_404, render, redirect
1cffbf1c   Etienne Pallier   moved pyros_djang...
4
5
6
from common.models import *
from django.db.models import Q
from django.contrib.auth.decorators import login_required
3b81a22b   Alexis Koralewski   Rework on Request...
7
8
9

from src.core.pyros_django.obsconfig.configpyros import ConfigPyros
from .forms import RequestForm, SequenceForm, AlbumForm, PlanForm, uneditablePlanForm
1cffbf1c   Etienne Pallier   moved pyros_djang...
10
11
12
from .validators import check_plan_validity, check_album_validity, check_sequence_validity, check_request_validity
from .RequestSerializer import RequestSerializer
import scheduler
4a596eec   Alexis Koralewski   Updating SP, Sequ...
13
from django.contrib import messages 
1cffbf1c   Etienne Pallier   moved pyros_djang...
14
15
""" logger """
from django.conf import settings
4a596eec   Alexis Koralewski   Updating SP, Sequ...
16
17
# "import utils.Logger as l
#"log = l.setupLogger("routine_manager-views", "routine_manager-views")
1cffbf1c   Etienne Pallier   moved pyros_djang...
18
19
20
21
22
23

""" XML Export / Import utils """
from wsgiref.util import FileWrapper
from django.utils.encoding import smart_str
from django.http import HttpResponse
import mimetypes
3b81a22b   Alexis Koralewski   Rework on Request...
24
import os, ast, datetime
1cffbf1c   Etienne Pallier   moved pyros_djang...
25
from pprint import pprint
4a596eec   Alexis Koralewski   Updating SP, Sequ...
26
from src.pyros_logger import log
1cffbf1c   Etienne Pallier   moved pyros_djang...
27
28
29
30
31
32
33
34
35
36
37

SAVED_REQUESTS_FOLDER = "misc/saved_requests/"


@login_required
def requests_list(request, status=0, message=""):
    """
        Retrieves and display the routines list (routine manager main page)
    """

    if settings.DEBUG:
4a596eec   Alexis Koralewski   Updating SP, Sequ...
38
39
        #log.info("From requests_list")
        pass
1cffbf1c   Etienne Pallier   moved pyros_djang...
40
41
42
43
44
45
46
47

    if status == "-1":
        error = True
    elif status == "1":
        success = True

    # TODO: uncomment for alert filter
#     requests_objs = Request.objects.filter(pyros_user=request.user).filter(is_alert=False).order_by("-updated")
3b81a22b   Alexis Koralewski   Rework on Request...
48
    sequences_objs = Sequence.objects.filter(pyros_user=request.user).order_by("-updated")
4a596eec   Alexis Koralewski   Updating SP, Sequ...
49
50
51
52
53
54
    sequences = []
    for seq in sequences_objs:
        nb_album = Album.objects.filter(sequence=seq).count
        nb_plan = Plan.objects.filter(album__in=Album.objects.filter(sequence=seq).values("id")).count
        sequences.append({"seq":seq, "nb_album":nb_album, "nb_plan":nb_plan})
    
3b81a22b   Alexis Koralewski   Rework on Request...
55

4a596eec   Alexis Koralewski   Updating SP, Sequ...
56
    #print("REQ/views: Les requetes sont:")
3b81a22b   Alexis Koralewski   Rework on Request...
57
58
    # requests_objs = Request.objects.filter(pyros_user=request.user).order_by("-updated")
    # print("REQ/views: Les requetes sont:")
1cffbf1c   Etienne Pallier   moved pyros_djang...
59

3b81a22b   Alexis Koralewski   Rework on Request...
60
61
62
63
64
65
66
67
68
    # requests = []

    # for req in requests_objs:
    #     #print("- REQ/views: requete", req)
    #     sequences = req.sequences
    #     nb_executed = sequences.filter(status=Sequence.EXECUTED).count
    #     nb_cancelled = sequences.filter(Q(status=Sequence.INVALID) | Q(status=Sequence.CANCELLED)
    #                                     | Q(status=Sequence.UNPLANNABLE)).count()
    #     requests.append({'req': req, 'nb_seq': sequences.count(), 'nb_executed': nb_executed, 'nb_cancelled': nb_cancelled})
1cffbf1c   Etienne Pallier   moved pyros_djang...
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83

    print("REQ/views: ICI:")
    # opens template src/routine_manager/templates/routine_manager/requests_list.html with all local variables
    return render(request, "routine_manager/requests_list.html", locals())

@login_required
def action_request(request, req_id, action, status=0, message=""):
    """
        Apply actions (view, edit, delete) on a given request
    """

    req = Request.objects.get(id=req_id)
    depth_level = 1

    if settings.DEBUG:
4a596eec   Alexis Koralewski   Updating SP, Sequ...
84
85
        #log.info("From action_request")
        pass
1cffbf1c   Etienne Pallier   moved pyros_djang...
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

    if status == "-1":
        error = True
    elif status == "1":
        success = True

    if req.submitted == True and action == "edit":
        error = True
        message = "You can't edit a submitted request"
        action = "view"

    if check_request_validity(req) == True:
        return redirect(unsubmit_request, req_id)
    if action == "edit":
        form = RequestForm(instance=req)
        edit = True
        return render(request, "routine_manager/view_request.html", locals())
    elif action == "view":
        form = RequestForm(instance=req, readonly=True)
        edit = False
        return render(request, "routine_manager/view_request.html", locals())
    elif action == "delete":
        req.delete()
        return redirect(requests_list, status='1', message="Successfully deleted the request")

    return redirect(requests_list)

@login_required
def request_validate(request, req_id):
    """
        Called when the request form was validated.
        Possible actions : Cancel, Save, Save and add sequence, Delete
    """

    action = request.POST.get("action")
    req = Request.objects.get(id=req_id)
    form = RequestForm(instance=req, data=request.POST)

    if (settings.DEBUG):
4a596eec   Alexis Koralewski   Updating SP, Sequ...
125
126
        #log.info("From request_validate")
        pass
1cffbf1c   Etienne Pallier   moved pyros_djang...
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

    if action == "cancel":
        if req.name == "New request":
            req.delete()
        return redirect(requests_list, status=1, message="Cancelled request modification")
    elif action == "delete":
        return redirect(action_request, req_id, "delete")
    elif form.is_valid():
        req = form.save()
        if action == "save":
            return redirect(action_request, req_id=req_id, action="edit", status=1, message="Request saved")
        if action == "save_and_add":
            return redirect(create_sequence, req_id=req_id)
    else:
        error = True
        message = "Please check your field's validity"
        depth_level = 1
        edit = True
        return render(request, "routine_manager/view_request.html", locals())


@login_required
def action_sequence(request, seq_id, action, status=0, message=""):
    """
        Apply actions (view, edit, delete) on a given sequence
    """
3b81a22b   Alexis Koralewski   Rework on Request...
153
154
    unit_name = os.environ["unit_name"]
    config = ConfigPyros(os.environ["PATH_TO_OBSCONF_FILE"], unit_name)
1cffbf1c   Etienne Pallier   moved pyros_djang...
155
156
    seq_id = int(seq_id)
    seq = Sequence.objects.get(id=seq_id)
3b81a22b   Alexis Koralewski   Rework on Request...
157
    depth_level = 1
1cffbf1c   Etienne Pallier   moved pyros_djang...
158
159

    if (settings.DEBUG):
4a596eec   Alexis Koralewski   Updating SP, Sequ...
160
161
        #log.info("From action_sequence")
        pass
1cffbf1c   Etienne Pallier   moved pyros_djang...
162
163
164
165
166
167
168
169
170
171
172
173

    if status == "-1":
        error = True
    elif status == "1":
        success = True

    if seq.status != Sequence.INCOMPLETE and seq.status != Sequence.COMPLETE and action == "edit":
        error = True
        message = "You can't edit a submitted request"
        action = "view"

    if check_sequence_validity(seq) == True:
3b81a22b   Alexis Koralewski   Rework on Request...
174
175
        #return redirect(unsubmit_request, req_id)
        pass
4a596eec   Alexis Koralewski   Updating SP, Sequ...
176
177
178
    horizon_line = config.getHorizonLine(config.unit_name)
    horizon_line_svg = f'<svg id="horizonline" width="30vw" height="5vh">\
    <line x1="{horizon_line[0][0]}" y1="{horizon_line[0][1]}" x2="{horizon_line[1][0]}" y2="{horizon_line[1][1]}" stroke="black" fontsize="2em"/>\
1b822613   Alexis Koralewski   small ui change o...
179
    </svg><p> (values : {horizon_line})</p>'
4a596eec   Alexis Koralewski   Updating SP, Sequ...
180
181
182
183
184
    if request.session.get("role") == "Admin":
        sp_list = None
    else:
        sp_of_user = request.user.get_scientific_program()
        sp_list = ScientificProgram.objects.observable_programs().filter(id__in=sp_of_user)
1cffbf1c   Etienne Pallier   moved pyros_djang...
185
    if action == "edit":
4a596eec   Alexis Koralewski   Updating SP, Sequ...
186
187
188
189
190
        sp_of_user = request.user.get_scientific_program()
        sp_list = ScientificProgram.objects.observable_programs().filter(id__in=sp_of_user)
        if len(sp_list) == 0 :
            messages.add_message(request,messages.INFO,"Can't submit a Sequence : there is no scientific program to be assigned with")
            return redirect(requests_list)
cca89707   Alexis Koralewski   adapting observat...
191
        form = SequenceForm(instance=seq, data_from_config=config.getEditableAttributesOfMount(config.unit_name), layouts = config.get_layouts(config.unit_name), sp_list=sp_list)
1cffbf1c   Etienne Pallier   moved pyros_djang...
192
193
194
        edit = True
        return render(request, "routine_manager/view_sequence.html", locals())
    elif action == "view":
cca89707   Alexis Koralewski   adapting observat...
195
        form = SequenceForm(instance=seq, data_from_config=config.getEditableAttributesOfMount(config.unit_name), layouts = config.get_layouts(config.unit_name), sp_list=sp_list)
1cffbf1c   Etienne Pallier   moved pyros_djang...
196
197
198
        edit = False
        return render(request, "routine_manager/view_sequence.html", locals())
    elif action == "delete":
4a596eec   Alexis Koralewski   Updating SP, Sequ...
199
        log.info(f"User {request.user} did action delete sequence {seq.name}")
1cffbf1c   Etienne Pallier   moved pyros_djang...
200
        seq.delete()
4a596eec   Alexis Koralewski   Updating SP, Sequ...
201
        #if check_sequence_validity(seq) == True:
3b81a22b   Alexis Koralewski   Rework on Request...
202
            #return redirect(unsubmit_request, req_id)
3b81a22b   Alexis Koralewski   Rework on Request...
203
        return redirect(requests_list)
1cffbf1c   Etienne Pallier   moved pyros_djang...
204
205
206
207
208
209
210
211
212
213
214

    return redirect(requests_list)

@login_required
def sequence_validate(request, seq_id):
    """
        Called when the sequence form was validated.
        Possible actions : Cancel, Save, Save and add album, Delete
    """

    if (settings.DEBUG):
4a596eec   Alexis Koralewski   Updating SP, Sequ...
215
216
        #log.info("From sequence_validate")
        pass
3b81a22b   Alexis Koralewski   Rework on Request...
217
218
    unit_name = os.environ["unit_name"]
    config = ConfigPyros(os.environ["PATH_TO_OBSCONF_FILE"], unit_name)
1cffbf1c   Etienne Pallier   moved pyros_djang...
219
220
221
    seq_id = int(seq_id)
    action = request.POST.get("action")
    seq = Sequence.objects.get(id=seq_id)
cca89707   Alexis Koralewski   adapting observat...
222
    form = SequenceForm(instance=seq, data=request.POST, data_from_config=config.getEditableAttributesOfMount(config.unit_name), layouts = config.get_layouts(config.unit_name))
1cffbf1c   Etienne Pallier   moved pyros_djang...
223
224
225
226

    if action == "cancel":
        if seq.name == "New sequence":
            seq.delete()
3b81a22b   Alexis Koralewski   Rework on Request...
227
        return redirect(requests_list)
1cffbf1c   Etienne Pallier   moved pyros_djang...
228
229
230
231
232
    elif action == "delete":
        return redirect(action_sequence, seq_id, "delete")
    elif form.is_valid():
        seq = form.save()
        if action == "save":
4a596eec   Alexis Koralewski   Updating SP, Sequ...
233
234
            message="Sequence saved"
            messages.add_message(request,messages.INFO,message)
1cffbf1c   Etienne Pallier   moved pyros_djang...
235
236
            return redirect(action_sequence, seq_id=seq_id, action="edit", status=1, message="Sequence saved")
        if action == "save_and_add":
cca89707   Alexis Koralewski   adapting observat...
237
238
239
240
241
242
            albums = config.getLayoutByName(unit_name=config.unit_name,name_of_layout=seq.config_attributes["layout"])["ALBUMS"]
            for album_name in albums:
                create_album(request,seq_id,album_name=album_name)
            #return redirect(create_album, seq_id=seq_id)
            messages.add_message(request,messages.INFO,"Created albums according to chosen layouts")
            return redirect(action_sequence, seq.id, "edit")
4a596eec   Alexis Koralewski   Updating SP, Sequ...
243
244
245
246
247
248
249
250
251
252
253
254
255
256
        if action == "save_and_submit":
            if check_sequence_validity(seq):
                seq.status = Sequence.TOBEPLANNED
                seq.save()
                message="Sequence submitted"
                messages.add_message(request,messages.INFO,message)
                log.info(f"User {request.user} did action submit sequence {seq} for period {seq.period} ")
                return redirect(action_sequence, seq_id=seq_id, action="edit", status=1, message="Sequence submitted")
            else:
                message = "Can't submit sequence because it's incomplete (Need at least 1 album with 1 plan)"
                messages.add_message(request,messages.ERROR,message)
                status = 1
                edit = True
                return render(request, "routine_manager/view_sequence.html", locals())        
1cffbf1c   Etienne Pallier   moved pyros_djang...
257
258
259
    else:
        error = True
        message = "Please check your field's validity"
3b81a22b   Alexis Koralewski   Rework on Request...
260
        depth_level = 1
1cffbf1c   Etienne Pallier   moved pyros_djang...
261
        edit = True
1cffbf1c   Etienne Pallier   moved pyros_djang...
262
263
264
265
266
267
268
        return render(request, "routine_manager/view_sequence.html", locals())

@login_required
def action_album(request, alb_id, action, status=0, message=""):
    """
        Apply actions (view, edit, delete) on a given album
    """
3b81a22b   Alexis Koralewski   Rework on Request...
269
270
    unit_name = os.environ["unit_name"]
    config = ConfigPyros(os.environ["PATH_TO_OBSCONF_FILE"], unit_name)
1cffbf1c   Etienne Pallier   moved pyros_djang...
271
272
273

    alb_id = int(alb_id)
    alb = Album.objects.get(id=alb_id)
1cffbf1c   Etienne Pallier   moved pyros_djang...
274
    seq_id = alb.sequence.id
3b81a22b   Alexis Koralewski   Rework on Request...
275
276
    depth_level = 2
    seq = alb.sequence
1cffbf1c   Etienne Pallier   moved pyros_djang...
277
    if (settings.DEBUG):
4a596eec   Alexis Koralewski   Updating SP, Sequ...
278
279
        #log.info("From action_album")
        pass
1cffbf1c   Etienne Pallier   moved pyros_djang...
280
281
282
283
284
285
286
287
288
289
290

    if status == "-1":
        error = True
    elif status == "1":
        success = True

    if alb.sequence.status != Sequence.INCOMPLETE and alb.sequence.status != Sequence.COMPLETE and action == "edit":
        error = True
        message = "You can't edit a submitted request"
        action = "view"

4a596eec   Alexis Koralewski   Updating SP, Sequ...
291
292
293
    if check_album_validity(alb) == True:
        #return redirect(unsubmit_request, req_id)
        pass
1cffbf1c   Etienne Pallier   moved pyros_djang...
294
    if action == "edit":
cca89707   Alexis Koralewski   adapting observat...
295
        form = AlbumForm(instance=alb,readonly=True)
1cffbf1c   Etienne Pallier   moved pyros_djang...
296
297
298
        edit = True
        return render(request, "routine_manager/view_album.html", locals())
    elif action == "view":
cca89707   Alexis Koralewski   adapting observat...
299
        form = AlbumForm(instance=alb, readonly=True)
1cffbf1c   Etienne Pallier   moved pyros_djang...
300
301
302
        edit = False
        return render(request, "routine_manager/view_album.html", locals())
    elif action == "delete":
4a596eec   Alexis Koralewski   Updating SP, Sequ...
303
        log.info(f"User {request.user} did action delete Album {alb.name} of Sequence {seq}")
1cffbf1c   Etienne Pallier   moved pyros_djang...
304
305
306
307
308
309
310
311
312
313
314
        alb.delete()
        return redirect(action_sequence, seq_id=alb.sequence.id, action="edit", status='1', message="Successfully deleted the album")

    return redirect(requests_list)

@login_required
def album_validate(request, alb_id):
    """
        Called when the album form was validated.
        Possible actions : Cancel, Save, Save and add plan, Delete
    """
3b81a22b   Alexis Koralewski   Rework on Request...
315
316
    unit_name = os.environ["unit_name"]
    config = ConfigPyros(os.environ["PATH_TO_OBSCONF_FILE"], unit_name)
1cffbf1c   Etienne Pallier   moved pyros_djang...
317
318
319
    alb_id = int(alb_id)
    action = request.POST.get("action")
    alb = Album.objects.get(id=alb_id)
cca89707   Alexis Koralewski   adapting observat...
320
    form = AlbumForm(instance=alb, data=request.POST)
3b81a22b   Alexis Koralewski   Rework on Request...
321
    
1cffbf1c   Etienne Pallier   moved pyros_djang...
322
    if (settings.DEBUG):
4a596eec   Alexis Koralewski   Updating SP, Sequ...
323
324
        #log.info("From album_validate")
        pass
1cffbf1c   Etienne Pallier   moved pyros_djang...
325

1cffbf1c   Etienne Pallier   moved pyros_djang...
326
    if action == "cancel":
cca89707   Alexis Koralewski   adapting observat...
327
        pass
1cffbf1c   Etienne Pallier   moved pyros_djang...
328
329
330
331
332
333
334
335
        if alb.name == "New album":
            alb.delete()
        return redirect(action_sequence, seq_id=alb.sequence.id, action="edit", status='1', message="Cancelled album modification")
    elif action == "delete":
        return redirect(action_album, alb_id, "delete")
    elif form.is_valid():
        alb = form.save()
        if action == "save":
3b81a22b   Alexis Koralewski   Rework on Request...
336
337
            return redirect(action_sequence, seq_id=alb.sequence.id, action="edit")
            #return redirect(action_album, alb_id=alb_id, action="edit", status=1, message="Album saved")
1cffbf1c   Etienne Pallier   moved pyros_djang...
338
339
340
341
342
        if action == "save_and_add":
            return redirect(create_plan, alb_id=alb_id)
    else:
        error = True
        message = "Please check your field's validity"
3b81a22b   Alexis Koralewski   Rework on Request...
343
        depth_level = 2
1cffbf1c   Etienne Pallier   moved pyros_djang...
344
        edit = True
1cffbf1c   Etienne Pallier   moved pyros_djang...
345
346
347
348
349
350
351
352
353
        seq_id = alb.sequence.id
        action = "edit"
        return render(request, "routine_manager/view_album.html", locals())

@login_required
def action_plan(request, plan_id, action, status=0, message=""):
    """
        Apply actions (view, edit, delete) on a given plan
    """
3b81a22b   Alexis Koralewski   Rework on Request...
354
355
    unit_name = os.environ["unit_name"]
    config = ConfigPyros(os.environ["PATH_TO_OBSCONF_FILE"], unit_name)
1cffbf1c   Etienne Pallier   moved pyros_djang...
356
357
    plan_id = int(plan_id)
    plan = Plan.objects.get(id=plan_id)
cca89707   Alexis Koralewski   adapting observat...
358
359
    album_name = plan.album.name 
    channel = config.getAlbumByName(config.unit_name,album_name)["CHANNELS"][0]
3b81a22b   Alexis Koralewski   Rework on Request...
360
    data_from_config = config.getEditableAttributesOfChannel(config.unit_name,channel)
1cffbf1c   Etienne Pallier   moved pyros_djang...
361
    seq_id = plan.album.sequence.id
3b81a22b   Alexis Koralewski   Rework on Request...
362
    seq = plan.album.sequence
1cffbf1c   Etienne Pallier   moved pyros_djang...
363
    alb_id = plan.album.id
3b81a22b   Alexis Koralewski   Rework on Request...
364
    depth_level = 3
4a596eec   Alexis Koralewski   Updating SP, Sequ...
365
366
    # get index of plan within the album. Adding one for human comprehension 
    index_of_plan_in_album = list(plan.album.plans.all().values_list("id",flat=True)).index(plan.id) + 1
1cffbf1c   Etienne Pallier   moved pyros_djang...
367
    if (settings.DEBUG):
4a596eec   Alexis Koralewski   Updating SP, Sequ...
368
369
        #log.info("From action_plan")
        pass
1cffbf1c   Etienne Pallier   moved pyros_djang...
370
371
372
373
374
375
376
377

    if status == "-1":
        error = True
    elif status == "1":
        success = True

    if plan.album.sequence.status != Sequence.INCOMPLETE and plan.album.sequence.status != Sequence.COMPLETE and action == "edit":
        error = True
4a596eec   Alexis Koralewski   Updating SP, Sequ...
378
        message = "You can't edit a submitted sequence"
1cffbf1c   Etienne Pallier   moved pyros_djang...
379
380
        action = "view"

4a596eec   Alexis Koralewski   Updating SP, Sequ...
381
   
1cffbf1c   Etienne Pallier   moved pyros_djang...
382
    if action == "edit":
3b81a22b   Alexis Koralewski   Rework on Request...
383
384
        form = PlanForm(edited_plan=plan, data_from_config=data_from_config)
        uneditableForm = uneditablePlanForm(data_from_config=config.getUneditableAttributesOfChannel(config.unit_name,channel))
1cffbf1c   Etienne Pallier   moved pyros_djang...
385
386
387
        edit = True
        return render(request, "routine_manager/view_plan.html", locals())
    elif action == "view":
3b81a22b   Alexis Koralewski   Rework on Request...
388
389
        form = PlanForm(edited_plan=plan, data_from_config=data_from_config,readonly=True)
        uneditableForm = uneditablePlanForm(data_from_config=config.getUneditableAttributesOfChannel(config.unit_name,channel))
1cffbf1c   Etienne Pallier   moved pyros_djang...
390
391
392
        edit = False
        return render(request, "routine_manager/view_plan.html", locals())
    elif action == "delete":
4a596eec   Alexis Koralewski   Updating SP, Sequ...
393
        log.info(f"User {request.user} did action delete Plan {plan.id} of Sequence {seq}")
1cffbf1c   Etienne Pallier   moved pyros_djang...
394
395
396
397
398
399
400
401
402
403
404
        plan.delete()
        return redirect(action_album, alb_id=plan.album.id, action="edit", status='1', message="Successfully deleted the plan")

    return redirect(requests_list)

@login_required
def plan_validate(request, plan_id):
    """
        Called when the plan form was validated.
        Possible actions : Cancel, Save, Delete
    """
3b81a22b   Alexis Koralewski   Rework on Request...
405
406
    unit_name = os.environ["unit_name"]
    config = ConfigPyros(os.environ["PATH_TO_OBSCONF_FILE"], unit_name)
1cffbf1c   Etienne Pallier   moved pyros_djang...
407
408
409
    plan_id = int(plan_id)
    action = request.POST.get("action")
    plan = Plan.objects.get(id=plan_id)
3b81a22b   Alexis Koralewski   Rework on Request...
410
411
412
413
    seq = plan.album.sequence
    name_of_channel_group = plan.album.name_of_channel_group
    channel = None
    if name_of_channel_group == "All":
cca89707   Alexis Koralewski   adapting observat...
414
        channel = config.getLayoutByName(config.unit_name,config.get_layouts(config.unit_name)["groups"][0]["name"])
3b81a22b   Alexis Koralewski   Rework on Request...
415
416
    else:
        # we retrieve config of the first channel of the group
cca89707   Alexis Koralewski   adapting observat...
417
        channel = config.getLayoutByName(config.unit_name,name_of_channel_group)["channels"][0]
3b81a22b   Alexis Koralewski   Rework on Request...
418
419
420
    data_from_config = config.getEditableAttributesOfChannel(config.unit_name,channel)
    #form = PlanForm(instance=plan, data=request.POST)
    form = PlanForm(edited_plan=plan, data_from_config=data_from_config)
1cffbf1c   Etienne Pallier   moved pyros_djang...
421
422

    if (settings.DEBUG):
4a596eec   Alexis Koralewski   Updating SP, Sequ...
423
424
        #log.info("From plan_validate")
        pass
1cffbf1c   Etienne Pallier   moved pyros_djang...
425
    if action == "cancel":
3b81a22b   Alexis Koralewski   Rework on Request...
426
427
        
        plan.delete()
1cffbf1c   Etienne Pallier   moved pyros_djang...
428
429
430
431
        return redirect(action_album, alb_id=plan.album.id, action="edit", status='1', message="Cancelled plan modification")
    elif action == "delete":
        return redirect(action_plan, plan_id, "delete")
    elif form.is_valid():
3b81a22b   Alexis Koralewski   Rework on Request...
432
        # unused
1cffbf1c   Etienne Pallier   moved pyros_djang...
433
434
        plan = form.save()
        if action == "save":
3b81a22b   Alexis Koralewski   Rework on Request...
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
            action="edit"
            status=1
            message="Plan saved"
            return redirect(action_plan, locals())
    elif action == "save":
        if request.POST:
            
            post_data = request.POST.copy()
            post_data.pop("csrfmiddlewaretoken")
            post_data.pop("action")
            nb_images = post_data.pop("nb_images")[0]
            config_attributes = {}
            for key,value in post_data.items():
                if type(value) == str:
                    try:
                        # linked values
                        new_dict = {key:{}}
                        splitted_values = value.split(";")
                        config_attributes[key] = {}
                        for splitted_value in splitted_values:
                            subkey,subvalue = splitted_value.split(":")
                            config_attributes[key][subkey] = ast.literal_eval(subvalue)
                    except:
                        # Do nothing, normal string
                        config_attributes[key] = ast.literal_eval(value)
            plan.nb_images = int(nb_images)
            plan.config_attributes = config_attributes
4a596eec   Alexis Koralewski   Updating SP, Sequ...
462
            
3b81a22b   Alexis Koralewski   Rework on Request...
463
            plan.save()
4a596eec   Alexis Koralewski   Updating SP, Sequ...
464
465
466
            if check_plan_validity(plan) == True:
                #return redirect(unsubmit_request, req_id)
                pass
3b81a22b   Alexis Koralewski   Rework on Request...
467
468
            return redirect(action_album, plan.album.id, "edit")
            #return redirect(action_plan, plan_id, "edit", 1, "Plan saved")
1cffbf1c   Etienne Pallier   moved pyros_djang...
469
470
471
472
    else:
        error = True
        message = "Please check your field's validity"
        edit = True
1cffbf1c   Etienne Pallier   moved pyros_djang...
473
474
        seq_id = plan.album.sequence.id
        alb_id = plan.album.id
3b81a22b   Alexis Koralewski   Rework on Request...
475
        depth_level = 3
1cffbf1c   Etienne Pallier   moved pyros_djang...
476
477
478
479
480
481
482
483
484
485
486
487
        return render(request, "routine_manager/view_plan.html", locals())

@login_required
def create_request(request):
    """
        Create a new request and redirects to the editing action on it
    """

    req = Request.objects.create(pyros_user=request.user, name="New request", is_alert=False, autodeposit=False, complete=False, submitted=False)
    return redirect(action_request, req.id, "edit")

@login_required
3b81a22b   Alexis Koralewski   Rework on Request...
488
def create_sequence(request):
1cffbf1c   Etienne Pallier   moved pyros_djang...
489
490
491
    """
        Create a new sequence and redirects to the editing action on it
    """
3b81a22b   Alexis Koralewski   Rework on Request...
492
493
    date_of_sequence = datetime.datetime.utcnow()
    date_of_sequence = date_of_sequence.strftime("%Y%m%dT%H%M%S")
4a596eec   Alexis Koralewski   Updating SP, Sequ...
494
495
496
497
498
    sp_of_user = request.user.get_scientific_program()
    sp_list = ScientificProgram.objects.observable_programs().filter(id__in=sp_of_user)
    if len(sp_list) == 0 :
        messages.add_message(request,messages.INFO,"Can't submit a Sequence : there is no scientific program to be assigned with")
        return redirect(requests_list)
3b81a22b   Alexis Koralewski   Rework on Request...
499
    seq = Sequence.objects.create(pyros_user=request.user, name=f"seq_{str(date_of_sequence)}", status=Sequence.INCOMPLETE)
4a596eec   Alexis Koralewski   Updating SP, Sequ...
500
    log.info(f"User {request.user} did action create Sequence {seq.name}")
1cffbf1c   Etienne Pallier   moved pyros_djang...
501
502
503
    return redirect(action_sequence, seq.id, "edit")

@login_required
cca89707   Alexis Koralewski   adapting observat...
504
def create_album(request, seq_id,album_name):
1cffbf1c   Etienne Pallier   moved pyros_djang...
505
506
507
508
509
    """
        Create a new album and redirects to the editing action on it
    """

    seq = Sequence.objects.get(id=seq_id)
cca89707   Alexis Koralewski   adapting observat...
510
    alb = Album.objects.create(sequence=seq, name=album_name, complete=False)
4a596eec   Alexis Koralewski   Updating SP, Sequ...
511
    log.info(f"User {request.user} did action create Album {alb.id} of Sequence {seq.name}")
cca89707   Alexis Koralewski   adapting observat...
512
    #return redirect(action_album, alb.id, "edit")
1cffbf1c   Etienne Pallier   moved pyros_djang...
513
514
515
516
517
518
519
520

@login_required
def create_plan(request, alb_id):
    """
        Create a new plan and redirects to the editing action on it
    """

    alb = Album.objects.get(id=alb_id)
3b81a22b   Alexis Koralewski   Rework on Request...
521
    plan = Plan.objects.create(album=alb,nb_images=1)
4a596eec   Alexis Koralewski   Updating SP, Sequ...
522
    log.info(f"User {request.user} did action create Plan {plan.id} of Sequence {plan.album.sequence.name}")
1cffbf1c   Etienne Pallier   moved pyros_djang...
523
524
525
526
527
528
529
530
531
    return redirect(action_plan, plan.id, "edit")

@login_required
def submit_request(request, req_id, redir):
    """
        Submits a request and its sequences for scheduling
    """

    if (settings.DEBUG):
4a596eec   Alexis Koralewski   Updating SP, Sequ...
532
        pass
1cffbf1c   Etienne Pallier   moved pyros_djang...
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
        log.info("From submit_request")

    req = Request.objects.get(id=req_id)
    error = False
    if req.complete == False:
        error = True
        message = "A request must be complete to be submitted"
    elif req.submitted == True:
        error = True
        message = "The request is already submitted"

    if error == True:
        return redirect(action_request, req_id=req_id, action="view", status=-1, message=message)

    for seq in req.sequences.all():
        seq.status = Sequence.TOBEPLANNED
        seq.save()
    req.submitted = True
    req.save()

    # TODO : changer le first_schedule ...
    '''
    if settings.USE_CELERY:
        print("WITH CELERY")
        scheduler.tasks.scheduling.delay(first_schedule=True, alert=False)
    else:
    '''
    print("Change 1st schedule")
    scheduler.tasks.scheduling().run(first_schedule=True, alert=False)

    message = "The request was submitted"
    if redir == "action_request":
        return redirect(action_request, req_id=req_id, action="view", status=1, message=message)
    else:
        return redirect(requests_list, status=1, message=message)

@login_required
def unsubmit_request(request, req_id):
    """
        Unsubmits a request and remove its sequences from scheduling
    """

    if (settings.DEBUG):
4a596eec   Alexis Koralewski   Updating SP, Sequ...
576
        pass
1cffbf1c   Etienne Pallier   moved pyros_djang...
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
        log.info("From unsubmit_request")

    req = Request.objects.get(id=req_id)

# TODO: uncomment pour la production
#     if req.sequences.filter(Q(status=Sequence.EXECUTED) | Q(status=Sequence.EXECUTING)).exists():
#         message = "You can't unsubmit a request with executed sequences"
#         return redirect(action_request, req_id=req_id, action="view", status=-1, message=message)

    req.submitted = False
    req.save()
    sequences = req.sequences.filter(Q(status=Sequence.TOBEPLANNED) | Q(status=Sequence.PLANNED) |
                                        Q(status=Sequence.INVALID) | Q(status=Sequence.UNPLANNABLE))
    for seq in sequences:
        seq.status = Sequence.COMPLETE
        seq.save()
    # TODO: uncomment
    # scheduler.tasks.scheduling.delay(first_schedule=True, alert=False)  # TODO : changer le first_schedule ...

    if req.complete == True:
        message = "The request was unsubmitted"
    else:
        message = "The request was unsubmitted because it is incomplete"
    return redirect(action_request, req_id=req_id, action="edit", status=1, message=message)

@login_required
def export_request(request, req_id):
    """
        Create an XML file with the given request, and send a download request to the user
    """

    if (settings.DEBUG):
4a596eec   Alexis Koralewski   Updating SP, Sequ...
609
610
        #log.info("From export_request")
        pass
1cffbf1c   Etienne Pallier   moved pyros_djang...
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638

    req = Request.objects.get(id=req_id)
    if req.complete == False:
        message = "Request must be completely valid to be serialized"
        return redirect(action_request, req_id=req_id, action="view", status=-1, message=message)

    file_name = SAVED_REQUESTS_FOLDER + "request" + str(req.id) + ".xml"
    rs = RequestSerializer()
    rs.serialize(req, file_name)

    wrapper = FileWrapper(open(file_name, "r"))
    content_type = mimetypes.guess_type(file_name)[0]

    response = HttpResponse(wrapper, content_type=content_type)
    response['Content-Length'] = os.path.getsize(file_name)
    response['Content-Disposition'] = 'attachment; filename=%s' % smart_str(os.path.basename(file_name))

    return response

@login_required
@csrf_exempt
def import_request(request):
    """
        Ask for a XML file, parse it and create a request in DB
        Don't do anything if there is a single error into the file
    """

    if (settings.DEBUG):
4a596eec   Alexis Koralewski   Updating SP, Sequ...
639
640
        pass
        #log.info("From import_request")
1cffbf1c   Etienne Pallier   moved pyros_djang...
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666

    log.info(request)

    if request.method == "POST":
        file = request.FILES.get("request_file")
        if file is None:
            status = -1
            message = "File does not exist"
        elif file.size > 1000000:
            status = -1
            message = "File is too big (more than 1 000 000 bytes)"
        else:
            rs = RequestSerializer()
            message = rs.unserialize(file.read(), request.user)
            if message != "":
                status = -1
            else:
                status = 1
                message = "Request imported successfully. Please check it before submitting for scheduling."
        print("message is", message)
    else:
        status = -1
        message = "Internal error"

    # Now, display the list of requests (updated with this new request)
    return redirect(requests_list, status=status, message=message)
3b81a22b   Alexis Koralewski   Rework on Request...
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697

@login_required
def test_create_plan(request):
    config = ConfigPyros(os.environ["PATH_TO_OBSCONF_FILE"],os.environ["unit_name"])
    if request.POST:
        
        post_data = request.POST.copy()
        post_data.pop("csrfmiddlewaretoken")
        nb_images = post_data.pop("nb_images")[0]
        config_attributes = {}
        for key,value in post_data.items():
            if type(value) == str:
                try:
                    # linked values
                    new_dict = {key:{}}
                    splitted_values = value.split(";")
                    config_attributes[key] = {}
                    for splitted_value in splitted_values:
                        subkey,subvalue = splitted_value.split(":")
                        config_attributes[key][subkey] = ast.literal_eval(subvalue)
                except:
                    # Do nothing, normal string
                    config_attributes[key] = ast.literal_eval(value)
        plan = Plan()
        plan.nb_images = int(nb_images)
        plan.config_attributes = config_attributes
        plan.save()
    form = PlanForm(data_from_config=config.getEditableAttributesOfChannel(config.unit_name,list(config.get_channels(config.unit_name).keys())[0]))
    uneditableForm = uneditablePlanForm(data_from_config=config.getUneditableAttributesOfChannel(config.unit_name,list(config.get_channels(config.unit_name).keys())[0]))
    return render(request,"routine_manager/testcreateplan.html",{"form":form,"uneditableForm":uneditableForm})

cca89707   Alexis Koralewski   adapting observat...
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719

@login_required
def create_albums(request,seq_id,layout):
    seq = Sequence.objects.get(id=seq_id)
    unit_name = os.environ["unit_name"]
    config = ConfigPyros(os.environ["PATH_TO_OBSCONF_FILE"], unit_name)
    albums = config.getLayoutByName(unit_name=config.unit_name,name_of_layout=layout)["ALBUMS"]
    for album_name in albums:
        create_album(request,seq_id,album_name=album_name)
        #return redirect(create_album, seq_id=seq_id)
    messages.add_message(request,messages.INFO,"Created album(s) according to chosen layout")
    return HttpResponse("ok")



@login_required
def delete_albums(request,seq_id):
    seq = Sequence.objects.get(id=seq_id)
    albums = Album.objects.filter(sequence=seq).delete()
    return HttpResponse(albums)


3b81a22b   Alexis Koralewski   Rework on Request...
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
@login_required
def edit_plan(request,id):
    plan = get_object_or_404(Plan,pk=id)
    config = ConfigPyros(os.environ["PATH_TO_OBSCONF_FILE"],os.environ["unit_name"])
    if request.POST:
        
        post_data = request.POST.copy()
        post_data.pop("csrfmiddlewaretoken")
        nb_images = post_data.pop("nb_images")[0]
        config_attributes = {}
        for key,value in post_data.items():
            if type(value) == str:
                try:
                    # linked values
                    new_dict = {key:{}}
                    splitted_values = value.split(";")
                    config_attributes[key] = {}
                    for splitted_value in splitted_values:
                        subkey,subvalue = splitted_value.split(":")
                        config_attributes[key][subkey] = ast.literal_eval(subvalue)
                except:
                    # Do nothing, normal string
                    config_attributes[key] = ast.literal_eval(value)
        plan.nb_images = int(nb_images)
        plan.config_attributes = config_attributes
        plan.save()
    form = PlanForm(data_from_config=config.getEditableAttributesOfChannel(config.unit_name,list(config.get_channels(config.unit_name).keys())[0]),edited_plan=plan)
    uneditableForm = uneditablePlanForm(data_from_config=config.getUneditableAttributesOfChannel(config.unit_name,list(config.get_channels(config.unit_name).keys())[0]))
    return render(request,"routine_manager/testcreateplan.html",{"form":form,"uneditableForm":uneditableForm})