Refactor settings form and layout; enhance form submission with JSON handling and improve modal functionality for room management
This commit is contained in:
parent
d7e38cb8da
commit
5a3176cad1
3 changed files with 201 additions and 219 deletions
112
routes.py
112
routes.py
|
@ -1,4 +1,4 @@
|
||||||
from flask import Blueprint, render_template, url_for, request, redirect, flash
|
from flask import Blueprint, render_template, url_for, request, redirect, flash, jsonify
|
||||||
from flask import current_app as app
|
from flask import current_app as app
|
||||||
from .models import Brand, Item, Inventory, RoomFunction, User, WorkLog, Room, Area
|
from .models import Brand, Item, Inventory, RoomFunction, User, WorkLog, Room, Area
|
||||||
from sqlalchemy import or_, delete
|
from sqlalchemy import or_, delete
|
||||||
|
@ -152,8 +152,7 @@ def index():
|
||||||
active_worklog_headers=active_worklog_headers,
|
active_worklog_headers=active_worklog_headers,
|
||||||
active_worklog_rows=active_worklog_rows,
|
active_worklog_rows=active_worklog_rows,
|
||||||
labels=labels,
|
labels=labels,
|
||||||
datasets=datasets,
|
datasets=datasets
|
||||||
endpoint='index'
|
|
||||||
)
|
)
|
||||||
|
|
||||||
def link(text, endpoint, **values):
|
def link(text, endpoint, **values):
|
||||||
|
@ -205,8 +204,7 @@ def list_inventory():
|
||||||
breadcrumb=[{'label': 'Inventory', 'url': url_for('main.inventory_index')}],
|
breadcrumb=[{'label': 'Inventory', 'url': url_for('main.inventory_index')}],
|
||||||
header=inventory_headers,
|
header=inventory_headers,
|
||||||
rows=[{"id": item.id, "cells": [row_fn(item) for row_fn in inventory_headers.values()]} for item in inventory],
|
rows=[{"id": item.id, "cells": [row_fn(item) for row_fn in inventory_headers.values()]} for item in inventory],
|
||||||
entry_route = 'inventory_item',
|
entry_route = 'inventory_item'
|
||||||
endpoint='list_inventory'
|
|
||||||
)
|
)
|
||||||
|
|
||||||
@main.route("/inventory/index")
|
@main.route("/inventory/index")
|
||||||
|
@ -235,8 +233,7 @@ def inventory_index():
|
||||||
'inventory_index.html',
|
'inventory_index.html',
|
||||||
title=f"Inventory ({category.capitalize()} Index)" if category else "Inventory",
|
title=f"Inventory ({category.capitalize()} Index)" if category else "Inventory",
|
||||||
category=category,
|
category=category,
|
||||||
listing=listing,
|
listing=listing
|
||||||
endpoint='inventory_index'
|
|
||||||
)
|
)
|
||||||
|
|
||||||
@main.route("/inventory_item/<id>", methods=['GET', 'POST'])
|
@main.route("/inventory_item/<id>", methods=['GET', 'POST'])
|
||||||
|
@ -271,9 +268,7 @@ def inventory_item(id):
|
||||||
worklog=worklog,
|
worklog=worklog,
|
||||||
worklog_headers=filtered_worklog_headers,
|
worklog_headers=filtered_worklog_headers,
|
||||||
worklog_rows=[{"id": log.id, "cells": [fn(log) for fn in filtered_worklog_headers.values()]} for log in worklog],
|
worklog_rows=[{"id": log.id, "cells": [fn(log) for fn in filtered_worklog_headers.values()]} for log in worklog],
|
||||||
types=types,
|
types=types
|
||||||
endpoint='inventory_item',
|
|
||||||
endpoint_args={'id': item.id}
|
|
||||||
)
|
)
|
||||||
|
|
||||||
@main.route("/users")
|
@main.route("/users")
|
||||||
|
@ -285,8 +280,7 @@ def list_users():
|
||||||
header = user_headers,
|
header = user_headers,
|
||||||
rows = [{"id": user.id, "cells": [fn(user) for fn in user_headers.values()]} for user in users],
|
rows = [{"id": user.id, "cells": [fn(user) for fn in user_headers.values()]} for user in users],
|
||||||
title = "Users",
|
title = "Users",
|
||||||
entry_route = 'user',
|
entry_route = 'user'
|
||||||
endpoint='list_users'
|
|
||||||
)
|
)
|
||||||
|
|
||||||
@main.route("/user/<id>")
|
@main.route("/user/<id>")
|
||||||
|
@ -322,9 +316,7 @@ def user(id):
|
||||||
return render_template(
|
return render_template(
|
||||||
'error.html',
|
'error.html',
|
||||||
title=title,
|
title=title,
|
||||||
message=f"User with id {id} not found!",
|
message=f"User with id {id} not found!"
|
||||||
endpoint='user',
|
|
||||||
endpoint_args={'id': -1}
|
|
||||||
)
|
)
|
||||||
|
|
||||||
return render_template(
|
return render_template(
|
||||||
|
@ -335,9 +327,7 @@ def user(id):
|
||||||
inventory_rows=[{"id": item.id, "cells": [fn(item) for fn in filtered_inventory_headers.values()]} for item in inventory],
|
inventory_rows=[{"id": item.id, "cells": [fn(item) for fn in filtered_inventory_headers.values()]} for item in inventory],
|
||||||
worklog=worklog,
|
worklog=worklog,
|
||||||
worklog_headers=filtered_worklog_headers,
|
worklog_headers=filtered_worklog_headers,
|
||||||
worklog_rows=[{"id": log.id, "cells": [fn(log) for fn in filtered_worklog_headers.values()]} for log in worklog],
|
worklog_rows=[{"id": log.id, "cells": [fn(log) for fn in filtered_worklog_headers.values()]} for log in worklog]
|
||||||
endpoint='user',
|
|
||||||
endpoint_args={'id': user.id}
|
|
||||||
)
|
)
|
||||||
|
|
||||||
@main.route("/worklog")
|
@main.route("/worklog")
|
||||||
|
@ -349,8 +339,7 @@ def list_worklog(page=1):
|
||||||
header=worklog_headers,
|
header=worklog_headers,
|
||||||
rows=[{"id": log.id, "cells": [fn(log) for fn in worklog_headers.values()]} for log in query.all()],
|
rows=[{"id": log.id, "cells": [fn(log) for fn in worklog_headers.values()]} for log in query.all()],
|
||||||
title="Work Log",
|
title="Work Log",
|
||||||
entry_route='worklog_entry',
|
entry_route='worklog_entry'
|
||||||
endpoint='list_worklog'
|
|
||||||
)
|
)
|
||||||
|
|
||||||
@main.route("/worklog/<id>")
|
@main.route("/worklog/<id>")
|
||||||
|
@ -373,9 +362,7 @@ def worklog_entry(id):
|
||||||
return render_template(
|
return render_template(
|
||||||
'error.html',
|
'error.html',
|
||||||
title=title,
|
title=title,
|
||||||
message=f"The work log with ID {id} is not found!",
|
message=f"The work log with ID {id} is not found!"
|
||||||
endpoint='worklog_entry',
|
|
||||||
endpoint_args={'id': -1}
|
|
||||||
)
|
)
|
||||||
|
|
||||||
return render_template(
|
return render_template(
|
||||||
|
@ -384,9 +371,7 @@ def worklog_entry(id):
|
||||||
log=log,
|
log=log,
|
||||||
users=users,
|
users=users,
|
||||||
items=items,
|
items=items,
|
||||||
form_fields=worklog_form_fields,
|
form_fields=worklog_form_fields
|
||||||
endpoint='worklog_entry',
|
|
||||||
endpoint_args={'id': log.id}
|
|
||||||
)
|
)
|
||||||
|
|
||||||
@main.route("/search")
|
@main.route("/search")
|
||||||
|
@ -446,7 +431,7 @@ def search():
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return render_template('search.html', title=f"Database Search ({query})" if query else "Database Search", results=results, query=query, endpoint='search')
|
return render_template('search.html', title=f"Database Search ({query})" if query else "Database Search", results=results, query=query)
|
||||||
|
|
||||||
@main.route('/settings', methods=['GET', 'POST'])
|
@main.route('/settings', methods=['GET', 'POST'])
|
||||||
def settings():
|
def settings():
|
||||||
|
@ -518,54 +503,35 @@ def settings():
|
||||||
types=[{"id": t.id, "name": t.description} for t in types],
|
types=[{"id": t.id, "name": t.description} for t in types],
|
||||||
sections=[s.serialize() for s in sections],
|
sections=[s.serialize() for s in sections],
|
||||||
functions=[f.serialize() for f in functions],
|
functions=[f.serialize() for f in functions],
|
||||||
rooms=[r.serialize() for r in rooms],
|
rooms=[r.serialize() for r in rooms]
|
||||||
endpoint='settings'
|
|
||||||
)
|
)
|
||||||
|
|
||||||
@main.route('/api/settings', methods=['POST'])
|
@main.route("/api/settings", methods=["POST"])
|
||||||
def api_settings():
|
def api_settings():
|
||||||
try:
|
try:
|
||||||
payload = request.get_json()
|
payload = request.get_json(force=True)
|
||||||
if not payload:
|
|
||||||
return {'error': 'No JSON payload'}, 400
|
|
||||||
|
|
||||||
for label, entries in [
|
|
||||||
('brands', payload.get('brands', [])),
|
|
||||||
('types', payload.get('types', [])),
|
|
||||||
('sections', payload.get('sections', [])),
|
|
||||||
('functions', payload.get('functions', [])),
|
|
||||||
('rooms', payload.get('rooms', [])),
|
|
||||||
]:
|
|
||||||
if not isinstance(entries, list):
|
|
||||||
return {'error': f"{label} must be a list"}, 400
|
|
||||||
for entry in entries:
|
|
||||||
if not isinstance(entry, dict):
|
|
||||||
return {'error': f'Each {label} entry must be a dict'}, 400
|
|
||||||
|
|
||||||
errors = []
|
|
||||||
errors += Brand.validate_state(payload.get("brands", []))
|
|
||||||
errors += Item.validate_state(payload.get("types", []))
|
|
||||||
errors += Area.validate_state(payload.get("sections", []))
|
|
||||||
errors += RoomFunction.validate_state(payload.get("functions", []))
|
|
||||||
errors += Room.validate_state(payload.get("rooms", []))
|
|
||||||
|
|
||||||
if errors:
|
|
||||||
return {'status': 'error', 'errors': errors}, 400
|
|
||||||
|
|
||||||
with db.session.begin():
|
|
||||||
brand_map = Brand.sync_from_state(payload.get('brands', []))
|
|
||||||
type_map = Item.sync_from_state(payload.get('types', []))
|
|
||||||
section_map = Area.sync_from_state(payload.get('sections', []))
|
|
||||||
function_map = RoomFunction.sync_from_state(payload.get('functions', []))
|
|
||||||
|
|
||||||
Room.sync_from_state(
|
|
||||||
submitted_rooms=payload.get('rooms', []),
|
|
||||||
section_map=section_map,
|
|
||||||
function_map=function_map
|
|
||||||
)
|
|
||||||
|
|
||||||
return {'status': 'ok'}, 200
|
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
traceback.print_exc()
|
return jsonify({"error": "Invalid JSON"}), 400
|
||||||
return {'status': 'error', 'message': str(e)}, 500
|
|
||||||
|
errors = []
|
||||||
|
errors += Brand.validate_state(payload.get("brands", []))
|
||||||
|
errors += Item.validate_state(payload.get("types", []))
|
||||||
|
errors += Area.validate_state(payload.get("sections", []))
|
||||||
|
errors += RoomFunction.validate_state(payload.get("functions", []))
|
||||||
|
errors += Room.validate_state(payload.get("rooms", []))
|
||||||
|
|
||||||
|
if errors:
|
||||||
|
return jsonify({"errors": errors}), 400
|
||||||
|
|
||||||
|
try:
|
||||||
|
with db.session.begin():
|
||||||
|
section_map = Area.sync_from_state(payload["sections"])
|
||||||
|
function_map = RoomFunction.sync_from_state(payload["functions"])
|
||||||
|
Brand.sync_from_state(payload["brands"])
|
||||||
|
Item.sync_from_state(payload["types"])
|
||||||
|
Room.sync_from_state(payload["rooms"], section_map, function_map)
|
||||||
|
except Exception as e:
|
||||||
|
db.session.rollback()
|
||||||
|
return jsonify({"errors": [str(e)]}), 500
|
||||||
|
|
||||||
|
return jsonify({"message": "Settings updated successfully."}), 200
|
||||||
|
|
|
@ -53,10 +53,7 @@
|
||||||
</div>
|
</div>
|
||||||
</nav>
|
</nav>
|
||||||
<main class="container-flex m-5">
|
<main class="container-flex m-5">
|
||||||
<form method="POST" id="settingsForm" action="{{ url_for('main.' + endpoint, **(endpoint_args or {})) }}">
|
|
||||||
{% block content %}{% endblock %}
|
{% block content %}{% endblock %}
|
||||||
<input type="hidden" name="formState" id="formStateField">
|
|
||||||
</form>
|
|
||||||
</main>
|
</main>
|
||||||
|
|
||||||
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.6/dist/js/bootstrap.bundle.min.js"
|
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.6/dist/js/bootstrap.bundle.min.js"
|
||||||
|
|
|
@ -3,147 +3,149 @@
|
||||||
{% block title %}{{ title }}{% endblock %}
|
{% block title %}{{ title }}{% endblock %}
|
||||||
|
|
||||||
{% block content %}
|
{% block content %}
|
||||||
{{ breadcrumbs.breadcrumb_header(
|
<form id="settingsForm">
|
||||||
title=title,
|
{{ breadcrumbs.breadcrumb_header(
|
||||||
submit_button=True
|
title=title,
|
||||||
) }}
|
submit_button=True
|
||||||
|
) }}
|
||||||
|
|
||||||
<div class="container">
|
<div class="container">
|
||||||
<div class="card mb-3">
|
<div class="card mb-3">
|
||||||
<div class="card-body">
|
<div class="card-body">
|
||||||
<h5 class="card-title">
|
<h5 class="card-title">
|
||||||
Inventory Settings
|
Inventory Settings
|
||||||
</h5>
|
</h5>
|
||||||
<div class="row">
|
|
||||||
<div class="col">
|
|
||||||
{{ combos.render_combobox(
|
|
||||||
id='brand',
|
|
||||||
options=brands,
|
|
||||||
label='Brands',
|
|
||||||
placeholder='Add a new brand'
|
|
||||||
) }}
|
|
||||||
</div>
|
|
||||||
<div class="col">
|
|
||||||
{{ combos.render_combobox(
|
|
||||||
id='type',
|
|
||||||
options=types,
|
|
||||||
label='Inventory Types',
|
|
||||||
placeholder='Add a new type'
|
|
||||||
) }}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div class="card">
|
|
||||||
<div class="card-body">
|
|
||||||
<h5 class="card-title">Location Settings</h5>
|
|
||||||
<div class="row">
|
|
||||||
<div class="col">
|
|
||||||
{{ combos.render_combobox(
|
|
||||||
id='section',
|
|
||||||
options=sections,
|
|
||||||
label='Sections',
|
|
||||||
placeholder='Add a new section'
|
|
||||||
) }}
|
|
||||||
</div>
|
|
||||||
<div class="col">
|
|
||||||
{{ combos.render_combobox(
|
|
||||||
id='function',
|
|
||||||
options=functions,
|
|
||||||
label='Functions',
|
|
||||||
placeholder='Add a new function'
|
|
||||||
) }}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div class="row">
|
|
||||||
{% set room_editor %}
|
|
||||||
const roomEditorModal = new bootstrap.Modal(document.getElementById('roomEditor'));
|
|
||||||
const input = document.getElementById('room-input');
|
|
||||||
const name = input.value.trim();
|
|
||||||
const existingOption = Array.from(document.getElementById('room-list').options)
|
|
||||||
.find(opt => opt.textContent.trim() === name);
|
|
||||||
|
|
||||||
const event = new CustomEvent('roomEditor:prepare', {
|
|
||||||
detail: {
|
|
||||||
id: existingOption?.value ?? '',
|
|
||||||
name: name,
|
|
||||||
sectionId: existingOption?.dataset.sectionId ?? '',
|
|
||||||
functionId: existingOption?.dataset.functionId ?? ''
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
document.getElementById('roomEditor').dispatchEvent(event);
|
|
||||||
roomEditorModal.show();
|
|
||||||
|
|
||||||
document.getElementById('room-input').value = '';
|
|
||||||
{% endset %}
|
|
||||||
<div class="col">
|
|
||||||
{{ combos.render_combobox(
|
|
||||||
id='room',
|
|
||||||
options=rooms,
|
|
||||||
label='Rooms',
|
|
||||||
placeholder='Add a new room',
|
|
||||||
onAdd=room_editor,
|
|
||||||
onEdit=room_editor,
|
|
||||||
data_attributes={'area_id': 'section-id', 'function_id': 'function-id'}
|
|
||||||
) }}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div class="modal fade" id="roomEditor" data-bs-backdrop="static" tabindex="-1">
|
|
||||||
<div class="modal-dialog">
|
|
||||||
<div class="modal-content">
|
|
||||||
<div class="modal-header">
|
|
||||||
<h1 class="modal-title fs-5" id="roomEditorLabel">Room Editor</h1>
|
|
||||||
</div>
|
|
||||||
<div class="modal-body">
|
|
||||||
<div class="row">
|
<div class="row">
|
||||||
<div class="col">
|
<div class="col">
|
||||||
<label for="roomName" class="form-label">Room Name</label>
|
{{ combos.render_combobox(
|
||||||
<input type="text" class="form-input" id="roomName" placeholder="Enter room name">
|
id='brand',
|
||||||
<input type="hidden" id="roomId">
|
options=brands,
|
||||||
|
label='Brands',
|
||||||
|
placeholder='Add a new brand'
|
||||||
|
) }}
|
||||||
|
</div>
|
||||||
|
<div class="col">
|
||||||
|
{{ combos.render_combobox(
|
||||||
|
id='type',
|
||||||
|
options=types,
|
||||||
|
label='Inventory Types',
|
||||||
|
placeholder='Add a new type'
|
||||||
|
) }}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="card">
|
||||||
|
<div class="card-body">
|
||||||
|
<h5 class="card-title">Location Settings</h5>
|
||||||
|
<div class="row">
|
||||||
|
<div class="col">
|
||||||
|
{{ combos.render_combobox(
|
||||||
|
id='section',
|
||||||
|
options=sections,
|
||||||
|
label='Sections',
|
||||||
|
placeholder='Add a new section'
|
||||||
|
) }}
|
||||||
|
</div>
|
||||||
|
<div class="col">
|
||||||
|
{{ combos.render_combobox(
|
||||||
|
id='function',
|
||||||
|
options=functions,
|
||||||
|
label='Functions',
|
||||||
|
placeholder='Add a new function'
|
||||||
|
) }}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="row">
|
<div class="row">
|
||||||
|
{% set room_editor %}
|
||||||
|
const roomEditorModal = new bootstrap.Modal(document.getElementById('roomEditor'));
|
||||||
|
const input = document.getElementById('room-input');
|
||||||
|
const name = input.value.trim();
|
||||||
|
const existingOption = Array.from(document.getElementById('room-list').options)
|
||||||
|
.find(opt => opt.textContent.trim() === name);
|
||||||
|
|
||||||
|
const event = new CustomEvent('roomEditor:prepare', {
|
||||||
|
detail: {
|
||||||
|
id: existingOption?.value ?? '',
|
||||||
|
name: name,
|
||||||
|
sectionId: existingOption?.dataset.sectionId ?? '',
|
||||||
|
functionId: existingOption?.dataset.functionId ?? ''
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
document.getElementById('roomEditor').dispatchEvent(event);
|
||||||
|
roomEditorModal.show();
|
||||||
|
|
||||||
|
document.getElementById('room-input').value = '';
|
||||||
|
{% endset %}
|
||||||
<div class="col">
|
<div class="col">
|
||||||
<label for="roomSection" class="form-label">Section</label>
|
{{ combos.render_combobox(
|
||||||
<select id="roomSection" class="form-select">
|
id='room',
|
||||||
<option value="">Select a section</option>
|
options=rooms,
|
||||||
{% for section in sections %}
|
label='Rooms',
|
||||||
<option value="{{ section.id }}">{{ section.name }}</option>
|
placeholder='Add a new room',
|
||||||
{% endfor %}
|
onAdd=room_editor,
|
||||||
</select>
|
onEdit=room_editor,
|
||||||
</div>
|
data_attributes={'area_id': 'section-id', 'function_id': 'function-id'}
|
||||||
<div class="col">
|
) }}
|
||||||
<label class="form-label">Function</label>
|
|
||||||
<select id="roomFunction" class="form-select">
|
|
||||||
<option value="">Select a function</option>
|
|
||||||
{% for function in functions %}
|
|
||||||
<option value="{{ function.id }}">{{ function.name }}</option>
|
|
||||||
{% endfor %}
|
|
||||||
</select>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="modal-footer">
|
</div>
|
||||||
<button type="button" class="btn btn-danger" data-bs-dismiss="modal"
|
</div>
|
||||||
id="roomEditorCancelButton">Cancel</button>
|
<div class="modal fade" id="roomEditor" data-bs-backdrop="static" tabindex="-1">
|
||||||
<button type="button" class="btn btn-primary" id="roomEditorSaveButton">Save</button>
|
<div class="modal-dialog">
|
||||||
|
<div class="modal-content">
|
||||||
|
<div class="modal-header">
|
||||||
|
<h1 class="modal-title fs-5" id="roomEditorLabel">Room Editor</h1>
|
||||||
|
</div>
|
||||||
|
<div class="modal-body">
|
||||||
|
<div class="row">
|
||||||
|
<div class="col">
|
||||||
|
<label for="roomName" class="form-label">Room Name</label>
|
||||||
|
<input type="text" class="form-input" id="roomName" placeholder="Enter room name">
|
||||||
|
<input type="hidden" id="roomId">
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="row">
|
||||||
|
<div class="col">
|
||||||
|
<label for="roomSection" class="form-label">Section</label>
|
||||||
|
<select id="roomSection" class="form-select">
|
||||||
|
<option value="">Select a section</option>
|
||||||
|
{% for section in sections %}
|
||||||
|
<option value="{{ section.id }}">{{ section.name }}</option>
|
||||||
|
{% endfor %}
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
<div class="col">
|
||||||
|
<label class="form-label">Function</label>
|
||||||
|
<select id="roomFunction" class="form-select">
|
||||||
|
<option value="">Select a function</option>
|
||||||
|
{% for function in functions %}
|
||||||
|
<option value="{{ function.id }}">{{ function.name }}</option>
|
||||||
|
{% endfor %}
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="modal-footer">
|
||||||
|
<button type="button" class="btn btn-danger" data-bs-dismiss="modal"
|
||||||
|
id="roomEditorCancelButton">Cancel</button>
|
||||||
|
<button type="button" class="btn btn-primary" id="roomEditorSaveButton">Save</button>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</form>
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
|
|
||||||
{% block script %}
|
{% block script %}
|
||||||
const formState = {
|
const formState = {
|
||||||
brands: {{ brands | tojson }},
|
brands: {{ brands | tojson }},
|
||||||
types: {{ types | tojson }},
|
types: {{ types | tojson }},
|
||||||
sections: {{ sections | tojson }},
|
sections: {{ sections | tojson }},
|
||||||
functions: {{ functions | tojson }},
|
functions: {{ functions | tojson }},
|
||||||
rooms: {{ rooms | tojson }},
|
rooms: {{ rooms | tojson }},
|
||||||
};
|
};
|
||||||
|
|
||||||
function buildFormState() {
|
function buildFormState() {
|
||||||
|
@ -162,7 +164,7 @@ submit_button=True
|
||||||
const roomOptions = Array.from(document.getElementById('room-list').options);
|
const roomOptions = Array.from(document.getElementById('room-list').options);
|
||||||
const rooms = roomOptions.map(opt => {
|
const rooms = roomOptions.map(opt => {
|
||||||
const data = opt.dataset;
|
const data = opt.dataset;
|
||||||
|
|
||||||
return {
|
return {
|
||||||
id: opt.value || undefined,
|
id: opt.value || undefined,
|
||||||
name: opt.textContent.trim(),
|
name: opt.textContent.trim(),
|
||||||
|
@ -187,21 +189,21 @@ submit_button=True
|
||||||
const cancelButton = document.getElementById('roomEditorCancelButton');
|
const cancelButton = document.getElementById('roomEditorCancelButton');
|
||||||
const form = document.getElementById('settingsForm');
|
const form = document.getElementById('settingsForm');
|
||||||
|
|
||||||
|
|
||||||
modal.addEventListener('roomEditor:prepare', (event) => {
|
modal.addEventListener('roomEditor:prepare', (event) => {
|
||||||
const { id, name, sectionId, functionId } = event.detail;
|
const { id, name, sectionId, functionId } = event.detail;
|
||||||
document.getElementById('roomId').value = id;
|
document.getElementById('roomId').value = id;
|
||||||
document.getElementById('roomName').value = name;
|
document.getElementById('roomName').value = name;
|
||||||
|
|
||||||
// Populate dropdowns before assigning selection
|
// Populate dropdowns before assigning selection
|
||||||
const modalSections = document.getElementById('roomSection');
|
const modalSections = document.getElementById('roomSection');
|
||||||
const modalFunctions = document.getElementById('roomFunction');
|
const modalFunctions = document.getElementById('roomFunction');
|
||||||
const pageSections = document.getElementById('section-list');
|
const pageSections = document.getElementById('section-list');
|
||||||
const pageFunctions = document.getElementById('function-list');
|
const pageFunctions = document.getElementById('function-list');
|
||||||
|
|
||||||
modalSections.innerHTML = '<option value="">Select a section</option>';
|
modalSections.innerHTML = '<option value="">Select a section</option>';
|
||||||
modalFunctions.innerHTML = '<option value="">Select a function</option>';
|
modalFunctions.innerHTML = '<option value="">Select a function</option>';
|
||||||
|
|
||||||
Array.from(pageSections.options).forEach(opt => {
|
Array.from(pageSections.options).forEach(opt => {
|
||||||
const option = new Option(opt.textContent, opt.value);
|
const option = new Option(opt.textContent, opt.value);
|
||||||
if (opt.value === sectionId) {
|
if (opt.value === sectionId) {
|
||||||
|
@ -209,7 +211,7 @@ submit_button=True
|
||||||
}
|
}
|
||||||
modalSections.appendChild(option);
|
modalSections.appendChild(option);
|
||||||
});
|
});
|
||||||
|
|
||||||
Array.from(pageFunctions.options).forEach(opt => {
|
Array.from(pageFunctions.options).forEach(opt => {
|
||||||
const option = new Option(opt.textContent, opt.value);
|
const option = new Option(opt.textContent, opt.value);
|
||||||
if (opt.value === functionId) {
|
if (opt.value === functionId) {
|
||||||
|
@ -219,15 +221,32 @@ submit_button=True
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
// Replace the whole submission logic with just JSON
|
|
||||||
form.addEventListener('submit', (event) => {
|
form.addEventListener('submit', (event) => {
|
||||||
event.preventDefault(); // 🚨 Stop form from leaving the building
|
event.preventDefault();
|
||||||
try {
|
try {
|
||||||
const state = buildFormState();
|
const state = buildFormState();
|
||||||
document.getElementById('formStateField').value = JSON.stringify(state);
|
fetch('/api/settings', {
|
||||||
form.submit(); // 🟢 Now it can go
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json'
|
||||||
|
},
|
||||||
|
body: JSON.stringify(state)
|
||||||
|
})
|
||||||
|
.then(response => {
|
||||||
|
if (!response.ok) {
|
||||||
|
return response.json().then(data => {
|
||||||
|
throw new Error(data.errors?.join("\n") || "Unknown error");
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return response.json();
|
||||||
|
})
|
||||||
|
.then(data => {
|
||||||
|
console.log("Sync result:", data);
|
||||||
|
})
|
||||||
|
.catch(err => {
|
||||||
|
console.error("Submission error:", err);
|
||||||
|
});
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
alert("Form submission failed: " + err.message);
|
|
||||||
console.error("Failed to build form state:", err);
|
console.error("Failed to build form state:", err);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
@ -242,27 +261,27 @@ submit_button=True
|
||||||
alert('Please enter a room name.');
|
alert('Please enter a room name.');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const roomList = document.getElementById('room-list');
|
const roomList = document.getElementById('room-list');
|
||||||
let existingOption = Array.from(roomList.options).find(opt => opt.value === idRaw);
|
let existingOption = Array.from(roomList.options).find(opt => opt.value === idRaw);
|
||||||
|
|
||||||
// If it's a brand new ID, generate one (string-based!)
|
// If it's a brand new ID, generate one (string-based!)
|
||||||
if (!idRaw) {
|
if (!idRaw) {
|
||||||
idRaw = ComboBoxWidget.createTempId("room");
|
idRaw = ComboBoxWidget.createTempId("room");
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!existingOption) {
|
if (!existingOption) {
|
||||||
existingOption = ComboBoxWidget.createOption(name, idRaw);
|
existingOption = ComboBoxWidget.createOption(name, idRaw);
|
||||||
roomList.appendChild(existingOption);
|
roomList.appendChild(existingOption);
|
||||||
}
|
}
|
||||||
|
|
||||||
existingOption.textContent = name;
|
existingOption.textContent = name;
|
||||||
existingOption.value = idRaw;
|
existingOption.value = idRaw;
|
||||||
existingOption.dataset.sectionId = sectionVal || "";
|
existingOption.dataset.sectionId = sectionVal || "";
|
||||||
existingOption.dataset.functionId = funcVal || "";
|
existingOption.dataset.functionId = funcVal || "";
|
||||||
|
|
||||||
ComboBoxWidget.sortOptions(roomList);
|
ComboBoxWidget.sortOptions(roomList);
|
||||||
|
|
||||||
// Update formState.rooms
|
// Update formState.rooms
|
||||||
const index = formState.rooms.findIndex(r => r.id === idRaw);
|
const index = formState.rooms.findIndex(r => r.id === idRaw);
|
||||||
const payload = {
|
const payload = {
|
||||||
|
@ -271,13 +290,13 @@ submit_button=True
|
||||||
section_id: sectionVal !== "" ? sectionVal : null,
|
section_id: sectionVal !== "" ? sectionVal : null,
|
||||||
function_id: funcVal !== "" ? funcVal : null
|
function_id: funcVal !== "" ? funcVal : null
|
||||||
};
|
};
|
||||||
|
|
||||||
if (index >= 0) {
|
if (index >= 0) {
|
||||||
formState.rooms[index] = payload;
|
formState.rooms[index] = payload;
|
||||||
} else {
|
} else {
|
||||||
formState.rooms.push(payload);
|
formState.rooms.push(payload);
|
||||||
}
|
}
|
||||||
|
|
||||||
bootstrap.Modal.getInstance(modal).hide();
|
bootstrap.Modal.getInstance(modal).hide();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
Loading…
Add table
Add a link
Reference in a new issue