Skip to content

Commit

Permalink
session ui ajax push to update the session status
Browse files Browse the repository at this point in the history
  • Loading branch information
microtechno9000 committed Nov 29, 2023
1 parent fe1a704 commit a071905
Show file tree
Hide file tree
Showing 4 changed files with 142 additions and 27 deletions.
14 changes: 14 additions & 0 deletions arm/ui/sessions/forms.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
"""
Forms used in sessions blueprint
"""
from flask_wtf import FlaskForm
from wtforms import StringField
from wtforms.validators import DataRequired


class SessionStatusForm(FlaskForm):
"""
Session Status update form
"""
id = StringField('id', validators=[DataRequired()])
value = StringField('value')
60 changes: 54 additions & 6 deletions arm/ui/sessions/routes.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,20 @@
ARM route blueprint for sessions pages
Covers
- sessions [GET]
- sessions/edit [GET]
- sessions/update [POST]
"""

from flask_login import login_required
from flask import render_template
from flask import render_template, request

from arm.ui import app, db
from arm.ui.sessions import route_sessions
from arm.models.sessions import Sessions
from arm.models.session_settings import SessionSettings
from arm.models.session_types import SessionTypes
from arm.models.system_drives import SystemDrives
from .forms import SessionStatusForm


"""
Expand Down Expand Up @@ -141,20 +145,64 @@ def sessions():
# Return the current list of system drives available to ARM
db_system_drives = SystemDrives.query.all()

form = SessionStatusForm()

return render_template('sessions.html',
db_session_types=db_session_types,
db_sessions=db_sessions,
db_system_drives=db_system_drives)
db_system_drives=db_system_drives,
form=form)


@route_sessions.route('/sessions/edit/<id>')
@route_sessions.route('/sessions/edit/<session_id>')
@login_required
def session_edit(id):
def session_edit(session_id):
"""
Page - Sessions
Method - GET
Overview - Session editor
"""
db_session = Sessions.query.where(id=id).first()
db_session = Sessions.query.where(id=session_id).first()

return render_template('sessions_edit.html',
return render_template('sessions_status.html',
db_session=db_session)


@route_sessions.route('/sessions/update', methods=['POST'])
@login_required
def session_update_status():
"""
Page - Session Update
Method - POST
Overview - Take user updates from Session Edit tab for active and drive changes
"""
form = SessionStatusForm()
status = False
response = "data value passed not valid"

if form.validate():
data = request.get_json()
app.logger.debug(f"Session Status update: {data}")

# Get the row ID from json, load value from database
[name, row_id] = data['id'].split('_')
db_session = Sessions.query.filter_by(id=int(row_id)).first()
app.logger.debug(f"Session name: {name} row: {row_id} value: {data['value']}")

if name == 'valid':
db_session.valid = data['value']
response = f"Updated Session {row_id} status"
status = True
app.logger.debug(f"Session db update - id: {db_session.valid}")
db.session.commit()

elif name == 'drive':
db_session.drive_id = int(data['value'])
response = f"Updated Session {row_id} drive"
status = True
app.logger.debug(f"Session db update - drive_id: {db_session.drive_id}")
db.session.commit()

app.logger.info("Updated session information")

return {'success': status, 'response': response}
68 changes: 55 additions & 13 deletions arm/ui/sessions/templates/sessions.html
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,8 @@ <h2> ARM - Sessions </h2>
aria-controls="session-drives-tab" aria-selected="true">Current Sessions</a>
</li>
<li class="nav-item" role="presentation">
<a class="nav-link" id="session-edit" data-toggle="tab" href="#sessionedit" role="tab"
aria-controls="session-edit-tab" aria-selected="false">Edit Sessions</a>
<a class="nav-link" id="session-status" data-toggle="tab" href="#sessionstatus" role="tab"
aria-controls="session-status-tab" aria-selected="false">Sessions Status</a>
</li>
<li class="nav-item" role="presentation">
<a class="nav-link" id="session-help" data-toggle="tab" href="#sessionhelp" role="tab"
Expand All @@ -33,7 +33,7 @@ <h2> ARM - Sessions </h2>
<!-- Active drives with sessions -->
{% include 'sessions_drives.html' %}
<!-- session edit tab -->
{% include 'sessions_edit.html' %}
{% include 'sessions_status.html' %}
<!-- session help tab -->
{% include 'sessions_help.html' %}
</div>
Expand All @@ -48,19 +48,61 @@ <h2> ARM - Sessions </h2>
{% block js %}
{{ super() }}
<script>
// Event listener for the Session edit scripts
document.addEventListener('DOMContentLoaded', function () {
// Get the form element
var form = document.getElementById('sessionEdits');
var form = document.getElementById('sessionstatus');
form.addEventListener('change', function () {
saveForm(event.target);
});
});

// Add change event listeners to form elements
form.addEventListener('change', function () {
saveForm();
});
});
// Save the form data (active and drive info) to the database
function saveForm(field) {
var formData = {};
formData.id = field.id;

function saveForm() {
// Todo: push the data to ARM API for update
console.log('Form data has changed. Sending data to the server...');
// Check if a checkbox and set true or false
if (field.type === 'checkbox') {
var checkbox = document.getElementById(field.id);
formData.value = checkbox.checked;
} else {
formData.value = field.value;
}

// Add the CSRF token to the formData
var csrfToken = document.getElementById('csrf_token').getAttribute('value');

console.log('Field with ID ' + field.id + ' has changed. New value: ' + formData[field.id]);

fetch('/sessions/update', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRFToken': csrfToken, // Include this line
},
body: JSON.stringify(formData)
})
.then(response => response.json())
.then(data => {
if (data.success === true) {
document.getElementById('successAlert').innerHTML = `<strong>Success:</strong> ${data.response}`;
document.getElementById('successAlert').style.display = 'block';
document.getElementById('errorAlert').style.display = 'none';
} else {
document.getElementById('errorAlert').innerHTML = `<strong>Error:</strong> ${data.response}`;
document.getElementById('errorAlert').style.display = 'block';
document.getElementById('successAlert').style.display = 'none';
}

// Handle the server response as needed
console.log('Server response:', data);
})
.catch(error => {
console.error('Error:', error);

document.getElementById('successAlert').style.display = 'none';
document.getElementById('errorAlert').style.display = 'block';
});
}
</script>
{% endblock %}
Original file line number Diff line number Diff line change
@@ -1,7 +1,14 @@

