From 3082e46aef1ea45975d792e6deecef217802bc05 Mon Sep 17 00:00:00 2001
From: Benjamin Bertrand <benjamin.bertrand@esss.se>
Date: Sat, 2 Dec 2017 00:39:55 +0100
Subject: [PATCH] Refactor attributes page

---
 app/main/forms.py             |  7 -------
 app/main/views.py             | 17 +++++++++--------
 app/static/js/attributes.js   |  6 +-----
 app/templates/attributes.html | 24 ++++++++++++------------
 app/templates/base.html       |  2 +-
 5 files changed, 23 insertions(+), 33 deletions(-)

diff --git a/app/main/forms.py b/app/main/forms.py
index c020d56..2b3e20b 100644
--- a/app/main/forms.py
+++ b/app/main/forms.py
@@ -27,15 +27,8 @@ class NoValidateSelectField(SelectField):
 
 
 class AttributeForm(FlaskForm):
-    kind = SelectField('Kind')
     name = StringField('name', validators=[validators.DataRequired()])
 
-    def __init__(self, *args, **kwargs):
-        super().__init__(*args, **kwargs)
-        self.kind.choices = utils.get_choices(
-            ('Manufacturer', 'Model', 'Location')
-        )
-
 
 class ItemForm(FlaskForm):
     ics_id = StringField('ICS id',
diff --git a/app/main/views.py b/app/main/views.py
index 99fb980..867225c 100644
--- a/app/main/views.py
+++ b/app/main/views.py
@@ -116,22 +116,23 @@ def qrcodes(kind='Action'):
     return render_template('qrcodes.html', kind=kind, images=images)
 
 
-@bp.route('/attributes', methods=('GET', 'POST'))
+@bp.route('/attributes/<kind>', methods=('GET', 'POST'))
 @login_groups_accepted('admin', 'create')
-def attributes():
-    kind = request.args.get('kind', 'Manufacturer')
-    form = AttributeForm(request.form, kind=kind)
+def attributes(kind):
+    form = AttributeForm()
     if form.validate_on_submit():
-        model = globals()[form.kind.data]
+        model = getattr(models, kind)
         new_model = model(name=form.name.data)
         db.session.add(new_model)
         try:
             db.session.commit()
         except sa.exc.IntegrityError as e:
             db.session.rollback()
-            flash(f'{form.name.data} already exists! Attribute not created.', 'error')
-        return redirect(url_for('main.attributes', kind=form.kind.data))
-    return render_template('attributes.html', form=form)
+            flash(f'{form.name.data} already exists! {kind} not created.', 'error')
+        else:
+            flash(f'{kind} {new_model} created!', 'success')
+        return redirect(url_for('main.attributes', kind=kind))
+    return render_template('attributes.html', kind=kind, form=form)
 
 
 @bp.route('/_retrieve_attributes_name/<kind>')
diff --git a/app/static/js/attributes.js b/app/static/js/attributes.js
index ea7ff61..4d9be6e 100644
--- a/app/static/js/attributes.js
+++ b/app/static/js/attributes.js
@@ -2,7 +2,7 @@ $(document).ready(function() {
 
   var attributes_table =  $("#attributes_table").DataTable({
     "ajax": function(data, callback, settings) {
-      var kind = $("#kind").val();
+      var kind = $('li a.nav-link.active').text();
       $.getJSON(
         $SCRIPT_ROOT + "/_retrieve_attributes_name/" + kind,
         function(json) {
@@ -12,8 +12,4 @@ $(document).ready(function() {
     "paging": false
   });
 
-  $("#kind").on('change', function() {
-    attributes_table.ajax.reload();
-  });
-
 });
diff --git a/app/templates/attributes.html b/app/templates/attributes.html
index dd6f972..362191e 100644
--- a/app/templates/attributes.html
+++ b/app/templates/attributes.html
@@ -1,27 +1,27 @@
 {%- extends "base.html" %}
-{% import "bootstrap/wtf.html" as wtf %}
+{% from "_helpers.html" import render_field %}
 
 {% block title %}Attributes - CSEntry{% endblock %}
 
 {% block main %}
   <ul class="nav nav-tabs">
+    {% for attribute in ('Manufacturer', 'Model', 'Location') %}
     <li class="nav-item">
-      <a class="nav-link active" href="{{ url_for('main.attributes') }}">Attributes</a>
+      <a class="nav-link {% if attribute == kind %}active{% endif %}" href="{{ url_for('main.attributes', kind=attribute) }}">{{ attribute }}</a>
     </li>
+    {% endfor %}
   </ul>
 
   <br>
 
-  <form method="POST" class="form-inline">
-    {{ form.csrf_token }}
-
-    {{ form.kind.label(class="sr-only") | safe }}
-    {{ form.kind(class="form-control mb-2 mr-sm-2 mb-sm-0") }}
-
-    {{ form.name.label(class="sr-only") | safe }}
-    {{ form.name(class="form-control mb-2 mr-sm-2 mb-sm-0", placeholder="name", required=True) }}
-
-    <button type="submit" class="btn btn-primary">Create</button>
+  <form id="attributeForm" method="POST">
+    {{ form.hidden_tag() }}
+    {{ render_field(form.name) }}
+    <div class="form-group row">
+      <div class="col-sm-10">
+        <button type="submit" class="btn btn-primary">Create</button>
+      </div>
+    </div>
   </form>
 
   <hr class="separator">
diff --git a/app/templates/base.html b/app/templates/base.html
index 7d40c2c..af3668f 100644
--- a/app/templates/base.html
+++ b/app/templates/base.html
@@ -25,7 +25,7 @@
           {% set path = request.path %}
           <a class="nav-item nav-link {{ is_active(path.startswith("/items")) }}" href="{{ url_for('main.list_items') }}">Items</a>
           <a class="nav-item nav-link {{ is_active(path.startswith("/hosts")) }}" href="{{ url_for('main.list_hosts') }}">Hosts</a>
-          <a class="nav-item nav-link {{ is_active(path.startswith("/attributes")) }}" href="{{ url_for('main.attributes') }}">Attributes</a>
+          <a class="nav-item nav-link {{ is_active(path.startswith("/attributes")) }}" href="{{ url_for('main.attributes', kind='Manufacturer') }}">Attributes</a>
           <a class="nav-item nav-link {{ is_active(path.startswith("/qrcodes")) }}" href="{{ url_for('main.qrcodes', kind='Action') }}">QR Codes</a>
           {% if current_user.is_authenticated and current_user.is_admin %}
             <a class="nav-item nav-link" href="{{ url_for('admin.index') }}">Admin</a>
-- 
GitLab