from flask import Blueprint, request, render_template, redirect, session from definitions.models import Asset, db from functions.process_csv import get_csv_data from config import item_attributes upload_bp = Blueprint('uploadcsv', __name__) @upload_bp.route('/uploadcsv', methods=['GET', 'POST']) def upload_file(): if request.method == 'POST': # Check if a file was uploaded if 'file' not in request.files: return redirect('uploadcsv') file = request.files['file'] # Check if the file is a CSV if file.filename == '' or not file.filename.endswith('.csv'): return redirect('uploadcsv') try: # Extract data from the CSV file csvdata = get_csv_data(file) # Identify the primary attribute primary_attrib = next( (attrib for attrib in item_attributes if attrib.primary), None ) if not primary_attrib: return "Primary attribute not defined in configuration." # Separate new and existing assets new_assets = [] existing_assets = [] for row in csvdata: primary_value = row[primary_attrib.attrib_name] asset_exists = Asset.query.filter_by(**{primary_attrib.attrib_name: primary_value}).first() if asset_exists: existing_assets.append(row) else: new_assets.append(row) session['assets'] = new_assets # Store new assets in session # Redirect to preview page with the CSV data return render_template( 'csv_preview.html', new_assets=new_assets, existing=existing_assets, item_attributes=item_attributes ) except Exception as e: # Handle errors during file processing print(f"Error processing CSV file: {str(e)}") return redirect('uploadcsv') # Render the upload page for GET requests return render_template('upload.html')