2025-02-01 17:53:13 +00:00
|
|
|
from flask import Blueprint, request, render_template, redirect, session
|
2025-01-30 09:58:34 +00:00
|
|
|
import csv
|
|
|
|
from io import TextIOWrapper
|
2025-02-11 18:45:53 +00:00
|
|
|
from definitions.models import Asset, db
|
2025-02-12 10:03:45 +00:00
|
|
|
from functions.process_csv import get_csv_data # Import the CSV processing function
|
2025-02-07 21:56:07 +00:00
|
|
|
from config import item_attributes # Import the configuration
|
2025-01-30 07:37:21 +00:00
|
|
|
|
2025-01-30 09:58:34 +00:00
|
|
|
# Create a Blueprint for upload
|
2025-01-30 07:37:21 +00:00
|
|
|
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:
|
2025-01-30 09:58:34 +00:00
|
|
|
return redirect('uploadcsv')
|
2025-01-30 07:37:21 +00:00
|
|
|
|
|
|
|
file = request.files['file']
|
|
|
|
|
|
|
|
# Check if the file is a CSV
|
|
|
|
if file.filename == '' or not file.filename.endswith('.csv'):
|
2025-01-30 09:58:34 +00:00
|
|
|
return redirect('uploadcsv')
|
2025-01-30 07:37:21 +00:00
|
|
|
|
|
|
|
try:
|
2025-01-30 09:58:34 +00:00
|
|
|
# Extract data from the CSV file
|
2025-02-05 08:26:37 +00:00
|
|
|
csvdata = get_csv_data(file)
|
2025-02-07 21:56:07 +00:00
|
|
|
|
|
|
|
# Identify the primary attribute
|
|
|
|
primary_attrib = next(
|
|
|
|
(attrib for attrib, config in item_attributes.items() if config.primary),
|
|
|
|
None
|
|
|
|
)
|
|
|
|
|
|
|
|
if not primary_attrib:
|
|
|
|
return "Primary attribute not defined in configuration."
|
|
|
|
|
|
|
|
# Separate new and existing assets
|
2025-02-05 08:26:37 +00:00
|
|
|
new_assets = []
|
|
|
|
existing_assets = []
|
|
|
|
for row in csvdata:
|
2025-02-07 21:56:07 +00:00
|
|
|
primary_value = row[primary_attrib]
|
|
|
|
asset_exists = Asset.query.filter_by(**{primary_attrib: primary_value}).first()
|
2025-02-05 08:26:37 +00:00
|
|
|
if asset_exists:
|
|
|
|
existing_assets.append(row)
|
|
|
|
else:
|
|
|
|
new_assets.append(row)
|
|
|
|
|
2025-02-07 21:56:07 +00:00
|
|
|
session['assets'] = new_assets # Store new assets in session
|
2025-01-30 07:37:21 +00:00
|
|
|
|
2025-01-30 09:58:34 +00:00
|
|
|
# Redirect to preview page with the CSV data
|
2025-02-07 21:56:07 +00:00
|
|
|
return render_template('csv_preview.html', new_assets=new_assets, existing=existing_assets, item_attributes=item_attributes)
|
2025-01-30 07:37:21 +00:00
|
|
|
|
|
|
|
except Exception as e:
|
|
|
|
# Handle errors during file processing
|
2025-01-30 09:58:34 +00:00
|
|
|
print(f"Error processing CSV file: {str(e)}")
|
|
|
|
return redirect('uploadcsv')
|
2025-01-30 07:37:21 +00:00
|
|
|
|
|
|
|
# Render the upload page for GET requests
|
2025-02-07 21:56:07 +00:00
|
|
|
return render_template('upload.html')
|