Refactor selector step logic
[pharos-tools.git] / dashboard / src / workflow / forms.py
1 ##############################################################################
2 # Copyright (c) 2018 Sawyer Bergeron, Parker Berberian, and others.
3 #
4 # All rights reserved. This program and the accompanying materials
5 # are made available under the terms of the Apache License, Version 2.0
6 # which accompanies this distribution, and is available at
7 # http://www.apache.org/licenses/LICENSE-2.0
8 ##############################################################################
9
10
11 import django.forms as forms
12 from django.forms import widgets, ValidationError
13 from django.utils.safestring import mark_safe
14 from django.template.loader import render_to_string
15 from django.forms.widgets import NumberInput
16
17 import json
18
19 from account.models import Lab
20 from account.models import UserProfile
21 from resource_inventory.models import (
22     OPNFVRole,
23     Installer,
24     Scenario,
25 )
26 from booking.lib import get_user_items, get_user_field_opts
27
28
29 class SearchableSelectMultipleWidget(widgets.SelectMultiple):
30     template_name = 'dashboard/searchable_select_multiple.html'
31
32     def __init__(self, attrs=None):
33         self.items = attrs['items']
34         self.show_from_noentry = attrs['show_from_noentry']
35         self.show_x_results = attrs['show_x_results']
36         self.results_scrollable = attrs['results_scrollable']
37         self.selectable_limit = attrs['selectable_limit']
38         self.placeholder = attrs['placeholder']
39         self.name = attrs['name']
40         self.initial = attrs.get("initial", [])
41
42         super(SearchableSelectMultipleWidget, self).__init__()
43
44     def render(self, name, value, attrs=None, renderer=None):
45
46         context = self.get_context(attrs)
47         return mark_safe(render_to_string(self.template_name, context))
48
49     def get_context(self, attrs):
50         return {
51             'items': self.items,
52             'name': self.name,
53             'show_from_noentry': self.show_from_noentry,
54             'show_x_results': self.show_x_results,
55             'results_scrollable': self.results_scrollable,
56             'selectable_limit': self.selectable_limit,
57             'placeholder': self.placeholder,
58             'initial': self.initial,
59         }
60
61
62 class SearchableSelectMultipleField(forms.Field):
63     def __init__(self, *args, required=True, widget=None, label=None, disabled=False,
64                  items=None, queryset=None, show_from_noentry=True, show_x_results=-1,
65                  results_scrollable=False, selectable_limit=-1, placeholder="search here",
66                  name="searchable_select", initial=[], **kwargs):
67         """from the documentation:
68         # required -- Boolean that specifies whether the field is required.
69         #             True by default.
70         # widget -- A Widget class, or instance of a Widget class, that should
71         #           be used for this Field when displaying it. Each Field has a
72         #           default Widget that it'll use if you don't specify this. In
73         #           most cases, the default widget is TextInput.
74         # label -- A verbose name for this field, for use in displaying this
75         #          field in a form. By default, Django will use a "pretty"
76         #          version of the form field name, if the Field is part of a
77         #          Form.
78         # initial -- A value to use in this Field's initial display. This value
79         #            is *not* used as a fallback if data isn't given.
80         # help_text -- An optional string to use as "help text" for this Field.
81         # error_messages -- An optional dictionary to override the default
82         #                   messages that the field will raise.
83         # show_hidden_initial -- Boolean that specifies if it is needed to render a
84         #                        hidden widget with initial value after widget.
85         # validators -- List of additional validators to use
86         # localize -- Boolean that specifies if the field should be localized.
87         # disabled -- Boolean that specifies whether the field is disabled, that
88         #             is its widget is shown in the form but not editable.
89         # label_suffix -- Suffix to be added to the label. Overrides
90         #                 form's label_suffix.
91         """
92
93         self.widget = widget
94         if self.widget is None:
95             self.widget = SearchableSelectMultipleWidget(
96                 attrs={
97                     'items': items,
98                     'initial': [obj.id for obj in initial],
99                     'show_from_noentry': show_from_noentry,
100                     'show_x_results': show_x_results,
101                     'results_scrollable': results_scrollable,
102                     'selectable_limit': selectable_limit,
103                     'placeholder': placeholder,
104                     'name': name,
105                     'disabled': disabled
106                 }
107             )
108         self.disabled = disabled
109         self.queryset = queryset
110         self.selectable_limit = selectable_limit
111
112         super().__init__(disabled=disabled, **kwargs)
113
114         self.required = required
115
116     def clean(self, data):
117         data = data[0]
118         if not data:
119             if self.required:
120                 raise ValidationError("Nothing was selected")
121             else:
122                 return []
123         data_as_list = json.loads(data)
124         if self.selectable_limit != -1:
125             if len(data_as_list) > self.selectable_limit:
126                 raise ValidationError("Too many items were selected")
127
128         items = []
129         for elem in data_as_list:
130             items.append(self.queryset.get(id=elem))
131
132         return items
133
134
135 class SearchableSelectAbstractForm(forms.Form):
136     def __init__(self, *args, queryset=None, initial=[], **kwargs):
137         self.queryset = queryset
138         items = self.generate_items(self.queryset)
139         options = self.generate_options()
140
141         super(SearchableSelectAbstractForm, self).__init__(*args, **kwargs)
142         self.fields['searchable_select'] = SearchableSelectMultipleField(
143             initial=initial,
144             items=items,
145             queryset=self.queryset,
146             **options
147         )
148
149     def get_validated_bundle(self):
150         bundles = self.cleaned_data['searchable_select']
151         if len(bundles) < 1:  # don't need to check for >1, as field does that for us
152             raise ValidationError("No bundle was selected")
153         return bundles[0]
154
155     def generate_items(self, queryset):
156         raise Exception("SearchableSelectAbstractForm does not implement concrete generate_items()")
157
158     def generate_options(self, disabled=False):
159         return {
160             'show_from_noentry': True,
161             'show_x_results': -1,
162             'results_scrollable': True,
163             'selectable_limit': 1,
164             'placeholder': 'Search for a Bundle',
165             'name': 'searchable_select',
166             'disabled': False
167         }
168
169
170 class SWConfigSelectorForm(SearchableSelectAbstractForm):
171     def generate_items(self, queryset):
172         items = {}
173
174         for bundle in queryset:
175             item = {}
176             item['small_name'] = bundle.name
177             item['expanded_name'] = bundle.owner.username
178             item['string'] = bundle.description
179             item['id'] = bundle.id
180             items[bundle.id] = item
181
182         return items
183
184
185 class ResourceSelectorForm(SearchableSelectAbstractForm):
186     def generate_items(self, queryset):
187         items = {}
188
189         for bundle in queryset:
190             item = {}
191             item['small_name'] = bundle.name
192             item['expanded_name'] = bundle.owner.username
193             item['string'] = bundle.description
194             item['id'] = bundle.id
195             items[bundle.id] = item
196
197         return items
198
199
200 class BookingMetaForm(forms.Form):
201
202     length = forms.IntegerField(
203         widget=NumberInput(
204             attrs={
205                 "type": "range",
206                 'min': "1",
207                 "max": "21",
208                 "value": "1"
209             }
210         )
211     )
212     purpose = forms.CharField(max_length=1000)
213     project = forms.CharField(max_length=400)
214     info_file = forms.CharField(max_length=1000, required=False)
215
216     def __init__(self, *args, user_initial=[], owner=None, **kwargs):
217         super(BookingMetaForm, self).__init__(**kwargs)
218
219         self.fields['users'] = SearchableSelectMultipleField(
220             queryset=UserProfile.objects.select_related('user').exclude(user=owner),
221             initial=user_initial,
222             items=get_user_items(exclude=owner),
223             required=False,
224             **get_user_field_opts()
225         )
226
227
228 class MultipleSelectFilterWidget(forms.Widget):
229     def __init__(self, attrs=None):
230         super(MultipleSelectFilterWidget, self).__init__(attrs)
231         self.attrs = attrs
232         self.template_name = "dashboard/multiple_select_filter_widget.html"
233
234     def render(self, name, value, attrs=None, renderer=None):
235         attrs = self.attrs
236         self.context = self.get_context(name, value, attrs)
237         html = render_to_string(self.template_name, context=self.context)
238         return mark_safe(html)
239
240     def get_context(self, name, value, attrs):
241         return attrs
242
243
244 class MultipleSelectFilterField(forms.Field):
245
246     def __init__(self, required=True, widget=None, label=None, initial=None,
247                  help_text='', error_messages=None, show_hidden_initial=False,
248                  validators=(), localize=False, disabled=False, label_suffix=None):
249         """from the documentation:
250         # required -- Boolean that specifies whether the field is required.
251         #             True by default.
252         # widget -- A Widget class, or instance of a Widget class, that should
253         #           be used for this Field when displaying it. Each Field has a
254         #           default Widget that it'll use if you don't specify this. In
255         #           most cases, the default widget is TextInput.
256         # label -- A verbose name for this field, for use in displaying this
257         #          field in a form. By default, Django will use a "pretty"
258         #          version of the form field name, if the Field is part of a
259         #          Form.
260         # initial -- A value to use in this Field's initial display. This value
261         #            is *not* used as a fallback if data isn't given.
262         # help_text -- An optional string to use as "help; text" for this Field.
263         # error_messages -- An optional dictionary to override the default
264         #                   messages that the field will raise.
265         # show_hidden_initial -- Boolean that specifies if it is needed to render a
266         #                        hidden widget with initial value after widget.
267         # validators -- List of additional validators to use
268         # localize -- Boolean that specifies if the field should be localized.
269         # disabled -- Boolean that specifies whether the field is disabled, that
270         #             is its widget is shown in the form but not editable.
271         # label_suffix -- Suffix to be added to the label. Overrides
272         #                 form's label_suffix.
273         """
274         # this is bad, but django forms are annoying
275         self.widget = widget
276         if self.widget is None:
277             self.widget = MultipleSelectFilterWidget()
278         super(MultipleSelectFilterField, self).__init__(
279             required=required,
280             widget=self.widget,
281             label=label,
282             initial=None,
283             help_text=help_text,
284             error_messages=error_messages,
285             show_hidden_initial=show_hidden_initial,
286             validators=validators,
287             localize=localize,
288             disabled=disabled,
289             label_suffix=label_suffix
290         )
291
292         def clean(data):
293             """
294             This method will raise a django.forms.ValidationError or return clean data
295             """
296             return data
297
298
299 class FormUtils:
300     @staticmethod
301     def getLabData(multiple_selectable_hosts):
302         """
303         Gets all labs and thier host profiles and returns a serialized version the form can understand.
304         Should be rewritten with a related query to make it faster
305         Should be moved outside of global scope
306         """
307         labs = {}
308         hosts = {}
309         items = {}
310         mapping = {}
311         for lab in Lab.objects.all():
312             slab = {}
313             slab['id'] = "lab_" + str(lab.lab_user.id)
314             slab['name'] = lab.name
315             slab['description'] = lab.description
316             slab['selected'] = 0
317             slab['selectable'] = 1
318             slab['follow'] = 1
319             if not multiple_selectable_hosts:
320                 slab['follow'] = 0
321             slab['multiple'] = 0
322             items[slab['id']] = slab
323             mapping[slab['id']] = []
324             labs[slab['id']] = slab
325             for host in lab.hostprofiles.all():
326                 shost = {}
327                 shost['forms'] = [{"name": "host_name", "type": "text", "placeholder": "hostname"}]
328                 shost['id'] = "host_" + str(host.id)
329                 shost['name'] = host.name
330                 shost['description'] = host.description
331                 shost['selected'] = 0
332                 shost['selectable'] = 1
333                 shost['follow'] = 0
334                 shost['multiple'] = multiple_selectable_hosts
335                 items[shost['id']] = shost
336                 mapping[slab['id']].append(shost['id'])
337                 if shost['id'] not in mapping:
338                     mapping[shost['id']] = []
339                 mapping[shost['id']].append(slab['id'])
340                 hosts[shost['id']] = shost
341
342         filter_objects = [("labs", labs.values()), ("hosts", hosts.values())]
343
344         context = {
345             'filter_objects': filter_objects,
346             'mapping': mapping,
347             'filter_items': items
348         }
349         return context
350
351
352 class HardwareDefinitionForm(forms.Form):
353
354     def __init__(self, *args, **kwargs):
355         selection_data = kwargs.pop("selection_data", False)
356         super(HardwareDefinitionForm, self).__init__(*args, **kwargs)
357         attrs = FormUtils.getLabData(1)
358         attrs['selection_data'] = selection_data
359         self.fields['filter_field'] = MultipleSelectFilterField(
360             widget=MultipleSelectFilterWidget(
361                 attrs=attrs
362             )
363         )
364
365
366 class PodDefinitionForm(forms.Form):
367
368     fields = ["xml"]
369     xml = forms.CharField()
370
371
372 class ResourceMetaForm(forms.Form):
373
374     bundle_name = forms.CharField(label="POD Name")
375     bundle_description = forms.CharField(label="POD Description", widget=forms.Textarea)
376
377
378 class GenericHostMetaForm(forms.Form):
379
380     host_profile = forms.CharField(label="Host Type", disabled=True, required=False)
381     host_name = forms.CharField(label="Host Name")
382
383
384 class NetworkDefinitionForm(forms.Form):
385     def __init__(self, *args, **kwargs):
386         super(NetworkDefinitionForm, self).__init__(**kwargs)
387
388
389 class NetworkConfigurationForm(forms.Form):
390     def __init__(self, *args, **kwargs):
391         super(NetworkConfigurationForm).__init__(**kwargs)
392
393
394 class HostSoftwareDefinitionForm(forms.Form):
395
396     host_name = forms.CharField(max_length=200, disabled=True, required=False)
397     headnode = forms.BooleanField(required=False, widget=forms.HiddenInput)
398
399     def __init__(self, *args, **kwargs):
400         imageQS = kwargs.pop("imageQS")
401         super(HostSoftwareDefinitionForm, self).__init__(*args, **kwargs)
402         self.fields['image'] = forms.ModelChoiceField(queryset=imageQS)
403
404
405 class WorkflowSelectionForm(forms.Form):
406     fields = ['workflow']
407
408     empty_permitted = False
409
410     workflow = forms.ChoiceField(
411         choices=(
412             (0, 'Booking'),
413             (1, 'Resource Bundle'),
414             (2, 'Software Configuration')
415         ),
416         label="Choose Workflow",
417         initial='booking',
418         required=True
419     )
420
421
422 class SnapshotHostSelectForm(forms.Form):
423     host = forms.CharField()
424
425
426 class BasicMetaForm(forms.Form):
427     name = forms.CharField()
428     description = forms.CharField(widget=forms.Textarea)
429
430
431 class ConfirmationForm(forms.Form):
432     fields = ['confirm']
433
434     confirm = forms.ChoiceField(
435         choices=(
436             (True, "Confirm"),
437             (False, "Cancel")
438         )
439     )
440
441
442 class OPNFVSelectionForm(forms.Form):
443     installer = forms.ModelChoiceField(queryset=Installer.objects.all(), required=True)
444     scenario = forms.ModelChoiceField(queryset=Scenario.objects.all(), required=True)
445
446
447 class OPNFVNetworkRoleForm(forms.Form):
448     role = forms.CharField(max_length=200, disabled=True, required=False)
449
450     def __init__(self, *args, config_bundle, **kwargs):
451         super(OPNFVNetworkRoleForm, self).__init__(*args, **kwargs)
452         self.fields['network'] = forms.ModelChoiceField(
453             queryset=config_bundle.bundle.networks.all()
454         )
455
456
457 class OPNFVHostRoleForm(forms.Form):
458     host_name = forms.CharField(max_length=200, disabled=True, required=False)
459     role = forms.ModelChoiceField(queryset=OPNFVRole.objects.all().order_by("name").distinct("name"))