diff --git a/routes/confirm_save.py b/routes/confirm_save.py index ed3f7e8..c818e42 100644 --- a/routes/confirm_save.py +++ b/routes/confirm_save.py @@ -1,24 +1,40 @@ -from flask import Blueprint, redirect, session, request, jsonify +from flask import Blueprint, redirect, session, request, flash, url_for from definitions.models import Asset, db -import json +from functions.validate_values import validate_values from config import item_attributes +import json confirm_save_bp = Blueprint('confirm_save', __name__) @confirm_save_bp.route('/confirm_save', methods=['POST']) def confirm_save(): + # Check if assets data is present in the request if 'assets' not in request.form: - return "No assets data found in the request.", 400 + flash("No assets data found in the request.", "error") + return redirect(url_for('uploadcsv.upload_file')) try: + # Parse the JSON data from the form edited_assets = json.loads(request.form['assets']) except json.JSONDecodeError: - return "Invalid JSON data in the request.", 400 + flash("Invalid JSON data in the request.", "error") + return redirect(url_for('uploadcsv.upload_file')) - session['assets'] = edited_assets + # Validate each asset + errors = [] + for i, asset_data in enumerate(edited_assets, start=1): + error = validate_values(asset_data) + if error: + errors.append(f"Row {i}: {error}") + if errors: + # If there are validation errors, flash them and redirect back to the preview page + for error in errors: + flash(error, "error") + return redirect(url_for('uploadcsv.upload_file')) + + # Save validated assets to the database for asset_data in edited_assets: - # Dynamically create the Asset object using item_attributes asset = Asset(**{ attrib.attrib_name: asset_data[attrib.attrib_name] for attrib in item_attributes @@ -29,7 +45,10 @@ def confirm_save(): db.session.commit() except Exception as e: db.session.rollback() - return f"Error saving data to the database: {str(e)}", 500 + flash(f"Error saving data to the database: {str(e)}", "error") + return redirect(url_for('uploadcsv.upload_file')) - session.pop('assets', None) # Clear session data + # Clear session data after successful insertion + session.pop('assets', None) + flash("Data successfully saved to the database.", "success") return redirect('/viewall') \ No newline at end of file diff --git a/templates/csv_preview.html b/templates/csv_preview.html index d373d40..e6abc22 100644 --- a/templates/csv_preview.html +++ b/templates/csv_preview.html @@ -9,7 +9,7 @@
{{ category }}: {{ message }}
- {% endfor %} +