project: list, create, delete 48/6348/2
authorlombardofr <lombardo@everyup.it>
Tue, 26 Jun 2018 21:44:40 +0000 (23:44 +0200)
committergarciadeblas <gerardo.garciadeblas@telefonica.com>
Thu, 19 Jul 2018 12:12:33 +0000 (13:12 +0100)
Change-Id: Ie609bdf317373ebc2fca3a400748f4c32f1c2088
Signed-off-by: lombardofr <lombardo@everyup.it>
lib/osm/osmclient/clientv2.py
projecthandler/template/project/modal/new_project.html [new file with mode: 0644]
projecthandler/template/project/new_project.html [deleted file]
projecthandler/template/project/projectlist.html
projecthandler/views.py

index 7103459..9acb590 100644 (file)
@@ -39,6 +39,77 @@ class Client(object):
 
         return result
 
+    def project_list(self, token):
+        result = {'error': True, 'data': ''}
+        headers = {"Content-Type": "application/yaml", "accept": "application/json",
+                   'Authorization': 'Bearer {}'.format(token['id'])}
+
+        _url = "{0}/admin/v1/projects".format(self._base_path)
+        try:
+            r = requests.get(_url, params=None, verify=False, stream=True, headers=headers)
+        except Exception as e:
+            log.exception(e)
+            result['data'] = str(e)
+            return result
+        if r.status_code == requests.codes.ok:
+            result['error'] = False
+        result['data'] = Util.json_loads_byteified(r.text)
+
+        return result
+
+    def project_get(self, token, id):
+        result = {'error': True, 'data': ''}
+        headers = {"Content-Type": "application/yaml", "accept": "application/json",
+                   'Authorization': 'Bearer {}'.format(token['id'])}
+        _url = "{0}/admin/v1/projects/{1}".format(self._base_path, id)
+        try:
+            r = requests.get(_url, params=None, verify=False, stream=True, headers=headers)
+        except Exception as e:
+            log.exception(e)
+            result['data'] = str(e)
+            return result
+        if r.status_code == requests.codes.ok:
+            result['error'] = False
+        result['data'] = Util.json_loads_byteified(r.text)
+
+    def project_create(self, token, project_data):
+
+        result = {'error': True, 'data': ''}
+        headers = {"Content-Type": "application/json", "accept": "application/json",
+                   'Authorization': 'Bearer {}'.format(token['id'])}
+
+        _url = "{0}/admin/v1/projects".format(self._base_path)
+
+        try:
+            r = requests.post(_url, json=project_data, verify=False, headers=headers)
+        except Exception as e:
+            log.exception(e)
+            result['data'] = str(e)
+            return result
+        print r.status_code
+        if r.status_code == requests.codes.created:
+            result['error'] = False
+        result['data'] = Util.json_loads_byteified(r.text)
+        return result
+
+    def project_delete(self, token, id):
+        result = {'error': True, 'data': ''}
+        headers = {"Content-Type": "application/yaml", "accept": "application/json",
+                   'Authorization': 'Bearer {}'.format(token['id'])}
+
+        _url = "{0}/admin/v1/projects/{1}".format(self._base_path, id)
+        try:
+            r = requests.delete(_url, params=None, verify=False, headers=headers)
+        except Exception as e:
+            log.exception(e)
+            result['data'] = str(e)
+            return result
+        if r.status_code == requests.codes.no_content:
+            result['error'] = False
+        else:
+            result['data'] = Util.json_loads_byteified(r.text)
+        return result
+
     def nsd_list(self, token):
         result = {'error': True, 'data': ''}
         headers = {"Content-Type": "application/yaml", "accept": "application/json",
diff --git a/projecthandler/template/project/modal/new_project.html b/projecthandler/template/project/modal/new_project.html
new file mode 100644 (file)
index 0000000..c346ec8
--- /dev/null
@@ -0,0 +1,32 @@
+<div class="modal" id="modal_new_project" xmlns="http://www.w3.org/1999/html">
+    <div class="modal-dialog">
+        <div class="modal-content">
+            <div class="modal-header">
+                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
+                    <span aria-hidden="true">×</span></button>
+                <h4 class="modal-title" id="modal_new_project_title">New Project</h4>
+            </div>
+            <form id="formNewProject" action='{% url "projects:new_project" %}'class="form-horizontal" method="post" >
+                     {% csrf_token %}
+            <div class="modal-body">
+
+                <div id="div_chose_id">
+                    <label>Project Name: </label>
+                    <input name="name" id="name"  size="40" maxlength="20"/>
+                </div>
+
+            </div>
+
+            <div class="modal-footer">
+                <button type="button" class="btn btn-default pull-left" data-dismiss="modal">Cancel</button>
+                <button class="btn btn-primary"
+                            data-loading-text="<i class='fa fa-circle-o-notch fa-spin'></i> Creating..."
+                            id="create_new_project">Create
+                    </button>
+            </div>
+                </form>
+        </div>
+        <!-- /.modal-content -->
+    </div>
+    <!-- /.modal-dialog -->
+</div>
\ No newline at end of file
diff --git a/projecthandler/template/project/new_project.html b/projecthandler/template/project/new_project.html
deleted file mode 100644 (file)
index 44fb435..0000000
+++ /dev/null
@@ -1,129 +0,0 @@
-{% extends "base.html" %}
-
-{% load staticfiles %}
-
-{% block head_block %}
-{{ block.super }}
-    <link rel="stylesheet" href="{% static "bower_components/admin-lte/plugins/select2/select2.css" %}">
-
-    <style type="text/css">
-
-  input:required:invalid, input:focus:invalid {
-
-    background-position: right top;
-    background-repeat: no-repeat;
-  }
-  input:required:valid {
-
-    background-position: right top;
-    background-repeat: no-repeat;
-  }
-
-</style>
-{% endblock %}
-
-{% block left_sidebar %}
-    {% include 'left_sidebar_base.html' %}
-{% endblock %}
-
-{% block breadcrumb_body %}
-{{ block.super }}
-<li><a href='{% url "projects:new_project" %}'>New Project</a></li>
-{% endblock %}
-
-{% block content_body %}
-{{ block.super }}
-<div class="row">
-    <div class="col-md-12">
-        <!-- general form elements -->
-        <div class="box box-primary">
-            <div class="box-header with-border">
-                <h3 class="box-title">New Project</h3>
-            </div>
-            <!-- /.box-header -->
-            <!-- form start -->
-            <form role="form" method="post" enctype="multipart/form-data">
-                {% csrf_token %}
-                <div class="box-body">
-                    <div class="row">
-                        <div class="form-group col-xs-3">
-                            <p for="typeButtonsSelect">Project Type</p>
-                            <input type="hidden" class="form-control input-sm" name="type" id="projectType"
-                                    required>
-                            <select id="select_type" class="js-example-basic-single form-control" style="width: 75%">
-
-                            </select>
-
-                        </div>
-                        <div class="form-group col-xs-4">
-                            <p for="projectName">Project Name</p>
-                            <input type="text" class="form-control input-sm" name="name" id="projectName"
-                                   placeholder="Enter Project name" required>
-                        </div>
-                        <div class="form-group col-xs-4">
-                            <p for="projectInfo">Info</p>
-                            <input type="text" class="form-control input-sm" name="info" id="projectInfo"
-                                   placeholder="Short Description">
-                        </div>
-
-
-                    </div>
-                    <div class="row">
-                        <div id="startGroup" class="form-group col-xs-5" style="display: none;">
-
-
-                            <div id="startButtonsSelect" class="btn-group" data-toggle="buttons">
-                                <label id="s-scratch" class="btn btn-primary active">
-                                    <input id="scratch" type="radio" name="startfrom" autocomplete="off" value="scratch">
-                                     Empty project
-                                </label>
-                                <label id="s-example" class="btn btn-primary">
-                                    <input type="radio" name="startfrom" autocomplete="off" value="example">
-                                     Example project
-                                </label>
-                                <label id="s-files" class="btn btn-primary">
-                                    <input type="radio" name="startfrom" autocomplete="off" value="files">
-                                     Load files
-                                </label>
-
-
-                            </div>
-                        </div>
-                    </div>
-                    <div id="typeStartContainer" class="row">
-                         <div class="form-group col-xs-8">
-                        {% autoescape off %}{{ type_container_template }}{% endautoescape %}
-                        </div>
-                    </div>
-
-                    <!-- /.box-body -->
-                </div>
-                <div class="box-footer">
-                    <button id="createButton" type="submit" class="btn btn-primary" disabled>Create</button>
-                </div>
-            </form>
-        </div>
-        <!-- /.box -->
-
-    </div>
-</div>
-{% endblock %}
-
-{% block resource_block %}
-{{ block.super }}
-    <!-- Select2 -->
-    <script src="{% static "bower_components/admin-lte/plugins/select2/select2.full.min.js" %}"></script>
-
-    <script src="{% static "src/projecthandler/new_project.js" %}"></script>
-<script>
-{% if data_type_selector %}
-var data_type_selector ={{ data_type_selector |safe }};
-{% endif %}
-
-{% if type_example_files %}
-var type_example_files = {{type_example_files | safe}};
-{% endif %}
-
-</script>
-{% endblock %}
-
index 033b0e0..6339679 100644 (file)
@@ -1,5 +1,6 @@
 {% extends "base.html" %}
-
+{% load get %}
+{% load date_tag %}
 {% load staticfiles %}
 
 {% block head_block %}
         <div class="box-header with-border">
                   <h3 class="box-title">Projects</h3>
             <div class="box-tools">
-                <a href="" class="btn btn-block btn-primary btn-sm" disabled><i class="fa fa-plus"></i><span> New Project</span></a>
+                <button type="button" class="btn btn-default" data-container="body"
+                                        data-toggle="tooltip" data-placement="top" title="New Project"
+                                        onclick="javascript:showModalNewProject()">
+                                    <i class="fa fa-plus"></i> New Project</button>
             </div>
         </div>
         <div class="box-body">
                                        <tr>
 
                                                <th>Name</th>
-                                               <th>Info</th>
-                                               <th>Type</th>
+
                                                <th>Modification Date</th>
                                                <th>Creation Date</th>
 
-                                               <th>Owner</th>
 
                                                <th><i class="far fa-trash-alt"></i></th>
                                        </tr>
                                        <tr>
 
                                                <td>
-                                                       <a href="javascript:openProject('{{ p.id }}')" >{{ p.name }}</a>
+                                                       <a href="javascript:openProject('{{ p.name }}')" >{{ p.name }}</a>
                                                </td>
-                                               <td>{{ p.info }}</td>
-                                               <td>{{ p.get_type }}</td>
-                                               <td>{{ p.updated_date }}</td>
-                                               <td>{{ p.created_date }}</td>
-                                               <td>{{ p.owner.username }}</td>
 
-                                               <td><a href="#"> Delete</a></td>
+                                               <td>{{ p|get_sub:"_admin,modified"|get_date}}</td>
+                        <td>{{ p|get_sub:"_admin,created"|get_date}}</td>
+
+                                               <td><a href="javascript:deleteProject('{% url 'projects:delete_project'  project_id=p|get:'_id' %}')"> Delete</a></td>
 
                                        </tr>
                                {% endfor %}
 </div>
 
 </div>
+{% include "modal/new_project.html" %}
 {% endblock %}
 
 {% block resource_block %}
        {{ block.super }}
-
+    <script>
+    function showModalNewProject(){
+        $('#modal_new_project').modal('show');
+    }
+
+    function deleteProject(url) {
+    bootbox.confirm("Are you sure want to delete?", function (result) {
+        if (result) {
+            $.ajax({
+            url: url,
+            type: 'GET',
+            headers: {
+                "Accept": 'application/json'
+            },
+            contentType: false,
+            processData: false
+        }).done(function (response,textStatus, jqXHR) {
+
+            bootbox.alert({
+                title: "Result",
+                message: "Project deleted.",
+                callback: function () {
+                    location.reload();
+                }
+            });
+        }).fail(function(result){
+            var data  = result.responseJSON;
+            var title = "Error " + (data.code ? data.code: 'unknown');
+                var message = data.detail ? data.detail: 'No detail available.';
+                bootbox.alert({
+                    title: title,
+                    message: message
+                });
+        });
+        }
+    })
+    }
+
+    $(document).ready(function () {
+    $("#formNewProject").submit(function (event) {
+        event.preventDefault(); //prevent default action
+        var post_url = $(this).attr("action"); //get form action url
+        var request_method = $(this).attr("method"); //get form GET/POST method
+        var form_data = new FormData(this); //Encode form elements for submission
+        console.log(post_url);
+        $.ajax({
+            url: post_url,
+            type: request_method,
+            data: form_data,
+            headers: {
+                "Accept": 'application/json'
+            },
+            contentType: false,
+            processData: false
+        }).done(function (response,textStatus, jqXHR) {
+            bootbox.alert({
+                    title: "Result",
+                    message: "Project created.",
+                callback: function () {
+                    location.reload();
+                }
+                });
+        }).fail(function(result){
+            var data  = result.responseJSON;
+            var title = "Error " + (data.code ? data.code: 'unknown');
+                var message = data.detail ? data.detail: 'No detail available.';
+                bootbox.alert({
+                    title: title,
+                    message: message
+                });
+        });
+    });
+    });
+
+
+
+
+    </script>
 
 
 {% endblock %}
\ No newline at end of file
index 6194b0a..0d50e10 100644 (file)
@@ -38,18 +38,26 @@ def home(request):
 
 @login_required
 def create_new_project(request):
-    return render(request, 'home.html', {})
+    if request.method == 'POST':
+        client = Client()
+        new_project_dict = request.POST.dict()
+        keys = ["name"]
+        project_data = dict(filter(lambda i: i[0] in keys and len(i[1]) > 0, new_project_dict.items()))
+        result = client.project_create(request.session['token'], project_data)
+        if isinstance(result, dict) and 'error' in result and result['error']:
+            print result
+            return __response_handler(request, result['data'], url=None,
+                                      status=result['data']['status'] if 'status' in result['data'] else 500)
+        else:
+            return __response_handler(request, {}, url=None, status=200)
 
 
 @login_required
 def user_projects(request):
-    csrf_token_value = get_token(request)
-    user = request.user
-    projects = user.get_projects()
-
+    client = Client()
+    result = client.project_list(request.session['token'])
     return render(request, 'projectlist.html', {
-        'projects': list(projects),
-        'csrf_token': csrf_token_value
+        'projects': result['data'] if result and result['error'] is False else [],
     })
 
 
@@ -85,23 +93,14 @@ def open_project(request, project_id=None):
 
 @login_required
 def delete_project(request, project_id=None):
-    if request.method == 'POST':
-
-        try:
-            ##TODO delete project
-            return redirect('projects:projects_list')
-        except Exception as e:
-            print e
-            return render(request, 'error.html', {'error_msg': 'Error deleting Project.'})
-
-    elif request.method == 'GET':
-        try:
-            return render(request, 'osm/osm_project_delete.html',
-                          {'project_id': project_id, 'project_name': project_id})
-
-        except Exception as e:
-            print e
-            return render(request, 'error.html', {'error_msg': 'Project not found.'})
+    client = Client()
+    result = client.project_delete(request.session['token'], project_id)
+    if isinstance(result, dict) and 'error' in result and result['error']:
+        print result
+        return __response_handler(request, result['data'], url=None,
+                                  status=result['data']['status'] if 'status' in result['data'] else 500)
+    else:
+        return __response_handler(request, {}, url=None, status=200)
 
 
 @login_required
@@ -198,7 +197,6 @@ def new_descriptor(request, project_id=None, descriptor_type=None):
         if result['error']:
             print result
             return __response_handler(request, result['data'], url=None, status=result['data']['status'] if 'status' in result['data'] else 500)
-
         else:
             return __response_handler(request, {}, url=None, status=200)