Compare commits
16 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 152a3ab135 | |||
| c2c5054814 | |||
| e058bd5f46 | |||
| d58958db39 | |||
| 9452743660 | |||
| 6a3865ef24 | |||
| 96d45710ac | |||
| dd3d8649a7 | |||
| 1af2a2be06 | |||
| 8e5e434116 | |||
| 2f9a93ee65 | |||
| 91467a1e76 | |||
| 3840348a2d | |||
| cdb7319c56 | |||
| 08bea97f0f | |||
| 9164cd030d |
+135
-91
@@ -3313,7 +3313,7 @@ def api_library_items():
|
||||
ausleihungen_db = db['ausleihungen']
|
||||
|
||||
query = {
|
||||
'ItemType': {'$in': ['book', 'cd', 'dvd', 'schoolbook', 'schulbuch', 'Buch', 'Schulbuch']},
|
||||
'ItemType': {'$in': ['book', 'cd', 'CD', 'DVD', 'dvd', 'schoolbook', 'schulbuch', 'Buch', 'Schulbuch']},
|
||||
'IsGroupedSubItem': {'$ne': True},
|
||||
'Deleted': {'$ne': True}
|
||||
}
|
||||
@@ -6366,13 +6366,22 @@ def edit_item(id):
|
||||
|
||||
return redirect(url_for('home_admin'))
|
||||
|
||||
def is_library_item(item):
|
||||
"""
|
||||
Prüft, ob ein Artikel ein Bibliotheks-Item ist.
|
||||
- 'other', None oder Leerstring -> Inventarsystem (False)
|
||||
- Jeder andere Medientyp ('Buch', 'CD', etc.) -> Bibliothek (True)
|
||||
"""
|
||||
if not item:
|
||||
return False
|
||||
item_type = item.get('ItemType', 'other')
|
||||
if not item_type:
|
||||
return False
|
||||
return item_type.strip().lower() != 'other'
|
||||
|
||||
|
||||
@app.route('/item_edit/<id>', methods=['GET', 'POST'])
|
||||
def item_edit(id):
|
||||
"""
|
||||
Endpoint zum Laden und Aktualisieren eines Eintrags (item_edit).
|
||||
"""
|
||||
# 1. Rechte- & Auth-Check
|
||||
if 'username' not in session:
|
||||
if request.method == 'POST' and request.is_json:
|
||||
return jsonify({'success': False, 'message': 'Nicht angemeldet.'}), 401
|
||||
@@ -6392,127 +6401,161 @@ def item_edit(id):
|
||||
flash('Ungültige Element-ID.', 'error')
|
||||
return redirect(url_for('home_admin'))
|
||||
|
||||
current_item = it.get_item(obj_id)
|
||||
if not current_item:
|
||||
flash('Element in der Datenbank nicht gefunden.', 'error')
|
||||
return redirect(url_for('home_admin'))
|
||||
|
||||
# --- GET: Template anzeigen ---
|
||||
# Bibliothek-Status ermitteln
|
||||
library_module_active = cfg.MODULES.is_enabled('library')
|
||||
is_lib_item = it.is_library_item(current_item)
|
||||
show_library_features = library_module_active and is_lib_item
|
||||
|
||||
# -------------------------------------------------------------------
|
||||
# GET METHOD
|
||||
# -------------------------------------------------------------------
|
||||
if request.method == 'GET':
|
||||
item = it.get_item(id)
|
||||
if not item:
|
||||
flash('Element nicht gefunden.', 'error')
|
||||
return redirect(url_for('home_admin'))
|
||||
current_item['_id'] = str(current_item['_id'])
|
||||
|
||||
item['_id'] = str(item['_id'])
|
||||
show_library = cfg.MODULES.is_enabled('library')
|
||||
base_code = current_item.get('Code_4', '')
|
||||
individual_codes = []
|
||||
if current_item.get('SeriesGroupId'):
|
||||
group_ids = it.get_group_item_ids(str(current_item['_id']))
|
||||
if group_ids:
|
||||
for gid in group_ids:
|
||||
g_item = it.get_item(gid)
|
||||
c4 = g_item.get('Code_4')
|
||||
if c4 and c4 != base_code:
|
||||
individual_codes.append(c4)
|
||||
|
||||
current_item['IndividualCodes'] = '\n'.join(individual_codes)
|
||||
|
||||
return render_template(
|
||||
'edit_library.html',
|
||||
username=session['username'],
|
||||
item=item,
|
||||
library_module_enabled=show_library,
|
||||
show_library_features=show_library,
|
||||
page_title=f"Bearbeiten: {item.get('Name', '')}"
|
||||
item=current_item,
|
||||
show_library_features=show_library_features,
|
||||
library_module_enabled=library_module_active,
|
||||
page_title=f"Bearbeiten: {current_item.get('Name', '')}"
|
||||
)
|
||||
|
||||
# --- POST: Speichern ---
|
||||
# -------------------------------------------------------------------
|
||||
# POST METHOD
|
||||
# -------------------------------------------------------------------
|
||||
redirect_target = request.referrer or url_for('home_admin')
|
||||
current_item = it.get_item(obj_id)
|
||||
|
||||
if not current_item:
|
||||
flash('Element in der Datenbank nicht gefunden.', 'error')
|
||||
return redirect(redirect_target)
|
||||
|
||||
# Formulardaten auslesen und bereinigen
|
||||
name = sanitize_form_value(request.form.get('name'))
|
||||
ort = sanitize_form_value(request.form.get('ort'))
|
||||
beschreibung = sanitize_form_value(request.form.get('beschreibung'))
|
||||
code_4 = sanitize_form_value(request.form.get('code_4'))
|
||||
isbn_raw = sanitize_form_value(request.form.get('isbn', ''))
|
||||
|
||||
anschaffungs_jahr = sanitize_form_value(request.form.get('anschaffungsjahr'))
|
||||
anschaffungs_kosten = sanitize_form_value(request.form.get('anschaffungskosten'))
|
||||
reservierbar = 'reservierbar' in request.form
|
||||
|
||||
item_type_input = sanitize_form_value(request.form.get('item_type_input'))
|
||||
library_category = sanitize_form_value(request.form.get('library_category'))
|
||||
code_4 = sanitize_form_value(request.form.get('code_4'))
|
||||
individual_codes_raw = request.form.get('individual_codes', '')
|
||||
|
||||
filter1 = expand_filter_selection(sanitize_form_value(request.form.getlist('filter')), 1)
|
||||
filter2 = expand_filter_selection(sanitize_form_value(request.form.getlist('filter2')), 2)
|
||||
filter3 = sanitize_form_value(request.form.getlist('filter3'))
|
||||
individual_codes = []
|
||||
for c in individual_codes_raw.replace('\r', '').split('\n'):
|
||||
clean_c = sanitize_form_value(c)
|
||||
if clean_c and clean_c != code_4 and clean_c not in individual_codes:
|
||||
individual_codes.append(clean_c)
|
||||
|
||||
# WICHTIG: Den aktuellen Verfügbarkeitsstatus aus der Datenbank übernehmen
|
||||
verfuegbar = current_item.get('Verfuegbar', True)
|
||||
all_codes_to_check = [code_4] + individual_codes
|
||||
|
||||
# Barcode Prüfen
|
||||
if code_4 and not it.is_code_unique(code_4, exclude_id=str(id)):
|
||||
flash(f'Der Code "{code_4}" wird bereits verwendet.', 'error')
|
||||
current_group_id = current_item.get('SeriesGroupId')
|
||||
client = MongoClient(cfg.MONGODB_HOST, cfg.MONGODB_PORT)
|
||||
db_instance = client[cfg.MONGODB_DB]
|
||||
items_col = db_instance['items']
|
||||
|
||||
has_code_error = False
|
||||
for code in all_codes_to_check:
|
||||
if not code:
|
||||
continue
|
||||
existing = items_col.find_one({'Code_4': code, 'Deleted': {'$ne': True}})
|
||||
if existing:
|
||||
is_same_item = str(existing['_id']) == str(id)
|
||||
is_in_same_group = current_group_id and existing.get('SeriesGroupId') == current_group_id
|
||||
if not is_same_item and not is_in_same_group:
|
||||
flash(f'Der Code "{code}" wird bereits von einem anderen Artikel verwendet.', 'error')
|
||||
has_code_error = True
|
||||
break
|
||||
client.close()
|
||||
|
||||
if has_code_error:
|
||||
return redirect(redirect_target)
|
||||
|
||||
# ISBN und Medientyp verarbeiten
|
||||
item_isbn = ''
|
||||
item_type = item_type_input or current_item.get('ItemType', 'general')
|
||||
if cfg.MODULES.is_enabled('library') and isbn_raw:
|
||||
item_isbn = normalize_and_validate_isbn(isbn_raw)
|
||||
if not item_isbn:
|
||||
flash('Ungültiges ISBN-Format.', 'error')
|
||||
return redirect(redirect_target)
|
||||
if show_library_features:
|
||||
# LIBRARY ITEM: Process ISBN/Medientyp/Category, preserve existing filters
|
||||
isbn_raw = sanitize_form_value(request.form.get('isbn', ''))
|
||||
item_isbn = normalize_and_validate_isbn(isbn_raw) if isbn_raw else ''
|
||||
item_type = sanitize_form_value(request.form.get('item_type_input', current_item.get('ItemType', 'Buch')))
|
||||
library_category = sanitize_form_value(request.form.get('library_category', ''))
|
||||
images = current_item.get('Images', [])
|
||||
|
||||
# Bilder verarbeiten (GridFS)
|
||||
images_to_keep = request.form.getlist('existing_images')
|
||||
original_images = current_item.get('Images', [])
|
||||
images = [img for img in original_images if img in images_to_keep]
|
||||
filter1 = current_item.get('Filter', [])
|
||||
filter2 = current_item.get('Filter2', [])
|
||||
filter3 = current_item.get('Filter3', [])
|
||||
else:
|
||||
# NON-LIBRARY (INVENTORY) ITEM: Process Filter 1-3 from form
|
||||
item_isbn = current_item.get('ISBN', '')
|
||||
item_type = 'other'
|
||||
library_category = current_item.get('library_category', '')
|
||||
|
||||
new_files = request.files.getlist('images')
|
||||
if new_files and new_files[0].filename != '':
|
||||
fs = get_gridfs()
|
||||
for file in new_files:
|
||||
if file and file.filename:
|
||||
is_allowed, error_msg = allowed_file(file.filename, file)
|
||||
if not is_allowed:
|
||||
flash(error_msg, 'error')
|
||||
return redirect(redirect_target)
|
||||
filter1 = expand_filter_selection(sanitize_form_value(request.form.getlist('filter')), 1)
|
||||
filter2 = expand_filter_selection(sanitize_form_value(request.form.getlist('filter2')), 2)
|
||||
filter3 = sanitize_form_value(request.form.getlist('filter3'))
|
||||
|
||||
try:
|
||||
secure_name = secure_filename(file.filename)
|
||||
file.seek(0)
|
||||
image_bytes = file.read()
|
||||
|
||||
if not image_bytes:
|
||||
continue
|
||||
|
||||
optimized_io = io.BytesIO()
|
||||
with Image.open(io.BytesIO(image_bytes)) as img:
|
||||
if img.mode not in ('RGB', 'RGBA'):
|
||||
img = img.convert('RGBA')
|
||||
|
||||
max_width = 800
|
||||
if img.width > max_width:
|
||||
ratio = max_width / img.width
|
||||
img = img.resize((max_width, int(img.height * ratio)), Image.Resampling.LANCZOS)
|
||||
|
||||
img.save(optimized_io, format='WEBP', quality=85, optimize=True)
|
||||
|
||||
optimized_io.seek(0)
|
||||
new_filename = f"{uuid.uuid4().hex}_{int(time.time())}.webp"
|
||||
|
||||
fs.put(
|
||||
optimized_io,
|
||||
filename=new_filename,
|
||||
content_type='image/webp',
|
||||
metadata={'original_filename': secure_name, 'item_id': str(id)}
|
||||
)
|
||||
images.append(new_filename)
|
||||
except Exception as e:
|
||||
app.logger.error(f"Bild-Fehler bei Item {id}: {e}")
|
||||
images_to_keep = request.form.getlist('existing_images')
|
||||
original_images = current_item.get('Images', [])
|
||||
images = [img for img in original_images if img in images_to_keep]
|
||||
|
||||
new_files = request.files.getlist('images')
|
||||
if new_files and new_files[0].filename != '':
|
||||
fs = get_gridfs()
|
||||
for file in new_files:
|
||||
if file and file.filename:
|
||||
is_allowed, error_msg = allowed_file(file.filename, file)
|
||||
if not is_allowed:
|
||||
flash(error_msg, 'error')
|
||||
return redirect(redirect_target)
|
||||
try:
|
||||
secure_name = secure_filename(file.filename)
|
||||
file.seek(0)
|
||||
image_bytes = file.read()
|
||||
if not image_bytes:
|
||||
continue
|
||||
optimized_io = io.BytesIO()
|
||||
with Image.open(io.BytesIO(image_bytes)) as img:
|
||||
if img.mode not in ('RGB', 'RGBA'):
|
||||
img = img.convert('RGBA')
|
||||
max_width = 800
|
||||
if img.width > max_width:
|
||||
ratio = max_width / img.width
|
||||
img = img.resize((max_width, int(img.height * ratio)), Image.Resampling.LANCZOS)
|
||||
img.save(optimized_io, format='WEBP', quality=85, optimize=True)
|
||||
optimized_io.seek(0)
|
||||
new_filename = f"{uuid.uuid4().hex}_{int(time.time())}.webp"
|
||||
fs.put(
|
||||
optimized_io,
|
||||
filename=new_filename,
|
||||
content_type='image/webp',
|
||||
metadata={'original_filename': secure_name, 'item_id': str(id)}
|
||||
)
|
||||
images.append(new_filename)
|
||||
except Exception as e:
|
||||
app.logger.error(f"Image error for item {id}: {e}")
|
||||
if ort and ort not in it.get_predefined_locations():
|
||||
it.add_predefined_location(ort)
|
||||
|
||||
it.sync_group_codes(str(id), code_4, individual_codes)
|
||||
|
||||
success = it.update_item(
|
||||
id=str(id),
|
||||
name=name,
|
||||
ort=ort,
|
||||
beschreibung=beschreibung,
|
||||
images=images,
|
||||
verfuegbar=verfuegbar,
|
||||
verfuegbar=current_item.get('Verfuegbar', True),
|
||||
filter1=filter1,
|
||||
filter2=filter2,
|
||||
filter3=filter3,
|
||||
@@ -6521,7 +6564,8 @@ def item_edit(id):
|
||||
code_4=code_4,
|
||||
reservierbar=reservierbar,
|
||||
isbn=item_isbn,
|
||||
item_type=item_type
|
||||
item_type=item_type,
|
||||
library_category=library_category
|
||||
)
|
||||
|
||||
if success:
|
||||
|
||||
+155
-10
@@ -20,12 +20,30 @@ Collection Structure:
|
||||
"""
|
||||
from bson.objectid import ObjectId
|
||||
from bson.errors import InvalidId
|
||||
import uuid
|
||||
import datetime
|
||||
import Web.modules.database.settings as cfg
|
||||
from Web.modules.database.settings import MongoClient
|
||||
import Web.modules.inventarsystem.data_protection as dp
|
||||
|
||||
|
||||
def is_library_item(item):
|
||||
"""
|
||||
Ermittelt zuverlässig, ob ein Objekt zur Bibliothek gehört.
|
||||
Gibt True zurück, wenn ItemType ein Medientyp ist (Buch, Schulbuch, CD, DVD etc.)
|
||||
ODER wenn is_library explizit True ist.
|
||||
"""
|
||||
if not item:
|
||||
return False
|
||||
|
||||
# 1. Prüfe zuerst den Medientyp (ItemType)
|
||||
item_type = str(item.get('ItemType', '') or '').strip().lower()
|
||||
if item_type and item_type not in ['other', 'general', 'none', 'null']:
|
||||
return True
|
||||
|
||||
# 2. Falls ItemType 'other' ist, prüfe das is_library Flag
|
||||
return bool(item.get('is_library', False))
|
||||
|
||||
def safe_decrypt_user(encrypted_user):
|
||||
"""
|
||||
Safely decrypt an encrypted username string.
|
||||
@@ -250,7 +268,10 @@ def get_group_item_ids(id):
|
||||
|
||||
|
||||
def update_item(id, name, ort, beschreibung, images, verfuegbar, filter1, filter2, filter3,
|
||||
ansch_jahr, ansch_kost, code_4, reservierbar, isbn=None, item_type='general'):
|
||||
ansch_jahr, ansch_kost, code_4, reservierbar, isbn="", item_type='other', library_category=""):
|
||||
"""
|
||||
Aktualisiert ein Objekt in MongoDB und setzt is_library korrekt basierend auf dem Medientyp.
|
||||
"""
|
||||
try:
|
||||
client = MongoClient(cfg.MONGODB_HOST, cfg.MONGODB_PORT)
|
||||
db = client[cfg.MONGODB_DB]
|
||||
@@ -258,29 +279,35 @@ def update_item(id, name, ort, beschreibung, images, verfuegbar, filter1, filter
|
||||
|
||||
old_item = items.find_one({'_id': ObjectId(id)})
|
||||
if not old_item:
|
||||
client.close()
|
||||
return False
|
||||
|
||||
series_group_id = old_item.get('SeriesGroupId')
|
||||
|
||||
# is_library automatisch anhand des neuen item_type bestimmen
|
||||
is_lib = is_library_item({'ItemType': item_type})
|
||||
|
||||
shared_update = {
|
||||
'Name': name,
|
||||
'Ort': ort,
|
||||
'Beschreibung': beschreibung,
|
||||
'Images': images,
|
||||
'Filter': filter1,
|
||||
'Filter2': filter2,
|
||||
'Filter3': filter3,
|
||||
'Images': images if isinstance(images, list) else [],
|
||||
'Filter': filter1 if isinstance(filter1, list) else [],
|
||||
'Filter2': filter2 if isinstance(filter2, list) else [],
|
||||
'Filter3': filter3 if isinstance(filter3, list) else [],
|
||||
'Anschaffungsjahr': ansch_jahr,
|
||||
'Anschaffungskosten': ansch_kost,
|
||||
'Reservierbar': reservierbar,
|
||||
'ISBN': isbn,
|
||||
'Reservierbar': bool(reservierbar),
|
||||
'ISBN': str(isbn) if isbn else '',
|
||||
'ItemType': item_type,
|
||||
'Verfuegbar': verfuegbar,
|
||||
'is_library': is_lib,
|
||||
'library_category': library_category,
|
||||
'Verfuegbar': bool(verfuegbar),
|
||||
'LastUpdated': datetime.datetime.now()
|
||||
}
|
||||
|
||||
specific_update = shared_update.copy()
|
||||
specific_update['Code_4'] = code_4
|
||||
specific_update['Code_4'] = str(code_4) if code_4 else ''
|
||||
|
||||
items.update_one({'_id': ObjectId(id)}, {'$set': specific_update})
|
||||
|
||||
@@ -1147,4 +1174,122 @@ def get_current_status(item_id, decrypt=True):
|
||||
return None
|
||||
except Exception as e:
|
||||
print(f"Error retrieving current status for item {item_id}: {e}")
|
||||
return None
|
||||
return None
|
||||
|
||||
def sync_group_codes(primary_obj_id, base_code, individual_codes_list):
|
||||
"""
|
||||
Synchronisiert die Barcodes einer Gruppe im korrekten Schema
|
||||
(angelehnt an das 'Augenmodell groß'-Vorbild).
|
||||
"""
|
||||
if not base_code:
|
||||
return False
|
||||
|
||||
# Alle Ziel-Codes zusammenführen (Basis-Code an erster Stelle)
|
||||
all_target_codes = [base_code]
|
||||
for c in individual_codes_list:
|
||||
if c and c not in all_target_codes:
|
||||
all_target_codes.append(c)
|
||||
|
||||
item_count = len(all_target_codes)
|
||||
|
||||
try:
|
||||
client = MongoClient(cfg.MONGODB_HOST, cfg.MONGODB_PORT)
|
||||
db = client[cfg.MONGODB_DB]
|
||||
items = db['items']
|
||||
|
||||
primary_item = items.find_one({'_id': ObjectId(primary_obj_id)})
|
||||
if not primary_item:
|
||||
client.close()
|
||||
return False
|
||||
|
||||
group_id = primary_item.get('SeriesGroupId')
|
||||
|
||||
# Wenn es mehr als 1 Item gibt und noch keine Gruppe existiert -> Neue GroupID erzeugen
|
||||
if not group_id and item_count > 1:
|
||||
group_id = str(uuid.uuid4())
|
||||
|
||||
# Wenn es nun eine Gruppe gibt (item_count > 1)
|
||||
if item_count > 1:
|
||||
# 1. Haupt-Item (Parent) aktualisieren
|
||||
items.update_one(
|
||||
{'_id': primary_item['_id']},
|
||||
{'$set': {
|
||||
'Code_4': base_code,
|
||||
'SeriesGroupId': group_id,
|
||||
'SeriesCount': item_count,
|
||||
'SeriesPosition': 1,
|
||||
'IsGroupedSubItem': False,
|
||||
'ParentItemId': None
|
||||
}}
|
||||
)
|
||||
|
||||
# Bestehende Gruppenmitglieder laden
|
||||
existing_items = list(items.find({'SeriesGroupId': group_id}))
|
||||
existing_map = {it.get('Code_4'): it for it in existing_items if
|
||||
it.get('Code_4') and str(it['_id']) != str(primary_item['_id'])}
|
||||
|
||||
# Alle verbleibenden Sub-Codes ab Position 2 abarbeiten
|
||||
processed_sub_ids = []
|
||||
for idx, code in enumerate(all_target_codes[1:], start=2):
|
||||
if code in existing_map:
|
||||
# Existiert bereits in der Gruppe -> Nur Position und Count aktualisieren
|
||||
sub_item = existing_map[code]
|
||||
processed_sub_ids.append(sub_item['_id'])
|
||||
items.update_one(
|
||||
{'_id': sub_item['_id']},
|
||||
{'$set': {
|
||||
'SeriesCount': item_count,
|
||||
'SeriesPosition': idx,
|
||||
'IsGroupedSubItem': True,
|
||||
'ParentItemId': str(primary_item['_id'])
|
||||
}}
|
||||
)
|
||||
else:
|
||||
# Neu hinzukommender Code -> Als Klon (Sub-Item) erstellen
|
||||
new_sub = primary_item.copy()
|
||||
if '_id' in new_sub:
|
||||
del new_sub['_id']
|
||||
|
||||
new_sub.update({
|
||||
'Code_4': code,
|
||||
'SeriesGroupId': group_id,
|
||||
'SeriesCount': item_count,
|
||||
'SeriesPosition': idx,
|
||||
'IsGroupedSubItem': True,
|
||||
'ParentItemId': str(primary_item['_id']),
|
||||
'LastUpdated': primary_item.get('LastUpdated')
|
||||
})
|
||||
inserted_res = items.insert_one(new_sub)
|
||||
processed_sub_ids.append(inserted_res.inserted_id)
|
||||
|
||||
# Nicht mehr benötigte Sub-Items aus dieser Gruppe entfernen
|
||||
for code, sub_item in existing_map.items():
|
||||
if sub_item['_id'] not in processed_sub_ids:
|
||||
items.delete_one({'_id': sub_item['_id']})
|
||||
|
||||
else:
|
||||
# Fall: Nur 1 einziges Item (keine Gruppe / Gruppe aufgelöst)
|
||||
# Eventuelle alte Sub-Items dieser Gruppe löschen
|
||||
if group_id:
|
||||
items.delete_many({
|
||||
'SeriesGroupId': group_id,
|
||||
'_id': {'$ne': primary_item['_id']}
|
||||
})
|
||||
|
||||
items.update_one(
|
||||
{'_id': primary_item['_id']},
|
||||
{'$set': {
|
||||
'Code_4': base_code,
|
||||
'SeriesGroupId': None,
|
||||
'SeriesCount': 1,
|
||||
'SeriesPosition': 1,
|
||||
'IsGroupedSubItem': False,
|
||||
'ParentItemId': None
|
||||
}}
|
||||
)
|
||||
|
||||
client.close()
|
||||
return True
|
||||
except Exception as e:
|
||||
print(f"Error syncing group codes: {e}")
|
||||
return False
|
||||
File diff suppressed because it is too large
Load Diff
+260
-757
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user