2025-01-30 07:37:21 +00:00
|
|
|
import csv
|
|
|
|
from io import TextIOWrapper
|
2025-02-11 08:14:14 +00:00
|
|
|
from config import item_attributes
|
2025-01-30 07:37:21 +00:00
|
|
|
|
2025-01-30 09:58:34 +00:00
|
|
|
def get_csv_data(file):
|
2025-01-30 07:37:21 +00:00
|
|
|
csv_file = TextIOWrapper(file, encoding='utf-8')
|
2025-01-30 09:58:34 +00:00
|
|
|
reader = csv.DictReader(csv_file, delimiter='|')
|
2025-01-30 07:37:21 +00:00
|
|
|
|
2025-02-11 08:14:14 +00:00
|
|
|
# Validate CSV headers based on config
|
2025-02-22 18:58:10 +00:00
|
|
|
required_headers = {attrib.display_name for attrib in item_attributes} # Use display names
|
|
|
|
csv_headers = set(reader.fieldnames) # Get headers present in the CSV file
|
2025-02-11 08:27:00 +00:00
|
|
|
|
|
|
|
# Check if the required headers exist
|
2025-02-22 18:58:10 +00:00
|
|
|
if not required_headers.issubset(csv_headers):
|
2025-02-11 08:14:14 +00:00
|
|
|
raise ValueError(f"CSV file must include headers: {', '.join(required_headers)}.")
|
2025-02-22 18:58:10 +00:00
|
|
|
|
2025-02-11 08:27:00 +00:00
|
|
|
# Check for invalid headers
|
2025-02-11 18:45:53 +00:00
|
|
|
if extra_headers := csv_headers - required_headers:
|
2025-02-11 08:27:00 +00:00
|
|
|
raise ValueError(f"Unexpected headers found: {', '.join(extra_headers)}")
|
2025-01-30 07:37:21 +00:00
|
|
|
|
2025-02-22 18:58:10 +00:00
|
|
|
# Map display names to attribute names
|
|
|
|
display_to_attrib = {attrib.display_name: attrib.attrib_name for attrib in item_attributes}
|
|
|
|
|
2025-02-11 08:14:14 +00:00
|
|
|
# Extract data dynamically based on config
|
2025-02-22 18:58:10 +00:00
|
|
|
return [
|
|
|
|
{display_to_attrib[header]: row[header] for header in required_headers}
|
|
|
|
for row in reader
|
|
|
|
]
|