diff options
64 files changed, 2005 insertions, 1845 deletions
diff --git a/requirements.txt b/requirements.txt index 9ea10a4..55e5fc9 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,7 +1,7 @@ celery==3.1.23 cryptography==2.3.1 Django==2.1 -django-bootstrap3==10.0.1 +django-bootstrap4==0.0.8 django-crispy-forms==1.7.2 django-filter==2.0.0 django-registration==2.1.2 diff --git a/src/booking/forms.py b/src/booking/forms.py index de427ab..df88cc6 100644 --- a/src/booking/forms.py +++ b/src/booking/forms.py @@ -10,12 +10,13 @@ import django.forms as forms from django.forms.widgets import NumberInput from workflow.forms import ( - SearchableSelectMultipleWidget, MultipleSelectFilterField, MultipleSelectFilterWidget, FormUtils) from account.models import UserProfile from resource_inventory.models import Image, Installer, Scenario +from workflow.forms import SearchableSelectMultipleField +from booking.lib import get_user_items, get_user_field_opts class QuickBookingForm(forms.Form): @@ -27,16 +28,11 @@ class QuickBookingForm(forms.Form): scenario = forms.ModelChoiceField(queryset=Scenario.objects.all(), required=False) def __init__(self, data=None, user=None, *args, **kwargs): - chosen_users = [] if "default_user" in kwargs: default_user = kwargs.pop("default_user") else: default_user = "you" self.default_user = default_user - if "chosen_users" in kwargs: - chosen_users = kwargs.pop("chosen_users") - elif data and "users" in data: - chosen_users = data.getlist("users") super(QuickBookingForm, self).__init__(data=data, **kwargs) @@ -44,15 +40,15 @@ class QuickBookingForm(forms.Form): Image.objects.filter(public=True) | Image.objects.filter(owner=user) ) - self.fields['users'] = forms.CharField( - widget=SearchableSelectMultipleWidget( - attrs=self.build_search_widget_attrs(chosen_users, default_user=default_user) - ), - required=False + self.fields['users'] = SearchableSelectMultipleField( + queryset=UserProfile.objects.select_related('user').exclude(user=user), + items=get_user_items(exclude=user), + required=False, + **get_user_field_opts() ) + attrs = FormUtils.getLabData(0) - attrs['selection_data'] = 'false' - self.fields['filter_field'] = MultipleSelectFilterField(widget=MultipleSelectFilterWidget(attrs=attrs)) + self.fields['filter_field'] = MultipleSelectFilterField(widget=MultipleSelectFilterWidget(**attrs)) self.fields['length'] = forms.IntegerField( widget=NumberInput( attrs={ diff --git a/src/booking/lib.py b/src/booking/lib.py new file mode 100644 index 0000000..8132c75 --- /dev/null +++ b/src/booking/lib.py @@ -0,0 +1,36 @@ +############################################################################## +# Copyright (c) 2019 Parker Berberian, Sawyer Bergeron, and others. +# +# All rights reserved. This program and the accompanying materials +# are made available under the terms of the Apache License, Version 2.0 +# which accompanies this distribution, and is available at +# http://www.apache.org/licenses/LICENSE-2.0 +############################################################################## + +from account.models import UserProfile + + +def get_user_field_opts(): + return { + 'show_from_noentry': False, + 'show_x_results': 5, + 'results_scrollable': True, + 'selectable_limit': -1, + 'placeholder': 'Search for other users', + 'name': 'users', + 'disabled': False + } + + +def get_user_items(exclude=None): + qs = UserProfile.objects.select_related('user').exclude(user=exclude) + items = {} + for up in qs: + item = { + 'id': up.id, + 'expanded_name': up.full_name, + 'small_name': up.user.username, + 'string': up.email_addr + } + items[up.id] = item + return items diff --git a/src/booking/quick_deployer.py b/src/booking/quick_deployer.py index 763c8a0..0e0cc5a 100644 --- a/src/booking/quick_deployer.py +++ b/src/booking/quick_deployer.py @@ -12,7 +12,6 @@ import json import uuid import re from django.db.models import Q -from django.contrib.auth.models import User from datetime import timedelta from django.utils import timezone from account.models import Lab @@ -97,25 +96,22 @@ class BookingPermissionException(Exception): pass -def parse_host_field(host_field_contents): - host_json = json.loads(host_field_contents) - lab_dict = host_json['labs'][0] - lab_id = list(lab_dict.keys())[0] - lab_user_id = int(lab_id.split("_")[-1]) - lab = Lab.objects.get(lab_user__id=lab_user_id) +def parse_host_field(host_json): + lab, profile = (None, None) + lab_dict = host_json['lab'] + for lab_info in lab_dict.values(): + if lab_info['selected']: + lab = Lab.objects.get(lab_user__id=lab_info['id']) - host_dict = host_json['hosts'][0] - profile_id = list(host_dict.keys())[0] - profile_id = int(profile_id.split("_")[-1]) - profile = HostProfile.objects.get(id=profile_id) + host_dict = host_json['host'] + for host_info in host_dict.values(): + if host_info['selected']: + profile = HostProfile.objects.get(pk=host_info['id']) - # check validity of field data before trying to apply to models - if len(host_json['labs']) != 1: + if lab is None: raise NoLabSelectedError("No lab was selected") - if not lab: - raise LabDNE("Lab with provided ID does not exist") - if not profile: - raise HostProfileDNE("Host type with provided ID does not exist") + if profile is None: + raise HostProfileDNE("No Host was selected") return lab, profile @@ -321,12 +317,8 @@ def create_from_form(form, request): ) booking.pdf = PDFTemplater.makePDF(booking) - users_field = users_field[2:-2] - if users_field: # may be empty after split, if no collaborators entered - users_field = json.loads(users_field) - for collaborator in users_field: - user = User.objects.get(id=collaborator['id']) - booking.collaborators.add(user) + for collaborator in users_field: # list of UserProfiles + booking.collaborators.add(collaborator.user) booking.save() @@ -334,6 +326,8 @@ def create_from_form(form, request): JobFactory.makeCompleteJob(booking) NotificationHandler.notify_new_booking(booking) + return booking + def drop_filter(user): installer_filter = {} diff --git a/src/booking/stats.py b/src/booking/stats.py index b706577..383723a 100644 --- a/src/booking/stats.py +++ b/src/booking/stats.py @@ -25,34 +25,34 @@ class StatisticsManager(object): some point in the given date span is the number of days to plot. The last x value will always be the current time """ - x_set = set() + data = [] x = [] y = [] users = [] now = datetime.datetime.now(pytz.utc) delta = datetime.timedelta(days=span) end = now - delta - bookings = Booking.objects.filter(start__lte=now, end__gte=end) - for booking in bookings: - x_set.add(booking.start) - if booking.end < now: - x_set.add(booking.end) + bookings = Booking.objects.filter(start__lte=now, end__gte=end).prefetch_related("collaborators") + for booking in bookings: # collect data from each booking + user_list = [u.pk for u in booking.collaborators.all()] + user_list.append(booking.owner.pk) + data.append((booking.start, 1, user_list)) + data.append((booking.end, -1, user_list)) - x_set.add(now) - x_set.add(end) + # sort based on time + data.sort(key=lambda i: i[0]) - x_list = list(x_set) - x_list.sort(reverse=True) - for time in x_list: - x.append(str(time)) - active = Booking.objects.filter(start__lte=time, end__gt=time) - booking_count = len(active) - users_set = set() - for booking in active: - users_set.add(booking.owner) - for user in booking.collaborators.all(): - users_set.add(user) - y.append(booking_count) - users.append(len(users_set)) + # collect data + count = 0 + active_users = {} + for datum in data: + x.append(str(datum[0])) # time + count += datum[1] # booking count + y.append(count) + for pk in datum[2]: # maintain count of each user's active bookings + active_users[pk] = active_users.setdefault(pk, 0) + datum[1] + if active_users[pk] == 0: + del active_users[pk] + users.append(len([x for x in active_users.values() if x > 0])) return {"booking": [x, y], "user": [x, users]} diff --git a/src/booking/views.py b/src/booking/views.py index 8211a0c..bad7dc9 100644 --- a/src/booking/views.py +++ b/src/booking/views.py @@ -16,6 +16,7 @@ from django.views import View from django.views.generic import TemplateView from django.shortcuts import redirect, render from django.db.models import Q +from django.urls import reverse from resource_inventory.models import ResourceBundle, HostProfile, Image, Host from resource_inventory.resource_manager import ResourceManager @@ -47,7 +48,7 @@ def quick_create(request): context['lab_profile_map'] = profiles - context['form'] = QuickBookingForm(initial={}, chosen_users=[], default_user=request.user.username, user=request.user) + context['form'] = QuickBookingForm(default_user=request.user.username, user=request.user) context.update(drop_filter(request.user)) @@ -60,14 +61,13 @@ def quick_create(request): if form.is_valid(): try: - create_from_form(form, request) + booking = create_from_form(form, request) + messages.success(request, "We've processed your request. " + "Check Account->My Bookings for the status of your new booking") + return redirect(reverse('booking:booking_detail', kwargs={'booking_id': booking.id})) except Exception as e: messages.error(request, "Whoops, an error occurred: " + str(e)) - return render(request, 'workflow/exit_redirect.html', context) - - messages.success(request, "We've processed your request. " - "Check Account->My Bookings for the status of your new booking") - return render(request, 'workflow/exit_redirect.html', context) + return render(request, 'booking/quick_deploy.html', context) else: messages.error(request, "Looks like the form didn't validate. Check that you entered everything correctly") return render(request, 'booking/quick_deploy.html', context) diff --git a/src/pharos_dashboard/settings.py b/src/pharos_dashboard/settings.py index 793eec7..86de78c 100644 --- a/src/pharos_dashboard/settings.py +++ b/src/pharos_dashboard/settings.py @@ -35,7 +35,7 @@ INSTALLED_APPS = [ 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.humanize', - 'bootstrap3', + 'bootstrap4', 'crispy_forms', 'rest_framework', 'rest_framework.authtoken', diff --git a/src/static/bower.json b/src/static/bower.json index 9ae744a..dda786d 100644 --- a/src/static/bower.json +++ b/src/static/bower.json @@ -16,12 +16,14 @@ "tests" ], "dependencies": { - "eonasdan-bootstrap-datetimepicker": "^4.17.37", "fullcalendar": "^2.9.0", "jquery-migrate": "^3.0.0", - "startbootstrap-sb-admin-2-blackrockdigital": "^3.3.7" - }, - "resolutions": { - "font-awesome": "~4.6.3" + "bootstrap": "4.3.1", + "popper.js": "1.14.3", + "Font-Awesome": "5.9.0", + "datatables.net": "1.10.19", + "datatables.net-bs4": "1.10.19", + "datatables.net-responsive": "2.1.1", + "datatables.net-responsive-bs4": "2.2.3" } } diff --git a/src/static/css/base.css b/src/static/css/base.css new file mode 100644 index 0000000..c51728c --- /dev/null +++ b/src/static/css/base.css @@ -0,0 +1,8 @@ +/* Rotating arrows when dropdown happens */ +i.fas.rotate { + transition: transform 0.3s ease-in-out; +} + +a[aria-expanded="true"] > i.rotate { + transform: rotate(180deg); +} diff --git a/src/templates/account/booking_list.html b/src/templates/account/booking_list.html index ed59b81..98ab5c8 100644 --- a/src/templates/account/booking_list.html +++ b/src/templates/account/booking_list.html @@ -3,9 +3,11 @@ <h2>Bookings I Own</h2> <div class="card_container"> {% for booking in bookings %} - <div class="detail_card"> - <div> + <div class="card"> + <div class="card-header"> <h3>Booking {{booking.id}}</h3> + </div> + <div class="card-body"> <ul class="list-group"> <li class="list-group-item">id: {{booking.id}}</li> <li class="list-group-item">lab: {{booking.lab}}</li> @@ -15,8 +17,8 @@ <li class="list-group-item">purpose: {{booking.purpose}}</li> </ul> </div> - <div class="detail_button_container"> - <a class="btn btn-primary" href="/booking/detail/{{booking.id}}/">Details</a> + <div class="card-footer d-flex"> + <a class="btn btn-primary ml-auto mr-2" href="/booking/detail/{{booking.id}}/">Details</a> <button class="btn btn-danger" onclick='cancel_booking({{booking.id}});' @@ -29,32 +31,37 @@ </div> <h2>Bookings I Collaborate On</h2> <div class="card_container"> - {% for booking in collab_bookings %} - <div class="detail_card"> - <div> - <h3>Booking {{booking.id}}</h3> - <ul class="list-group"> - <li class="list-group-item">id: {{booking.id}}</li> - <li class="list-group-item">lab: {{booking.lab}}</li> - <li class="list-group-item">resource: {{booking.resource.template.name}}</li> - <li class="list-group-item">start: {{booking.start}}</li> - <li class="list-group-item">end: {{booking.end}}</li> - <li class="list-group-item">purpose: {{booking.purpose}}</li> - </ul> + {% for booking in collab_bookings %} + <div class="card"> + <div class="card-header"> + <h3>Booking {{booking.id}}</h3> + </div> + <div class="card-body"> + <ul class="list-group"> + <li class="list-group-item">id: {{booking.id}}</li> + <li class="list-group-item">lab: {{booking.lab}}</li> + <li class="list-group-item">resource: {{booking.resource.template.name}}</li> + <li class="list-group-item">start: {{booking.start}}</li> + <li class="list-group-item">end: {{booking.end}}</li> + <li class="list-group-item">purpose: {{booking.purpose}}</li> + </ul> + </div> + <div class="card-footer d-flex"> + <a class="btn btn-primary ml-auto" href="/booking/detail/{{booking.id}}/">Details</a> + </div> </div> - <a class="btn btn-primary" href="/booking/detail/{{booking.id}}/">Details</a> - </div> - {% endfor %} + {% endfor %} </div> - <h2>Expired Bookings <i class="fa fa-fw fa-caret-down" onclick='toggle_display("expired_bookings");'></i> </h2> <div id="expired_bookings" class="card_container" style="display:none;"> {% for booking in expired_bookings %} - <div class="detail_card"> - <div> + <div class="card"> + <div class="card-header"> <h3>Booking {{booking.id}}</h3> + </div> + <div class="card-body"> <ul class="list-group"> <li class="list-group-item">id: {{booking.id}}</li> <li class="list-group-item">lab: {{booking.lab}}</li> @@ -65,7 +72,9 @@ <li class="list-group-item">owner: {{booking.owner.userprofile.email_addr}}</li> </ul> </div> - <a class="btn btn-primary" href="/booking/detail/{{booking.id}}/">Details</a> + <div class="card-footer d-flex"> + <a class="btn btn-primary ml-auto" href="/booking/detail/{{booking.id}}/">Details</a> + </div> </div> {% endfor %} </div> diff --git a/src/templates/account/configuration_list.html b/src/templates/account/configuration_list.html index b920ba6..6f7844a 100644 --- a/src/templates/account/configuration_list.html +++ b/src/templates/account/configuration_list.html @@ -2,9 +2,11 @@ {% block content %} <div class="card_container"> {% for config in configurations %} - <div class="detail_card"> - <div> + <div class="card"> + <div class="card-header"> <h3>Configuration {{config.id}}</h3> + </div> + <div class="card-body"> <ul class="list-group"> <li class="list-group-item">id: {{config.id}}</li> <li class="list-group-item">name: {{config.name}}</li> @@ -12,10 +14,9 @@ <li class="list-group-item">resource: {{config.bundle}}</li> </ul> </div> - <div class="detail_button_container"> + <div class="card-footer"> <button - class="btn btn-danger" - style="width:49%;float:right;" + class="btn btn-danger w-100" onclick='delete_config({{config.id}});' data-toggle="modal" data-target="#configModal" diff --git a/src/templates/account/image_list.html b/src/templates/account/image_list.html index cd83dcf..068e096 100644 --- a/src/templates/account/image_list.html +++ b/src/templates/account/image_list.html @@ -3,9 +3,11 @@ <h2>Images I Own</h2> <div class="card_container"> {% for image in images %} - <div class="detail_card"> - <div> + <div class="card"> + <div class="card-header"> <h3>Image {{image.id}}</h3> + </div> + <div class="card-body"> <ul class="list-group"> <li class="list-group-item">id: {{image.id}}</li> <li class="list-group-item">lab: {{image.from_lab.name}}</li> @@ -14,10 +16,9 @@ <li class="list-group-item">host profile: {{image.host_type.name}}</li> </ul> </div> - <div class="detail_button_container"> + <div class="card-footer"> <button - class="btn btn-danger" - style="width:49%;float:right;" + class="btn btn-danger w-100" onclick='delete_image({{image.id}});' data-toggle="modal" data-target="#imageModal" @@ -29,9 +30,11 @@ <h2>Public Images</h2> <div class="card_container"> {% for image in public_images %} - <div class="detail_card"> - <div> + <div class="card"> + <div class="card-header"> <h3>Image {{image.id}}</h3> + </div> + <div class="card-body"> <ul class="list-group"> <li class="list-group-item">id: {{image.id}}</li> <li class="list-group-item">lab: {{image.from_lab.name}}</li> diff --git a/src/templates/account/resource_list.html b/src/templates/account/resource_list.html index 1391e8e..f92f78e 100644 --- a/src/templates/account/resource_list.html +++ b/src/templates/account/resource_list.html @@ -2,18 +2,20 @@ {% block content %} <div class="card_container"> {% for resource in resources %} - <div class="detail_card"> - <div> + <div class="card"> + <div class="card-header"> <h3>Resource {{resource.id}}</h3> + </div> + <div class="card-body p-4"> <ul class="list-group"> <li class="list-group-item">id: {{resource.id}}</li> <li class="list-group-item">name: {{resource.name}}</li> <li class="list-group-item">description: {{resource.description}}</li> </ul> </div> - <div class="detail_button_container"> + <div class="card-footer"> <button - class="btn btn-danger" + class="btn btn-danger w-100" onclick='delete_resource({{resource.id}});' data-toggle="modal" data-target="#resModal" diff --git a/src/templates/account/userprofile_update_form.html b/src/templates/account/userprofile_update_form.html index f1d2852..6ab8242 100644 --- a/src/templates/account/userprofile_update_form.html +++ b/src/templates/account/userprofile_update_form.html @@ -1,17 +1,12 @@ -{% extends "layout.html" %} -{% load bootstrap3 %} +{% extends "base.html" %} +{% load bootstrap4 %} -{% block basecontent %} - <div class="container"> +{% block content %} + <div class="container-fluid"> <div class="row"> - <div class="col-md-4 col-md-offset-4"> + <div class="col-12 col-xl-6"> {% bootstrap_messages %} <div class="login-panel panel panel-default"> - <div class="panel-heading"> - <h3 class="panel-title"> - {{ title }} - </h3> - </div> <div class="panel-body"> <form enctype="multipart/form-data" method="post"> {% csrf_token %} @@ -35,4 +30,4 @@ </div> </div> </div> -{% endblock basecontent %} +{% endblock content %} diff --git a/src/templates/base.html b/src/templates/base.html index f48a201..62a9ed5 100644 --- a/src/templates/base.html +++ b/src/templates/base.html @@ -1,52 +1,51 @@ {% extends "layout.html" %} -{% load bootstrap3 %} +{% load bootstrap4 %} {% load staticfiles %} {% block extrahead %} - <!-- Custom CSS --> - <link href="{% static "bower_components/startbootstrap-sb-admin-2-blackrockdigital/dist/css/sb-admin-2.min.css" %}" - rel="stylesheet"> - <link href="{% static "css/theme.css" %}" rel="stylesheet"> - <link href="{% static "css/detail_view.css" %}" rel="stylesheet"> - +<!-- Custom CSS --> +<link href="{% static "css/detail_view.css" %}" rel="stylesheet"> +<link href="{% static "css/base.css" %}" rel="stylesheet"> <script type="text/javascript"> - function cwf(type) - { + function cwf(type) { $.ajax({ type: "POST", url: "/", - data: {"create":type}, - beforeSend: function(request) { + data: { + "create": type + }, + beforeSend: function (request) { request.setRequestHeader("X-CSRFToken", - $('input[name="csrfmiddlewaretoken"]').val() + $('input[name="csrfmiddlewaretoken"]').val() ); } }).done(function (data) { window.location.replace("/wf/"); - }).fail(function(jqxHR, textstatus) { - alert("Something went wrong...");}); + }).fail(function (jqxHR, textstatus) { + alert("Something went wrong..."); + }); } - function continue_wf() - { + + function continue_wf() { window.location.replace("/wf/"); } - function toggle_create_drop() - { + function toggle_create_drop() { drop_div = document.getElementById("create_drop"); - if (drop_div.style.display === "none") - { + if (drop_div.style.display === "none") { drop_div.style.display = "inherit"; - } - else - { + } else { drop_div.style.display = "none"; } } </script> <style> + .navbar { + min-width: 200px; + } + .create_drop { display: none; width: 100%; @@ -66,137 +65,172 @@ border-top: 1px solid #E7E7E7; border-bottom: 1px solid #E7E7E7; } + + #wrapper { + height: 100vh; + } </style> {% endblock %} {% block basecontent %} - <div id="wrapper"> - <!-- Navigation --> - <nav class="navbar navbar-default navbar-static-top" role="navigation" - style="margin-bottom: 0"> - <div class="navbar-header"> - <button type="button" class="navbar-toggle" data-toggle="collapse" - data-target=".navbar-collapse"> - <span class="sr-only">Toggle navigation</span> - <span class="icon-bar"></span> - <span class="icon-bar"></span> - <span class="icon-bar"></span> - </button> - <a href="https://www.opnfv.org/" class="navbar-left"><img - src="{% static "img/opnfv-logo.png" %}"></a> - <a class="navbar-brand" href={% url 'dashboard:index' %}>Pharos Dashboard</a> +<div id="wrapper" class="d-flex flex-column"> + <!-- Navigation --> + <nav class="navbar navbar-light bg-light navbar-fixed-top border-bottom py-0" role="navigation" style="margin-bottom: 0"> + <div class="container-fluid"> + <div class="col order-2 order-lg-1 text-center text-lg-left"> + <a href="https://www.opnfv.org/" class="navbar-brand"> + <img src="{% static "img/opnfv-logo.png" %}"> + </a> + <a class="navbar-brand" href={% url 'dashboard:index' %}> + Pharos Dashboard + </a> </div> <!-- /.navbar-header --> + <div class="col-2 order-1 order-lg-3 d-lg-none"> + <button class="btn border" type="button" data-toggle="collapse" data-target="#sidebar" + aria-expanded="false" aria-controls="sidebar"> + <i class="fas fa-bars"></i> + </button> + </div> + <div class="col-2 order-3"> + <ul class="nav ml-auto"> + <li class="dropdown ml-auto"> + <a class="nav-link p-0 text-dark p-2" data-toggle="dropdown" href="#"> + {% if request.user.username %} + {{request.user.username}} + {% else %} + <i class="fas fa-user"></i> + {% endif %} + <i class="fas fa-caret-down rotate"></i> + </a> + <div class="dropdown-menu dropdown-menu-right"> + {% if user.is_authenticated %} + <a href="{% url 'account:settings' %}" class="text-dark dropdown-item"> + <i class="fas fa-cog"></i> + Settings + </a> + <a href="{% url 'account:logout' %}?next={{ request.path }}" class="text-dark dropdown-item"> + <i class="fas fa-sign-out-alt"></i> + Logout + </a> + {% else %} + <a href="{% url 'account:login' %}" class="text-dark dropdown-item"> + <i class="fas fa-sign-in-alt"></i> + Login with Jira + </a> + {% endif %} + </div> <!-- End dropdown-menu --> + </li> <!-- End dropdown --> + </ul> + </div> <!-- End top right account menu --> + </div> + </nav> + <!-- /.navbar-top-links --> - <ul class="nav navbar-top-links navbar-right"> - <li class="dropdown"> - <a class="dropdown-toggle" data-toggle="dropdown" href="#"> - <i class="fa fa-user fa-fw"></i> <i class="fa fa-caret-down"></i> - </a> - <ul class="dropdown-menu dropdown-user"> - {% if user.is_authenticated %} - <li><a href="{% url 'account:settings' %}"><i - class="fa fa-gear fa-fw"></i> - Settings</a> - </li> - <li class="divider"></li> - <li><a href="{% url 'account:logout' %}?next={{ request.path }}"><i - class="fa fa-sign-out fa-fw"></i> - Logout</a> - </li> - {% else %} - <li><a href="{% url 'account:login' %}"><i - class="fa fa-sign-in fa-fw"></i> - Login with Jira</a> - <li> - {% endif %} - </ul> - <!-- /.dropdown-user --> - </li> - <!-- /.dropdown --> - </ul> - <!-- /.navbar-top-links --> - - <div class="navbar-default sidebar" role="navigation"> - <div class="sidebar-nav navbar-collapse"> - <ul class="nav" id="side-menu"> - <li> - <a href="/"><i class="fa fa-fw"></i>Home</a> - </li> - <li style="width: 100%;"> - <a href="javascript:toggle_create_drop();"><i class="fa fa-fw"></i>Create<i - class="fa fa-fw fa-caret-down"></i> + <!-- Page Content --> + <div class="container-fluid d-lg-flex flex-lg-grow-1 px-0"> + <div class="row h-100 w-100 mx-0"> + <div class="col-12 col-lg-auto px-0 border-right border-left bg-light" role="navigation"> + <nav class="navbar navbar-expand-lg border-bottom p-0 w-100"> + <div class="collapse navbar-collapse" id="sidebar"> + <div class="list-group list-group-flush w-100 bg-light"> + <a href="/" class="list-group-item list-group-item-action bg-light"> + Home + </a> + {% csrf_token %} + <a class="list-group-item list-group-item-action bg-light" data-toggle="collapse" + href="#createList" role="button"> + Create <i class="fas fa-angle-down rotate"></i> + </a> + <div class="collapse" id="createList"> + <a href="/booking/quick/" class="list-group-item list-group-item-action list-group-item-secondary"> + Express Booking + </a> + <a href="#" onclick="cwf(0)" class="list-group-item list-group-item-action list-group-item-secondary"> + Book a Pod + </a> + <a href="#" onclick="cwf(1)" class="list-group-item list-group-item-action list-group-item-secondary"> + Design a Pod + </a> + <a href="#" onclick="cwf(2)" class="list-group-item list-group-item-action list-group-item-secondary"> + Configure a Pod + </a> + <a href="#" onclick="cwf(3)" class="list-group-item list-group-item-action list-group-item-secondary"> + Create a Snapshot </a> - {% csrf_token %} - <div id="create_drop" class="create_drop" style="display:none"> - <button class="btn drop_btn" onclick="location.href='/booking/quick/'">Express Booking</a> - <button class="btn drop_btn" onclick="cwf(0)">Book a Pod</button> - <button class="btn drop_btn" onclick="cwf(1)">Design a Pod</button> - <button class="btn drop_btn" onclick="cwf(2)">Configure a Pod</button> - <button class="btn drop_btn" onclick="cwf(3)">Create a Snapshot</button> - <button class="btn drop_btn" onclick="cwf(4)">Configure OPNFV</button> - </div> - </li> - <li> - <a href="{% url 'resource:hosts' %}"><i - class="fa fa-fw"></i>Hosts + <a href="#" onclick="cwf(4)" class="list-group-item list-group-item-action list-group-item-secondary"> + Configure OPNFV </a> - </li> - {% if user.is_authenticated %} - <li> - <a href="{% url 'account:users' %}"><i - class="fa fa-fw"></i>User List + </div> + <a href="{% url 'resource:hosts' %}" class="list-group-item list-group-item-action bg-light"> + Hosts </a> - </li> - {% endif %} - <li> - <a href="{% url 'booking:list' %}"><i - class="fa fa-fw"></i>Booking List + {% if user.is_authenticated %} + <a href="{% url 'account:users' %}" class="list-group-item list-group-item-action bg-light"> + User List + </a> + {% endif %} + <a href="{% url 'booking:list' %}" class="list-group-item list-group-item-action bg-light"> + Booking List </a> - </li> - <li> - <a href="{% url 'booking:stats' %}"><i - class="fa fa-fw"></i>Booking Statistics</a> - </li> - <li> - <a href="{% url 'account:my-account' %}"><i - class="fa fa-fw"></i>Account + <a href="{% url 'booking:stats' %}" class="list-group-item list-group-item-action bg-light"> + Booking Statistics </a> - </li> - <li> - <a href="{% url 'dashboard:all_labs' %}"><i - class="fa fa-fw"></i>Lab Info + <!-- <a href="{% url 'account:my-account' %}" class="list-group-item list-group-item-action bg-light"> + Account + </a> --> + <a class="list-group-item list-group-item-action bg-light" data-toggle="collapse" + href="#accountList" role="button"> + Account <i class="fas fa-angle-down rotate"></i> </a> - </li> - <li> - <a href="{% url 'notifier:messages' %}"><i - class="fa fa-fw"></i>Inbox + <div class="collapse" id="accountList"> + <a href="{% url 'account:my-resources' %}" class="list-group-item list-group-item-action list-group-item-secondary"> + My Resources + </a> + <a href="{% url 'account:my-bookings' %}" class="list-group-item list-group-item-action list-group-item-secondary"> + My Bookings + </a> + <a href="{% url 'account:my-configurations' %}" class="list-group-item list-group-item-action list-group-item-secondary"> + My Configurations + </a> + <a href="{% url 'account:my-images' %}" class="list-group-item list-group-item-action list-group-item-secondary"> + My Snapshots + </a> + </div> + <a href="{% url 'dashboard:all_labs' %}" class="list-group-item list-group-item-action bg-light"> + Lab Info </a> - </li> - </ul> - </div> - <!-- /.sidebar-collapse --> + <a href="{% url 'notifier:messages' %}" class="list-group-item list-group-item-action bg-light"> + Inbox + </a> + </div> + </div> + </nav> + <!--/.well --> </div> - <!-- /.navbar-static-side --> - </nav> + <!--/span--> - <!-- Page Content --> - <div id="page-wrapper"> - {% if title %} - <div class="row"> - <div class="col-lg-12"> - <h1 class="page-header">{{ title }}</h1> + <div class="col flex-grow-1 d-flex flex-column"> + {% if title %} + <div class="row flex-shrink-1"> + <div class="col-lg-12"> + <h1 class="page-header">{{ title }}</h1> + </div> + <!-- /.col-lg-12 --> </div> - <!-- /.col-lg-12 --> + {% endif %} + <div id="bsm">{% bootstrap_messages %}</div> + <!-- Content block placed here --> + {% block content %} + {% endblock content %} </div> - {% endif %} - <div id="bsm">{% bootstrap_messages %}</div> + <!--/span--> - {% block content %} - {% endblock content %} </div> - <!-- /#page-wrapper --> + <!--/row--> </div> - <!-- /#wrapper --> + <!-- /#page-wrapper --> +</div> +<!-- /#wrapper --> {% endblock basecontent %} diff --git a/src/templates/booking/booking_calendar.html b/src/templates/booking/booking_calendar.html index 1b29dc2..ddcb45d 100644 --- a/src/templates/booking/booking_calendar.html +++ b/src/templates/booking/booking_calendar.html @@ -1,7 +1,7 @@ {% extends "base.html" %} {% load staticfiles %} -{% load bootstrap3 %} +{% load bootstrap4 %} {% block extrahead %} {{ block.super }} diff --git a/src/templates/booking/booking_delete.html b/src/templates/booking/booking_delete.html index 76a5634..b89eb15 100644 --- a/src/templates/booking/booking_delete.html +++ b/src/templates/booking/booking_delete.html @@ -1,5 +1,5 @@ {% load jira_filters %} -{% load bootstrap3 %} +{% load bootstrap4 %} <p> Really delete Booking from {{ booking.start}} to {{ booking.end }}? diff --git a/src/templates/booking/booking_detail.html b/src/templates/booking/booking_detail.html index ac00e22..918f5af 100644 --- a/src/templates/booking/booking_detail.html +++ b/src/templates/booking/booking_detail.html @@ -1,6 +1,6 @@ {% extends "base.html" %} {% load staticfiles %} -{% load bootstrap3 %} +{% load bootstrap4 %} {% block extrahead %} {{block.super}} @@ -19,13 +19,13 @@ <div class="container-fluid"> <div class="row"> - <div class="col-lg-4"> - <div class="panel panel-default"> - <div class="panel-heading clearfix"> + <div class="col-12 col-lg-5"> + <div class="card mb-4"> + <div class="card-header d-flex"> <h4 style="display: inline;">Overview</h4> - <a data-toggle="collapse" data-target="#panel_overview" class="btn pull-right" style="line-height: 1;">Expand</a> + <button data-toggle="collapse" data-target="#panel_overview" class="btn btn-outline-secondary ml-auto">Expand</button> </div> - <div class="panel-body collapse in" id="panel_overview"> + <div class="card-body collapse show" id="panel_overview"> <table class="table"> <tr> <td>Purpose</td> @@ -60,12 +60,12 @@ </div> <div class="row"> <div class="col-lg-12"> - <div class="panel panel-default"> - <div class="panel-heading clearfix"> + <div class="card"> + <div class="card-header d-flex"> <h4 style="display: inline;">Pod</h4> - <a data-toggle="collapse" data-target="#pod_panel" class="btn pull-right" style="line-height: 1;" >Expand</a> + <button data-toggle="collapse" data-target="#pod_panel" class="btn btn-outline-secondary ml-auto">Expand</button> </div> - <div class="panel-body pod_panel collapse in" id="pod_panel"> + <div class="card-body collapse show" id="pod_panel"> <table class="table"> {% for host in booking.resource.hosts.all %} <tr> @@ -177,14 +177,14 @@ </div> </div> </div> - <div class="col-lg-8"> - <div class="panel panel-default"> - <div class="panel-heading clearfix"> + <div class="col"> + <div class="card mb-4"> + <div class="card-header d-flex"> <h4 style="display: inline;">Deployment Progress</h4> <p style="display: inline; margin-left: 10px;"> These are the different tasks that have to be completed before your deployment is ready</p> - <a data-toggle="collapse" data-target="#panel_tasks" class="btn pull-right" style="line-height: 1;" >Expand</a> + <button data-toggle="collapse" data-target="#panel_tasks" class="btn btn-outline-secondary ml-auto">Expand</button> </div> - <div class="panel-body collapse in" id="panel_tasks"> + <div class="card-body collapse show" id="panel_tasks"> <table class="table"> <style> .progress { @@ -269,15 +269,15 @@ </div> </div> <div class="row"> - <div class="col-lg-8"> - <div class="panel panel-default"> - <div class="panel-heading clearfix"> + <div class="col"> + <div class="card"> + <div class="card-header d-flex"> <h4 style="display: inline;">PDF</h4> - <a data-toggle="collapse" data-target="#pdf_panel" class="btn pull-right" style="line-height: 1;" >Expand</a> + <button data-toggle="collapse" data-target="#pdf_panel" class="btn btn-outline-secondary ml-auto">Expand</button> </div> - <div class="panel-body collapse in" id="pdf_panel" style="padding: 0px;"> + <div class="card-body collapse show" id="pdf_panel" style="padding: 0px;"> <pre class="prettyprint lang-yaml" style="margin: 0px; padding: 15px; border: none;"> -{{pdf}} + {{pdf}} </pre> </div> </div> diff --git a/src/templates/booking/booking_list.html b/src/templates/booking/booking_list.html index a245450..591ecc9 100644 --- a/src/templates/booking/booking_list.html +++ b/src/templates/booking/booking_list.html @@ -1,44 +1,38 @@ {% extends "base.html" %} {% load staticfiles %} -{% load bootstrap3 %} +{% load bootstrap4 %} {% block extrahead %} {{ block.super }} <!-- DataTables CSS --> - <link href="{% static "bower_components/datatables-plugins/integration/bootstrap/3/dataTables.bootstrap.css" %}" + <link href="{% static "bower_components/datatables.net-bs4/css/dataTables.bootstrap4.min.css" %}" rel="stylesheet"> <!-- DataTables Responsive CSS --> - <link href="{% static "bower_components/datatables-responsive/css/dataTables.responsive.css" %}" + <link href="{% static "bower_components/datatables.net-responsive-bs4/css/responsive.bootstrap4.min.css" %}" rel="stylesheet"> {% endblock extrahead %} {% block content %} <div class="row"> - <div class="panel-body"> - <div class="dataTables_wrapper"> - <table class="table table-striped table-bordered table-hover" id="table" - cellspacing="0" - width="100%"> - {% include "booking/booking_table.html" %} - </table> - </div> - <!-- /.table-responsive --> - <!-- /.panel-body --> - <!-- /.panel --> + <div class="col"> + <div class="panel-body"> + <div class="dataTables_wrapper"> + <table class="table table-striped table-bordered table-hover" id="table" + cellspacing="0" + width="100%"> + {% include "booking/booking_table.html" %} + </table> + </div> + </div> </div> - <!-- /.col-lg-12 --> </div> {% endblock content %} {% block extrajs %} <!-- DataTables JavaScript --> - <link href="{% static "bower_components/datatables-plugins/integration/bootstrap/3/dataTables.bootstrap.css" %}" - rel="stylesheet"> - - - <script src={% static "bower_components/datatables/media/js/jquery.dataTables.min.js" %}></script> - <script src={% static "bower_components/datatables-plugins/integration/bootstrap/3/dataTables.bootstrap.min.js" %}></script> + <script src={% static "bower_components/datatables.net/js/jquery.dataTables.min.js" %}></script> + <script src={% static "bower_components/datatables.net-bs4/js/dataTables.bootstrap4.min.js" %}></script> <script type="text/javascript"> $(document).ready(function () { diff --git a/src/templates/booking/quick_deploy.html b/src/templates/booking/quick_deploy.html index 03eb78c..ea80af4 100644 --- a/src/templates/booking/quick_deploy.html +++ b/src/templates/booking/quick_deploy.html @@ -1,6 +1,6 @@ {% extends "base.html" %} {% load staticfiles %} -{% load bootstrap3 %} +{% load bootstrap4 %} {% block content %} <style> .grid_container { @@ -26,14 +26,23 @@ .grid_element_2third { grid-column-start: span 8; } + .collaborator_pane { + display: flex; + flex-direction: column; + } #id_length { -moz-appearance: none; border: none; box-shadow: none; } + input[type=range]::-moz-range-track { background: #cccccc; } + + .grid_element { + overflow: hidden; + } </style> {% bootstrap_form_errors form type='non_fields' %} <form id="quick_booking_form" action="/booking/quick/" method="POST" class="form"> @@ -70,77 +79,57 @@ </div> </div> <script type="text/javascript"> - var normalize = function(data) - { - //converts the top level keys in data to map to lists - var normalized = {} - for( var key in data ){ - normalized[key] = []; - for( var subkey in data[key] ){ - normalized[key].push(data[key][subkey]); - } - } - return normalized; - } - var update_page_contents = function(response) - { - document.open(); - document.write(response); - document.close(); - } - //form hamdler code - submit_form = function() + function submit_form() { - //altered from initial prototype: form submits automatically, - //but needs formatting for multiple select field - var data = normalize(result); - data = JSON.stringify(data); - document.getElementById("filter_field").value = data; + //formats data for form submission + document.getElementById("filter_field").value = JSON.stringify(result); } - var sup_image_dict = {{ image_filter|safe }}; - var sup_installer_dict = {{ installer_filter|safe }}; - var sup_scenario_dict = {{ scenario_filter|safe }}; - - function imageHider() { - var data = normalize(result); - var drop = document.getElementById("id_image"); + function hide_dropdown(drop_id) { + var drop = document.getElementById(drop_id); + //select 'blank' option for( var i=0; i < drop.length; i++ ) { if ( drop.options[i].text == '---------' ) - { drop.selectedIndex = i; - } } + //cross browser hide children $('#id_image').children().hide(); - for( var i = 0; i < drop.childNodes.length; i++ ) { drop.childNodes[i].disabled = true; // closest we can get on safari to hiding it outright } + } + function get_selected_value(key){ + for( var attr in result[key] ){ + if( attr in {} ) + continue; + else + return attr; + } + return null; + } - var empty_map = {} + var sup_image_dict = {{ image_filter|safe }}; + var sup_installer_dict = {{ installer_filter|safe }}; + var sup_scenario_dict = {{ scenario_filter|safe }}; + + function imageHider() { + var drop = document.getElementById("id_image"); + + hide_dropdown("id_image"); + + var lab_pk = get_selected_value("lab"); + var host_pk = get_selected_value("host"); for ( var i=0; i < drop.childNodes.length; i++ ) { var image_object = sup_image_dict[drop.childNodes[i].value]; if( image_object ) //weed out empty option { - var lab_pk = "" - for( var j in data["labs"][0] ) - { - if( j in {} ) { continue; } - else { lab_pk = j; break; } - } - var host_pk = ""; - for( var j in data["hosts"][0] ) - { - if( j in {} ) { continue; } - else { host_pk = j; break; } - } if( image_object.host_profile == host_pk && image_object.lab == lab_pk ) { drop.childNodes[i].style.display = "inherit"; @@ -171,28 +160,15 @@ document.getElementById('id_installer').addEventListener('change', scenarioHider); function dropFilter(target, target_filter, master) { - ob = document.getElementById(target); + var dropdown = document.getElementById(target); - for(var i=0; i<ob.options.length; i++) { - if ( ob.options[i].text == '---------' ) { - ob.selectedIndex = i; - } - } - - targ_id = "#" + target; - - $(targ_id).children().hide(); + hide_dropdown(target); - for (var i = 0; i < document.getElementById(target).childNodes.length; i++) - { - document.getElementById(target).childNodes[i].disabled = true; - } var drop = document.getElementById(master); var opts = target_filter[drop.options[drop.selectedIndex].value]; if (!opts) { opts = {}; } - var emptyMap = {} var map = Object.create(null); for (var i = 0; i < opts.length; i++) { @@ -200,34 +176,14 @@ map[j] = true; } - for (var i = 0; i < document.getElementById(target).childNodes.length; i++) { - if (document.getElementById(target).childNodes[i].value in opts && !(document.getElementById(target).childNodes[i].value in emptyMap) ) { - document.getElementById(target).childNodes[i].style.display = "inherit"; - document.getElementById(target).childNodes[i].disabled = false; + for (var i = 0; i < dropdown.childNodes.length; i++) { + if (dropdown.childNodes[i].value in opts && !(dropdown.childNodes[i].value in {}) ) { + dropdown.childNodes[i].style.display = "inherit"; + dropdown.childNodes[i].disabled = false; } } } </script> - <button onclick="submit_form();" class="btn btn-success">Confirm</button> + <button id="quick_booking_confirm" onclick="submit_form();" class="btn btn-success">Confirm</button> </form> -<script> - //context vars - var prefill_host_selection = "{{host_select_field_prefill_data|default:""|safe}}"; - var prefill_purpose = "{{prefill_purpose|default:""|safe}}"; - var prefill_project = "{{prefill_project|default:""|safe}}"; - var prefill_hostname = "{{prefill_hostname|default:""|safe}}"; - - //to handle prefill - function prefill_host_select_field(data) - { - // - if(data) - { - make_selection(data); - } - } - - //call init functions - prefill_host_select_field(prefill_host_selection); -</script> {% endblock %} diff --git a/src/templates/booking/stats.html b/src/templates/booking/stats.html index 42eebdd..8bc68cd 100644 --- a/src/templates/booking/stats.html +++ b/src/templates/booking/stats.html @@ -41,17 +41,28 @@ function getData(){ {% endblock %} {% block content %} - <p>Number of days to plot: </p> - <div class="form-group"> - <input id="number_days" type="number" class="form-control" min="1" step="1" style="display:inline;width:200px"/> - <button class="btn btn-primary" onclick="getData();" style="display:inline;">Submit</button> - </div> - <div id="all_graph_container"> - <div id="booking_graph_wrapper"> - <div id="booking_graph_container"/> + <div class="container-fluid"> + <div class="row"> + <div class="col"> + <p>Number of days to plot: </p> + <div class="form-group"> + <input id="number_days" type="number" class="form-control" min="1" step="1" style="display:inline;width:200px"/> + <button class="btn btn-primary" onclick="getData();" style="display:inline;">Submit</button> + </div> + </div> </div> - <div id="user_graph_wrapper" > - <div id="user_graph_container"/> + <div class="row"> + <div class="col-12 col-md-10"> + <!-- These graphs do NOT get redrawn when the browser size is changed --> + <div id="all_graph_container border" class="mw-100"> + <div id="booking_graph_wrapper"> + <div id="booking_graph_container"/> + </div> + <div id="user_graph_wrapper"> + <div id="user_graph_container"/> + </div> + </div> + </div> </div> </div> <script> diff --git a/src/templates/booking/steps/booking_confirm.html b/src/templates/booking/steps/booking_confirm.html index 9c7e951..40c30a9 100644 --- a/src/templates/booking/steps/booking_confirm.html +++ b/src/templates/booking/steps/booking_confirm.html @@ -1,7 +1,7 @@ {% extends "workflow/viewport-element.html" %} {% load staticfiles %} -{% load bootstrap3 %} +{% load bootstrap4 %} {% block content %} diff --git a/src/templates/booking/steps/booking_meta.html b/src/templates/booking/steps/booking_meta.html index fe43f53..710d4ee 100644 --- a/src/templates/booking/steps/booking_meta.html +++ b/src/templates/booking/steps/booking_meta.html @@ -1,7 +1,7 @@ {% extends "workflow/viewport-element.html" %} {% load staticfiles %} -{% load bootstrap3 %} +{% load bootstrap4 %} {% block content %} @@ -10,6 +10,17 @@ padding: 5%; } + .bkcontrib_panel { + display: flex; + flex-direction: column; + } + + .bkcontrib_panel > .form-group { + flex: 1; + display: flex; + flex-direction: column; + } + .panel{ padding: 5%; /*border: solid 1px black;*/ @@ -48,10 +59,11 @@ </script> {% bootstrap_field form.info_file %} <p>You must provide a url to your project's INFO.yaml file if you are a PTL and you are trying to book a POD with multiple servers in it.</p> + {% bootstrap_field form.deploy_opnfv %} </div> <div class="panel panel_center"> </div> - <div class="panel"> + <div class="panel bkcontrib_panel"> <p>You may add collaborators on your booking to share resources with coworkers.</p> {% bootstrap_field form.users label="Collaborators" %} </div> diff --git a/src/templates/booking/steps/resource_select.html b/src/templates/booking/steps/resource_select.html index 7ccceb3..382316f 100644 --- a/src/templates/booking/steps/resource_select.html +++ b/src/templates/booking/steps/resource_select.html @@ -1,7 +1,7 @@ {% extends "workflow/viewport-element.html" %} {% load staticfiles %} -{% load bootstrap3 %} +{% load bootstrap4 %} {% block content %} diff --git a/src/templates/booking/steps/swconfig_select.html b/src/templates/booking/steps/swconfig_select.html index 15c79d8..60a0df7 100644 --- a/src/templates/booking/steps/swconfig_select.html +++ b/src/templates/booking/steps/swconfig_select.html @@ -1,7 +1,7 @@ {% extends "workflow/viewport-element.html" %} {% load staticfiles %} -{% load bootstrap3 %} +{% load bootstrap4 %} {% block content %} diff --git a/src/templates/config_bundle/steps/assign_host_roles.html b/src/templates/config_bundle/steps/assign_host_roles.html index 3ba7665..b87a17f 100644 --- a/src/templates/config_bundle/steps/assign_host_roles.html +++ b/src/templates/config_bundle/steps/assign_host_roles.html @@ -1,6 +1,6 @@ {% extends "config_bundle/steps/table_formset.html" %} -{% load bootstrap3 %} +{% load bootstrap4 %} {% block table %} <thead> diff --git a/src/templates/config_bundle/steps/assign_network_roles.html b/src/templates/config_bundle/steps/assign_network_roles.html index 0e887d6..aa1df44 100644 --- a/src/templates/config_bundle/steps/assign_network_roles.html +++ b/src/templates/config_bundle/steps/assign_network_roles.html @@ -1,6 +1,6 @@ {% extends "config_bundle/steps/table_formset.html" %} -{% load bootstrap3 %} +{% load bootstrap4 %} {% block table %} <thead> diff --git a/src/templates/config_bundle/steps/config_software.html b/src/templates/config_bundle/steps/config_software.html index b181c7e..68417bc 100644 --- a/src/templates/config_bundle/steps/config_software.html +++ b/src/templates/config_bundle/steps/config_software.html @@ -1,7 +1,7 @@ {% extends "workflow/viewport-element.html" %} {% load staticfiles %} -{% load bootstrap3 %} +{% load bootstrap4 %} {% block content %} diff --git a/src/templates/config_bundle/steps/define_software.html b/src/templates/config_bundle/steps/define_software.html index ba1ff34..87e5997 100644 --- a/src/templates/config_bundle/steps/define_software.html +++ b/src/templates/config_bundle/steps/define_software.html @@ -1,6 +1,6 @@ {% extends "config_bundle/steps/table_formset.html" %} -{% load bootstrap3 %} +{% load bootstrap4 %} {% block table %} <thead> diff --git a/src/templates/config_bundle/steps/pick_installer.html b/src/templates/config_bundle/steps/pick_installer.html index 3b170d9..31a06de 100644 --- a/src/templates/config_bundle/steps/pick_installer.html +++ b/src/templates/config_bundle/steps/pick_installer.html @@ -1,7 +1,7 @@ {% extends "workflow/viewport-element.html" %} {% load staticfiles %} -{% load bootstrap3 %} +{% load bootstrap4 %} {% block content %} diff --git a/src/templates/config_bundle/steps/table_formset.html b/src/templates/config_bundle/steps/table_formset.html index ad2c5a3..18edc72 100644 --- a/src/templates/config_bundle/steps/table_formset.html +++ b/src/templates/config_bundle/steps/table_formset.html @@ -1,15 +1,16 @@ {% extends "workflow/viewport-element.html" %} {% load staticfiles %} -{% load bootstrap3 %} +{% load bootstrap4 %} {% block extrahead %} <!-- DataTables CSS --> - <link href="{% static "bower_components/datatables-plugins/integration/bootstrap/3/dataTables.bootstrap.css" %}" + <link href="{% static "bower_components/datatables.net-bs4/css/dataTables.bootstrap4.min.css" %}" rel="stylesheet"> <!-- DataTables Responsive CSS --> - <link href="{% static "bower_components/datatables-responsive/css/dataTables.responsive.css" %}" rel="stylesheet"> + <link href="{% static "bower_components/datatables.net-responsive-bs4/css/responsive.bootstrap4.min.css" %}" + rel="stylesheet"> {% endblock extrahead %} {% block content %} @@ -42,8 +43,8 @@ {{ block.super }} <!-- DataTables JavaScript --> - <script src={% static "bower_components/datatables/media/js/jquery.dataTables.min.js" %}></script> - <script src={% static "bower_components/datatables-plugins/integration/bootstrap/3/dataTables.bootstrap.min.js" %}></script> + <script src={% static "bower_components/datatables.net/js/jquery.dataTables.min.js" %}></script> + <script src={% static "bower_components/datatables.net-bs4/js/dataTables.bootstrap4.min.js" %}></script> <script src={% static "js/dataTables-sort.js" %}></script> diff --git a/src/templates/dashboard/genericselect.html b/src/templates/dashboard/genericselect.html new file mode 100644 index 0000000..441d8dc --- /dev/null +++ b/src/templates/dashboard/genericselect.html @@ -0,0 +1,104 @@ +{% extends "workflow/viewport-element.html" %} +{% load staticfiles %} + +{% load bootstrap4 %} + +{% block content %} + +<style> + #page-wrapper { + display: flex; + flex-direction: column; + } + + #{{select_type}}_form_div div { + } + + #{{select_type}}_form_div > * { + margin-left: 10px; + margin-right: 10px; + margin-bottom: 20px; + } + + #{{select_type}}_form_div div * { + } + + #{{select_type}}_form_div { + flex: 1; + margin: 30px; + display: flex; + flex-direction: column; + } + + #select_section { + flex: 1; + display: flex; + flex-direction: column; + } + + #{{select_type}}_select_form { + flex: 1; + display: flex; + flex-direction: column; + } + + .autocomplete { + flex: 1; + } + + #create_section { + } + + #select_header_section { + } + + h3 { + margin-top: 0; + margin-bottom: 0; + vertical-align: middle; + } + + .divider { + border-top: 1px solid #ccc; + } + + +</style> + +<div id="{{select_type}}_form_div"> + <h3 id="create_section">Create a Resource + <button class="btn btn-primary {% if disabled %} disabled {% endif %}" + {% if not disabled %}onclick="parent.add_wf({{addable_type_num}})" + {% endif %}>Here + </button> + </h3> + <div class="divider"></div> + <h3 id="select_header_section">Or select from the list below:</h3> + <div id="select_section"> + <form id="{{select_type}}_select_form" method="post" action="" class="form" id="{{select_type}}selectorform"> + {% csrf_token %} + {{ form|default:"<p>no form loaded</p>" }} + {% buttons %} + + {% endbuttons %} + </form> + </div> +</div> + +<script> + {% if disabled %} + disable(); + {% endif %} +</script> + +{% endblock content %} +{% block onleave %} +var form = $("#{{select_type}}_select_form"); +var formData = form.serialize(); +var req = new XMLHttpRequest(); +req.open("POST", "/wf/workflow/", false); +req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); +req.onerror = function() { alert("problem with form submission"); } +req.send(formData); +{% endblock %} + diff --git a/src/templates/dashboard/lab_detail.html b/src/templates/dashboard/lab_detail.html index 7938e86..336b32e 100644 --- a/src/templates/dashboard/lab_detail.html +++ b/src/templates/dashboard/lab_detail.html @@ -9,12 +9,12 @@ {% block content %} <div class="row"> <div class="col-lg-4"> - <div class="panel panel-default"> - <div class="panel-heading clearfix"> - <h4 style="display: inline;">Lab Profile</h4> - <a data-toggle="collapse" data-target="#panel_overview" class="btn pull-right" style="line-height: 1;" >Expand</a> + <div class="card my-2"> + <div class="card-header d-flex"> + <h4>Lab Profile</h4> + <button class="btn btn-outline-secondary ml-auto" data-toggle="collapse" data-target="#panel_overview">Expand</button> </div> - <div class="panel-body" id="panel_overview"> + <div id="panel_overview" class="card-body collapse show"> <table class="table"> <tr> <td>Lab Name: </td><td>{{lab.name}}</td> @@ -50,19 +50,18 @@ </table> </div> </div> - <div class="panel panel-default"> - <div class="panel-heading clearfix"> - <h4 style="display: inline;">Host Profiles</h4> - - <a data-toggle="collapse" data-target="#profile_panel" class="btn pull-right" style="line-height: 1;" >Expand</a> + <div class="card my-2"> + <div class="card-header d-flex"> + <h4 class="d-inline-block">Host Profiles</h4> + <button data-toggle="collapse" data-target="#profile_panel" class="btn btn-outline-secondary ml-auto" style="line-height: 1;" >Expand</button> </div> - <div class="panel-body pod_panel" id="profile_panel"> + <div id="profile_panel" class="card-body collapse show"> <table class="table"> {% for profile in hostprofiles %} <tr> <td>{{profile.name}}</td> <td>{{profile.description}}</td> - <td><a href="/resource/profiles/{{ profile.id }}" class="btn btn-primary">Profile</a></td> + <td><a href="/resource/profiles/{{ profile.id }}" class="btn btn-info">Profile</a></td> </tr> {% endfor %} </table> @@ -70,31 +69,30 @@ </div> - <div class="panel panel-default"> - <div class="panel-heading clearfix"> + <div class="card my-2"> + <div class="card-header d-flex"> <h4 style="display: inline;">Networking Capabilities</h4> - <a data-toggle="collapse" data-target="#network_panel" class="btn pull-right" style="line-height: 1;" >Expand</a> + <button data-toggle="collapse" data-target="#network_panel" class="btn btn-outline-secondary ml-auto" style="line-height: 1;" >Expand</button> </div> - <div class="panel-body" id="network_panel"> - - <table class="table"> - <tr> - <td>Block Size: (number of VLANs allowed per deployment)</td><td>{{lab.vlan_manager.block_size}}</td> - </tr> - <tr> - <td>Overlapping Vlans Allowed (user can pick which VLANs they wish to use): </td> - <td>{{lab.vlan_manager.allow_overlapping}}</td> - </tr> - </table> + <div class="card-body collapse show" id="network_panel"> + <table class="table"> + <tr> + <td>Block Size: (number of VLANs allowed per deployment)</td><td>{{lab.vlan_manager.block_size}}</td> + </tr> + <tr> + <td>Overlapping Vlans Allowed (user can pick which VLANs they wish to use): </td> + <td>{{lab.vlan_manager.allow_overlapping}}</td> + </tr> + </table> </div> </div> - <div class="panel panel-default"> - <div class="panel-heading clearfix"> - <h4 style="display: inline;">Images</h4> - <a data-toggle="collapse" data-target="#image_panel" class="btn pull-right" style="line-height: 1;" >Expand</a> + <div class="card my-2"> + <div class="card-header d-flex"> + <h4>Images</h4> + <button data-toggle="collapse" data-target="#image_panel" class="btn btn-outline-secondary ml-auto">Expand</button> </div> - <div class="panel-body" id="image_panel"> + <div class="card-body collapse show" id="image_panel"> <table class="table"> <tr> <th>Name</th> @@ -116,14 +114,13 @@ </div> <div class="col-lg-8"> - <div class="panel panel-default"> - <div class="panel-heading clearfix"> - <h4 style="display: inline;">Lab Hosts</h4> - <p style="display: inline; margin-left: 10px;"></p> - <a data-toggle="collapse" data-target="#lab_hosts_panel" class="btn pull-right" style="line-height: 1;" >Expand</a> + <div class="card my-2"> + <div class="card-header d-flex"> + <h4>Lab Hosts</h4> + <button data-toggle="collapse" data-target="#lab_hosts_panel" class="btn btn-outline-secondary ml-auto">Expand</button> </div> - <div class="panel-body" id="lab_hosts_panel"> + <div class="card-body collapse show" id="lab_hosts_panel"> <table class="table"> <tr> <th>Name</th> diff --git a/src/templates/dashboard/lab_list.html b/src/templates/dashboard/lab_list.html index c459dd9..9cde80c 100644 --- a/src/templates/dashboard/lab_list.html +++ b/src/templates/dashboard/lab_list.html @@ -1,26 +1,28 @@ {% extends "base.html" %} {% block content %} - <h2>Labs</h2> - <div class="card_container"> +<h2>Labs</h2> +<div class="card_container"> {% for lab in labs %} - <div class="detail_card"> - <div> - <h3>{{lab.name}}</h3> - <ul class="list-group"> - <li class="list-group-item">name: {{lab.name}}</li> - <li class="list-group-item">description: {{lab.description}}</li> - <li class="list-group-item">location: {{lab.location}}</li> - {% if lab.status == 0 %} - <li class="list-group-item">status: Up</li> - {% elif lab.status == 100 %} - <li class="list-group-item">status: Down for Maintenance</li> - {% elif lab.status == 200 %} - <li class="list-group-item">status: Down</li> - {% endif %} - </ul> - </div> - <a class="btn btn-primary" href="/lab/{{lab.name}}/">Details</a> + <div class="card"> + <div class="card-header"> + <h3 class="mt-2">{{lab.name}}</h3> + </div> + <div class="p-4"> + <ul class="list-group"> + <li class="list-group-item">name: {{lab.name}}</li> + <li class="list-group-item">description: {{lab.description}}</li> + <li class="list-group-item">location: {{lab.location}}</li> + {% if lab.status == 0 %} + <li class="list-group-item">status: Up</li> + {% elif lab.status == 100 %} + <li class="list-group-item">status: Down for Maintenance</li> + {% elif lab.status == 200 %} + <li class="list-group-item">status: Down</li> + {% endif %} + </ul> + <a class="btn btn-primary mt-4 w-100" href="/lab/{{lab.name}}/">Details</a> </div> - {% endfor %} </div> -{% endblock %} + {% endfor %} +</div> +{% endblock %}
\ No newline at end of file diff --git a/src/templates/dashboard/landing.html b/src/templates/dashboard/landing.html index fb75d5f..e6a235f 100644 --- a/src/templates/dashboard/landing.html +++ b/src/templates/dashboard/landing.html @@ -2,27 +2,30 @@ {% load staticfiles %} {% block content %} - <div class="" style="text-align: center;"> - {% if not request.user.is_anonymous %} - {% if not request.user.userprofile.ssh_public_key %} - <h4 style="display: inline; text-align: center; border: 3px solid red; padding: 10px; border-radius: 10000px; height: 40px;"> - Warning: you need to upload an ssh key under <a href="/accounts/settings">account settings</a> if you wish to log into the servers you book - </h4> - {% endif %} - {% else %} - {% endif %} +<div class="" style="text-align: center;"> + {% if not request.user.is_anonymous %} + {% if not request.user.userprofile.ssh_public_key %} + <div class="alert alert-danger" role="alert"> + Warning: you need to upload an ssh key under <a href="/accounts/settings">account settings</a> if you wish to + log into the servers you book </div> + {% endif %} + {% else %} + {% endif %} +</div> {% csrf_token %} <style> - .wf_create{ + .wf_create { display: inline-block; text-align: center; } - .wf_create_div{ + + .wf_create_div { text-align: center; } - .hidden_form{ + + .hidden_form { display: none; } @@ -39,81 +42,117 @@ display: grid; grid-template-columns: 1fr 30px 1fr; } + .grid_panel { padding: 30px; } + .btn-primary { margin: 10px; } + h2 { border-bottom: 1px solid #cccccc; } - h1 { - } -</style> -<div class="landing_container"> - <div class="info_panel grid_panel"> - <h2>About Us:</h2> - <p>The Lab as a Service (LaaS) project aims to help in the development and testing of LFN projects such as OPNFV by hosting hardware and providing access to the community. Currently, the only participating lab is the University of New Hampshire Interoperability Lab (UNH-IOL).</p> - <p>To get started, you can request access to a server at the right. PTL's have the ability to design and book a whole block of servers with customized layer2 networks (e.g. a Pharos Pod). Read more here: <a href="https://wiki.opnfv.org/display/INF/Lab+as+a+Service+2.0">LaaS Wiki</a></p> + h1 {} +</style> +<div class="container-fluid"> + <div class="row"> + <!-- About us --> + <div class="col-12 col-lg-6 mb-4"> + <h2>About Us:</h2> + <p>The Lab as a Service (LaaS) project aims to help in the development and testing of LFN projects such as + OPNFV + by hosting hardware and providing access to the community. Currently, the only participating lab is the + University of New Hampshire Interoperability Lab (UNH-IOL).</p> + <p>To get started, you can request access to a server at the right. PTL's have the ability to design and + book a + whole block of servers with customized layer2 networks (e.g. a Pharos Pod). Read more here: <a + href="https://wiki.opnfv.org/display/INF/Lab+as+a+Service+2.0">LaaS Wiki</a></p> + </div> + <!-- Get started --> + <div class="col-12 col-lg-6 mb-4"> + <h2>Get Started:</h2> + {% if request.user.is_anonymous %} + <h4 style="text-align:center;">To get started, please log in with your <a href="/accounts/login">Linux + Foundation Jira account</a></h4> + {% else %} + <p>To get started, book a server below:</p> + <a class="wf_create btn btn-primary" + style="display: flex; flex-direction: column; justify-content: center; margin: 20px; height: 100pt; vertical-align: middle; text-align: center; color: #FFF;" + href="/booking/quick/"> + <p style="font-size: xx-large">Book a Server</p> + </a> + <p>PTLs can use our advanced options to book multi-node pods. If you are a PTL, you may use the options + below: + </p> + <div class='container'> + <div class="row"> + <div class="col-12 col-xl-4"> + <button class="wf_create btn btn-primary w-100" onclick="cwf(0)">Book a Pod</button> + </div> + <div class="col-12 col-xl-4"> + <button class="wf_create btn btn-primary w-100" onclick="cwf(1)">Design a Pod</button> + </div> + <div class="col-12 col-xl-4"> + <button class="wf_create btn btn-primary w-100" onclick="cwf(2)">Configure a Pod</button> + </div> + </div> + {% endif %} + </div> + </div> + <!-- Returning users --> {% if not request.user.is_anonymous %} - <h2 style="margin-top: 50px;">Returning Users:</h2> - <p>If you're a returning user, some of the following options may be of interest:</p> - <button class="wf_create btn btn-primary" onclick="cwf(3)">Snapshot a Host</button> - <a class="wf_create btn btn-primary" href="{% url 'account:my-bookings' %}">My Bookings</a> - {% if manager == True %} - <button class="wf_continue btn btn-primary" onclick="continue_wf()">Continue Unfinished Workflow</button> - {% endif %} - {% endif %} - </div> - <div class=""> - </div> - <div class="actions_panel grid_panel"> - <h2>Get Started:</h2> - {% if request.user.is_anonymous %} - <h4 style="text-align:center;">To get started, please log in with your <a href="/accounts/login">Linux Foundation Jira account</a></h4> - {% else %} - <p>To get started, book a server below:</p> - <a class="wf_create btn btn-primary" style="display: flex; flex-direction: column; justify-content: center; margin: 20px; height: 100pt; vertical-align: middle; text-align: center; color: #FFF;" href="/booking/quick/"><p style="font-size: xx-large">Book a Server</p></a> - <p>PTLs can use our advanced options to book multi-node pods. If you are a PTL, you may use the options below:</p> - <div class='wf_create_div'> - - <button class="wf_create btn btn-primary" onclick="cwf(0)">Book a Pod</button> - <button class="wf_create btn btn-primary" onclick="cwf(1)">Design a Pod</button> - <button class="wf_create btn btn-primary" onclick="cwf(2)">Configure a Pod</button> - {% endif %} + <div class="col-12 col-lg-6 offset-lg-6 mb-4 mt-lg-4"> + <h2 class="ht-4">Returning Users:</h2> + <p>If you're a returning user, some of the following options may be of interest:</p> + <div class="container"> + <div class="row"> + <div class="col-12 col-xl-4"> + <button class="wf_create btn btn-primary w-100" onclick="cwf(3)">Snapshot a Host</button> + </div> + <div class="col-12 col-xl-4"> + <a class="wf_create btn btn-primary w-100" href="{% url 'account:my-bookings' %}">My + Bookings</a> + </div> + {% if manager == True %} + <div class="col-12 col-xl-4"> + <button class="wf_continue btn btn-primary w-100" onclick="continue_wf()">Resume + Workflow</button> + </div> + {% endif %} + </div> + </div> </div> + {% endif %} </div> </div> - - - - <script type="text/javascript"> - function cwf(type) - { + function cwf(type) { $.ajax({ type: "POST", url: "/", - data: {"create":type}, - beforeSend: function(request) { + data: { + "create": type + }, + beforeSend: function (request) { request.setRequestHeader("X-CSRFToken", - $('input[name="csrfmiddlewaretoken"]').val() + $('input[name="csrfmiddlewaretoken"]').val() ); } }).done(function (data) { window.location.replace("/wf/"); - }).fail(function(jqxHR, textstatus) { - alert("Something went wrong...");}); + }).fail(function (jqxHR, textstatus) { + alert("Something went wrong..."); + }); } - function continue_wf() - { + + function continue_wf() { window.location.replace("/wf/"); } - </script> <div class="hidden_form" id="form_div"> @@ -130,4 +169,4 @@ {% block vport_comm %} {% endblock %} -{% endblock content %} +{% endblock content %}
\ No newline at end of file diff --git a/src/templates/dashboard/multiple_select_filter_widget.html b/src/templates/dashboard/multiple_select_filter_widget.html index c7a1943..3a7e148 100644 --- a/src/templates/dashboard/multiple_select_filter_widget.html +++ b/src/templates/dashboard/multiple_select_filter_widget.html @@ -4,6 +4,7 @@ grid-template-columns: 1fr 1fr 1fr; border: 0px; } + .class_grid_wrapper { border: 0px; text-align: center; @@ -20,112 +21,92 @@ display: grid; grid-template-columns: 1fr 1fr; } + .grid-item { cursor: pointer; - border:1px solid #cccccc; + border: 1px solid #cccccc; border-radius: 5px; - margin:20px; + margin: 20px; height: 200px; padding: 7px; - transition-property: box-shadow, background-color; - transition-duration: .2s; -} - -.grid-item:hover { - box-shadow: 0px 0px 7px 0px rgba(0,0,0,0.45); - transition-property: box-shadow; - transition-duration: .2s; - + transition: border-color ease-in-out .1s,box-shadow ease-in-out .1s; + box-shadow: 0 1px 1px rgba(0,0,0,.075); } .selected_node { - box-shadow: 0px 0px 4px 0px rgba(0,0,0,0.45); - background-color: #fff; - transition-property: background-color; - transition-duration: .2s; + border-color: #40c640; + box-shadow: 0 1px 1px rgba(0,0,0,.075),0 0 8px rgba(109, 243, 76, 0.6); + transition: border-color ease-in-out .1s,box-shadow ease-in-out .1s; } .disabled_node { cursor: not-allowed; background-color: #EFEFEF; - transition-property: box-shadow; - transition-duration: .2s; - border: 1px solid #ccc; } -.disabled_node:hover { -} +.disabled_node:hover {} .cleared_node { background-color: #FFFFFF; } -.grid-item-header -{ +.grid-item-header { font-weight: bold; font-size: 20px; margin-top: 10px; } -#dropdown_wrapper > div > h5 { - margin: 12px; - display: inline-block; - vertical-align: middle; +.dropdown_item { + border: 1px; + border-style: solid; + border-color: lightgray; + border-radius: 5px; + margin: 20px; + padding: 2px; + grid-column: 1; + display: grid; + grid-template-columns: 1fr 3fr 1fr; + justify-items: center; } -#dropdown_wrapper > div > button { - padding: 7px; +.dropdown_item > button { margin: 2px; - float: right; - width: 80px; + justify-self: end; } -#dropdown_wrapper > div > input { - padding: 7px; - margin: 2px; - float: right; - width: 300px; - width: calc(100% - 240px); + +.dropdown_item > h5 { + margin: auto; } -#dropdown_wrapper > div { - border:2px; - border-style:none; - border-color:black; - border-radius: 5px; - margin:20px; - padding: 2px; - box-shadow: 0px 0px 7px 0px rgba(0,0,0,0.75); - transition-property: box-shadow, background-color; - transition-duration: .2s; - display: inline-block; - vertical-align: middle; +.dropdown_item > input { + padding: 7px; + margin: 2px; + width: 90%; } #dropdown_wrapper { display: grid; - grid-template-columns: 3fr 5fr; + grid-template-columns: 4fr 5fr; } - </style> + <input name="filter_field" id="filter_field" type="hidden"/> <div id="grid_wrapper" class="grid_wrapper"> -{% for object_class, object_list in filter_objects %} -<div class="class_grid_wrapper"> - <div style="display:inline-block;margin:auto"> - <h4>{{object_class}}</h4> - </div> - <div id="{{object_class}}" class="object_class_wrapper"> - {% for obj in object_list %} - <div id="object_parent"> - <div id="{{ obj.id|default:'not_provided' }}" class="grid-item"> - <p class="grid-item-header">{{obj.name}}</p> - <p class="grid-item-description">{{obj.description}}</p> - <button type="button" class="btn btn-success grid-item-select-btn" onclick="processClick('{{obj.id}}', {% if obj.multiple %}true{% else %}false{% endif %});">{% if obj.multiple %}Add{% else %}Select{% endif %}</button> +{% for object_class, object_list in display_objects %} + <div class="class_grid_wrapper"> + <div style="display:inline-block;margin:auto"> + <h4>{{object_class}}</h4> + </div> + <div id="{{object_class}}" class="object_class_wrapper"> + {% for obj in object_list %} + <div id="{{ obj.id|default:'not_provided' }}" class="grid-item"> + <p class="grid-item-header">{{obj.name}}</p> + <p class="grid-item-description">{{obj.description}}</p> + <button type="button" class="btn btn-success grid-item-select-btn" onclick="processClick( + '{{obj.id}}');">{% if obj.multiple %}Add{% else %}Select{% endif %}</button> + </div> + {% endfor %} </div> - <input type="hidden" name="{{obj.id}}_selected" value="false"/> - </div> - {% endfor %} - </div> </div> {% endfor %} </div> @@ -135,63 +116,55 @@ <script> var initialized = false; -var mapping = {{ mapping|safe }}; +var inputs = []; +var graph_neighbors = {{ neighbors|safe }}; var filter_items = {{ filter_items|safe }}; var result = {}; -var selection = {{selection_data|default_if_none:"null"|safe}}; var dropdown_count = 0; -{% if selection_data %} -make_selection({{selection_data|safe}}); -{% endif %} +{% if initial_value %} -function make_selection( selection_data ){ - if(!initialized) { - filter_field_init(); - } - for(var k in selection_data) { - selected_items = selection_data[k]; - for( var selected_item in selected_items ){ - var node = filter_items[selected_item]; - if(!node['multiple']){ - var input_value = selected_items[selected_item]; - if( input_value != 'false' ) { - select(node); - markAndSweep(node); - } - var div = document.getElementById(selected_item) - var inputs = div.parentNode.getElementsByTagName("input") - var input = div.parentNode.getElementsByTagName("input")[0] - input.value = input_value; - updateResult(selected_item); - } else { - make_multiple_selection(selected_items, selected_item); +var initial_value = {{ initial_value|safe }}; + + +function make_selection( initial_data ){ + try_init(); + for(var item_class in initial_data) { + var selected_items = initial_data[item_class]; + for( var node_id in selected_items ){ + var node = filter_items[node_id]; + var selection_data = selected_items[node_id] + if( selection_data.selected ) { + select(node); + markAndSweep(node); + updateResult(node); + } + if(node['multiple']){ + make_multiple_selection(node, selection_data); } } } } -function make_multiple_selection(data, item_class){ - var node = filter_items[item_class]; - select(node); - markAndSweep(node); - prepop_data = data[item_class]; - for(var i=0; i<prepop_data.length; i++){ - var div = add_item_prepopulate(node, prepop_data[i]); - updateObjectResult(div); +function make_multiple_selection(node, selection_data){ + prepop_data = selection_data.values; + for(var k in prepop_data){ + var div = add_item_prepopulate(node, prepop_data[k]); + updateObjectResult(node, div.id, prepop_data[k]); } } +make_selection({{initial_value|safe}}); + +{% endif %} + function markAndSweep(root){ - for(var nodeId in filter_items) { - node = filter_items[nodeId]; + for(var i in filter_items) { + node = filter_items[i]; node['marked'] = true; //mark all nodes - //clears grey background of everything } - toCheck = []; - toCheck.push(root); - + toCheck = [root]; while(toCheck.length > 0){ node = toCheck.pop(); if(!node['marked']) { @@ -199,11 +172,10 @@ function markAndSweep(root){ continue; } node['marked'] = false; //mark as visited - if(node['follow'] || node == root){ //add neighbors if we want to follow this node (labs) - var mappingId = node.id - var neighbors = mapping[mappingId]; - for(var neighId in neighbors) { - neighId = neighbors[neighId]; + if(node['follow'] || node == root){ //add neighbors if we want to follow this node + var neighbors = graph_neighbors[node.id]; + for(var i in neighbors) { + var neighId = neighbors[i]; var neighbor = filter_items[neighId]; toCheck.push(neighbor); } @@ -211,8 +183,8 @@ function markAndSweep(root){ } //now remove all nodes still marked - for(var nodeId in filter_items){ - node = filter_items[nodeId]; + for(var i in filter_items){ + node = filter_items[i]; if(node['marked']){ disable_node(node); } @@ -223,7 +195,7 @@ function process(node) { if(node['selected']) { markAndSweep(node); } - else { + else { //TODO: make this not dumb var selected = [] //remember the currently selected, then reset everything and reselect one at a time for(var nodeId in filter_items) { @@ -232,7 +204,6 @@ function process(node) { selected.push(node); } clear(node); - } for(var i=0; i<selected.length; i++) { node = selected[i]; @@ -248,9 +219,6 @@ function select(node) { elem.classList.remove('cleared_node'); elem.classList.remove('disabled_node'); elem.classList.add('selected_node'); - var input = elem.parentNode.getElementsByTagName("input")[0]; - input.disabled = false; - input.value = true; } function clear(node) { @@ -260,7 +228,6 @@ function clear(node) { elem.classList.add('cleared_node') elem.classList.remove('disabled_node'); elem.classList.remove('selected_node'); - elem.parentNode.getElementsByTagName("input")[0].disabled = true; } function disable_node(node) { @@ -270,60 +237,54 @@ function disable_node(node) { elem.classList.remove('cleared_node'); elem.classList.add('disabled_node'); elem.classList.remove('selected_node'); - elem.parentNode.getElementsByTagName("input")[0].disabled = true; } -function processClick(id, multiple){ - if(!initialized){ - filter_field_init(); - } - var element = document.getElementById(id); +function processClick(id){ + try_init(); var node = filter_items[id]; - if(!node['selectable']){ + if(!node['selectable']) return; + + if(node['multiple']){ + return processClickMultiple(node); + } else { + return processClickSingle(node); } - if(multiple){ - return processClickMultipleObject(node); - } +} + +function processClickSingle(node){ node['selected'] = !node['selected']; //toggle on click if(node['selected']) { select(node); - } - else { + } else { clear(node); } process(node); - updateResult(id); + updateResult(node); } -function processClickMultipleObject(node){ +function processClickMultiple(node){ select(node); - add_node(node); + var div = add_node(node); process(node); + updateObjectResult(node, div.id, ""); } function add_node(node){ - return add_item_prepopulate(node, {}); + return add_item_prepopulate(node, false); } -inputs = [] - -function restrictchars(input) -{ - if( input.validity.patternMismatch ) - { +function restrictchars(input){ + if( input.validity.patternMismatch ){ input.setCustomValidity("Only alphanumeric characters (a-z, A-Z, 0-9), underscore(_), and hyphen (-) are allowed"); input.reportValidity(); } - input.value = input.value.replace(/([^A-Za-z0-9-_.])+/g, ""); - checkunique(input); } -function checkunique(tocheck) -{ +function checkunique(tocheck){ val = tocheck.value; for( var i = 0; i < inputs.length; i++ ) { @@ -337,109 +298,83 @@ function checkunique(tocheck) tocheck.setCustomValidity(""); } -function add_item_prepopulate(node, prepopulate){ - inputs = []; - var div = document.createElement("DIV"); - div.class = node['id']; - div.id = "dropdown_" + dropdown_count; - dropdown_count++; - var label = document.createElement("H5"); - label.appendChild(document.createTextNode(node['name'])); - div.appendChild(label); - button = document.createElement("BUTTON"); +function make_remove_button(div, node){ + var button = document.createElement("BUTTON"); button.type = "button"; button.appendChild(document.createTextNode("Remove")); button.classList.add("btn-danger"); button.classList.add("btn"); - div.appendChild(button); - for(var i=0; i<node['forms'].length; i++){ - form = node['forms'][i]; - var input = document.createElement("INPUT"); - input.type = form['type']; - input.name = form['name']; - input.pattern = "(?=^.{1,253}$)(^([A-Za-z0-9-_]{1,62}\.)*[A-Za-z0-9-_]{1,63})"; - input.title = "Only alphanumeric characters (a-z, A-Z, 0-9), underscore(_), and hyphen (-) are allowed" - input.placeholder = form['placeholder']; - inputs.push(input); - input.onchange = function() { updateObjectResult(div); restrictchars(this); }; - input.oninput = function() { restrictchars(this); }; - if(form['name'] in prepopulate){ - input.value = prepopulate[form['name']]; - } - div.appendChild(input); - } - //add class id to dropdown object - var hiddenInput = document.createElement("INPUT"); - hiddenInput.type = "hidden"; - hiddenInput.name = "class"; - hiddenInput.value = node['id']; - div.appendChild(hiddenInput); button.onclick = function(){ - remove_dropdown(div.id); + remove_dropdown(div.id, node.id); } + return button; +} + +function make_input(div, node, prepopulate){ + var input = document.createElement("INPUT"); + input.type = node.form.type; + input.name = node.id + node.form.name + input.pattern = "(?=^.{1,253}$)(^([A-Za-z0-9-_]{1,62}\.)*[A-Za-z0-9-_]{1,63})"; + input.title = "Only alphanumeric characters (a-z, A-Z, 0-9), underscore(_), and hyphen (-) are allowed" + input.placeholder = node.form.placeholder; + inputs.push(input); + input.onchange = function() { updateObjectResult(node, div.id, input.value); restrictchars(this); }; + input.oninput = function() { restrictchars(this); }; + if(prepopulate) + input.value = prepopulate; + return input; +} + +function add_item_prepopulate(node, prepopulate){ + var div = document.createElement("DIV"); + div.id = "dropdown_" + dropdown_count; + div.classList.add("dropdown_item"); + dropdown_count++; + var label = document.createElement("H5") + label.appendChild(document.createTextNode(node['name'])) + div.appendChild(label); + div.appendChild(make_input(div, node, prepopulate)); + div.appendChild(make_remove_button(div, node)); document.getElementById("dropdown_wrapper").appendChild(div); - var linebreak = document.createElement("BR"); - document.getElementById("dropdown_wrapper").appendChild(linebreak); - updateObjectResult(div); return div; } -function remove_dropdown(id){ - var div = document.getElementById(id); +function remove_dropdown(div_id, node_id){ + var div = document.getElementById(div_id); + var node = filter_items[node_id] var parent = div.parentNode; div.parentNode.removeChild(div); + delete result[node.class][node.id]['values'][div.id]; + //checks if we have removed last item in class - var deselect_class = true; - var div_inputs = div.getElementsByTagName("input"); - var div_class = div_inputs[div_inputs.length-1].value; - var result_class = document.getElementById(div_class).parentNode.parentNode.id; - delete result[result_class][div.id]; - for(var i=0; i<parent.children.length; i++){ - var inputs = parent.children[i].getElementsByTagName("input"); - var object_class = ""; - for(var k=0; k<inputs.length; k++){ - if(inputs[k].name == "class"){ - object_class = inputs[k].value; - } - } - if(object_class == div_class){ - deselect_class = false; - } - } - if(deselect_class){ - clear(filter_items[div_class]); + if(jQuery.isEmptyObject(result[node.class][node.id]['values'])){ + delete result[node.class][node.id]; + clear(node); } } - -function updateResult(nodeId){ - if(!initialized){ - filter_field_init(); - } - if(!filter_items[nodeId]['multiple']){ - var node = document.getElementById(nodeId); - var value = {} - value[nodeId] = node.parentNode.getElementsByTagName("input")[0].value; - result[node.parentNode.parentNode.id] = {}; - result[node.parentNode.parentNode.id][nodeId] = value; +function updateResult(node){ + try_init(); + if(!node['multiple']){ + result[node.class][node.id] = {selected: node.selected, id: node.model_id} + if(!node.selected) + delete result[node.class][node.id]; } } -function updateObjectResult(parentElem){ - node_type = document.getElementById(parentElem.class).parentNode.parentNode.id; - input = {}; - inputs = parentElem.getElementsByTagName("input"); - for(var i in inputs){ - var e = inputs[i]; - input[e.name] = e.value; - } - result[node_type][parentElem.id] = input; +function updateObjectResult(node, childKey, childValue){ + try_init(); + if(!result[node.class][node.id]) + result[node.class][node.id] = {selected: true, id: node.model_id, values: {}} + + result[node.class][node.id]['values'][childKey] = childValue; } -function filter_field_init() { +function try_init() { + if(initialized) return; for(nodeId in filter_items) { - element = document.getElementById(nodeId); - node = filter_items[nodeId]; - result[element.parentNode.parentNode.id] = {} + var element = document.getElementById(nodeId); + var node = filter_items[nodeId]; + result[node.class] = {} } initialized = true; } diff --git a/src/templates/dashboard/resource.html b/src/templates/dashboard/resource.html index 28e7998..f36ee7b 100644 --- a/src/templates/dashboard/resource.html +++ b/src/templates/dashboard/resource.html @@ -7,11 +7,11 @@ <link href="{% static "bower_components/morrisjs/morris.css" %}" rel="stylesheet"> <!-- DataTables CSS --> - <link href="{% static "bower_components/datatables-plugins/integration/bootstrap/3/dataTables.bootstrap.css" %}" + <link href="{% static "bower_components/datatables.net-bs4/css/dataTables.bootstrap4.min.css" %}" rel="stylesheet"> <!-- DataTables Responsive CSS --> - <link href="{% static "bower_components/datatables-responsive/css/dataTables.responsive.css" %}" + <link href="{% static "bower_components/datatables.net-responsive-bs4/css/responsive.bootstrap4.min.css" %}" rel="stylesheet"> {% endblock extrahead %} @@ -23,11 +23,11 @@ {% block extrajs %} <!-- DataTables JavaScript --> - <link href="{% static "bower_components/datatables-plugins/integration/bootstrap/3/dataTables.bootstrap.css" %}" + <link href="{% static "bower_components/datatables/media/css/dataTables.bootstrap.css" %}" rel="stylesheet"> - <script src={% static "bower_components/datatables/media/js/jquery.dataTables.min.js" %}></script> - <script src={% static "bower_components/datatables-plugins/integration/bootstrap/3/dataTables.bootstrap.min.js" %}></script> + <script src={% static "bower_components/datatables.net/js/jquery.dataTables.min.js" %}></script> + <script src={% static "bower_components/datatables.net-bs4/js/dataTables.bootstrap4.min.js" %}></script> diff --git a/src/templates/dashboard/resource_all.html b/src/templates/dashboard/resource_all.html index 0b0d0d4..fb8cc7e 100644 --- a/src/templates/dashboard/resource_all.html +++ b/src/templates/dashboard/resource_all.html @@ -7,11 +7,11 @@ <link href="{% static "bower_components/morrisjs/morris.css" %}" rel="stylesheet"> <!-- DataTables CSS --> - <link href="{% static "bower_components/datatables-plugins/integration/bootstrap/3/dataTables.bootstrap.css" %}" + <link href="{% static "bower_components/datatables.net-bs4/css/dataTables.bootstrap4.min.css" %}" rel="stylesheet"> <!-- DataTables Responsive CSS --> - <link href="{% static "bower_components/datatables-responsive/css/dataTables.responsive.css" %}" + <link href="{% static "bower_components/datatables.net-responsive-bs4/css/responsive.bootstrap4.min.css" %}" rel="stylesheet"> {% endblock extrahead %} @@ -36,11 +36,11 @@ {% block extrajs %} <!-- DataTables JavaScript --> - <link href="{% static "bower_components/datatables-plugins/integration/bootstrap/3/dataTables.bootstrap.css" %}" + <link href="{% static "bower_components/datatables/media/css/dataTables.bootstrap.css" %}" rel="stylesheet"> - <script src={% static "bower_components/datatables/media/js/jquery.dataTables.min.js" %}></script> - <script src={% static "bower_components/datatables-plugins/integration/bootstrap/3/dataTables.bootstrap.min.js" %}></script> + <script src={% static "bower_components/datatables.net/js/jquery.dataTables.min.js" %}></script> + <script src={% static "bower_components/datatables.net-bs4/js/dataTables.bootstrap4.min.js" %}></script> diff --git a/src/templates/dashboard/searchable_select_multiple.html b/src/templates/dashboard/searchable_select_multiple.html index c08fbe5..91ed09c 100644 --- a/src/templates/dashboard/searchable_select_multiple.html +++ b/src/templates/dashboard/searchable_select_multiple.html @@ -1,41 +1,57 @@ <script src="https://code.jquery.com/jquery-2.2.4.min.js"></script> -<div class="autocomplete" style="width:400px;"> +<div id="search_select_outer" class="autocomplete"> <div id="warning_pane" style="background: #FFFFFF; color: #CC0000;"> {% if incompatible == "true" %} <h3>Warning: Incompatible Configuration</h3> <p>Please make a different selection, as the current config conflicts with the selected pod</p> {% endif %} </div> - <input id="user_field" name="ignore_this" class="form-control" autocomplete="off" type="text" placeholder="{{placeholder}}" value="{{initial.name}}" oninput="search(this.value)" + <div id="added_counter"> + <p id="added_number">0</p> + <p id="addable_limit">/ {% if selectable_limit > -1 %} {{ selectable_limit }} {% else %} ∞ {% endif %}added</p> + </div> + + <div id="added_list"> + + </div> + + <input id="user_field" name="ignore_this" class="form-control" autocomplete="off" type="text" placeholder="{{placeholder}}" value="" oninput="search(this.value)" {% if disabled %} disabled {% endif %} > + </input> <input type="hidden" id="selector" name="{{ name }}" class="form-control" style="display: none;" {% if disabled %} disabled {% endif %} > </input> - <ul id="drop_results"></ul> - - - <div id="default_entry_wrap" style="display: none;"> - <div class="list_entry unremovable_list_entry"> - <p id="default_text" class="full_name"></p> - <button class="btn-remove btn disabled">remove</button> - </div> + <div id="scroll_restrictor"> + <ul id="drop_results"></ul> </div> + <style> + #scroll_restrictor { + flex: 1; + position: relative; + overflow-y: auto; + padding-bottom: 10px; + } - <div id="added_list"> + #added_list { + margin-bottom: 5px; + } - </div> - <div id="added_counter" style="text-align: center; margin: 10px;"><p id="added_number" style="display: inline;">0</p><p style="display: inline;">/ - {% if selectable_limit > -1 %} {{ selectable_limit }} {% else %} ∞ {% endif %}added</p></div> - <style> + .autocomplete { + display: flex; + flex: 1; + flex-direction: column; + } #user_field { font-size: 14pt; - width: 400px; padding: 5px; + height: 40px; + border: 1px solid #ccc; + border-radius: 5px; } @@ -43,69 +59,135 @@ list-style-type: none; padding: 0; margin: 0; - max-height: 300px; min-height: 0; - overflow-y: scroll; - overflow-x: hidden; border: solid 1px #ddd; - display: none; + border-top: none; + border-bottom: none; + visibility: inherit; + flex: 1; + + position: absolute; + width: 100%; } #drop_results li a{ font-size: 14pt; - border: 1px solid #ddd; background-color: #f6f6f6; - padding: 12px; + padding: 7px; text-decoration: none; display: block; - width: 400px; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; } - .btn-remove { - float: right; - height: 30px; - margin: 4px; + #drop_results li a { + border-bottom: 1px solid #ddd; } .list_entry { - width: 400px; - border: 1px solid #ddd; - border-radius: 3px; + border: 1px solid #ccc; + border-radius: 5px; margin-top: 5px; vertical-align: middle; line-height: 40px; height: 40px; padding-left: 12px; + width: 100%; + display: flex; } #drop_results li a:hover{ background-color: #ffffff; } - .small_name { - display: inline-block; + .added_entry_text { + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + display: inline; + width: 100%; + } + + .btn-remove { + float: right; + height: 30px; + margin: 4px; + padding: 1px; + max-width: 20%; + width: 15%; + min-width: 70px; + overflow: hidden; + text-overflow: ellipsis; + } + + .entry_tooltip { + display: none; + } + + #drop_results li a:hover .entry_tooltip { + position: absolute; + background: #444; + color: #ddd; + text-align: center; + font-size: 12pt; + border-radius: 3px; + } - .full_name { + #drop_results { + max-width: 100%; display: inline-block; + list-style-type: none; + overflow: hidden; + white-space: nowrap; + text-overflow: ellipsis; + } + + #drop_results li { + overflow: hidden; + text-overflow: ellipsis; } + #added_counter { + text-align: center; + } + + #added_number, #addable_limit { + display: inline; + } </style> </div> <script type="text/javascript"> //flags - var show_from_noentry = {{show_from_noentry|default:"false"}}; - var show_x_results = {{show_x_results|default:-1}}; - var results_scrollable = {{results_scrollable|default:"false"}}; - var selectable_limit = {{selectable_limit|default:-1}}; - var field_name = "{{name|default:"users"}}"; - var placeholder = "{{placeholder|default:"begin typing"}}"; - var default_entry = "{{default_entry}}"; + var show_from_noentry = {{show_from_noentry|yesno:"true,false"}}; // whether to show any results before user starts typing + var show_x_results = {{show_x_results|default:-1}}; // how many results to show at a time, -1 shows all results + var results_scrollable = {{results_scrollable|yesno:"true,false"}}; // whether list should be scrollable + var selectable_limit = {{selectable_limit|default:-1}}; // how many selections can be made, -1 allows infinitely many + var placeholder = "{{placeholder|default:"begin typing"}}"; // placeholder that goes in text box //needed info - var items = {{items|safe}} + var items = {{items|safe}} // items to add to trie. Type is a dictionary of dictionaries with structure: + /* + { + id# : { + "id": any, identifiable on backend + "small_name": string, displayed first (before separator), searchable (use for e.g. username) + "expanded_name": string, displayed second (after separator), searchable (use for e.g. email address) + "string": string, not displayed, still searchable + } + } + */ + + /* used later: + {{ selectable_limit }}: changes what number displays for field + {{ name }}: form identifiable name, relevant for backend + // when submitted, form will contain field data in post with name as the key + {{ placeholder }}: "greyed out" contents put into search field initially to guide user as to what they're searching for + {{ initial }}: in search_field_init(), marked safe, an array of id's each referring to an id from items + */ //tries var expanded_name_trie = {} @@ -116,18 +198,6 @@ string_trie.isComplete = false; var added_items = []; - var initial_log = {{ initial|safe }}; - - var added_template = {{ added_list|default:"{}" }}; - - if( default_entry ) - { - var default_entry_div = document.getElementById("default_entry_wrap"); - default_entry_div.style.display = "inherit"; - - var entry_p = document.getElementById("default_text"); - entry_p.innerText = default_entry; - } search_field_init(); @@ -200,7 +270,11 @@ if( str.length == 1 ) { new_trie.isComplete = true; - new_trie.itemID = id; + if( !new_trie.ids ) + { + new_trie.ids = []; + } + new_trie.ids.push(id); } inner_trie = new_trie; str = str.substring(1); @@ -274,7 +348,7 @@ } if ( trie.isComplete ) { - itemIDs.push( trie.itemID ); + itemIDs.push(...trie.ids); } return itemIDs; @@ -298,6 +372,14 @@ return results; } + function generate_element_text(obj) + { + var content_strings = [obj['expanded_name'], obj['small_name'], obj['string']].filter(x => Boolean(x)); + var result = content_strings.shift(); + if( result == null || content_strings.length < 1) return result; + return result + " (" + content_strings.join(", ") + ")"; + } + function dropdown(ids) { /* @@ -315,27 +397,34 @@ var result_entry = document.createElement("li"); var result_button = document.createElement("a"); var obj = items[id]; - var result_text = document.createTextNode(obj['small_name'] + " : " + obj['expanded_name']); - result_button.appendChild(result_text); + var result_text = generate_element_text(obj); + result_button.appendChild(document.createTextNode(result_text)); result_button.setAttribute('onclick', 'select_item("' + obj['id'] + '")'); + var tooltip = document.createElement("span"); + var tooltiptext = document.createTextNode(result_text); + tooltip.appendChild(tooltiptext); + tooltip.setAttribute('class', 'entry_tooltip'); + result_button.appendChild(tooltip); result_entry.appendChild(result_button); drop.appendChild(result_entry); } + var scroll_restrictor = document.getElementById("scroll_restrictor"); + if( !drop.firstChild ) { - drop.style.display = 'none'; + scroll_restrictor.style.visibility = 'hidden'; } else { - drop.style.display = 'inherit'; + scroll_restrictor.style.visibility = 'inherit'; } } function select_item(item_id) { //TODO make faster - var item = items[item_id]; + var item = items[item_id]['id']; if( (selectable_limit > -1 && added_items.length < selectable_limit) || selectable_limit < 0 ) { if( added_items.indexOf(item) == -1 ) @@ -344,7 +433,10 @@ } } update_selected_list(); + // clear search bar contents + document.getElementById("user_field").value = ""; document.getElementById("user_field").focus(); + search(""); } function remove_item(item_ref) @@ -357,11 +449,6 @@ document.getElementById("user_field").focus(); } - function edit_item(item_id){ - var wf_type = "{{wf_type}}"; - parent.add_edit_wf(wf_type, item_id); - } - function update_selected_list() { document.getElementById("added_number").innerText = added_items.length; @@ -382,32 +469,21 @@ for( var key in added_items ) { - item = added_items[key]; + item_id = added_items[key]; + item = items[item_id]; - list_html += '<div class="list_entry"><p class="full_name">' - + item["expanded_name"] - + '</p><p class="small_name">, ' - + item["small_name"] - + '</p><button onclick="remove_item(' + var element_entry_text = generate_element_text(item); + + list_html += '<div class="list_entry">' + + '<p class="added_entry_text">' + + element_entry_text + + '</p>' + + '<button onclick="remove_item(' + Object.values(items).indexOf(item) + ')" class="btn-remove btn">remove</button>'; - {% if edit %} - list_html += '<button onclick="edit_item(' - + item['id'] - + ')" class="btn-remove btn">edit</button>'; - {% endif %} list_html += '</div>'; } added_list.innerHTML = list_html; } - </script> -<style> - .full_name { - display: inline-block; - } - .small_name { - display: inline-block; - } -</style> diff --git a/src/templates/dashboard/table.html b/src/templates/dashboard/table.html index b3f4b5f..0a37ded 100644 --- a/src/templates/dashboard/table.html +++ b/src/templates/dashboard/table.html @@ -4,11 +4,12 @@ {% block extrahead %} {{ block.super }} <!-- DataTables CSS --> - <link href="{% static "bower_components/datatables-plugins/integration/bootstrap/3/dataTables.bootstrap.css" %}" + <link href="{% static "bower_components/datatables.net-bs4/css/dataTables.bootstrap4.min.css" %}" rel="stylesheet"> <!-- DataTables Responsive CSS --> - <link href="{% static "bower_components/datatables-responsive/css/dataTables.responsive.css" %}" rel="stylesheet"> + <link href="{% static "bower_components/datatables.net-responsive-bs4/css/responsive.bootstrap4.min.css" %}" + rel="stylesheet"> {% endblock extrahead %} {% block content %} @@ -34,8 +35,8 @@ {% block extrajs %} <!-- DataTables JavaScript --> - <script src={% static "bower_components/datatables/media/js/jquery.dataTables.min.js" %}></script> - <script src={% static "bower_components/datatables-plugins/integration/bootstrap/3/dataTables.bootstrap.min.js" %}></script> + <script src={% static "bower_components/datatables.net/js/jquery.dataTables.min.js" %}></script> + <script src={% static "bower_components/datatables.net-bs4/js/dataTables.bootstrap4.min.js" %}></script> <script src={% static "js/dataTables-sort.js" %}></script> diff --git a/src/templates/layout.html b/src/templates/layout.html index 13f182b..d37d4f5 100644 --- a/src/templates/layout.html +++ b/src/templates/layout.html @@ -20,7 +20,7 @@ <link href="{% static "bower_components/metisMenu/dist/metisMenu.min.css" %}" rel="stylesheet"> <!-- Custom Fonts --> - <link href="{% static "bower_components/font-awesome/css/font-awesome.min.css" %}" + <link href="{% static "bower_components/Font-Awesome/css/all.min.css" %}" rel="stylesheet" type="text/css"> <!-- Favicon --> @@ -50,17 +50,12 @@ {#<!-- jQuery -->#} {#<script src="{% static "bower_components/jquery/dist/jquery.min.js" %}"></script>#} {#<script src="{% static "bower_components/jquery-migrate/jquery-migrate.min.js" %}"></script>#} - +<!-- Popper.js --> +<script src="{% static "bower_components/popper.js/dist/umd/popper.min.js" %}"></script> {#<script src="https://code.jquery.com/jquery-2.2.0.min.js"></script>#} <!-- Bootstrap Core JavaScript --> <script src="{% static "bower_components/bootstrap/dist/js/bootstrap.min.js" %}"></script> -<!-- Metis Menu Plugin JavaScript --> -<script src="{% static "bower_components/metisMenu/dist/metisMenu.min.js" %}"></script> - -<!-- Custom Theme JavaScript --> -<script src="{% static "bower_components/startbootstrap-sb-admin-2-blackrockdigital/dist/js/sb-admin-2.min.js" %}"></script> - {% block extrajs %} {% endblock extrajs %} </body> diff --git a/src/templates/notifier/inbox.html b/src/templates/notifier/inbox.html index 4184d1d..72207ed 100644 --- a/src/templates/notifier/inbox.html +++ b/src/templates/notifier/inbox.html @@ -6,97 +6,124 @@ {% block content %} <style media="screen"> - - .inbox-panel { - display: grid; - grid-template-columns: 30% 5% 65%; - } - - .section-panel { - padding: 10px; - } - - .iframe-panel { - padding: 0px; - margin-top: 0px; - } - - .card-container { - border: 1px solid #cccccc; - border-bottom: 0px; - } - .card { - height: 50px; - position: relative; - border-bottom: 1px solid #cccccc; - padding: 10px; - width: 100%; - background-color: #ffffff; - z-index: 5; - } - .selected-card { - background-color: #f3f3f3; - } - - .card:hover { - box-shadow: 0px 0 5px 2px #cccccc; - z-index: 6; - } - - #inbox-iframe { - height: calc(100vh - 57px); - } - - .half_width { - width: 50%; - } - .card-wrapper { - } - - #page-wrapper{ - padding: 0px; - } - - .read_notification{ - background-color: #efefef; - } + .inbox-panel { + display: grid; + grid-template-columns: 30% 5% 65%; + } + + .section-panel { + padding: 10px; + } + + .iframe-panel { + padding: 0px; + margin-top: 0px; + } + + .card-container { + border: 1px solid #cccccc; + border-bottom: 0px; + } + + .card { + height: 50px; + position: relative; + border-bottom: 1px solid #cccccc; + padding: 10px; + width: 100%; + background-color: #ffffff; + z-index: 5; + } + + .selected-card { + background-color: #f3f3f3; + } + + .card:hover { + box-shadow: 0px 0 5px 2px #cccccc; + z-index: 6; + } + + .half_width { + width: 50%; + } + + #page-wrapper { + padding: 0px; + } + + .read_notification { + background-color: #efefef; + } + + .scrollable { + overflow-y: auto; + } </style> - -<div class="inbox-panel"> - <div class="section-panel"> - <h4>New:</h4> - <div class="card-container"> - {% for notification in unread_notifications %} - <div class="inbox-entry card" onclick="showmessage({{notification.id}}); setactive(this);"> - {{ notification }} +<div class="container-fluid d-flex flex-grow-1 flex-column"> + <div class="row mt-3 mb-2"> + <div class="col-2 px-0"> + <div class="btn-group w-100" id="filterGroup"> + <button class="btn btn-secondary active" data-read="-1">All</button> + <button class="btn btn-secondary" data-read="0">Unread</button> + <button class="btn btn-secondary" data-read="1">Read</button> + </div> </div> - {% endfor %} </div> - <h4>Read:</h4> - <div class="card-container"> - {% for notification in read_notifications %} - <div class="inbox-entry card read_notification" onclick="showmessage({{notification.id}}); setactive(this);"> - {{ notification }} + <div class="row flex-grow-1" id="fixHeight"> + <!-- Notification list && Controls --> + <div class="mb-2 mb-lg-0 col-lg-2 px-0 mh-100"> + <div class="list-group rounded-0 rounded-left scrollable mh-100 notifications" id="unreadNotifications" data-read="0"> + {% for notification in unread_notifications %} + <a + href="#" + onclick="showmessage({{notification.id}}); setactive(this);" + class="list-group-item list-group-item-action notification"> + {{ notification }} + </a> + {% endfor %} + </div> + <div class="list-group rounded-0 rounded-left scrollable mh-100 notifications" id="readNotifications" data-read="1"> + {% for notification in read_notifications %} + <a + href="#" + onclick="showmessage({{notification.id}}); setactive(this);" + class="list-group-item list-group-item-action list-group-item-secondary notification"> + {{ notification }} + </a> + {% endfor %} + </div> + </div> + <!-- Content --> + <div class="col ml-lg-2 border mh-100 p-4"> + <iframe class="w-100 h-100" id="inbox-iframe" frameBorder="0" scrolling="yes">Please select a notification</iframe> </div> - {% endfor %} </div> - </div> - <div> - </div> - <div class="iframe-panel inbox-expanded-view"> - <div class="inbox-iframe-div"> - <iframe id="inbox-iframe" frameBorder="0" width="100%" height="100vh" scrolling="yes">Please select a notification</iframe> - </div> - </div> </div> <script type="text/javascript"> - - function showmessage(msg_id) - { - iframe = document.getElementById("inbox-iframe"); - iframe.src = "notification/" + msg_id; - } - + function showmessage(msg_id) { + iframe = document.getElementById("inbox-iframe"); + iframe.src = "notification/" + msg_id; + } + + function setactive(obj) { + $(".notification").removeClass("active"); + $(obj).addClass("active"); + } + + $(document).ready(function(){ + // For all / unread / read + $("#filterGroup button").click(function(){ + let read = $(this).attr("data-read"); + $(this).siblings().removeClass("active"); + $(".notifications").addClass("d-none"); + $(this).addClass("active"); + if (read === "-1") { + return $(".notifications").removeClass("d-none"); + } + $(`.notifications[data-read="${read}"]`).removeClass("d-none"); + }); + }); </script> -{% endblock %} +{% endblock %}
\ No newline at end of file diff --git a/src/templates/resource/hostprofile_detail.html b/src/templates/resource/hostprofile_detail.html index 0776b9e..dc20600 100644 --- a/src/templates/resource/hostprofile_detail.html +++ b/src/templates/resource/hostprofile_detail.html @@ -4,45 +4,35 @@ {% block content %} <div class="row"> <div class="col-lg-6"> - <div class="panel panel-default"> - <div class="panel-heading clearfix"> + <div class="card mb-4"> + <div class="card-header d-flex"> <h4 style="display: inline;">Available at</h4> - <a data-toggle="collapse" data-target="#panel_overview" class="btn pull-right" style="line-height: 1;" >Expand</a> + <button data-toggle="collapse" data-target="#avilableAt" class="btn ml-auto btn-outline-secondary">Expand</button> </div> - <div class="panel-body" id="panel_overview"> - <table class="table"> - <tr> - <td> - <ul> - {% for lab in hostprofile.labs.all %} - <li>{{lab.name}}</li> - {% endfor %} - </ul> - </td> - </tr> - </table> + <div class="card-body collapse show" id="avilableAt"> + <ul class="list-group"> + {% for lab in hostprofile.labs.all %} + <li class="list-group-item">{{lab.name}}</li> + {% endfor %} + </ul> </div> </div> - <div class="panel panel-default"> - <div class="panel-heading clearfix"> + <div class="card mb-4"> + <div class="card-header d-flex"> <h4 style="display: inline;">RAM</h4> - <a data-toggle="collapse" data-target="#panel_overview" class="btn pull-right" style="line-height: 1;" >Expand</a> + <button data-toggle="collapse" data-target="#ramPanel" class="btn ml-auto btn-outline-secondary">Expand</button> </div> - <div class="panel-body" id="panel_overview"> - <table class="table"> - <tr> - <td>{{hostprofile.ramprofile.first.amount}}G, - {{hostprofile.ramprofile.first.channels}} channels</td> - </tr> - </table> + <div class="card-body collapse show" id="ramPanel"> + {{hostprofile.ramprofile.first.amount}}G, + {{hostprofile.ramprofile.first.channels}} channels </div> </div> - <div class="panel panel-default"> - <div class="panel-heading clearfix"> + <div class="card mb-4"> + <div class="card-header d-flex"> <h4 style="display: inline;">CPU</h4> - <a data-toggle="collapse" data-target="#panel_overview" class="btn pull-right" style="line-height: 1;" >Expand</a> + <button data-toggle="collapse" data-target="#cpuPanel" class="btn ml-auto btn-outline-secondary">Expand</button> </div> - <div class="panel-body" id="panel_overview"> + <div class="card-body collapse show" id="cpuPanel"> <table class="table"> <tr> <td>Arch:</td> @@ -59,42 +49,12 @@ </table> </div> </div> - </div> - <div class="col-lg-6"> - <div class="panel panel-default"> - <div class="panel-heading clearfix"> - <h4 style="display: inline;">Interfaces</h4> - <a data-toggle="collapse" data-target="#panel_overview" class="btn pull-right" style="line-height: 1;" >Expand</a> - </div> - <div class="panel-body" id="panel_overview"> - <table class="table"> - {% for intprof in hostprofile.interfaceprofile.all %} - <tr> - <td> - <table class="table borderless"> - <tr> - <td>Name:</td> - <td>{{intprof.name}}</td> - </tr> - <tr> - <td>Speed:</td> - <td>{{intprof.speed}}</td> - </tr> - </table> - </td> - </tr> - {% endfor %} - </table> - </div> - </div> - </div> - <div class="col-lg-6"> - <div class="panel panel-default"> - <div class="panel-heading clearfix"> + <div class="card mb-4"> + <div class="card-header d-flex"> <h4 style="display: inline;">Disk</h4> - <a data-toggle="collapse" data-target="#panel_overview" class="btn pull-right" style="line-height: 1;" >Expand</a> + <button data-toggle="collapse" data-target="#diskPanel" class="btn ml-auto btn-outline-secondary">Expand</button> </div> - <div class="panel-body" id="panel_overview"> + <div class="card-body collapse show" id="diskPanel"> <table class="table"> <tr> <td>Size:</td> @@ -112,5 +72,31 @@ </div> </div> </div> + <div class="col-lg-6"> + <div class="card"> + <div class="card-header d-flex"> + <h4 style="display: inline;">Interfaces</h4> + <button data-toggle="collapse" data-target="#interfacePanel" class="btn ml-auto btn-outline-secondary">Expand</button> + </div> + <div class="card-body collapse show" id="interfacePanel"> + <table class="table"> + <thead> + <tr> + <th>Name</th> + <th>Speed</th> + </tr> + </thead> + <tbody> + {% for intprof in hostprofile.interfaceprofile.all %} + <tr> + <td>{{intprof.name}}</td> + <td>{{intprof.speed}}</td> + </tr> + {% endfor %} + </tbody> + </table> + </div> + </div> + </div> </div> {% endblock content %} diff --git a/src/templates/resource/steps/define_hardware.html b/src/templates/resource/steps/define_hardware.html index 933b4ab..77df5a2 100644 --- a/src/templates/resource/steps/define_hardware.html +++ b/src/templates/resource/steps/define_hardware.html @@ -1,7 +1,7 @@ {% extends "workflow/viewport-element.html" %} {% load staticfiles %} -{% load bootstrap3 %} +{% load bootstrap4 %} {% block content %} <p>Note that not all labs host every kind of machine. @@ -26,7 +26,7 @@ var normalize = function(data){ } return normalized; } -var data = normalize(result); +var data = result; data = JSON.stringify(data); document.getElementById("filter_field").value = data; var formData = $("#define_hardware_form").serialize(); diff --git a/src/templates/resource/steps/host_info.html b/src/templates/resource/steps/host_info.html index 0275727..bbbafdc 100644 --- a/src/templates/resource/steps/host_info.html +++ b/src/templates/resource/steps/host_info.html @@ -1,7 +1,7 @@ {% extends "workflow/viewport-element.html" %} {% load staticfiles %} -{% load bootstrap3 %} +{% load bootstrap4 %} {% block content %} diff --git a/src/templates/resource/steps/meta_info.html b/src/templates/resource/steps/meta_info.html index da98267..cebd343 100644 --- a/src/templates/resource/steps/meta_info.html +++ b/src/templates/resource/steps/meta_info.html @@ -1,7 +1,7 @@ {% extends "workflow/viewport-element.html" %} {% load staticfiles %} -{% load bootstrap3 %} +{% load bootstrap4 %} {% block content %} diff --git a/src/templates/resource/steps/pod_definition.html b/src/templates/resource/steps/pod_definition.html index 2cb6257..f8aaa74 100644 --- a/src/templates/resource/steps/pod_definition.html +++ b/src/templates/resource/steps/pod_definition.html @@ -206,7 +206,7 @@ function deleteCell(cellId) { } function newNetworkWindow() { - var innerHtml = 'Name: <input type="text" name="net_name" id="net_name_input" style="margin:5px;"><br>'; + var innerHtml = 'Name: <input type="text" name="net_name" maxlength="100" id="net_name_input" style="margin:5px;"><br>'; innerHtml += '<button style="width: 46%;" onclick="parseNetworkWindow()">Okay</button>'; innerHtml += '<button style="width: 46%;" onclick="currentWindow.destroy();">Cancel</button><br>'; innerHtml += '<div id="current_window_errors"/>'; diff --git a/src/templates/snapshot_workflow/steps/meta.html b/src/templates/snapshot_workflow/steps/meta.html index cc49691..bea475d 100644 --- a/src/templates/snapshot_workflow/steps/meta.html +++ b/src/templates/snapshot_workflow/steps/meta.html @@ -1,7 +1,7 @@ {% extends "workflow/viewport-element.html" %} {% load staticfiles %} -{% load bootstrap3 %} +{% load bootstrap4 %} {% block content %} <style> diff --git a/src/templates/snapshot_workflow/steps/select_host.html b/src/templates/snapshot_workflow/steps/select_host.html index 27a9238..f438bac 100644 --- a/src/templates/snapshot_workflow/steps/select_host.html +++ b/src/templates/snapshot_workflow/steps/select_host.html @@ -1,7 +1,7 @@ {% extends "workflow/viewport-element.html" %} {% load staticfiles %} -{% load bootstrap3 %} +{% load bootstrap4 %} {% block content %} diff --git a/src/templates/workflow/confirm.html b/src/templates/workflow/confirm.html index 2510204..c1f3440 100644 --- a/src/templates/workflow/confirm.html +++ b/src/templates/workflow/confirm.html @@ -1,7 +1,7 @@ {% extends "workflow/viewport-element.html" %} {% load staticfiles %} -{% load bootstrap3 %} +{% load bootstrap4 %} {% block content %} @@ -58,6 +58,17 @@ <script> var select = document.getElementById("id_confirm"); + function processResponseText(json) + { + var dict = JSON.parse(json); + + if( !dict["redir_url"] ) { + window.top.refresh_iframe(); + } else { + top.window.location.href = dict["redir_url"]; + } + } + function delete_manager() { var form = $("#manager_delete_form"); @@ -67,7 +78,7 @@ req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); req.onerror = function() { alert("problem with cleaning up session"); } req.onreadystatechange = function() { if(req.readyState === 4 ) { - window.top.refresh_iframe(); + processResponseText(req.responseText); }} req.send(formData); } diff --git a/src/templates/workflow/exit_redirect.html b/src/templates/workflow/exit_redirect.html deleted file mode 100644 index b08df78..0000000 --- a/src/templates/workflow/exit_redirect.html +++ /dev/null @@ -1,6 +0,0 @@ -<!DOCTYPE html> -<html> - <script> - top.window.location.href='/'; - </script> -</html> diff --git a/src/templates/workflow/resource_select.html b/src/templates/workflow/resource_select.html index c319ff5..cd04137 100644 --- a/src/templates/workflow/resource_select.html +++ b/src/templates/workflow/resource_select.html @@ -1,7 +1,7 @@ {% extends "workflow/viewport-element.html" %} {% load staticfiles %} -{% load bootstrap3 %} +{% load bootstrap4 %} {% block content %} diff --git a/src/templates/workflow/viewport-base.html b/src/templates/workflow/viewport-base.html index beea7d2..aa01d7e 100644 --- a/src/templates/workflow/viewport-base.html +++ b/src/templates/workflow/viewport-base.html @@ -1,12 +1,12 @@ {% extends "base.html" %} {% load staticfiles %} -{% load bootstrap3 %} +{% load bootstrap4 %} {% block content %} <style> - .go_btn{ + .go_btn { position: absolute; width: 100px; @@ -14,43 +14,36 @@ height: calc(100% - 170px); } - .go_btn_disabled{ - background-color: #ffffff; + + .go_btn_disabled { + background-color: #ffffff; } - .go_forward{ + + .go_forward { right: 0px; border-left: none; } - .go_back{ + .go_back { left: 251px; border-right: none; } - .btn_wrapper{ + .btn_wrapper { text-align: center; margin-bottom: 5px; } {% if DEBUG %} - - .add_btn_wrapper{ - right: 130px; - top: 10px; - position: absolute; - } + .add_btn_wrapper { + right: 130px; + top: 10px; + position: absolute; + } {% endif %} - - - .options{ - position: absolute; - top: 60px; - right: 20px; - } - #breadcrumbs { margin-bottom: 0; } @@ -59,23 +52,25 @@ margin: 0; } - .step{ + .step { display: inline; padding: 7px; margin: 1px; font-size: 14pt; cursor: default; } + .step:active { -webkit-box-shadow: inherit; box-shadow: inherit; } + .step_active:active { -webkit-box-shadow: inherit; box-shadow: inherit; } - .step_active{ + .step_active { display: inline; padding: 7px; margin: 1px; @@ -85,26 +80,22 @@ border-bottom: 4px solid #41ba78 !important; } - .step_hidden - { + .step_hidden { background: #EFEFEF; color: #999999; } - .step_invalid::after - { + .step_invalid::after { content: " \2612"; color: #CC3300; } - .step_valid::after - { + .step_valid::after { content: " \2611"; color: #41ba78; } - .step_untouched::after - { + .step_untouched::after { content: " \2610"; } @@ -126,55 +117,153 @@ background-color: inherit; } - #breadcrumbs.breadcrumb > li { + #breadcrumbs.breadcrumb>li { border: 1px solid #cccccc; border-left: none; } - #breadcrumbs.breadcrumb > li:first-child { + + #breadcrumbs.breadcrumb>li:first-child { border-left: 1px solid #cccccc; } - #breadcrumbs.breadcrumb > li + li:before { + + #breadcrumbs.breadcrumb>li+li:before { content: ""; width: 0; margin: 0; padding: 0; } -</style> -<button id="gof" onclick="go('next')" class="btn go_btn go_forward">Go Forward</button> -<button id="gob" onclick="go('prev')" class="btn go_btn go_back">Go Back</button> + #topPagination .topcrumb { + flex: 1 1 0; + display: flex; + align-content: center; + justify-content: center; + border: 1px solid #dee2e6; + border-left: none; + } + + .topcrumb > span { + color: #343a40; + cursor: default; + } -<div class="options"> - <button id="cancel_btn" class="btn btn-primary" onclick="cancel_wf()">Cancel</button> + .topcrumb.active > span { + background: #007bff; + color: white; + } + + .topcrumb.disabled > span { + color: #6c757d; + background: #f8f9fa; + } +</style> +<!-- Pagination --> +<div class="row mt-3"> + <div class="col"> + <nav> + <ul class="pagination d-flex flex-row" id="topPagination"> + <li class="page-item flex-shrink-1 page-control"> + <a class="page-link" href="#" id="gob" onclick="go('prev')"> + <i class="fas fa-backward"></i> Back + </a> + </li> + <li class="page-item flex-grow-1 active"> + <a class="page-link disabled" href="#"> + Select <i class="far fa-check-square"></i> + </a> + </li> + <li class="page-item flex-grow-1"> + <a class="page-link disabled" href="#"> + Configure <i class="far fa-square"></i> + </a> + </li> + <li class="page-item flex-grow-1"> + <a class="page-link disabled" href="#"> + Information <i class="far fa-square"></i> + </a> + </li> + <li class="page-item flex-grow-1"> + <a class="page-link disabled" href="#"> + OPNFV <i class="far fa-square"></i> + </a> + </li> + <li class="page-item flex-grow-1"> + <a class="page-link disabled" href="#"> + Confirm <i class="far fa-square"></i> + </a> + </li> + <li class="page-item flex-shrink-1 page-control"> + <a class="page-link text-right" href="#" id="gof" onclick="go('next')"> + Next <i class="fas fa-forward"></i> + </a> + </li> + </ul> + </nav> + </div> +</div> +<!-- Top header --> +<div class="row px-4"> + <div class="col"> + <div id="iframe_header" class="row view-header"> + <div class="col-lg-12 step_header"> + <h1 class="step_title d-inline-block" id="view_title"></h1> + <span class="description text-muted" id="view_desc"></span> + <p class="step_message" id="view_message"></p> + </div> + <script> + function update_description(title, desc) { + document.getElementById("view_title").innerText = title; + document.getElementById("view_desc").innerText = desc; + } + + function update_message(message, stepstatus) { + document.getElementById("view_message").innerText = message; + document.getElementById("view_message").className = "step_message"; + document.getElementById("view_message").classList.add("message_" + stepstatus); + } + </script> + <!-- /.col-lg-12 --> + </div> + </div> + <div class="col-auto align-self-center d-flex"> + <button id="cancel_btn" class="btn btn-danger ml-auto" onclick="cancel_wf()">Cancel</button> + </div> +</div> +<!-- Content here --> +<div class="row d-flex flex-column flex-grow-1"> + <div class="container-fluid d-flex flex-column h-100"> + <div class="row d-flex flex-grow-1 p-4"> + <!-- iframe workflow --> + <div class="col-12 d-flex border flex-grow-1"> + <!-- This was where the iframe went --> + <iframe src="/wf/workflow" class="w-100 h-100" scrolling="yes" id="viewport-iframe" + frameBorder="0"></iframe> + </div> + </div> + </div> </div> <div class="btn_wrapper"> -<ol id="breadcrumbs" class="btn-group breadcrumb"> -</ol> </div> {% csrf_token %} <script type="text/javascript"> - - update_context(); var step = 0; var page_count = 0; var context_data = false; - function go(to) - { + function go(to) { step_on_leave(); request_leave(to); } - function request_leave(to) - { + function request_leave(to) { $.ajax({ type: "GET", url: "/wf/manager/", - beforeSend: function(request) { + beforeSend: function (request) { request.setRequestHeader("X-CSRFToken", - $('input[name="csrfmiddlewaretoken"]').val()); + $('input[name="csrfmiddlewaretoken"]').val()); }, success: function (data) { confirm_permission(to, data); @@ -183,49 +272,44 @@ }); } - function confirm_permission(to, data) - { - if( errors_exist(data) ) - { - var continueanyway = confirm("The current step has errors that will prevent it from saving. Continue anyway?"); - if( !continueanyway ) - { + function confirm_permission(to, data) { + if (errors_exist(data)) { + if (to != "prev") { return; } } - var problem = function() { + var problem = function () { alert("There was a problem"); } //makes an asynch request req = new XMLHttpRequest(); url = "/wf/workflow/?step=" + to; req.open("GET", url, true); - req.onload = function(e) { - if(req.readyState === 4){ - if(req.status < 300){ + req.onload = function (e) { + if (req.readyState === 4) { + if (req.status < 300) { document.getElementById("viewport-iframe").srcdoc = this.responseText; - } else { problem(); } - } else { problem(); } + } else { + problem(); + } + } else { + problem(); + } } req.onerror = problem; req.send(); } - function step_on_leave() - { + function step_on_leave() { document.getElementById("viewport-iframe").contentWindow.step_on_leave(); } - function errors_exist(data) - { + function errors_exist(data) { var stat = data['steps'][data['active']]['valid']; - if( stat >= 100 && stat < 200 ) - { + if (stat >= 100 && stat < 200) { return true; - } - else - { + } else { return false; } } @@ -234,9 +318,9 @@ $.ajax({ type: "GET", url: "/wf/manager/", - beforeSend: function(request) { + beforeSend: function (request) { request.setRequestHeader("X-CSRFToken", - $('input[name="csrfmiddlewaretoken"]').val()); + $('input[name="csrfmiddlewaretoken"]').val()); }, success: function (data) { update_page(data); @@ -244,120 +328,100 @@ }); } - function update_page(data) - { + function update_page(data) { context_data = data; update_breadcrumbs(data); - if(data["workflow_count"] == 1) - { - document.getElementById("cancel_btn").innerText = "Exit Workflow"; - } - else - { - document.getElementById("cancel_btn").innerText = "Return to Parent"; + if (data["workflow_count"] == 1) { + document.getElementById("cancel_btn").innerText = "Exit Workflow"; + } else { + document.getElementById("cancel_btn").innerText = "Return to Parent"; } } function update_breadcrumbs(meta_json) { step = meta_json['active']; page_count = meta_json['steps'].length; - if( step == 0 ) - { - var btn = document.getElementById("gob"); - btn.classList.add("go_btn_disabled"); - btn.disabled = true; - } - else - { - var btn = document.getElementById("gob"); - btn.classList.remove("go_btn_disabled"); - btn.disabled = false; + if (step == 0) { + var btn = document.getElementById("gob"); + btn.classList.add("invisible"); + btn.disabled = true; + } else { + var btn = document.getElementById("gob"); + btn.classList.remove("invisible"); + btn.disabled = false; } - if( step == page_count - 1 ) - { - var btn = document.getElementById("gof"); - btn.classList.add("go_btn_disabled"); - btn.disabled = true; - } - else - { - var btn = document.getElementById("gof"); - btn.classList.remove("go_btn_disabled"); - btn.disabled = false; + if (step == page_count - 1) { + var btn = document.getElementById("gof"); + btn.classList.add("invisible"); + btn.disabled = true; + } else { + var btn = document.getElementById("gof"); + btn.classList.remove("invisible"); + btn.disabled = false; } //remove all children of breadcrumbs so we can redraw - var container = document.getElementById("breadcrumbs"); - while(container.firstChild){ - container.removeChild(container.firstChild); - } - + $("#topPagination").children().not(".page-control").remove(); draw_steps(meta_json); } - function draw_steps(meta_json){ - for( var i = 0; i < meta_json["steps"].length; i++ ) - { + function draw_steps(meta_json) { + for (var i = 0; i < meta_json["steps"].length; i++) { meta_json["steps"][i]["index"] = i; var step_btn = create_step(meta_json["steps"][i], i == meta_json["active"]); - document.getElementById("breadcrumbs").appendChild(step_btn); + $("#topPagination li:last-child").before(step_btn); } } - function create_step(step_json, active){ + function create_step(step_json, active) { var step_dom = document.createElement("li"); - if(active){ - step_dom.className = "step_active"; - - } else{ - step_dom.className = "step"; + // First create the dom object depending on active or not + if (active) { + step_dom.className = "topcrumb active"; + } else { + step_dom.className = "topcrumb"; } - step_dom.appendChild(document.createTextNode(step_json['title'])); + $(step_dom).html(`<span class="d-flex align-items-center justify-content-center text-capitalize w-100">${step_json['title']}</span>`) var code = step_json['valid']; stat = ""; msg = ""; - if( code < 100 ) - { - step_dom.classList.add("step_untouched"); - + if (code < 100) { + $(step_dom).children().first().append("<i class='ml-2 far fa-square'></i>") stat = ""; msg = ""; - } - else if( code < 200 ) - { - step_dom.classList.add("step_invalid"); + } else if (code < 200) { + $(step_dom).children().first().append("<i class='ml-2 fas fa-minus-square'></i>") stat = "invalid"; msg = step_json['message']; - } - else if( code < 300 ) - { - step_dom.classList.add("step_valid"); + } else if (code < 300) { + $(step_dom).children().first().append("<i class='ml-2 far fa-check-square'></i>") stat = "valid"; msg = step_json['message']; } - if( step_json['enabled'] == false ) - { - step_dom.classList.add("step_hidden"); + if (step_json['enabled'] == false) { + step_dom.classList.add("disabled"); } - if(active) - { + if (active) { update_message(msg, stat); } - step_dom.classList.add("btn"); var step_number = step_json['index']; return step_dom; } - function cancel_wf(){ + function cancel_wf() { var form = $("#workflow_pop_form"); var formData = form.serialize(); var req = new XMLHttpRequest(); req.open("POST", "/wf/workflow/finish/", false); req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); - req.onerror = function() { alert("problem occurred while trying to cancel current workflow"); } - req.onreadystatechange = function() { if(req.readyState === 4){ - refresh_iframe(); - }}; + req.onerror = function () { + alert("problem occurred while trying to cancel current workflow"); + } + req.onreadystatechange = function () { + if (req.readyState === 4) { + refresh_iframe(); + } + }; req.send(formData); } @@ -365,43 +429,45 @@ req = new XMLHttpRequest(); url = "/wf/workflow/"; req.open("GET", url, true); - req.onload = function(e) { + req.onload = function (e) { var doc = document.getElementById("viewport-iframe").contentWindow.document; - doc.open(); doc.write(this.responseText); doc.close(); + doc.open(); + doc.write(this.responseText); + doc.close(); } req.send(); } - function write_iframe(contents) - { - document.getElementById("viewport-iframe").contentWindow.document.innerHTML= contents; + function write_iframe(contents) { + document.getElementById("viewport-iframe").contentWindow.document.innerHTML = contents; } - function redirect_root() - { + function redirect_root() { window.location.replace('/wf/'); } - function add_wf(type){ + function add_wf(type) { add_wf_internal(type, false); } - function add_edit_wf(type, target){ + function add_edit_wf(type, target) { add_wf_internal(type, target); } - function add_wf_internal(type, itemid){ - data = {"add": type}; - if(itemid){ + function add_wf_internal(type, itemid) { + data = { + "add": type + }; + if (itemid) { data['target'] = itemid; } $.ajax({ type: "POST", url: "/wf/manager/", data: data, - beforeSend: function(request) { + beforeSend: function (request) { request.setRequestHeader("X-CSRFToken", - $('input[name="csrfmiddlewaretoken"]').val() + $('input[name="csrfmiddlewaretoken"]').val() ); }, success: refresh_wf_iframe() @@ -409,66 +475,12 @@ } function refresh_wf_iframe() { - window.location=window.location; + window.location = window.location; } </script> -<div id="iframe_header" class="row view-header"> - <div class="col-lg-12 step_header"> - <h1 class="step_title" id="view_title"></h1> - <p class="description" id="view_desc"></p> - <p class="step_message" id="view_message"></p> - </div> - <style> - #view_desc{ - margin-bottom: 15px; - margin-top: 5px; - margin-left: 30px; - display: inline; - } - #view_title{ - margin-top: 5px; - margin-bottom: 0px; - display: inline; - } - #view_message{ - margin-top: 10px; - margin-bottom: 5px; - float: right; - } - .message_invalid{ - color: #ff4400; - } - .message_valid{ - color: #44cc00; - } - .step_header{ - border-bottom: 1px solid #eee; - border-top: 1px solid #eee; - left: 101px; - width: calc(100% - 202px); - } - </style> - <script> - function update_description(title, desc){ - document.getElementById("view_title").innerText = title; - document.getElementById("view_desc").innerText = desc; - } - function update_message(message, stepstatus){ - document.getElementById("view_message").innerText = message; - document.getElementById("view_message").className = "step_message"; - document.getElementById("view_message").classList.add("message_" + stepstatus); - } - - </script> - <!-- /.col-lg-12 --> -</div> <div style="display: none;" id="workflow_pop_form_div"> -<form id="workflow_pop_form" action="/wf/workflow/finish/" method="post"> - {% csrf_token %} -</form> -</div> - -<div class="iframe_div"> - <iframe src="/wf/workflow" class="iframe_elem" scrolling="yes" id="viewport-iframe"></iframe> + <form id="workflow_pop_form" action="/wf/workflow/finish/" method="post"> + {% csrf_token %} + </form> </div> -{% endblock content %} +{% endblock content %}
\ No newline at end of file diff --git a/src/templates/workflow/viewport-element.html b/src/templates/workflow/viewport-element.html index f25e644..7a7165a 100644 --- a/src/templates/workflow/viewport-element.html +++ b/src/templates/workflow/viewport-element.html @@ -1,5 +1,5 @@ {% extends "layout.html" %} -{% load bootstrap3 %} +{% load bootstrap4 %} {% load staticfiles %} {% block basecontent %} diff --git a/src/workflow/booking_workflow.py b/src/workflow/booking_workflow.py index eb87728..42372ce 100644 --- a/src/workflow/booking_workflow.py +++ b/src/workflow/booking_workflow.py @@ -8,188 +8,136 @@ ############################################################################## from django.contrib import messages -from django.shortcuts import render -from django.contrib.auth.models import User from django.utils import timezone -import json from datetime import timedelta from booking.models import Booking -from workflow.models import WorkflowStep -from workflow.forms import ResourceSelectorForm, SWConfigSelectorForm, BookingMetaForm -from resource_inventory.models import GenericResourceBundle, ResourceBundle, ConfigBundle +from workflow.models import WorkflowStep, AbstractSelectOrCreate +from workflow.forms import ResourceSelectorForm, SWConfigSelectorForm, BookingMetaForm, OPNFVSelectForm +from resource_inventory.models import GenericResourceBundle, ConfigBundle, OPNFVConfig -class Resource_Select(WorkflowStep): - template = 'booking/steps/resource_select.html' +""" +subclassing notes: + subclasses have to define the following class attributes: + self.repo_key: main output of step, where the selected/created single selector + result is placed at the end + self.confirm_key: +""" + + +class Abstract_Resource_Select(AbstractSelectOrCreate): + form = ResourceSelectorForm + template = 'dashboard/genericselect.html' title = "Select Resource" description = "Select a resource template to use for your deployment" short_title = "pod select" def __init__(self, *args, **kwargs): - super(Resource_Select, self).__init__(*args, **kwargs) - self.repo_key = self.repo.SELECTED_GRESOURCE_BUNDLE - self.repo_check_key = False - self.confirm_key = "booking" + super().__init__(*args, **kwargs) + self.select_repo_key = self.repo.SELECTED_GRESOURCE_BUNDLE + self.confirm_key = self.workflow_type - def get_context(self): - context = super(Resource_Select, self).get_context() - default = [] - - chosen_bundle = self.repo_get(self.repo_key, False) - if chosen_bundle: - default.append(chosen_bundle.id) + def alert_bundle_missing(self): + self.set_invalid("Please select a valid resource bundle") - bundle = chosen_bundle - edit = self.repo_get(self.repo.EDIT, False) + def get_form_queryset(self): user = self.repo_get(self.repo.SESSION_USER) - context['form'] = ResourceSelectorForm( - data={"user": user}, - chosen_resource=default, - bundle=bundle, - edit=edit - ) - return context + qs = GenericResourceBundle.objects.filter(owner=user) + return qs - def post_render(self, request): - form = ResourceSelectorForm(request.POST) - context = self.get_context() - if form.is_valid(): - data = form.cleaned_data['generic_resource_bundle'] - data = data[2:-2] - if not data: - self.set_invalid("Please select a valid bundle") - return render(request, self.template, context) - selected_bundle = json.loads(data) - if len(selected_bundle) < 1: - self.set_invalid("Please select a valid bundle") - return render(request, self.template, context) - selected_id = selected_bundle[0]['id'] - gresource_bundle = None - try: - selected_id = int(selected_id) - gresource_bundle = GenericResourceBundle.objects.get(id=selected_id) - except ValueError: - # we want the bundle in the repo - gresource_bundle = self.repo_get( - self.repo.GRESOURCE_BUNDLE_MODELS, - {} - ).get("bundle", GenericResourceBundle()) - self.repo_put( - self.repo_key, - gresource_bundle - ) - confirm = self.repo_get(self.repo.CONFIRMATION) - if self.confirm_key not in confirm: - confirm[self.confirm_key] = {} - confirm[self.confirm_key]["resource name"] = gresource_bundle.name - self.repo_put(self.repo.CONFIRMATION, confirm) - messages.add_message(request, messages.SUCCESS, 'Form Validated Successfully', fail_silently=True) - self.set_valid("Step Completed") - return render(request, self.template, context) - else: - messages.add_message(request, messages.ERROR, "Form Didn't Validate", fail_silently=True) - self.set_invalid("Please complete the fields highlighted in red to continue") - return render(request, self.template, context) + def get_page_context(self): + return { + 'select_type': 'resource', + 'select_type_title': 'Resource Bundle', + 'addable_type_num': 1 + } + def put_confirm_info(self, bundle): + confirm_dict = self.repo_get(self.repo.CONFIRMATION) + if self.confirm_key not in confirm_dict: + confirm_dict[self.confirm_key] = {} + confirm_dict[self.confirm_key]["Resource Template"] = bundle.name + self.repo_put(self.repo.CONFIRMATION, confirm_dict) -class Booking_Resource_Select(Resource_Select): - def __init__(self, *args, **kwargs): - super(Booking_Resource_Select, self).__init__(*args, **kwargs) - self.repo_key = self.repo.SELECTED_GRESOURCE_BUNDLE - self.confirm_key = "booking" +class Booking_Resource_Select(Abstract_Resource_Select): + workflow_type = "booking" - def get_context(self): - context = super(Booking_Resource_Select, self).get_context() - return context - def post_render(self, request): - response = super(Booking_Resource_Select, self).post_render(request) - models = self.repo_get(self.repo.BOOKING_MODELS, {}) - if "booking" not in models: - models['booking'] = Booking() - booking = models['booking'] - resource = self.repo_get(self.repo_key, False) - if resource: - try: - booking.resource.template = resource - except Exception: - booking.resource = ResourceBundle(template=resource) - models['booking'] = booking - self.repo_put(self.repo.BOOKING_MODELS, models) - return response - - -class SWConfig_Select(WorkflowStep): - template = 'booking/steps/swconfig_select.html' +class SWConfig_Select(AbstractSelectOrCreate): title = "Select Software Configuration" description = "Choose the software and related configurations you want to have used for your deployment" short_title = "pod config" + form = SWConfigSelectorForm - def post_render(self, request): - form = SWConfigSelectorForm(request.POST) - if form.is_valid(): + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self.select_repo_key = self.repo.SELECTED_CONFIG_BUNDLE + self.confirm_key = "booking" - bundle_json = form.cleaned_data['software_bundle'] - bundle_json = bundle_json[2:-2] # Stupid django string bug - if not bundle_json: - self.set_invalid("Please select a valid config") - return self.render(request) - bundle_json = json.loads(bundle_json) - if len(bundle_json) < 1: - self.set_invalid("Please select a valid config") - return self.render(request) - bundle = None - id = int(bundle_json[0]['id']) - bundle = ConfigBundle.objects.get(id=id) - - grb = self.repo_get(self.repo.SELECTED_GRESOURCE_BUNDLE) - - if grb and bundle.bundle != grb: - self.set_invalid("Incompatible config selected for resource bundle") - return self.render(request) - if not grb: - self.repo_set(self.repo.SELECTED_GRESOURCE_BUNDLE, bundle.bundle) + def alert_bundle_missing(self): + self.set_invalid("Please select a valid pod config") - models = self.repo_get(self.repo.BOOKING_MODELS, {}) - if "booking" not in models: - models['booking'] = Booking() - models['booking'].config_bundle = bundle - self.repo_put(self.repo.BOOKING_MODELS, models) - confirm = self.repo_get(self.repo.CONFIRMATION) - if "booking" not in confirm: - confirm['booking'] = {} - confirm['booking']["configuration name"] = bundle.name - self.repo_put(self.repo.CONFIRMATION, confirm) - self.set_valid("Step Completed") - messages.add_message(request, messages.SUCCESS, 'Form Validated Successfully', fail_silently=True) - else: - self.set_invalid("Please select or create a valid config") - messages.add_message(request, messages.ERROR, "Form Didn't Validate", fail_silently=True) + def get_form_queryset(self): + user = self.repo_get(self.repo.SESSION_USER) + grb = self.repo_get(self.repo.SELECTED_GRESOURCE_BUNDLE) + qs = ConfigBundle.objects.filter(owner=user).filter(bundle=grb) + return qs - return self.render(request) + def put_confirm_info(self, bundle): + confirm_dict = self.repo_get(self.repo.CONFIRMATION) + if self.confirm_key not in confirm_dict: + confirm_dict[self.confirm_key] = {} + confirm_dict[self.confirm_key]["Software Configuration"] = bundle.name + self.repo_put(self.repo.CONFIRMATION, confirm_dict) - def get_context(self): - context = super(SWConfig_Select, self).get_context() - default = [] - bundle = None - chosen_bundle = None - created_bundle = self.repo_get(self.repo.SELECTED_CONFIG_BUNDLE) - booking = self.repo_get(self.repo.BOOKING_MODELS, {}).get("booking", False) - try: - chosen_bundle = booking.config_bundle - default.append(chosen_bundle.id) - bundle = chosen_bundle - except Exception: - if created_bundle: - default.append(created_bundle.id) - bundle = created_bundle - edit = self.repo_get(self.repo.EDIT, False) - grb = self.repo_get(self.repo.SELECTED_GRESOURCE_BUNDLE) - context['form'] = SWConfigSelectorForm(chosen_software=default, bundle=bundle, edit=edit, resource=grb) - return context + def get_page_context(self): + return { + 'select_type': 'swconfig', + 'select_type_title': 'Software Config', + 'addable_type_num': 2 + } + + +class OPNFV_EnablePicker(object): + pass + + +class OPNFV_Select(AbstractSelectOrCreate, OPNFV_EnablePicker): + title = "Choose an OPNFV Config" + description = "Choose or create a description of how you want to deploy OPNFV" + short_title = "opnfv config" + form = OPNFVSelectForm + enabled = False + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self.select_repo_key = self.repo.SELECTED_OPNFV_CONFIG + self.confirm_key = "booking" + + def alert_bundle_missing(self): + self.set_invalid("Please select a valid OPNFV config") + + def get_form_queryset(self): + cb = self.repo_get(self.repo.SELECTED_CONFIG_BUNDLE) + qs = OPNFVConfig.objects.filter(bundle=cb) + return qs + + def put_confirm_info(self, config): + confirm_dict = self.repo_get(self.repo.CONFIRMATION) + if self.confirm_key not in confirm_dict: + confirm_dict[self.confirm_key] = {} + confirm_dict[self.confirm_key]["OPNFV Configuration"] = config.name + self.repo_put(self.repo.CONFIRMATION, confirm_dict) + + def get_page_context(self): + return { + 'select_type': 'opnfv', + 'select_type_title': 'OPNFV Config', + 'addable_type_num': 4 + } class Booking_Meta(WorkflowStep): @@ -214,23 +162,17 @@ class Booking_Meta(WorkflowStep): initial['info_file'] = info users = models.get("collaborators", []) for user in users: - default.append(user.id) + default.append(user.userprofile) except Exception: pass - default_user = self.repo_get(self.repo.SESSION_USER) - if default_user is None: - # TODO: error - default_user = "you" - else: - default_user = default_user.username + owner = self.repo_get(self.repo.SESSION_USER) - context['form'] = BookingMetaForm(initial=initial, chosen_users=default, default_user=default_user) + context['form'] = BookingMetaForm(initial=initial, user_initial=default, owner=owner) return context def post_render(self, request): - form = BookingMetaForm(data=request.POST) - context = self.get_context() + form = BookingMetaForm(data=request.POST, owner=request.user) forms = self.repo_get(self.repo.BOOKING_FORMS, {}) @@ -253,15 +195,16 @@ class Booking_Meta(WorkflowStep): for key in ['length', 'project', 'purpose']: confirm['booking'][key] = form.cleaned_data[key] - user_data = form.cleaned_data['users'] + if form.cleaned_data["deploy_opnfv"]: + self.repo_get(self.repo.SESSION_MANAGER).set_step_statuses(OPNFV_EnablePicker, desired_enabled=True) + else: + self.repo_get(self.repo.SESSION_MANAGER).set_step_statuses(OPNFV_EnablePicker, desired_enabled=False) + + userprofile_list = form.cleaned_data['users'] confirm['booking']['collaborators'] = [] - user_data = user_data[2:-2] # fixes malformed string from querydict - if user_data: - form_users = json.loads(user_data) - for user_json in form_users: - user = User.objects.get(pk=user_json['id']) - models['collaborators'].append(user) - confirm['booking']['collaborators'].append(user.username) + for userprofile in userprofile_list: + models['collaborators'].append(userprofile.user) + confirm['booking']['collaborators'].append(userprofile.user.username) info_file = form.cleaned_data.get("info_file", False) if info_file: @@ -274,5 +217,4 @@ class Booking_Meta(WorkflowStep): else: messages.add_message(request, messages.ERROR, "Form didn't validate", fail_silently=True) self.set_invalid("Please complete the fields highlighted in red to continue") - context['form'] = form # TODO: store this form - return render(request, self.template, context) + return self.render(request) diff --git a/src/workflow/forms.py b/src/workflow/forms.py index 6d26b5c..ee44ecd 100644 --- a/src/workflow/forms.py +++ b/src/workflow/forms.py @@ -9,40 +9,37 @@ import django.forms as forms -from django.forms import widgets +from django.forms import widgets, ValidationError from django.utils.safestring import mark_safe from django.template.loader import render_to_string from django.forms.widgets import NumberInput +import json + from account.models import Lab from account.models import UserProfile from resource_inventory.models import ( - GenericResourceBundle, - ConfigBundle, OPNFVRole, Installer, Scenario, ) +from booking.lib import get_user_items, get_user_field_opts class SearchableSelectMultipleWidget(widgets.SelectMultiple): template_name = 'dashboard/searchable_select_multiple.html' def __init__(self, attrs=None): - self.items = attrs['set'] + self.items = attrs['items'] self.show_from_noentry = attrs['show_from_noentry'] self.show_x_results = attrs['show_x_results'] - self.results_scrollable = attrs['scrollable'] + self.results_scrollable = attrs['results_scrollable'] self.selectable_limit = attrs['selectable_limit'] self.placeholder = attrs['placeholder'] self.name = attrs['name'] - self.initial = attrs.get("initial", "") - self.default_entry = attrs.get("default_entry", "") - self.edit = attrs.get("edit", False) - self.wf_type = attrs.get("wf_type") - self.incompatible = attrs.get("incompatible", "false") + self.initial = attrs.get("initial", []) - super(SearchableSelectMultipleWidget, self).__init__(attrs) + super(SearchableSelectMultipleWidget, self).__init__() def render(self, name, value, attrs=None, renderer=None): @@ -59,132 +56,160 @@ class SearchableSelectMultipleWidget(widgets.SelectMultiple): 'selectable_limit': self.selectable_limit, 'placeholder': self.placeholder, 'initial': self.initial, - 'default_entry': self.default_entry, - 'edit': self.edit, - 'wf_type': self.wf_type, - 'incompatible': self.incompatible } -class ResourceSelectorForm(forms.Form): +class SearchableSelectMultipleField(forms.Field): + def __init__(self, *args, required=True, widget=None, label=None, disabled=False, + items=None, queryset=None, show_from_noentry=True, show_x_results=-1, + results_scrollable=False, selectable_limit=-1, placeholder="search here", + name="searchable_select", initial=[], **kwargs): + """from the documentation: + # required -- Boolean that specifies whether the field is required. + # True by default. + # widget -- A Widget class, or instance of a Widget class, that should + # be used for this Field when displaying it. Each Field has a + # default Widget that it'll use if you don't specify this. In + # most cases, the default widget is TextInput. + # label -- A verbose name for this field, for use in displaying this + # field in a form. By default, Django will use a "pretty" + # version of the form field name, if the Field is part of a + # Form. + # initial -- A value to use in this Field's initial display. This value + # is *not* used as a fallback if data isn't given. + # help_text -- An optional string to use as "help text" for this Field. + # error_messages -- An optional dictionary to override the default + # messages that the field will raise. + # show_hidden_initial -- Boolean that specifies if it is needed to render a + # hidden widget with initial value after widget. + # validators -- List of additional validators to use + # localize -- Boolean that specifies if the field should be localized. + # disabled -- Boolean that specifies whether the field is disabled, that + # is its widget is shown in the form but not editable. + # label_suffix -- Suffix to be added to the label. Overrides + # form's label_suffix. + """ - def __init__(self, data=None, **kwargs): - chosen_resource = "" - bundle = None - edit = False - if "chosen_resource" in kwargs: - chosen_resource = kwargs.pop("chosen_resource") - if "bundle" in kwargs: - bundle = kwargs.pop("bundle") - if "edit" in kwargs: - edit = kwargs.pop("edit") - super(ResourceSelectorForm, self).__init__(data=data, **kwargs) - queryset = GenericResourceBundle.objects.select_related("owner").all() - if data and 'user' in data: - queryset = queryset.filter(owner=data['user']) + self.widget = widget + if self.widget is None: + self.widget = SearchableSelectMultipleWidget( + attrs={ + 'items': items, + 'initial': [obj.id for obj in initial], + 'show_from_noentry': show_from_noentry, + 'show_x_results': show_x_results, + 'results_scrollable': results_scrollable, + 'selectable_limit': selectable_limit, + 'placeholder': placeholder, + 'name': name, + 'disabled': disabled + } + ) + self.disabled = disabled + self.queryset = queryset + self.selectable_limit = selectable_limit - attrs = self.build_search_widget_attrs(chosen_resource, bundle, edit, queryset) + super().__init__(disabled=disabled, **kwargs) - self.fields['generic_resource_bundle'] = forms.CharField( - widget=SearchableSelectMultipleWidget(attrs=attrs) - ) + self.required = required - def build_search_widget_attrs(self, chosen_resource, bundle, edit, queryset): - resources = {} - for res in queryset: - displayable = {} - displayable['small_name'] = res.name - if res.owner: - displayable['expanded_name'] = res.owner.username + def clean(self, data): + data = data[0] + if not data: + if self.required: + raise ValidationError("Nothing was selected") else: - displayable['expanded_name'] = "" - displayable['string'] = res.description - displayable['id'] = res.id - resources[res.id] = displayable - - attrs = { - 'set': resources, - 'show_from_noentry': "true", + return [] + data_as_list = json.loads(data) + if self.selectable_limit != -1: + if len(data_as_list) > self.selectable_limit: + raise ValidationError("Too many items were selected") + + items = [] + for elem in data_as_list: + items.append(self.queryset.get(id=elem)) + + return items + + +class SearchableSelectAbstractForm(forms.Form): + def __init__(self, *args, queryset=None, initial=[], **kwargs): + self.queryset = queryset + items = self.generate_items(self.queryset) + options = self.generate_options() + + super(SearchableSelectAbstractForm, self).__init__(*args, **kwargs) + self.fields['searchable_select'] = SearchableSelectMultipleField( + initial=initial, + items=items, + queryset=self.queryset, + **options + ) + + def get_validated_bundle(self): + bundles = self.cleaned_data['searchable_select'] + if len(bundles) < 1: # don't need to check for >1, as field does that for us + raise ValidationError("No bundle was selected") + return bundles[0] + + def generate_items(self, queryset): + raise Exception("SearchableSelectAbstractForm does not implement concrete generate_items()") + + def generate_options(self, disabled=False): + return { + 'show_from_noentry': True, 'show_x_results': -1, - 'scrollable': "true", + 'results_scrollable': True, 'selectable_limit': 1, - 'name': "generic_resource_bundle", - 'placeholder': "resource", - 'initial': chosen_resource, - 'edit': edit, - 'wf_type': 1 + 'placeholder': 'Search for a Bundle', + 'name': 'searchable_select', + 'disabled': False } - return attrs -class SWConfigSelectorForm(forms.Form): +class SWConfigSelectorForm(SearchableSelectAbstractForm): + def generate_items(self, queryset): + items = {} - def __init__(self, *args, **kwargs): - chosen_software = "" - bundle = None - edit = False - resource = None - user = None - if "chosen_software" in kwargs: - chosen_software = kwargs.pop("chosen_software") - - if "bundle" in kwargs: - bundle = kwargs.pop("bundle") - if "edit" in kwargs: - edit = kwargs.pop("edit") - if "resource" in kwargs: - resource = kwargs.pop("resource") - if "user" in kwargs: - user = kwargs.pop("user") - super(SWConfigSelectorForm, self).__init__(*args, **kwargs) - attrs = self.build_search_widget_attrs(chosen_software, bundle, edit, resource, user) - self.fields['software_bundle'] = forms.CharField( - widget=SearchableSelectMultipleWidget(attrs=attrs) - ) + for bundle in queryset: + items[bundle.id] = { + 'expanded_name': bundle.name, + 'small_name': bundle.owner.username, + 'string': bundle.description, + 'id': bundle.id + } + + return items - def build_search_widget_attrs(self, chosen, bundle, edit, resource, user): - configs = {} - queryset = ConfigBundle.objects.select_related('owner').all() - if resource: - if user is None: - user = resource.owner - queryset = queryset.filter(bundle=resource) - if user: - queryset = queryset.filter(owner=user) +class OPNFVSelectForm(SearchableSelectAbstractForm): + def generate_items(self, queryset): + items = {} for config in queryset: - displayable = {} - displayable['small_name'] = config.name - displayable['expanded_name'] = config.owner.username - displayable['string'] = config.description - displayable['id'] = config.id - configs[config.id] = displayable - - incompatible_choice = "false" - if bundle and bundle.id not in configs: - displayable = {} - displayable['small_name'] = bundle.name - displayable['expanded_name'] = bundle.owner.username - displayable['string'] = bundle.description - displayable['id'] = bundle.id - configs[bundle.id] = displayable - incompatible_choice = "true" - - attrs = { - 'set': configs, - 'show_from_noentry': "true", - 'show_x_results': -1, - 'scrollable': "true", - 'selectable_limit': 1, - 'name': "software_bundle", - 'placeholder': "config", - 'initial': chosen, - 'edit': edit, - 'wf_type': 2, - 'incompatible': incompatible_choice - } - return attrs + items[config.id] = { + 'expanded_name': config.name, + 'small_name': config.bundle.owner.username, + 'string': config.description, + 'id': config.id + } + + return items + + +class ResourceSelectorForm(SearchableSelectAbstractForm): + def generate_items(self, queryset): + items = {} + + for bundle in queryset: + items[bundle.id] = { + 'expanded_name': bundle.name, + 'small_name': bundle.owner.username, + 'string': bundle.description, + 'id': bundle.id + } + + return items class BookingMetaForm(forms.Form): @@ -202,187 +227,116 @@ class BookingMetaForm(forms.Form): purpose = forms.CharField(max_length=1000) project = forms.CharField(max_length=400) info_file = forms.CharField(max_length=1000, required=False) + deploy_opnfv = forms.BooleanField(required=False) - def __init__(self, data=None, *args, **kwargs): - chosen_users = [] - if "default_user" in kwargs: - default_user = kwargs.pop("default_user") - else: - default_user = "you" - self.default_user = default_user - if "chosen_users" in kwargs: - chosen_users = kwargs.pop("chosen_users") - elif data and "users" in data: - chosen_users = data.getlist("users") - else: - pass + def __init__(self, *args, user_initial=[], owner=None, **kwargs): + super(BookingMetaForm, self).__init__(**kwargs) - super(BookingMetaForm, self).__init__(data=data, **kwargs) - - self.fields['users'] = forms.CharField( - widget=SearchableSelectMultipleWidget( - attrs=self.build_search_widget_attrs(chosen_users, default_user=default_user) - ), - required=False + self.fields['users'] = SearchableSelectMultipleField( + queryset=UserProfile.objects.select_related('user').exclude(user=owner), + initial=user_initial, + items=get_user_items(exclude=owner), + required=False, + **get_user_field_opts() ) - def build_user_list(self): - """ - returns a mapping of UserProfile ids to displayable objects expected by - searchable multiple select widget - """ - try: - users = {} - d_qset = UserProfile.objects.select_related('user').all().exclude(user__username=self.default_user) - for userprofile in d_qset: - user = { - 'id': userprofile.user.id, - 'expanded_name': userprofile.full_name, - 'small_name': userprofile.user.username, - 'string': userprofile.email_addr - } - - users[userprofile.user.id] = user - - return users - except Exception: - pass - - def build_search_widget_attrs(self, chosen_users, default_user="you"): - - attrs = { - 'set': self.build_user_list(), - 'show_from_noentry': "false", - 'show_x_results': 10, - 'scrollable': "false", - 'selectable_limit': -1, - 'name': "users", - 'placeholder': "username", - 'initial': chosen_users, - 'edit': False - } - return attrs - class MultipleSelectFilterWidget(forms.Widget): - def __init__(self, attrs=None): - super(MultipleSelectFilterWidget, self).__init__(attrs) - self.attrs = attrs + def __init__(self, *args, display_objects=None, filter_items=None, neighbors=None, **kwargs): + super(MultipleSelectFilterWidget, self).__init__(*args, **kwargs) + self.display_objects = display_objects + self.filter_items = filter_items + self.neighbors = neighbors self.template_name = "dashboard/multiple_select_filter_widget.html" def render(self, name, value, attrs=None, renderer=None): - attrs = self.attrs - self.context = self.get_context(name, value, attrs) - html = render_to_string(self.template_name, context=self.context) + context = self.get_context(name, value, attrs) + html = render_to_string(self.template_name, context=context) return mark_safe(html) def get_context(self, name, value, attrs): - return attrs + return { + 'display_objects': self.display_objects, + 'neighbors': self.neighbors, + 'filter_items': self.filter_items, + 'initial_value': value + } class MultipleSelectFilterField(forms.Field): - def __init__(self, required=True, widget=None, label=None, initial=None, - help_text='', error_messages=None, show_hidden_initial=False, - validators=(), localize=False, disabled=False, label_suffix=None): - """from the documentation: - # required -- Boolean that specifies whether the field is required. - # True by default. - # widget -- A Widget class, or instance of a Widget class, that should - # be used for this Field when displaying it. Each Field has a - # default Widget that it'll use if you don't specify this. In - # most cases, the default widget is TextInput. - # label -- A verbose name for this field, for use in displaying this - # field in a form. By default, Django will use a "pretty" - # version of the form field name, if the Field is part of a - # Form. - # initial -- A value to use in this Field's initial display. This value - # is *not* used as a fallback if data isn't given. - # help_text -- An optional string to use as "help text" for this Field. - # error_messages -- An optional dictionary to override the default - # messages that the field will raise. - # show_hidden_initial -- Boolean that specifies if it is needed to render a - # hidden widget with initial value after widget. - # validators -- List of additional validators to use - # localize -- Boolean that specifies if the field should be localized. - # disabled -- Boolean that specifies whether the field is disabled, that - # is its widget is shown in the form but not editable. - # label_suffix -- Suffix to be added to the label. Overrides - # form's label_suffix. - """ - # this is bad, but django forms are annoying - self.widget = widget - if self.widget is None: - self.widget = MultipleSelectFilterWidget() - super(MultipleSelectFilterField, self).__init__( - required=required, - widget=self.widget, - label=label, - initial=None, - help_text=help_text, - error_messages=error_messages, - show_hidden_initial=show_hidden_initial, - validators=validators, - localize=localize, - disabled=disabled, - label_suffix=label_suffix - ) + def __init__(self, **kwargs): + self.initial = kwargs.get("initial") + super().__init__(**kwargs) - def clean(data): - """ - This method will raise a django.forms.ValidationError or return clean data - """ - return data + def to_python(self, value): + return json.loads(value) class FormUtils: @staticmethod - def getLabData(multiple_selectable_hosts): + def getLabData(multiple_hosts=False): """ Gets all labs and thier host profiles and returns a serialized version the form can understand. Should be rewritten with a related query to make it faster - Should be moved outside of global scope """ + # javascript truthy variables + true = 1 + false = 0 + if multiple_hosts: + multiple_hosts = true + else: + multiple_hosts = false labs = {} hosts = {} items = {} - mapping = {} + neighbors = {} for lab in Lab.objects.all(): - slab = {} - slab['id'] = "lab_" + str(lab.lab_user.id) - slab['name'] = lab.name - slab['description'] = lab.description - slab['selected'] = 0 - slab['selectable'] = 1 - slab['follow'] = 1 - if not multiple_selectable_hosts: - slab['follow'] = 0 - slab['multiple'] = 0 - items[slab['id']] = slab - mapping[slab['id']] = [] - labs[slab['id']] = slab + lab_node = { + 'id': "lab_" + str(lab.lab_user.id), + 'model_id': lab.lab_user.id, + 'name': lab.name, + 'description': lab.description, + 'selected': false, + 'selectable': true, + 'follow': false, + 'multiple': false, + 'class': 'lab' + } + if multiple_hosts: + # "follow" this lab node to discover more hosts if allowed + lab_node['follow'] = true + items[lab_node['id']] = lab_node + neighbors[lab_node['id']] = [] + labs[lab_node['id']] = lab_node + for host in lab.hostprofiles.all(): - shost = {} - shost['forms'] = [{"name": "host_name", "type": "text", "placeholder": "hostname"}] - shost['id'] = "host_" + str(host.id) - shost['name'] = host.name - shost['description'] = host.description - shost['selected'] = 0 - shost['selectable'] = 1 - shost['follow'] = 0 - shost['multiple'] = multiple_selectable_hosts - items[shost['id']] = shost - mapping[slab['id']].append(shost['id']) - if shost['id'] not in mapping: - mapping[shost['id']] = [] - mapping[shost['id']].append(slab['id']) - hosts[shost['id']] = shost - - filter_objects = [("labs", labs.values()), ("hosts", hosts.values())] + host_node = { + 'form': {"name": "host_name", "type": "text", "placeholder": "hostname"}, + 'id': "host_" + str(host.id), + 'model_id': host.id, + 'name': host.name, + 'description': host.description, + 'selected': false, + 'selectable': true, + 'follow': false, + 'multiple': multiple_hosts, + 'class': 'host' + } + if multiple_hosts: + host_node['values'] = [] # place to store multiple values + items[host_node['id']] = host_node + neighbors[lab_node['id']].append(host_node['id']) + if host_node['id'] not in neighbors: + neighbors[host_node['id']] = [] + neighbors[host_node['id']].append(lab_node['id']) + hosts[host_node['id']] = host_node + + display_objects = [("lab", labs.values()), ("host", hosts.values())] context = { - 'filter_objects': filter_objects, - 'mapping': mapping, + 'display_objects': display_objects, + 'neighbors': neighbors, 'filter_items': items } return context @@ -391,14 +345,10 @@ class FormUtils: class HardwareDefinitionForm(forms.Form): def __init__(self, *args, **kwargs): - selection_data = kwargs.pop("selection_data", False) super(HardwareDefinitionForm, self).__init__(*args, **kwargs) - attrs = FormUtils.getLabData(1) - attrs['selection_data'] = selection_data + attrs = FormUtils.getLabData(multiple_hosts=True) self.fields['filter_field'] = MultipleSelectFilterField( - widget=MultipleSelectFilterWidget( - attrs=attrs - ) + widget=MultipleSelectFilterWidget(**attrs) ) diff --git a/src/workflow/models.py b/src/workflow/models.py index 25d7e84..6c6bd9a 100644 --- a/src/workflow/models.py +++ b/src/workflow/models.py @@ -240,6 +240,67 @@ class WorkflowStep(object): return self.repo.put(key, value, self.id) +""" +subclassing notes: + subclasses have to define the following class attributes: + self.select_repo_key: where the selected "object" or "bundle" is to be placed in the repo + self.form: the form to be used + alert_bundle_missing(): what message to display if a user does not select/selects an invalid object + get_form_queryset(): generate a queryset to be used to filter available items for the field + get_page_context(): return simple context such as page header and other info +""" + + +class AbstractSelectOrCreate(WorkflowStep): + template = 'dashboard/genericselect.html' + title = "Select a Bundle" + short_title = "select" + description = "Generic bundle selector step" + + select_repo_key = None + form = None # subclasses are expected to use a form that is a subclass of SearchableSelectGenericForm + + def alert_bundle_missing(self): # override in subclasses to change message if field isn't filled out + self.set_invalid("Please select a valid bundle") + + def post_render(self, request): + context = self.get_context() + form = self.form(request.POST, queryset=self.get_form_queryset()) + if form.is_valid(): + bundle = form.get_validated_bundle() + if not bundle: + self.alert_bundle_missing() + return render(request, self.template, context) + self.repo_put(self.select_repo_key, bundle) + self.put_confirm_info(bundle) + self.set_valid("Step Completed") + else: + self.alert_bundle_missing() + messages.add_message(request, messages.ERROR, "Form Didn't Validate", fail_silently=True) + + return self.render(request) + + def get_context(self): + default = [] + + bundle = self.repo_get(self.select_repo_key, False) + if bundle: + default.append(bundle) + + form = self.form(queryset=self.get_form_queryset(), initial=default) + + context = {'form': form, **self.get_page_context()} + context.update(super().get_context()) + + return context + + def get_page_context(): + return { + 'select_type': 'generic', + 'select_type_title': 'Generic Bundle' + } + + class Confirmation_Step(WorkflowStep): template = 'workflow/confirm.html' title = "Confirm Changes" @@ -335,6 +396,7 @@ class Repository(): self.el[key] = value def get(self, key, default, id): + self.add_get_history(key, id) return self.el.get(key, default) @@ -359,6 +421,7 @@ class Repository(): errors = self.make_snapshot() if errors: return errors + # if GRB WF, create it if self.GRESOURCE_BUNDLE_MODELS in self.el: errors = self.make_generic_resource_bundle() @@ -427,6 +490,9 @@ class Repository(): pass JobFactory.makeSnapshotTask(image, booking, host) + self.el[self.RESULT] = image + self.el[self.HAS_RESULT] = True + def make_generic_resource_bundle(self): owner = self.el[self.SESSION_USER] if self.GRESOURCE_BUNDLE_MODELS in self.el: @@ -493,13 +559,14 @@ class Repository(): return "GRB no models given. CODE:0x0001" self.el[self.RESULT] = bundle + self.el[self.HAS_RESULT] = True return False def make_software_config_bundle(self): models = self.el[self.CONFIG_MODELS] if 'bundle' in models: bundle = models['bundle'] - bundle.bundle = bundle.bundle + bundle.bundle = self.el[self.SELECTED_GRESOURCE_BUNDLE] try: bundle.save() except Exception as e: @@ -537,15 +604,22 @@ class Repository(): models = self.el[self.BOOKING_MODELS] owner = self.el[self.SESSION_USER] + if 'booking' in models: + booking = models['booking'] + else: + return "BOOK, no booking model exists. CODE:0x000f" + + selected_grb = None + if self.SELECTED_GRESOURCE_BUNDLE in self.el: selected_grb = self.el[self.SELECTED_GRESOURCE_BUNDLE] else: return "BOOK, no selected resource. CODE:0x000e" - if 'booking' in models: - booking = models['booking'] - else: - return "BOOK, no booking model exists. CODE:0x000f" + if self.SELECTED_CONFIG_BUNDLE not in self.el: + return "BOOK, no selected config bundle. CODE:0x001f" + + booking.config_bundle = self.el[self.SELECTED_CONFIG_BUNDLE] if not booking.start: return "BOOK, booking has no start. CODE:0x0010" @@ -567,7 +641,6 @@ class Repository(): booking.resource = resource_bundle booking.owner = owner - booking.config_bundle = booking.config_bundle booking.lab = selected_grb.lab is_allowed = BookingAuthManager().booking_allowed(booking, self) @@ -598,9 +671,12 @@ class Repository(): except Exception as e: return "BOOK, saving booking generated exception: " + str(e) + " CODE:0x0016" + self.el[self.RESULT] = booking + self.el[self.HAS_RESULT] = True + def make_opnfv_config(self): opnfv_models = self.el[self.OPNFV_MODELS] - config_bundle = opnfv_models['configbundle'] + config_bundle = self.el[self.SELECTED_CONFIG_BUNDLE] if not config_bundle: return "No Configuration bundle selected" info = opnfv_models.get("meta", {}) @@ -644,10 +720,13 @@ class Repository(): ) self.el[self.RESULT] = opnfv_config + self.el[self.HAS_RESULT] = True def __init__(self): self.el = {} self.el[self.CONFIRMATION] = {} self.el["active_step"] = 0 + self.el[self.HAS_RESULT] = False + self.el[self.RESULT] = None self.get_history = {} self.put_history = {} diff --git a/src/workflow/opnfv_workflow.py b/src/workflow/opnfv_workflow.py index 490d2f0..7d499ec 100644 --- a/src/workflow/opnfv_workflow.py +++ b/src/workflow/opnfv_workflow.py @@ -9,66 +9,39 @@ from django.forms import formset_factory -from django.contrib import messages -import json - -from workflow.models import WorkflowStep +from workflow.models import WorkflowStep, AbstractSelectOrCreate from resource_inventory.models import ConfigBundle, OPNFV_SETTINGS from workflow.forms import OPNFVSelectionForm, OPNFVNetworkRoleForm, OPNFVHostRoleForm, SWConfigSelectorForm, BasicMetaForm -class OPNFV_Resource_Select(WorkflowStep): - template = 'booking/steps/swconfig_select.html' +class OPNFV_Resource_Select(AbstractSelectOrCreate): title = "Select Software Configuration" - description = "Choose the software and related configurations you want to use to configure OPNFV" - short_title = "software configuration" - modified_key = "configbundle_step" + description = "Choose the software bundle you wish to use as a base for your OPNFV configuration" + short_title = "software config" + form = SWConfigSelectorForm - def update_confirmation(self): - confirm = self.repo_get(self.repo.CONFIRMATION, {}) - config_bundle = self.repo_get(self.repo.OPNFV_MODELS, {}).get("configbundle") - if not config_bundle: - return - confirm['software bundle'] = config_bundle.name - confirm['hardware POD'] = config_bundle.bundle.name - self.repo_put(self.repo.CONFIRMATION, confirm) + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self.select_repo_key = self.repo.SELECTED_CONFIG_BUNDLE - def post_render(self, request): - models = self.repo_get(self.repo.OPNFV_MODELS, {}) - form = SWConfigSelectorForm(request.POST) - if form.is_valid(): - bundle_json = form.cleaned_data['software_bundle'] - bundle_json = bundle_json[2:-2] # Stupid django string bug - if not bundle_json: - self.set_invalid("Please select a valid config") - return self.render(request) - bundle_json = json.loads(bundle_json) - if len(bundle_json) < 1: - self.set_invalid("Please select a valid config") - return self.render(request) - bundle = None - id = int(bundle_json[0]['id']) - bundle = ConfigBundle.objects.get(id=id) - - models['configbundle'] = bundle - self.repo_put(self.repo.OPNFV_MODELS, models) - self.set_valid("Step Completed") - messages.add_message(request, messages.SUCCESS, 'Form Validated Successfully', fail_silently=True) - self.update_confirmation() - else: - self.set_invalid("Please select or create a valid config") - messages.add_message(request, messages.ERROR, "Form Didn't Validate", fail_silently=True) - - return self.render(request) - - def get_context(self): - context = super(OPNFV_Resource_Select, self).get_context() - default = [] + def get_form_queryset(self): user = self.repo_get(self.repo.SESSION_USER) - - context['form'] = SWConfigSelectorForm(chosen_software=default, bundle=None, edit=True, resource=None, user=user) - return context + qs = ConfigBundle.objects.filter(owner=user) + return qs + + def put_confirm_info(self, bundle): + confirm_dict = self.repo_get(self.repo.CONFIRMATION) + confirm_dict['software bundle'] = bundle.name + confirm_dict['hardware POD'] = bundle.bundle.name + self.repo_put(self.repo.CONFIRMATION, confirm_dict) + + def get_page_context(self): + return { + 'select_type': 'swconfig', + 'select_type_title': 'Software Config', + 'addable_type_num': 2 + } class Pick_Installer(WorkflowStep): @@ -92,7 +65,7 @@ class Pick_Installer(WorkflowStep): def get_context(self): context = super(Pick_Installer, self).get_context() - models = self.repo_get(self.repo.OPNFV_MODELS, None) + models = self.repo_get(self.repo.OPNFV_MODELS, {}) initial = { "installer": models.get("installer_chosen"), "scenario": models.get("scenario_chosen") @@ -155,7 +128,7 @@ class Assign_Network_Roles(WorkflowStep): def get_context(self): context = super(Assign_Network_Roles, self).get_context() - config_bundle = self.repo_get(self.repo.OPNFV_MODELS, {}).get("configbundle") + config_bundle = self.repo_get(self.repo.SELECTED_CONFIG_BUNDLE) if config_bundle is None: context["unavailable"] = True return context @@ -179,7 +152,7 @@ class Assign_Network_Roles(WorkflowStep): def post_render(self, request): models = self.repo_get(self.repo.OPNFV_MODELS, {}) - config_bundle = models.get("configbundle") + config_bundle = self.repo_get(self.repo.SELECTED_CONFIG_BUNDLE) roles = OPNFV_SETTINGS.NETWORK_ROLES net_role_formset = self.create_netformset(roles, config_bundle, data=request.POST) if net_role_formset.is_valid(): @@ -228,8 +201,7 @@ class Assign_Host_Roles(WorkflowStep): # taken verbatim from Define_Software in def get_context(self): context = super(Assign_Host_Roles, self).get_context() - models = self.repo_get(self.repo.OPNFV_MODELS, {}) - config = models.get("configbundle") + config = self.repo_get(self.repo.SELECTED_CONFIG_BUNDLE) if config is None: context['error'] = "Please select a Configuration on the first step" diff --git a/src/workflow/resource_bundle_workflow.py b/src/workflow/resource_bundle_workflow.py index ced355f..a4657ab 100644 --- a/src/workflow/resource_bundle_workflow.py +++ b/src/workflow/resource_bundle_workflow.py @@ -52,65 +52,47 @@ class Define_Hardware(WorkflowStep): description = "Choose the type and amount of machines you want" short_title = "hosts" + def __init__(self, *args, **kwargs): + self.form = None + super().__init__(*args, **kwargs) + def get_context(self): context = super(Define_Hardware, self).get_context() - selection_data = {"hosts": {}, "labs": {}} - models = self.repo_get(self.repo.GRESOURCE_BUNDLE_MODELS, {}) - hosts = models.get("hosts", []) - for host in hosts: - profile_id = "host_" + str(host.profile.id) - if profile_id not in selection_data['hosts']: - selection_data['hosts'][profile_id] = [] - selection_data['hosts'][profile_id].append({"host_name": host.resource.name, "class": profile_id}) - - if models.get("bundle", GenericResourceBundle()).lab: - selection_data['labs'] = {"lab_" + str(models.get("bundle").lab.lab_user.id): "true"} - - form = HardwareDefinitionForm( - selection_data=selection_data - ) - context['form'] = form + context['form'] = self.form or HardwareDefinitionForm() return context - def render(self, request): - self.context = self.get_context() - return render(request, self.template, self.context) - def update_models(self, data): - data = json.loads(data['filter_field']) + data = data['filter_field'] models = self.repo_get(self.repo.GRESOURCE_BUNDLE_MODELS, {}) models['hosts'] = [] # This will always clear existing data when this step changes models['interfaces'] = {} if "bundle" not in models: models['bundle'] = GenericResourceBundle(owner=self.repo_get(self.repo.SESSION_USER)) - host_data = data['hosts'] + host_data = data['host'] names = {} - for host_dict in host_data: - id = host_dict['class'] - # bit of formatting - id = int(id.split("_")[-1]) + for host_profile_dict in host_data.values(): + id = host_profile_dict['id'] profile = HostProfile.objects.get(id=id) # instantiate genericHost and store in repo - name = host_dict['host_name'] - if not re.match(r"(?=^.{1,253}$)(^([A-Za-z0-9-_]{1,62}\.)*[A-Za-z0-9-_]{1,63})", name): - raise InvalidHostnameException("Hostname must comply to RFC 952 and all extensions to it until this point") - if name in names: - raise NonUniqueHostnameException("All hosts must have unique names") - names[name] = True - genericResource = GenericResource(bundle=models['bundle'], name=name) - genericHost = GenericHost(profile=profile, resource=genericResource) - models['hosts'].append(genericHost) - for interface_profile in profile.interfaceprofile.all(): - genericInterface = GenericInterface(profile=interface_profile, host=genericHost) - if genericHost.resource.name not in models['interfaces']: - models['interfaces'][genericHost.resource.name] = [] - models['interfaces'][genericHost.resource.name].append(genericInterface) + for name in host_profile_dict['values'].values(): + if not re.match(r"(?=^.{1,253}$)(^([A-Za-z0-9-_]{1,62}\.)*[A-Za-z0-9-_]{1,63})", name): + raise InvalidHostnameException("Invalid hostname: '" + name + "'") + if name in names: + raise NonUniqueHostnameException("All hosts must have unique names") + names[name] = True + genericResource = GenericResource(bundle=models['bundle'], name=name) + genericHost = GenericHost(profile=profile, resource=genericResource) + models['hosts'].append(genericHost) + for interface_profile in profile.interfaceprofile.all(): + genericInterface = GenericInterface(profile=interface_profile, host=genericHost) + if genericHost.resource.name not in models['interfaces']: + models['interfaces'][genericHost.resource.name] = [] + models['interfaces'][genericHost.resource.name].append(genericInterface) # add selected lab to models - for lab_dict in data['labs']: - if list(lab_dict.values())[0]: # True for lab the user selected - lab_user_id = int(list(lab_dict.keys())[0].split("_")[-1]) - models['bundle'].lab = Lab.objects.get(lab_user__id=lab_user_id) + for lab_dict in data['lab'].values(): + if lab_dict['selected']: + models['bundle'].lab = Lab.objects.get(lab_user__id=lab_dict['id']) break # if somehow we get two 'true' labs, we only use one # return to repo @@ -133,15 +115,11 @@ class Define_Hardware(WorkflowStep): try: self.form = HardwareDefinitionForm(request.POST) if self.form.is_valid(): - if len(json.loads(self.form.cleaned_data['filter_field'])['labs']) != 1: - self.set_invalid("Please select one lab") - else: - self.update_models(self.form.cleaned_data) - self.update_confirmation() - self.set_valid("Step Completed") + self.update_models(self.form.cleaned_data) + self.update_confirmation() + self.set_valid("Step Completed") else: self.set_invalid("Please complete the fields highlighted in red to continue") - pass except Exception as e: self.set_invalid(str(e)) self.context = self.get_context() diff --git a/src/workflow/sw_bundle_workflow.py b/src/workflow/sw_bundle_workflow.py index 329b716..0c558fc 100644 --- a/src/workflow/sw_bundle_workflow.py +++ b/src/workflow/sw_bundle_workflow.py @@ -12,25 +12,12 @@ from django.forms import formset_factory from workflow.models import WorkflowStep from workflow.forms import BasicMetaForm, HostSoftwareDefinitionForm -from workflow.booking_workflow import Resource_Select +from workflow.booking_workflow import Abstract_Resource_Select from resource_inventory.models import Image, GenericHost, ConfigBundle, HostConfiguration -# resource selection step is reused from Booking workflow -class SWConf_Resource_Select(Resource_Select): - def __init__(self, *args, **kwargs): - super(SWConf_Resource_Select, self).__init__(*args, **kwargs) - self.repo_key = self.repo.SELECTED_GRESOURCE_BUNDLE - self.confirm_key = "configuration" - - def post_render(self, request): - response = super(SWConf_Resource_Select, self).post_render(request) - models = self.repo_get(self.repo.CONFIG_MODELS, {}) - bundle = models.get("bundle", ConfigBundle(owner=self.repo_get(self.repo.SESSION_USER))) - bundle.bundle = self.repo_get(self.repo_key) # super put grb here - models['bundle'] = bundle - self.repo_put(self.repo.CONFIG_MODELS, models) - return response +class SWConf_Resource_Select(Abstract_Resource_Select): + workflow_type = "configuration" class Define_Software(WorkflowStep): diff --git a/src/workflow/urls.py b/src/workflow/urls.py index b131d84..5a97904 100644 --- a/src/workflow/urls.py +++ b/src/workflow/urls.py @@ -14,7 +14,7 @@ from django.conf import settings from workflow.views import step_view, delete_session, manager_view, viewport_view from workflow.models import Repository from workflow.resource_bundle_workflow import Define_Hardware, Define_Nets, Resource_Meta_Info -from workflow.booking_workflow import SWConfig_Select, Resource_Select, Booking_Meta +from workflow.booking_workflow import SWConfig_Select, Booking_Resource_Select, Booking_Meta app_name = 'workflow' urlpatterns = [ @@ -31,4 +31,4 @@ if settings.TESTING: urlpatterns.append(url(r'^workflow/step/resource_meta$', Resource_Meta_Info("", Repository()).test_render)) urlpatterns.append(url(r'^workflow/step/booking_meta$', Booking_Meta("", Repository()).test_render)) urlpatterns.append(url(r'^workflow/step/software_select$', SWConfig_Select("", Repository()).test_render)) - urlpatterns.append(url(r'^workflow/step/resource_select$', Resource_Select("", Repository()).test_render)) + urlpatterns.append(url(r'^workflow/step/resource_select$', Booking_Resource_Select("", Repository()).test_render)) diff --git a/src/workflow/views.py b/src/workflow/views.py index f2e37ef..7ed9031 100644 --- a/src/workflow/views.py +++ b/src/workflow/views.py @@ -8,12 +8,14 @@ ############################################################################## -from django.http import HttpResponse, HttpResponseGone +from django.http import HttpResponseGone, JsonResponse from django.shortcuts import render +from django.urls import reverse import uuid from workflow.workflow_manager import ManagerTracker, SessionManager +from booking.models import Booking import logging logger = logging.getLogger(__name__) @@ -29,23 +31,33 @@ def attempt_auth(request): return None +def get_redirect_response(result): + if not result: + return {} + + # need to get type of result, and switch on the type + # since has_result, result must be populated with a valid object + if isinstance(result, Booking): + return { + 'redir_url': reverse('booking:booking_detail', kwargs={'booking_id': result.id}) + } + else: + return {} + + def delete_session(request): manager = attempt_auth(request) if not manager: return HttpResponseGone("No session found that relates to current request") - if manager.pop_workflow(): - return HttpResponse('') - else: - del ManagerTracker.managers[request.session['manager_session']] - return render(request, 'workflow/exit_redirect.html') + not_last_workflow, result = manager.pop_workflow() - try: + if not_last_workflow: # this was not the last workflow, so don't redirect away + return JsonResponse({}) + else: del ManagerTracker.managers[request.session['manager_session']] - return HttpResponse('') - except Exception: - return None + return JsonResponse(get_redirect_response(result)) def step_view(request): diff --git a/src/workflow/workflow_factory.py b/src/workflow/workflow_factory.py index 08cf296..03c8126 100644 --- a/src/workflow/workflow_factory.py +++ b/src/workflow/workflow_factory.py @@ -8,7 +8,7 @@ ############################################################################## -from workflow.booking_workflow import Booking_Resource_Select, SWConfig_Select, Booking_Meta +from workflow.booking_workflow import Booking_Resource_Select, SWConfig_Select, Booking_Meta, OPNFV_Select from workflow.resource_bundle_workflow import Define_Hardware, Define_Nets, Resource_Meta_Info from workflow.sw_bundle_workflow import Config_Software, Define_Software, SWConf_Resource_Select from workflow.snapshot_workflow import Select_Host_Step, Image_Meta_Step @@ -76,6 +76,7 @@ class WorkflowFactory(): Booking_Resource_Select, SWConfig_Select, Booking_Meta, + OPNFV_Select, ] resource_steps = [ diff --git a/src/workflow/workflow_manager.py b/src/workflow/workflow_manager.py index 525aa6f..80b8a67 100644 --- a/src/workflow/workflow_manager.py +++ b/src/workflow/workflow_manager.py @@ -64,15 +64,15 @@ class SessionManager(): ) def pop_workflow(self): - if(len(self.workflows) <= 1): - return False - - if self.workflows[-1].repository.el[self.workflows[-1].repository.HAS_RESULT]: - key = self.workflows[-1].repository.el[self.workflows[-1].repository.RESULT_KEY] - result = self.workflows[-1].repository.el[self.workflows[-1].repository.RESULT] - self.workflows[-2].repository.el[key] = result - self.workflows.pop() - return True + multiple_wfs = len(self.workflows) > 1 + if multiple_wfs: + if self.workflows[-1].repository.el[Repository.RESULT]: # move result + key = self.workflows[-1].repository.el[Repository.RESULT_KEY] + result = self.workflows[-1].repository.el[Repository.RESULT] + self.workflows[-2].repository.el[key] = result + self.workflows.pop() + current_repo = self.workflows[-1].repository + return (multiple_wfs, current_repo.el[current_repo.RESULT]) def status(self, request): try: @@ -97,7 +97,13 @@ class SessionManager(): def post_render(self, request): return self.active_workflow().steps[self.active_workflow().active_index].post_render(request) + def get_active_step(self): + return self.active_workflow().steps[self.active_workflow().active_index] + def go_next(self, **kwargs): + # need to verify current step is valid to allow this + if self.get_active_step().valid < 200: + return next_step = self.active_workflow().active_index + 1 if next_step >= len(self.active_workflow().steps): raise Exception("Out of bounds request for step") |