{% block session_drives %}
<div class="tab-pane pt-5" id="sessionedit" role="tabpanel" aria-labelledby="session-drives-tab">
<div class="tab-pane pt-5" id="sessionstatus" role="tabpanel" aria-labelledby="session-status-tab">
<!-- DIVs for update alert/status -->
<div class="alert alert-success" role="alert" id="successAlert" style="display: none;">
</div>
<div class="alert alert-danger" role="alert" id="errorAlert" style="display: none;">
</div>

<form class="container content" id="sessionEdits">
{{ form.hidden_tag() }}
<table class="table table-hover table-sm ">
<caption>ARM Sessions Editor, assign drives and active status.</caption>
<thead class="thead-light">
Expand All @@ -11,7 +18,7 @@
<th scope="col">Active</th>
<th scope="col">Disc</th>
<th scope="col">Description</th>
<th scope="col">Edit</th>
<th scope="col"></th>
</tr>
</thead>
<tbody>
Expand All @@ -21,19 +28,23 @@
<td class="text-left font-weight-normal">{{ session.name }}</td>
<td class="font-weight-normal">
{% if session.valid %}
<input class="form-check-input" type="checkbox" value="" id="valid{{ session.id }}" checked>
<input class="form-check-input" type="checkbox" value="" id="valid_{{ session.id }}" checked>
{% else %}
<input class="form-check-input" type="checkbox" value="" id="valid{{ session.id }}">
<input class="form-check-input" type="checkbox" value="" id="valid_{{ session.id }}">
{% endif %}
</td>
<td class="font-weight-normal">
<select>
<option>Select a drive</option>
<select id="drive_{{ session.id }}">
<option value="0">Select a drive</option>
{% for drive in db_system_drives %}
{% if session.drive.drive_id == drive.drive_id %}
<option selected value="{{ drive.drive_id }}">{{ drive.name }} | {{ drive.mount }}</option>
<option selected value="{{ drive.drive_id }}">
{{ drive.name }} | {{ drive.mount }}
</option>
{% else %}
<option value="{{ drive.drive_id }}">{{ drive.name }} | {{ drive.mount }}</option>
<option value="{{ drive.drive_id }}">
{{ drive.name }} | {{ drive.mount }}
</option>
{% endif %}
{% endfor %}
</select>
Expand Down

0 comments on commit a071905

Please sign in to comment.