Compare commits
6 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| bc5e08142a | |||
| 373839cf03 | |||
| 8e31309c55 | |||
| e8391dbf1e | |||
| bc274da006 | |||
| f0b5edff79 |
+61
-45
@@ -11862,6 +11862,37 @@ def batch_upload_page():
|
||||
|
||||
return render_template('upload_batch.html')
|
||||
|
||||
def clean_db_field(val):
|
||||
"""Bereinigt Werte, die fälschlicherweise als String-Listen oder mit Klammern aus der CSV kommen."""
|
||||
import ast
|
||||
import pandas as pd
|
||||
|
||||
if not val or pd.isna(val):
|
||||
return None
|
||||
|
||||
val_str = str(val).strip()
|
||||
|
||||
# Wenn es wie eine Liste aussieht (z.B. "['100177']" oder "['']")
|
||||
if val_str.startswith("[") and val_str.endswith("]"):
|
||||
try:
|
||||
parsed = ast.literal_eval(val_str)
|
||||
if isinstance(parsed, list):
|
||||
# Nimm das erste Element der Liste, wenn vorhanden
|
||||
for item in parsed:
|
||||
cleaned_item = str(item).strip()
|
||||
if cleaned_item and cleaned_item not in ("", "''", '""', "None", "nan"):
|
||||
return cleaned_item
|
||||
return None
|
||||
except Exception:
|
||||
# Fallback bei Syntaxfehlern
|
||||
inner = val_str[1:-1].strip().replace("'", "").replace('"', '')
|
||||
return inner if inner and inner not in ("''", '""') else None
|
||||
|
||||
if val_str in ("[]", "['']", '[""]', "nan", "None", "''", '""'):
|
||||
return None
|
||||
|
||||
return val_str
|
||||
|
||||
|
||||
|
||||
@app.route('/upload_csv_batch', methods=['POST'])
|
||||
@@ -11878,13 +11909,6 @@ def upload_csv_batch():
|
||||
username = session.get('username', 'System')
|
||||
|
||||
def generate_unique_batch_code(base_code, position):
|
||||
"""
|
||||
Generiert einen eindeutigen Code für einen Artikel innerhalb einer Serie (Batch).
|
||||
|
||||
:param base_code: Der Code des ersten Artikels in der Gruppe (String oder None).
|
||||
:param position: Die Position des aktuellen Artikels in der Gruppe (Integer).
|
||||
:return: Ein eindeutiger Code als String.
|
||||
"""
|
||||
if base_code:
|
||||
return f"{base_code}-{position}"
|
||||
else:
|
||||
@@ -11913,8 +11937,8 @@ def upload_csv_batch():
|
||||
return jsonify({"success": False, "message": "Die CSV muss zwingend eine 'Name' Spalte enthalten."}), 400
|
||||
|
||||
# 3. Bilder verarbeiten & Duplikate im selben Durchlauf filtern (Hash-Matching)
|
||||
image_mapping = {} # Original-Dateiname (ohne Ext) -> GridFS Filename (.webp)
|
||||
processed_hashes = {} # SHA-256 Hash -> GridFS Filename (.webp)
|
||||
image_mapping = {}
|
||||
processed_hashes = {}
|
||||
processed_count = 0
|
||||
dedup_count = 0
|
||||
error_count = 0
|
||||
@@ -11934,18 +11958,14 @@ def upload_csv_batch():
|
||||
error_count += 1
|
||||
continue
|
||||
|
||||
# SHA-256 Hash des Bildinhalts zur Erkennung identischer Bilder
|
||||
img_hash = hashlib.sha256(image_bytes).hexdigest()
|
||||
|
||||
if img_hash in processed_hashes:
|
||||
# Bild ist identisch zu einem bereits verarbeiteten Bild im selben Batch
|
||||
existing_filename = processed_hashes[img_hash]
|
||||
image_mapping[base_name_no_ext] = existing_filename
|
||||
dedup_count += 1
|
||||
app.logger.info(f"{image_log_prefix} Duplikat erkannt ({original_secure_name}). Wiederverwendung von: {existing_filename}")
|
||||
continue
|
||||
|
||||
# Neues Bild verarbeiten und nach WebP konvertieren
|
||||
optimized_io = io.BytesIO()
|
||||
with Image.open(io.BytesIO(image_bytes)) as img:
|
||||
if img.mode not in ('RGB', 'RGBA'):
|
||||
@@ -11962,8 +11982,7 @@ def upload_csv_batch():
|
||||
optimized_io.seek(0)
|
||||
new_filename = f"{uuid.uuid4().hex}_{int(time.time())}.webp"
|
||||
|
||||
# In GridFS speichern
|
||||
file_id = fs.put(
|
||||
fs.put(
|
||||
optimized_io,
|
||||
filename=new_filename,
|
||||
content_type='image/webp',
|
||||
@@ -11974,7 +11993,6 @@ def upload_csv_batch():
|
||||
}
|
||||
)
|
||||
|
||||
# In Hash-Tabelle und Mapping sichern
|
||||
processed_hashes[img_hash] = new_filename
|
||||
image_mapping[base_name_no_ext] = new_filename
|
||||
processed_count += 1
|
||||
@@ -11989,8 +12007,8 @@ def upload_csv_batch():
|
||||
except Exception:
|
||||
predefined_locations = []
|
||||
|
||||
# 5. Dataframe bereinigen & gruppieren
|
||||
df['Name'] = df['Name'].fillna('Unbenannt').astype(str)
|
||||
# 5. Dataframe bereinigen
|
||||
df['Name'] = df['Name'].fillna('Unbenannt').astype(str).str.strip()
|
||||
df = df.fillna({
|
||||
'Ort': 'Unbekannt',
|
||||
'Beschreibung': '',
|
||||
@@ -11999,21 +12017,28 @@ def upload_csv_batch():
|
||||
'Anschaffungskosten': ''
|
||||
})
|
||||
|
||||
created_item_ids = []
|
||||
grouped_items = df.groupby('Name')
|
||||
# --- WICHTIG: Gruppierung über einen normalisierten Schlüssel ermöglichen ---
|
||||
# Erstellt eine unsichtbare Hilfsspalte, die Leerzeichen/Groß-Kleinschreibung ignoriert,
|
||||
# damit identische Artikel-Typen sauber als Serie erkannt werden.
|
||||
df['GroupKey'] = df['Name'].str.lower()
|
||||
|
||||
for name, group in grouped_items:
|
||||
created_item_ids = []
|
||||
grouped_items = df.groupby('GroupKey')
|
||||
|
||||
for group_key, group in grouped_items:
|
||||
item_count = len(group)
|
||||
series_group_id = str(uuid.uuid4()) if item_count > 1 else None
|
||||
parent_item_id = None
|
||||
|
||||
# Originalen Namen des ersten Elements der Gruppe übernehmen
|
||||
actual_group_name = group.iloc[0]['Name']
|
||||
|
||||
# Basis-Code für automatisierte Seriencodes ermitteln
|
||||
first_row_code = str(group.iloc[0].get('Code_4', '')).strip()
|
||||
first_row_code = clean_db_field(group.iloc[0].get('Code_4', ''))
|
||||
base_code = first_row_code if first_row_code else None
|
||||
|
||||
for position, (index, row) in enumerate(group.iterrows(), start=1):
|
||||
|
||||
# Ort automatisch zu predefined_locations hinzufügen, falls neu
|
||||
ort_val = str(row['Ort']).strip()
|
||||
if ort_val and ort_val not in predefined_locations:
|
||||
try:
|
||||
@@ -12022,7 +12047,7 @@ def upload_csv_batch():
|
||||
except Exception as e:
|
||||
app.logger.warning(f"Ort {ort_val} konnte nicht hinzugefügt werden: {e}")
|
||||
|
||||
# Bilder für diesen Artikel zuordnen
|
||||
# Bilder zuordnen und pro Artikel deduplizieren
|
||||
item_image_filenames = []
|
||||
if 'Images' in row and pd.notna(row['Images']):
|
||||
try:
|
||||
@@ -12032,19 +12057,13 @@ def upload_csv_batch():
|
||||
base_img_name = os.path.splitext(img_name)[0]
|
||||
if base_img_name in image_mapping:
|
||||
item_image_filenames.append(image_mapping[base_img_name])
|
||||
else:
|
||||
app.logger.warning(f"Bild {img_name} in CSV definiert, aber nicht hochgeladen.")
|
||||
except (ValueError, SyntaxError):
|
||||
pass
|
||||
|
||||
# --- NEU: BILDER-REFERENZEN PRO ARTIKEL DEDUPLIZIEREN ---
|
||||
# Falls die CSV z.B. ['bild1.jpg', 'bild1.jpg'] enthält, filtern wir das hier heraus,
|
||||
# damit die GridFS-Datei nicht doppelt als Referenz gespeichert wird.
|
||||
unique_image_filenames = []
|
||||
for img in item_image_filenames:
|
||||
if img not in unique_image_filenames:
|
||||
unique_image_filenames.append(img)
|
||||
# --------------------------------------------------------
|
||||
|
||||
def parse_filter_col(col_data):
|
||||
try:
|
||||
@@ -12059,26 +12078,28 @@ def upload_csv_batch():
|
||||
|
||||
reservierbar = bool(row.get('Reservierbar', False))
|
||||
|
||||
# Code_4 Behandlung: Falls in CSV definiert nutzen, sonst Batch-Code erzeugen
|
||||
row_code = str(row.get('Code_4', '')).strip()
|
||||
# Code_4 / Barcode sauber extrahieren und bereinigen
|
||||
raw_code = row.get('Code_4') or row.get('Barcode') or ''
|
||||
row_code = clean_db_field(raw_code)
|
||||
|
||||
if row_code:
|
||||
unique_code = row_code
|
||||
elif 'generate_unique_batch_code' in globals():
|
||||
elif item_count > 1:
|
||||
unique_code = generate_unique_batch_code(base_code, position)
|
||||
else:
|
||||
unique_code = None
|
||||
|
||||
# DB Insert (exakt abgestimmt auf die 10 positionellen Argumente)
|
||||
# DB Insert
|
||||
item_id = it.add_item(
|
||||
str(row['Name']), # 1. Name
|
||||
str(actual_group_name), # 1. Name
|
||||
ort_val, # 2. Ort
|
||||
str(row['Beschreibung']), # 3. Beschreibung
|
||||
unique_image_filenames, # 4. Image Filenames (GridFS) -> HIER GEÄNDERT
|
||||
unique_image_filenames, # 4. Image Filenames (GridFS)
|
||||
filter_upload, # 5. Filter 1
|
||||
filter_upload2, # 6. Filter 2
|
||||
filter_upload3, # 7. Filter 3
|
||||
str(row['Anschaffungsjahr']) if row['Anschaffungsjahr'] else None, # 8. Jahr
|
||||
str(row['Anschaffungskosten']) if row['Anschaffungskosten'] else None, # 9. Kosten
|
||||
clean_db_field(row.get('Anschaffungsjahr')), # 8. Jahr
|
||||
clean_db_field(row.get('Anschaffungskosten')),# 9. Kosten
|
||||
unique_code, # 10. Unique Code / Code_4
|
||||
reservierbar=reservierbar,
|
||||
series_group_id=series_group_id,
|
||||
@@ -12097,16 +12118,11 @@ def upload_csv_batch():
|
||||
if position == 1:
|
||||
parent_item_id = str(item_id)
|
||||
else:
|
||||
app.logger.error(f"Fehler beim Erstellen von Item: {row['Name']} (Index {index})")
|
||||
|
||||
app.logger.info(
|
||||
f"Batch Upload abgeschlossen: {len(created_item_ids)} Items erstellt. "
|
||||
f"{processed_count} neue Bilder hochgeladen, {dedup_count} Bild-Duplikate zusammengeführt."
|
||||
)
|
||||
app.logger.error(f"Fehler beim Erstellen von Item: {actual_group_name} (Index {index})")
|
||||
|
||||
return jsonify({
|
||||
"success": True,
|
||||
"message": f"Upload erfolgreich. {len(created_item_ids)} Items importiert. {processed_count} neue Bilder gespeichert ({dedup_count} Duplikate zusammengeführt).",
|
||||
"message": f"Upload erfolgreich. {len(created_item_ids)} Items importiert.",
|
||||
"created_count": len(created_item_ids),
|
||||
"images_processed": processed_count,
|
||||
"images_deduplicated": dedup_count,
|
||||
|
||||
+112
-89
@@ -48,30 +48,62 @@
|
||||
</div>
|
||||
|
||||
<script>
|
||||
// Robuster CSV-Parser, der Kommas innerhalb von Anführungszeichen ignoriert
|
||||
function parseCSVLine(text) {
|
||||
const result = [];
|
||||
let cur = '';
|
||||
let inQuotes = false;
|
||||
for (let i = 0; i < text.length; i++) {
|
||||
const c = text[i];
|
||||
if (c === '"' || c === "'") {
|
||||
inQuotes = !inQuotes;
|
||||
} else if (c === ',' && !inQuotes) {
|
||||
result.push(cur.trim());
|
||||
cur = '';
|
||||
// 1. Robuster CSV-Parser, der Zeilenumbrüche und Kommas in Texten korrekt ignoriert
|
||||
function parseCSV(csvString) {
|
||||
const rows = [];
|
||||
let currentRow = [];
|
||||
let currentCell = '';
|
||||
let insideQuotes = false;
|
||||
|
||||
for (let i = 0; i < csvString.length; i++) {
|
||||
const char = csvString[i];
|
||||
const nextChar = csvString[i + 1];
|
||||
|
||||
if (char === '"' && insideQuotes && nextChar === '"') {
|
||||
currentCell += '"';
|
||||
i++; // Escaped Quotes ("") überspringen
|
||||
} else if (char === '"') {
|
||||
insideQuotes = !insideQuotes;
|
||||
} else if (char === ',' && !insideQuotes) {
|
||||
currentRow.push(currentCell);
|
||||
currentCell = '';
|
||||
} else if ((char === '\n' || char === '\r') && !insideQuotes) {
|
||||
if (char === '\r' && nextChar === '\n') i++; // Windows Umbrüche überspringen
|
||||
currentRow.push(currentCell);
|
||||
if (currentRow.length > 1 || currentRow[0] !== '') {
|
||||
rows.push(currentRow);
|
||||
}
|
||||
currentRow = [];
|
||||
currentCell = '';
|
||||
} else {
|
||||
cur += c;
|
||||
currentCell += char;
|
||||
}
|
||||
}
|
||||
result.push(cur.trim());
|
||||
return result;
|
||||
if (currentCell !== '' || currentRow.length > 0) {
|
||||
currentRow.push(currentCell);
|
||||
if (currentRow.length > 1 || currentRow[0] !== '') {
|
||||
rows.push(currentRow);
|
||||
}
|
||||
}
|
||||
return rows;
|
||||
}
|
||||
|
||||
// Extrahiert Bildnamen aus Einträgen wie "['bild1.jpg', 'bild2.jpg']" oder "bild1.jpg"
|
||||
// 2. Baut das Array wieder sicher zu einer sauberen CSV-Zeile für das Backend zusammen
|
||||
function rowToCSV(rowArray) {
|
||||
return rowArray.map(cell => {
|
||||
if (cell === null || cell === undefined) return '';
|
||||
let cellStr = String(cell);
|
||||
if (cellStr.includes(',') || cellStr.includes('"') || cellStr.includes('\n') || cellStr.includes('\r')) {
|
||||
return '"' + cellStr.replace(/"/g, '""') + '"';
|
||||
}
|
||||
return cellStr;
|
||||
}).join(',');
|
||||
}
|
||||
|
||||
// 3. Bildnamen extrahieren
|
||||
function extractImageNames(cellValue) {
|
||||
if (!cellValue) return [];
|
||||
let raw = cellValue.replace(/^["']|["']$/g, '').trim();
|
||||
let raw = String(cellValue).replace(/^["']|["']$/g, '').trim();
|
||||
if (raw.startsWith('[') && raw.endsWith(']')) {
|
||||
try {
|
||||
const jsonValid = raw.replace(/'/g, '"');
|
||||
@@ -116,116 +148,107 @@ document.getElementById('batchUploadForm').addEventListener('submit', async func
|
||||
const csvFile = csvInput.files[0];
|
||||
const allImages = Array.from(imageInput.files);
|
||||
|
||||
// Map für schnellen Dateinamen-Vergleich (ohne Pfadangabe)
|
||||
const imageMap = new Map();
|
||||
allImages.forEach(file => {
|
||||
imageMap.set(file.name.toLowerCase(), file);
|
||||
});
|
||||
|
||||
const BATCH_SIZE = 50;
|
||||
const BATCH_SIZE = 20;
|
||||
|
||||
try {
|
||||
const csvText = await csvFile.text();
|
||||
let rows = csvText.split(/\r?\n/).filter(r => r.trim().length > 0);
|
||||
const allRows = parseCSV(csvText);
|
||||
|
||||
if (rows.length <= 1) {
|
||||
if (allRows.length <= 1) {
|
||||
throw new Error("CSV-Datei ist leer oder enthält nur Kopfzeilen.");
|
||||
}
|
||||
|
||||
const headerRow = rows[0];
|
||||
const dataRows = rows.slice(1);
|
||||
const headerRow = allRows[0];
|
||||
const dataRows = allRows.slice(1);
|
||||
|
||||
// 1. Client-Deduplizierung
|
||||
const uniqueRowsSet = new Set();
|
||||
const uniqueDataRows = [];
|
||||
let duplicateCount = 0;
|
||||
log(`${dataRows.length} Einträge gefunden. Bereite Batches vor...`);
|
||||
|
||||
for (const row of dataRows) {
|
||||
if (uniqueRowsSet.has(row)) {
|
||||
duplicateCount++;
|
||||
} else {
|
||||
uniqueRowsSet.add(row);
|
||||
uniqueDataRows.push(row);
|
||||
}
|
||||
}
|
||||
const imagesColIndex = headerRow.findIndex(h => h.toLowerCase().trim() === 'images');
|
||||
|
||||
log(`${uniqueDataRows.length} eindeutige Einträge. ${duplicateCount} Duplikate entfernt.`);
|
||||
|
||||
// Spalten-Index von "Images" ermitteln
|
||||
const headers = parseCSVLine(headerRow).map(h => h.replace(/['"]/g, '').trim());
|
||||
const imagesColIndex = headers.findIndex(h => h.toLowerCase() === 'images');
|
||||
|
||||
// 2. In Batches aufteilen
|
||||
const batches = [];
|
||||
for (let i = 0; i < uniqueDataRows.length; i += BATCH_SIZE) {
|
||||
batches.push(uniqueDataRows.slice(i, i + BATCH_SIZE));
|
||||
for (let i = 0; i < dataRows.length; i += BATCH_SIZE) {
|
||||
batches.push(dataRows.slice(i, i + BATCH_SIZE));
|
||||
}
|
||||
|
||||
progressBar.max = batches.length;
|
||||
progressBar.value = 0;
|
||||
|
||||
// 3. Sequenzieller Upload
|
||||
// Sequenzieller Upload mit Fehlertoleranz pro Batch
|
||||
for (let b = 0; b < batches.length; b++) {
|
||||
const batchRows = batches[b];
|
||||
progressText.textContent = `Lade Batch ${b + 1} von ${batches.length} hoch...`;
|
||||
|
||||
// Zuordnung der benötigten Bilder für diesen Batch
|
||||
const requiredImagesForBatch = new Set();
|
||||
try {
|
||||
const requiredImagesForBatch = new Set();
|
||||
|
||||
if (imagesColIndex !== -1) {
|
||||
batchRows.forEach(rowStr => {
|
||||
const cols = parseCSVLine(rowStr);
|
||||
if (cols[imagesColIndex]) {
|
||||
const imgNames = extractImageNames(cols[imagesColIndex]);
|
||||
imgNames.forEach(name => {
|
||||
const fileMatch = imageMap.get(name.toLowerCase());
|
||||
if (fileMatch) {
|
||||
requiredImagesForBatch.add(fileMatch);
|
||||
}
|
||||
});
|
||||
if (imagesColIndex !== -1) {
|
||||
batchRows.forEach(rowCols => {
|
||||
if (rowCols[imagesColIndex]) {
|
||||
const imgNames = extractImageNames(rowCols[imagesColIndex]);
|
||||
imgNames.forEach(name => {
|
||||
const fileMatch = imageMap.get(name.toLowerCase());
|
||||
if (fileMatch) {
|
||||
requiredImagesForBatch.add(fileMatch);
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
const batchCsvArray = [headerRow, ...batchRows];
|
||||
const batchCsvText = batchCsvArray.map(rowToCSV).join('\n');
|
||||
const batchCsvBlob = new Blob([batchCsvText], { type: 'text/csv' });
|
||||
|
||||
const formData = new FormData();
|
||||
formData.append('csv_file', batchCsvBlob, `batch_${b + 1}.csv`);
|
||||
|
||||
if (csrfToken) {
|
||||
formData.append('csrf_token', csrfToken);
|
||||
}
|
||||
|
||||
requiredImagesForBatch.forEach(imgFile => {
|
||||
formData.append('images', imgFile);
|
||||
});
|
||||
|
||||
log(`Batch ${b + 1}: ${batchRows.length} Items & ${requiredImagesForBatch.size} zugehörige Bilder.`);
|
||||
|
||||
const response = await fetch('/upload_csv_batch', {
|
||||
method: 'POST',
|
||||
body: formData,
|
||||
headers: {
|
||||
'X-CSRFToken': csrfToken || ''
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// CSV für diesen Batch erstellen
|
||||
const batchCsvText = [headerRow, ...batchRows].join('\n');
|
||||
const batchCsvBlob = new Blob([batchCsvText], { type: 'text/csv' });
|
||||
const responseText = await response.text();
|
||||
let result;
|
||||
|
||||
const formData = new FormData();
|
||||
formData.append('csv_file', batchCsvBlob, `batch_${b + 1}.csv`);
|
||||
|
||||
// CSRF-Token im Form-Field übergeben
|
||||
if (csrfToken) {
|
||||
formData.append('csrf_token', csrfToken);
|
||||
}
|
||||
|
||||
// Zugehörige Bilder anfügen
|
||||
requiredImagesForBatch.forEach(imgFile => {
|
||||
formData.append('images', imgFile);
|
||||
});
|
||||
|
||||
log(`Batch ${b + 1}: ${batchRows.length} Items & ${requiredImagesForBatch.size} zugehörige Bilder.`);
|
||||
|
||||
// Request mit CSRF-Header ausführen
|
||||
const response = await fetch('/upload_csv_batch', {
|
||||
method: 'POST',
|
||||
body: formData,
|
||||
headers: {
|
||||
'X-CSRFToken': csrfToken || ''
|
||||
try {
|
||||
result = JSON.parse(responseText);
|
||||
} catch (parseErr) {
|
||||
throw new Error(`Server-Fehler (Status ${response.status}). HTML statt JSON erhalten.`);
|
||||
}
|
||||
});
|
||||
|
||||
const result = await response.json();
|
||||
if (!response.ok || !result.success) {
|
||||
throw new Error(result.message || `Server-Fehler ${response.status}`);
|
||||
}
|
||||
|
||||
if (!response.ok || !result.success) {
|
||||
throw new Error(result.message || `Server-Fehler ${response.status}`);
|
||||
log(`Batch ${b + 1} erfolgreich abgeschlossen.`);
|
||||
|
||||
} catch (batchErr) {
|
||||
log(`⚠️ FEHLER in Batch ${b + 1}: ${batchErr.message}. Überspringe und fahre fort...`);
|
||||
console.error(`Batch ${b + 1} fehlgeschlagen:`, batchErr);
|
||||
}
|
||||
|
||||
log(`Batch ${b + 1} abgeschlossen: ${result.message}`);
|
||||
progressBar.value = b + 1;
|
||||
}
|
||||
|
||||
progressText.textContent = "Upload erfolgreich beendet!";
|
||||
progressText.textContent = "Upload-Prozess beendet!";
|
||||
uploadBtn.disabled = false;
|
||||
|
||||
} catch (err) {
|
||||
|
||||
Reference in New Issue
Block a user