Compare commits
28 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| bd7ef61f5a | |||
| df0f7d3066 | |||
| 2215fc76d8 | |||
| e177936359 | |||
| ae4a7226fa | |||
| 16a10a8c09 | |||
| 3d4048d23b | |||
| 6985f32fe9 | |||
| ab7a369b6e | |||
| 27be38dfc9 | |||
| 140fb5f743 | |||
| 9ea0ae6157 | |||
| bb89b434ed | |||
| ac4d125d73 | |||
| 3f6830e8c8 | |||
| 0ea5d2db26 | |||
| 41d9c0a848 | |||
| f6e3db9b4a | |||
| 7e5ee7b5ea | |||
| 2528e79895 | |||
| 542caa520f | |||
| 5136e40587 | |||
| c62b2b553d | |||
| 8783f97a09 | |||
| 43e09b41f1 | |||
| 84257dc289 | |||
| c4b3850369 | |||
| 28e9487fe1 |
+307
-212
@@ -16,6 +16,7 @@ Features:
|
||||
- History logging of item usage
|
||||
- Booking and reservation of items
|
||||
"""
|
||||
from random import random
|
||||
|
||||
from flask import Flask, render_template, request, redirect, url_for, session, flash, send_from_directory, get_flashed_messages, jsonify, Response, make_response, send_file, abort
|
||||
from werkzeug.utils import secure_filename
|
||||
@@ -67,13 +68,11 @@ import logging
|
||||
from logging.handlers import RotatingFileHandler
|
||||
import secrets
|
||||
import importlib
|
||||
import atexit
|
||||
try:
|
||||
redis = importlib.import_module('redis')
|
||||
except Exception:
|
||||
redis = None
|
||||
# QR Code functionality deactivated
|
||||
# import qrcode
|
||||
# from qrcode.constants import ERROR_CORRECT_L
|
||||
import threading
|
||||
import shutil
|
||||
import uuid
|
||||
@@ -125,10 +124,6 @@ app.register_blueprint(terminplaner_bp, url_prefix='/terminplaner')
|
||||
|
||||
if not os.path.exists(app.config['UPLOAD_FOLDER']):
|
||||
os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)
|
||||
# QR Code directory creation deactivated
|
||||
# if not os.path.exists(app.config['QR_CODE_FOLDER']):
|
||||
# os.makedirs(app.config['QR_CODE_FOLDER'])
|
||||
|
||||
BACKUP_FOLDER = cfg.BACKUP_FOLDER
|
||||
if not os.path.exists(BACKUP_FOLDER):
|
||||
try:
|
||||
@@ -158,7 +153,7 @@ def print(*args, **kwargs):
|
||||
app.logger.info(message)
|
||||
|
||||
|
||||
STUDENT_CARD_ENCRYPTED_FIELDS = ('SchülerName', 'Klasse', 'Notizen')
|
||||
STUDENT_CARD_ENCRYPTED_FIELDS = ('ausweis_ident', 'SchülerName', 'Klasse', 'Notizen')
|
||||
|
||||
|
||||
def _decrypt_student_card_doc(card_doc):
|
||||
@@ -1459,7 +1454,7 @@ def update_appointment_statuses():
|
||||
- Geplante Termine, die aktiviert werden sollten
|
||||
- Aktive Termine, die beendet werden sollten
|
||||
"""
|
||||
current_time = datetime.datetime.now()
|
||||
current_time = datetime.datetime.now(datetime.timezone.utc)
|
||||
|
||||
try:
|
||||
# Hole alle Termine mit Status 'planned' oder 'active'
|
||||
@@ -1485,7 +1480,7 @@ def update_appointment_statuses():
|
||||
new_status = au.get_current_status(appointment, log_changes=True, user='scheduler')
|
||||
|
||||
# Wenn sich der Status geändert hat, aktualisiere in der Datenbank
|
||||
if new_status != old_status:
|
||||
if new_status != old_status and not it.is_library_item(appointment.get('Item')):
|
||||
extra_fields = {}
|
||||
|
||||
# --- Conflict resolver: planned → active transition ---
|
||||
@@ -1591,6 +1586,9 @@ def update_appointment_statuses():
|
||||
app.logger.warning(
|
||||
f"Failed to create activation notification for {appointment.get('_id')}: {notif_err}"
|
||||
)
|
||||
elif it.is_library_item(appointment.get('Item')):
|
||||
# Introduction of an messaging system and a Mahnstufen implementation for the library Book bookings after the designatet time.
|
||||
pass
|
||||
|
||||
client.close()
|
||||
|
||||
@@ -1602,78 +1600,116 @@ def update_appointment_statuses():
|
||||
except Exception as e:
|
||||
app.logger.error(f"Automatic appointment status update failed: {e}")
|
||||
|
||||
# Schedule jobs - only start scheduler if this is the main process or a single-worker deployment
|
||||
# This prevents race conditions in multi-worker Gunicorn environments
|
||||
|
||||
# Initialize scheduler instances
|
||||
scheduler = BackgroundScheduler()
|
||||
_scheduler_initialized = False
|
||||
_scheduler_worker_id = None # Tracks the unique ID of the worker holding the lock
|
||||
|
||||
|
||||
def _initialize_scheduler():
|
||||
"""Initialize the background scheduler in a safe way for multi-worker deployments."""
|
||||
global _scheduler_initialized
|
||||
if _scheduler_initialized or not cfg.SCHEDULER_ENABLED:
|
||||
"""Initialize the background scheduler safely using an atomic MongoDB lock."""
|
||||
global _scheduler_initialized, _scheduler_worker_id
|
||||
if _scheduler_initialized or not getattr(cfg, 'SCHEDULER_ENABLED', False):
|
||||
return
|
||||
|
||||
|
||||
try:
|
||||
# For multi-worker Gunicorn, use a lock file to ensure only one instance starts the scheduler
|
||||
# Clean up any stale lock file from previous runs (older than 5 minutes)
|
||||
scheduler_lock_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), '.scheduler_lock')
|
||||
try:
|
||||
if os.path.exists(scheduler_lock_path):
|
||||
lock_age = time.time() - os.path.getmtime(scheduler_lock_path)
|
||||
if lock_age > 300: # 5 minutes - indicates a stale lock from a previous container run
|
||||
os.remove(scheduler_lock_path)
|
||||
app.logger.info(f"Removed stale scheduler lock file (age: {lock_age:.0f}s)")
|
||||
except Exception as e:
|
||||
app.logger.warning(f"Could not clean up scheduler lock file: {e}")
|
||||
client = MongoClient(MONGODB_HOST, MONGODB_PORT)
|
||||
db = client[MONGODB_DB]
|
||||
locks_col = db['system_locks']
|
||||
|
||||
# Always try to remove lock file on startup (extra safety)
|
||||
try:
|
||||
if os.path.exists(scheduler_lock_path):
|
||||
os.remove(scheduler_lock_path)
|
||||
app.logger.info("Scheduler lock file removed on startup.")
|
||||
except Exception as e:
|
||||
app.logger.warning(f"Could not remove scheduler lock file on startup: {e}")
|
||||
# 1. Generate a unique ID for this specific worker process
|
||||
_scheduler_worker_id = str(uuid.uuid4())
|
||||
now = datetime.datetime.now(datetime.timezone.utc)
|
||||
|
||||
# 2. Ensure the lock document exists (initialize if missing)
|
||||
try:
|
||||
# Try to create the lock file - only succeeds if it doesn't exist
|
||||
lock_fd = os.open(scheduler_lock_path, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o644)
|
||||
os.close(lock_fd)
|
||||
should_start = True
|
||||
except FileExistsError:
|
||||
should_start = False
|
||||
app.logger.warning("Scheduler lock exists - another process is already running the scheduler")
|
||||
locks_col.insert_one({
|
||||
'_id': 'scheduler_lock',
|
||||
'locked_at': datetime.datetime.min.replace(tzinfo=datetime.timezone.utc),
|
||||
'worker_id': None
|
||||
})
|
||||
except DuplicateKeyError:
|
||||
pass # Document already exists, which is expected
|
||||
|
||||
if should_start:
|
||||
# 3. Try to acquire the lock atomically
|
||||
# We only acquire if the current lock is older than 5 minutes (stale/crashed worker)
|
||||
# or if it was explicitly released (1970 init date)
|
||||
lock_timeout = now - datetime.timedelta(minutes=5)
|
||||
|
||||
acquired = locks_col.find_one_and_update(
|
||||
{
|
||||
'_id': 'scheduler_lock',
|
||||
'locked_at': {'$lt': lock_timeout}
|
||||
},
|
||||
{
|
||||
'$set': {
|
||||
'locked_at': now,
|
||||
'worker_id': _scheduler_worker_id
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
if acquired is not None:
|
||||
# 4. Lock acquired successfully - this is the master worker
|
||||
scheduler.add_job(func=create_daily_backup, trigger="interval", hours=cfg.BACKUP_INTERVAL_HOURS)
|
||||
scheduler.add_job(func=update_appointment_statuses, trigger="interval", minutes=cfg.SCHEDULER_INTERVAL_MIN)
|
||||
scheduler.add_job(func=create_return_reminders, trigger="interval", minutes=cfg.SCHEDULER_INTERVAL_MIN)
|
||||
scheduler.add_job(func=cleanup_expired_trial_tenants, trigger="interval", hours=1)
|
||||
|
||||
# 5. Add a heartbeat job to keep the lock alive
|
||||
def renew_lock_heartbeat():
|
||||
try:
|
||||
hb_client = MongoClient(MONGODB_HOST, MONGODB_PORT)
|
||||
hb_db = hb_client[MONGODB_DB]
|
||||
hb_db['system_locks'].update_one(
|
||||
{'_id': 'scheduler_lock', 'worker_id': _scheduler_worker_id},
|
||||
{'$set': {'locked_at': datetime.datetime.now(datetime.timezone.utc)}}
|
||||
)
|
||||
hb_client.close()
|
||||
except Exception as e:
|
||||
app.logger.error(f"Scheduler heartbeat failed: {e}")
|
||||
|
||||
# Run heartbeat every 2 minutes (safely below the 5-minute timeout)
|
||||
scheduler.add_job(func=renew_lock_heartbeat, trigger="interval", minutes=2)
|
||||
|
||||
scheduler.start()
|
||||
_scheduler_initialized = True
|
||||
app.logger.info(f"Scheduler started successfully (interval={cfg.SCHEDULER_INTERVAL_MIN} min)")
|
||||
app.logger.info(f"Scheduler started successfully (Worker ID: {_scheduler_worker_id})")
|
||||
else:
|
||||
app.logger.info("Scheduler skipped - another worker instance is running it")
|
||||
app.logger.info("Scheduler skipped - another active worker holds the MongoDB lock")
|
||||
|
||||
client.close()
|
||||
|
||||
except Exception as e:
|
||||
app.logger.error(f"Failed to initialize scheduler: {e}")
|
||||
app.logger.error(f"Failed to initialize scheduler with MongoDB lock: {e}")
|
||||
_scheduler_initialized = False
|
||||
|
||||
|
||||
# Initialize scheduler on app startup
|
||||
_initialize_scheduler()
|
||||
|
||||
# Register shutdown handler to stop scheduler when app is terminated
|
||||
import atexit
|
||||
|
||||
def _shutdown_scheduler():
|
||||
if cfg.SCHEDULER_ENABLED and _scheduler_initialized:
|
||||
"""Gracefully shut down the scheduler and release the MongoDB lock."""
|
||||
global _scheduler_initialized, _scheduler_worker_id
|
||||
if getattr(cfg, 'SCHEDULER_ENABLED', False) and _scheduler_initialized:
|
||||
try:
|
||||
scheduler.shutdown()
|
||||
lock_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), '.scheduler_lock')
|
||||
try:
|
||||
os.remove(lock_path)
|
||||
except Exception:
|
||||
pass
|
||||
scheduler.shutdown(wait=False)
|
||||
|
||||
# Release the lock so a newly spawned worker can immediately take over
|
||||
client = MongoClient(MONGODB_HOST, MONGODB_PORT)
|
||||
db = client[MONGODB_DB]
|
||||
db['system_locks'].update_one(
|
||||
{'_id': 'scheduler_lock', 'worker_id': _scheduler_worker_id},
|
||||
{'$set': {'locked_at': datetime.datetime.min.replace(tzinfo=datetime.timezone.utc)}}
|
||||
)
|
||||
client.close()
|
||||
app.logger.info(f"Scheduler shut down and lock released (Worker ID: {_scheduler_worker_id})")
|
||||
except Exception as e:
|
||||
app.logger.error(f"Error during scheduler shutdown: {e}")
|
||||
|
||||
|
||||
atexit.register(_shutdown_scheduler)
|
||||
|
||||
"""-------------------------------------------------------------File Upload Validation----------------------------------------------------------------------------- """
|
||||
@@ -2101,16 +2137,28 @@ def _build_student_card_excel_id(student_name, class_name, row_number, used_ids)
|
||||
return candidate
|
||||
|
||||
|
||||
def generate_ausweis_id_excel(existing_ids_set):
|
||||
"""Generates a unique ID and checks against DB and current import queue."""
|
||||
while True:
|
||||
random_digits = "".join(random.choices(string.digits, k=6))
|
||||
new_id = f"ID_{random_digits}"
|
||||
|
||||
# Prüfe sowohl in den bereits in dieser Session generierten IDs als auch in der DB
|
||||
if new_id.upper() not in existing_ids_set and not us.get_user_by_student_card(new_id):
|
||||
print(f"Generated unique ID: {new_id}")
|
||||
return new_id
|
||||
else:
|
||||
print(f"Already found: {new_id}, trying another...")
|
||||
|
||||
def _upload_student_cards_excel():
|
||||
"""Bulk import student cards from Excel with automatic name/class mapping."""
|
||||
"""Bulk import student cards with optional school year rollover (Abgleich)."""
|
||||
if 'username' not in session:
|
||||
flash('Nicht angemeldet.', 'error')
|
||||
return redirect(url_for('login'))
|
||||
|
||||
current_permissions = us.get_effective_permissions(session['username'])
|
||||
|
||||
if not current_permissions['actions'].get('can_manage_user', False):
|
||||
flash('Ihnen fehlen die nötigen Berechtigungen, um diese Aktion auszuführen.', 'error')
|
||||
flash('Ihnen fehlen die nötigen Berechtigungen.', 'error')
|
||||
return redirect(url_for('library_view'))
|
||||
|
||||
if not cfg.MODULES.is_enabled('student_cards'):
|
||||
@@ -2127,6 +2175,9 @@ def _upload_student_cards_excel():
|
||||
flash('Nur .xlsx oder .csv Dateien werden unterstützt.', 'error')
|
||||
return redirect(url_for('student_cards_admin'))
|
||||
|
||||
# CHECKBOX / SCHALTER: Schuljahres-Abgleich aktiviert?
|
||||
rollover_mode = request.form.get('rollover_mode') in ['true', '1', 'on']
|
||||
|
||||
try:
|
||||
header_row, data_rows = _load_tabular_upload(excel_file)
|
||||
except Exception as exc:
|
||||
@@ -2141,12 +2192,14 @@ def _upload_student_cards_excel():
|
||||
|
||||
synonyms = {
|
||||
'ausweis_id': ['ausweis_id', 'ausweisid', 'ausweis-id', 'karte', 'kartennummer', 'card_id', 'id'],
|
||||
'student_name': ['student_name', 'schuelername', 'schülername', 'schueler', 'schüler', 'name', 'vollname', 'vorname_nachname', 'nachname_vorname'],
|
||||
'ausweis_ident': ['lokales differenzierungsmerkmal', 'lokales_differenzierungsmerkmal', 'ausweis_ident',
|
||||
'differenzierungsmerkmal'],
|
||||
'first_name': ['vorname', 'first_name', 'firstname', 'rufname'],
|
||||
'last_name': ['nachname', 'last_name', 'lastname'],
|
||||
'class_name': ['klasse', 'class', 'class_name', 'jahrgang', 'jahrgangsstufe', 'stufe', 'gruppe', 'asv_klasse'],
|
||||
'notes': ['notizen', 'notes', 'bemerkungen', 'bemerkung', 'hinweis', 'hinweise'],
|
||||
'default_borrow_days': ['standard_ausleihdauer', 'ausleihdauer', 'borrow_days', 'tage', 'leihtage', 'max_borrow_days'],
|
||||
'default_borrow_days': ['standard_ausleihdauer', 'ausleihdauer', 'borrow_days', 'tage', 'leihtage',
|
||||
'max_borrow_days'],
|
||||
}
|
||||
|
||||
def col_index(key):
|
||||
@@ -2158,7 +2211,7 @@ def _upload_student_cards_excel():
|
||||
|
||||
mapped_indices = {
|
||||
'ausweis_id': col_index('ausweis_id'),
|
||||
'student_name': col_index('student_name'),
|
||||
'ausweis_ident': col_index('ausweis_ident'),
|
||||
'first_name': col_index('first_name'),
|
||||
'last_name': col_index('last_name'),
|
||||
'class_name': col_index('class_name'),
|
||||
@@ -2177,12 +2230,11 @@ def _upload_student_cards_excel():
|
||||
client = MongoClient(cfg.MONGODB_HOST, cfg.MONGODB_PORT)
|
||||
try:
|
||||
db = client[cfg.MONGODB_DB]
|
||||
student_cards = list(db['student_cards'].find())
|
||||
existing_ids.update(
|
||||
str(card.get('AusweisId', '')).strip().upper()
|
||||
for card in student_cards.find({}, {'AusweisId': 1})
|
||||
if card.get('AusweisId')
|
||||
)
|
||||
raw_db_cards = list(db['student_cards'].find())
|
||||
|
||||
for card in raw_db_cards:
|
||||
if card.get('AusweisId'):
|
||||
existing_ids.add(str(card.get('AusweisId')).strip().upper())
|
||||
|
||||
processed_rows = 0
|
||||
for row_number, row_values in enumerate(data_rows, start=2):
|
||||
@@ -2198,33 +2250,22 @@ def _upload_student_cards_excel():
|
||||
return row_values[idx]
|
||||
|
||||
ausweis_id = sanitize_form_value(val('ausweis_id'))
|
||||
student_name = sanitize_form_value(val('student_name'))
|
||||
first_name = sanitize_form_value(val('first_name'))
|
||||
last_name = sanitize_form_value(val('last_name'))
|
||||
class_name = sanitize_form_value(val('class_name'))
|
||||
ausweis_ident = sanitize_form_value(val('ausweis_ident'))
|
||||
class_name = sanitize_form_value(val('class_name')) or ""
|
||||
notes = sanitize_form_value(val('notes'))
|
||||
default_borrow_days = _excel_int(val('default_borrow_days')) or cfg.STUDENT_DEFAULT_BORROW_DAYS
|
||||
|
||||
if not student_name and first_name and last_name:
|
||||
student_name = f'{first_name} {last_name}'.strip()
|
||||
validation_warnings.append((row_number, 'Schülername wurde aus Vorname und Nachname zusammengesetzt'))
|
||||
default_borrow_days = _excel_int(val('default_borrow_days')) or 14
|
||||
|
||||
first_name = sanitize_form_value(val('first_name')) or ""
|
||||
last_name = sanitize_form_value(val('last_name')) or ""
|
||||
student_name = f"{first_name} {last_name}".strip()
|
||||
|
||||
if not ausweis_id and not student_name and not class_name:
|
||||
continue
|
||||
|
||||
row_errors = []
|
||||
if not student_name:
|
||||
row_errors.append('Schülername fehlt')
|
||||
|
||||
if not ausweis_id and student_name:
|
||||
ausweis_id = _build_student_card_excel_id(student_name, class_name, row_number, existing_ids)
|
||||
validation_warnings.append((row_number, f'Ausweis-ID wurde automatisch erzeugt: {ausweis_id}'))
|
||||
elif ausweis_id:
|
||||
ausweis_id = str(ausweis_id).strip().upper()
|
||||
if ausweis_id in existing_ids:
|
||||
row_errors.append(f'Ausweis-ID {ausweis_id} existiert bereits')
|
||||
else:
|
||||
existing_ids.add(ausweis_id)
|
||||
row_errors.append('Vorname und Nachname fehlen')
|
||||
|
||||
if row_errors:
|
||||
validation_errors.append((row_number, '; '.join(row_errors)))
|
||||
@@ -2233,34 +2274,105 @@ def _upload_student_cards_excel():
|
||||
planned_rows.append({
|
||||
'row_number': row_number,
|
||||
'ausweis_id': ausweis_id,
|
||||
'ausweis_ident': ausweis_ident,
|
||||
'student_name': student_name,
|
||||
'first_name': first_name,
|
||||
'last_name': last_name,
|
||||
'class_name': class_name,
|
||||
'notes': notes,
|
||||
'default_borrow_days': default_borrow_days,
|
||||
})
|
||||
finally:
|
||||
client.close()
|
||||
|
||||
if validation_errors:
|
||||
details = '; '.join([f'Zeile {n}: {msg}' for n, msg in validation_errors[:15]])
|
||||
flash(f'Validierung fehlgeschlagen ({len(validation_errors)} Zeilen). {details}', 'error')
|
||||
return redirect(url_for('student_cards_admin'))
|
||||
if validation_errors:
|
||||
details = '; '.join([f'Zeile {n}: {msg}' for n, msg in validation_errors[:15]])
|
||||
flash(f'Validierung fehlgeschlagen ({len(validation_errors)} Zeilen). {details}', 'error')
|
||||
return redirect(url_for('student_cards_admin'))
|
||||
|
||||
if validation_only:
|
||||
warning_text = ''
|
||||
if validation_warnings:
|
||||
warning_details = '; '.join([f'Zeile {n}: {msg}' for n, msg in validation_warnings[:10]])
|
||||
warning_text = f' Hinweise: {warning_details}'
|
||||
flash(f'Validierung erfolgreich: {len(planned_rows)} Ausweise würden importiert.{warning_text}', 'success')
|
||||
return redirect(url_for('student_cards_admin'))
|
||||
matched_db_doc_ids = set()
|
||||
rows_to_create = []
|
||||
matched_count = 0
|
||||
|
||||
client = MongoClient(cfg.MONGODB_HOST, cfg.MONGODB_PORT)
|
||||
try:
|
||||
db = client[cfg.MONGODB_DB]
|
||||
student_cards = db['student_cards']
|
||||
if rollover_mode:
|
||||
decrypted_db_cards = []
|
||||
for doc in raw_db_cards:
|
||||
dec_name = dp.decrypt_text(doc.get('SchülerName')) if doc.get('SchülerName') else ""
|
||||
dec_class = dp.decrypt_text(doc.get('Klasse')) if doc.get('Klasse') else ""
|
||||
dec_ident = doc.get('AusweisIdent') or ""
|
||||
|
||||
if dec_ident and dec_ident.startswith("gAAAAA"):
|
||||
try:
|
||||
dec_ident = dp.decrypt_text(dec_ident)
|
||||
except:
|
||||
pass
|
||||
|
||||
decrypted_db_cards.append({
|
||||
'_id': doc['_id'],
|
||||
'AusweisId': str(doc.get('AusweisId', '')).strip().upper(),
|
||||
'AusweisIdent': str(dec_ident or '').strip().upper(),
|
||||
'SchülerName': str(dec_name or '').strip().lower(),
|
||||
'Klasse': str(dec_class or '').strip().lower(),
|
||||
})
|
||||
|
||||
for excel_row in planned_rows:
|
||||
ex_ident = str(excel_row['ausweis_ident'] or '').strip().upper()
|
||||
ex_name = str(excel_row['student_name'] or '').strip().lower()
|
||||
ex_class = str(excel_row['class_name'] or '').strip().lower()
|
||||
|
||||
match_found = None
|
||||
|
||||
for db_card in decrypted_db_cards:
|
||||
if db_card['_id'] in matched_db_doc_ids:
|
||||
continue
|
||||
ident_matches = ex_ident and (ex_ident == db_card['AusweisIdent'])
|
||||
|
||||
secondary_matches = (ex_name and ex_name == db_card['SchülerName']) and \
|
||||
(ex_class and ex_class == db_card['Klasse'])
|
||||
|
||||
if ident_matches or secondary_matches:
|
||||
match_found = db_card
|
||||
break
|
||||
|
||||
if match_found:
|
||||
matched_db_doc_ids.add(match_found['_id'])
|
||||
matched_count += 1
|
||||
else:
|
||||
rows_to_create.append(excel_row)
|
||||
|
||||
db_ids_to_delete = [
|
||||
doc['_id'] for doc in raw_db_cards
|
||||
if doc['_id'] not in matched_db_doc_ids
|
||||
]
|
||||
else:
|
||||
rows_to_create = planned_rows
|
||||
db_ids_to_delete = []
|
||||
|
||||
if validation_only:
|
||||
flash(
|
||||
f'Validierung erfolgreich ({len(planned_rows)} Excel-Zeilen). '
|
||||
f'Abgleich: {matched_count} unverändert, {len(rows_to_create)} neu, {len(db_ids_to_delete)} zum Löschen.',
|
||||
'success'
|
||||
)
|
||||
return redirect(url_for('student_cards_admin'))
|
||||
|
||||
student_cards_col = db['student_cards']
|
||||
|
||||
deleted_count = 0
|
||||
if db_ids_to_delete:
|
||||
res = student_cards_col.delete_many({'_id': {'$in': db_ids_to_delete}})
|
||||
deleted_count = res.deleted_count
|
||||
|
||||
created_total = 0
|
||||
for row in planned_rows:
|
||||
for row in rows_to_create:
|
||||
row_ausweis_id = row['ausweis_id']
|
||||
if not row_ausweis_id:
|
||||
row_ausweis_id = generate_ausweis_id(existing_ids)
|
||||
existing_ids.add(row_ausweis_id.upper())
|
||||
|
||||
row_ausweis_ident = row['ausweis_ident']
|
||||
if not row_ausweis_ident:
|
||||
random_chars = "".join(random.choices(string.ascii_uppercase + string.digits, k=5))
|
||||
row_ausweis_ident = f"LD-{random_chars}"
|
||||
|
||||
encrypted_payload = encrypt_document_fields(
|
||||
{
|
||||
'SchülerName': row['student_name'],
|
||||
@@ -2269,29 +2381,33 @@ def _upload_student_cards_excel():
|
||||
},
|
||||
STUDENT_CARD_ENCRYPTED_FIELDS
|
||||
)
|
||||
student_cards.insert_one({
|
||||
'AusweisId': row['ausweis_id'],
|
||||
student_cards_col.insert_one({
|
||||
'AusweisId': row_ausweis_id,
|
||||
'AusweisIdent': row_ausweis_ident,
|
||||
'StandardAusleihdauer': int(row['default_borrow_days']),
|
||||
'Erstellt': datetime.datetime.now(),
|
||||
**encrypted_payload,
|
||||
})
|
||||
created_total += 1
|
||||
|
||||
except Exception as exc:
|
||||
app.logger.error(f'Error importing student cards from Excel: {exc}')
|
||||
flash(f'Fehler beim Import der Bibliotheksausweise', 'error')
|
||||
app.logger.error(f'Error importing student cards: {exc}')
|
||||
flash('Fehler beim Verarbeiten der Bibliotheksausweise.', 'error')
|
||||
return redirect(url_for('student_cards_admin'))
|
||||
finally:
|
||||
client.close()
|
||||
|
||||
if validation_warnings:
|
||||
warning_details = '; '.join([f'Zeile {n}: {msg}' for n, msg in validation_warnings[:10]])
|
||||
flash(f'Excel-Import erfolgreich: {created_total} Ausweise importiert. Hinweise: {warning_details}', 'warning')
|
||||
if rollover_mode:
|
||||
flash(
|
||||
f'Schuljahres-Abgleich erfolgreich: {matched_count} Schüler beibehalten, '
|
||||
f'{created_total} neu hinzugefügt, {deleted_count} alte Einträge gelöscht.',
|
||||
'success'
|
||||
)
|
||||
else:
|
||||
flash(f'Excel-Import erfolgreich: {created_total} Ausweise importiert.', 'success')
|
||||
|
||||
return redirect(url_for('student_cards_admin'))
|
||||
|
||||
|
||||
def _upload_excel_items(scope='inventory'):
|
||||
"""Bulk import inventory/library items from Excel with validation-first workflow."""
|
||||
if 'username' not in session:
|
||||
@@ -3826,9 +3942,15 @@ def api_item_detail(item_id):
|
||||
{f'<p><strong>Ausgeliehen von:</strong> {html.escape(str(borrower_value))}</p>' if borrower_value and status_label == 'Ausgeliehen' else ''}
|
||||
{borrows_html}
|
||||
"""
|
||||
|
||||
ctx = get_tenant_context()
|
||||
current_tenant_id = ctx.tenant_id if ctx else None
|
||||
|
||||
client.close()
|
||||
return detail_html, 200
|
||||
return jsonify({
|
||||
'html': detail_html,
|
||||
'images': item.get('Images', item.get('Bilder', [])),
|
||||
'tenant': str(current_tenant_id)
|
||||
}), 200
|
||||
except Exception as e:
|
||||
app.logger.error(f"Error fetching item detail: {e}")
|
||||
return jsonify({'error': 'An error occurred while fetching the item detail'}), 500
|
||||
@@ -3979,6 +4101,19 @@ def library_admin():
|
||||
back_target='library'
|
||||
)
|
||||
|
||||
def generate_ausweis_id():
|
||||
import random
|
||||
import string
|
||||
|
||||
while True:
|
||||
random_digits = "".join(random.choices(string.digits, k=6))
|
||||
new_id = f"ID_{random_digits}"
|
||||
|
||||
if not us.get_user_by_student_card(new_id):
|
||||
print(f"Generated unique ID: {new_id}")
|
||||
return new_id
|
||||
else:
|
||||
print(f"Already found: {new_id}, trying another...")
|
||||
|
||||
@app.route('/student_cards_admin', methods=['GET', 'POST'])
|
||||
def student_cards_admin():
|
||||
@@ -4015,6 +4150,7 @@ def student_cards_admin():
|
||||
edit_mode = True
|
||||
form_data = {
|
||||
'card_id': str(card['_id']),
|
||||
'ausweis_ident': card.get('ausweis_ident', ''),
|
||||
'ausweis_id': card.get('AusweisId', ''),
|
||||
'student_name': card.get('SchülerName', ''),
|
||||
'default_borrow_days': card.get('StandardAusleihdauer', 14),
|
||||
@@ -4029,6 +4165,7 @@ def student_cards_admin():
|
||||
if request.method == 'POST':
|
||||
action = request.form.get('action', 'add')
|
||||
ausweis_id = request.form.get('ausweis_id', '').strip().upper()
|
||||
ausweis_ident = request.form.get('ausweis_ident', '').strip()
|
||||
student_name = request.form.get('student_name', '').strip()
|
||||
student_name_alias = student_name
|
||||
default_borrow_days = request.form.get('default_borrow_days', 14)
|
||||
@@ -4054,9 +4191,12 @@ def student_cards_admin():
|
||||
existing = student_cards.find_one({'AusweisId': ausweis_id, '_id': {'$ne': ObjectId(card_id)}})
|
||||
if existing:
|
||||
flash('Diese Ausweis-ID existiert bereits.', 'error')
|
||||
if not ausweis_ident:
|
||||
ausweis_ident = ausweis_id
|
||||
else:
|
||||
encrypted_payload = encrypt_document_fields(
|
||||
{
|
||||
'ausweis_ident': ausweis_ident,
|
||||
'SchülerName': student_name_alias,
|
||||
'Klasse': class_name,
|
||||
'Notizen': notes,
|
||||
@@ -4079,17 +4219,25 @@ def student_cards_admin():
|
||||
flash('Fehler beim Aktualisieren des Ausweises.', 'error')
|
||||
|
||||
elif action == 'add':
|
||||
if not ausweis_id or not student_name:
|
||||
flash('Bitte Ausweis-ID und Schülername angeben.', 'error')
|
||||
if not student_name:
|
||||
flash('Bitte Schülername angeben.', 'error')
|
||||
else:
|
||||
# Check if ID already exists
|
||||
existing = student_cards.find_one({'AusweisId': ausweis_id})
|
||||
if ausweis_id:
|
||||
existing = student_cards.find_one({'AusweisId': ausweis_id})
|
||||
else:
|
||||
ausweis_id = generate_ausweis_id()
|
||||
existing = False
|
||||
if not ausweis_ident:
|
||||
ausweis_ident = ausweis_id
|
||||
|
||||
if existing:
|
||||
flash('Diese Ausweis-ID existiert bereits.', 'error')
|
||||
flash('Diese ID existiert bereits.', 'error')
|
||||
else:
|
||||
try:
|
||||
encrypted_payload = encrypt_document_fields(
|
||||
{
|
||||
'ausweis_ident': ausweis_ident,
|
||||
'SchülerName': student_name_alias,
|
||||
'Klasse': class_name,
|
||||
'Notizen': notes,
|
||||
@@ -5481,7 +5629,7 @@ def upload_item():
|
||||
fs = get_gridfs()
|
||||
|
||||
if cfg.MODULES.is_enabled('library') and sanitize_form_value(request.form.get('item_type_input', '')) != "other":
|
||||
success_redirect_endpoint = 'library'
|
||||
success_redirect_endpoint = 'library_view'
|
||||
else:
|
||||
success_redirect_endpoint = 'home_admin'
|
||||
|
||||
@@ -5825,7 +5973,9 @@ def upload_item():
|
||||
|
||||
if item_id:
|
||||
success_msg = f'Element wurde erfolgreich hinzugefügt ({len(created_item_ids)} erstellt)'
|
||||
fs = get_gridfs() # Deine GridFS Verbindung
|
||||
|
||||
it.cleanup_orphaned_images(fs, dry_run=True)
|
||||
if upload_mode == 'library':
|
||||
try:
|
||||
_append_audit_event_standalone(
|
||||
@@ -7239,62 +7389,6 @@ def check_availability():
|
||||
except Exception as e:
|
||||
return jsonify({'ok': False}), 500
|
||||
|
||||
|
||||
# def create_qr_code(id):
|
||||
# """
|
||||
# Generate a QR code for an item.
|
||||
# The QR code contains a URL that points to the item details.
|
||||
#
|
||||
# Args:
|
||||
# id (str): ID of the item to generate QR code for
|
||||
#
|
||||
# Returns:
|
||||
# str: Filename of the generated QR code, or None if item not found
|
||||
# """
|
||||
# qr = qrcode.QRCode(
|
||||
# version=1,
|
||||
# error_correction=ERROR_CORRECT_L, # Use imported constant
|
||||
# box_size=10,
|
||||
# border=4,
|
||||
# )
|
||||
#
|
||||
# # Parse and reconstruct the URL properly
|
||||
# parsed_url = urlparse(request.url_root)
|
||||
#
|
||||
# # Force HTTPS if needed
|
||||
# scheme = 'https' if parsed_url.scheme == 'http' else parsed_url.scheme
|
||||
#
|
||||
# # Properly reconstruct the base URL
|
||||
# base_url = urlunparse((scheme, parsed_url.netloc, '', '', '', ''))
|
||||
#
|
||||
# # URL that will open this item directly
|
||||
# item_url = f"{base_url}:{Port}/item/{id}"
|
||||
# qr.add_data(item_url)
|
||||
# qr.make(fit=True)
|
||||
#
|
||||
# item = it.get_item(id)
|
||||
# if not item:
|
||||
# return None
|
||||
#
|
||||
# img = qr.make_image(fill_color="black", back_color="white")
|
||||
#
|
||||
# # Create a unique filename using UUID
|
||||
# unique_id = str(uuid.uuid4())
|
||||
# timestamp = time.strftime("%Y%m%d%H%M%S")
|
||||
#
|
||||
# # Still include the original name for readability but ensure uniqueness with UUID
|
||||
# safe_name = secure_filename(item['Name'])
|
||||
# filename = f"{safe_name}_{unique_id}_{timestamp}.png"
|
||||
# qr_path = os.path.join(app.config['QR_CODE_FOLDER'], filename)
|
||||
#
|
||||
#
|
||||
# # Fix the file handling - save to file object, not string
|
||||
# with open(qr_path, 'wb') as f:
|
||||
# img.save(f)
|
||||
#
|
||||
# return filename
|
||||
|
||||
# Fix fromisoformat None value checks
|
||||
@app.route('/plan_booking', methods=['POST'])
|
||||
def plan_booking():
|
||||
"""
|
||||
@@ -9958,25 +10052,28 @@ def fetch_book_info(isbn):
|
||||
app.logger.error(f"Error fetching book data: {e}")
|
||||
return jsonify({"error": f"Failed to fetch book information"}), 500
|
||||
|
||||
|
||||
@app.route('/download_book_cover', methods=['POST'])
|
||||
def download_book_cover():
|
||||
"""
|
||||
API endpoint to download and save a book cover image from URL
|
||||
API endpoint to download a book cover image from URL
|
||||
and save it directly to MongoDB GridFS.
|
||||
"""
|
||||
if 'username' not in session:
|
||||
return jsonify({"error": "Not authorized"}), 403
|
||||
|
||||
current_permissions = us.get_effective_permissions(session['username'])
|
||||
|
||||
|
||||
if not current_permissions['actions'].get('can_insert', False):
|
||||
flash('Ihnen fehlen die nötigen Berechtigungen, um diese Aktion auszuführen.', 'error')
|
||||
return redirect(url_for('library_view'))
|
||||
return jsonify({"error": "Ihnen fehlen die nötigen Berechtigungen."}), 403
|
||||
|
||||
if not cfg.MODULES.is_enabled('library'):
|
||||
return jsonify({"error": "Bibliotheks-Modul ist deaktiviert."}), 403
|
||||
|
||||
|
||||
try:
|
||||
data = request.get_json()
|
||||
image_url = data.get('url')
|
||||
|
||||
|
||||
if not image_url:
|
||||
return jsonify({"error": "No image URL provided"}), 400
|
||||
|
||||
@@ -9984,71 +10081,69 @@ def download_book_cover():
|
||||
if parsed_url.scheme != 'https' or not parsed_url.netloc:
|
||||
return jsonify({"error": "Only public HTTPS URLs are allowed"}), 400
|
||||
|
||||
# 2. SSRF Protection: Strict Allowlist Check
|
||||
# if parsed_url.netloc not in ALLOWED_COVER_DOMAINS:
|
||||
# return jsonify({"error": "Target host is not an allowed book cover provider"}), 403
|
||||
|
||||
# Download the image (allow_redirects=False prevents redirecting to internal IPs)
|
||||
response = requests.get(image_url, stream=True, timeout=10, allow_redirects=False)
|
||||
|
||||
|
||||
if response.status_code != 200:
|
||||
return jsonify({"error": f"Failed to download image: Status {response.status_code}"}), 400
|
||||
|
||||
# Check content type
|
||||
|
||||
content_type = response.headers.get('content-type', '')
|
||||
allowed_types = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif']
|
||||
|
||||
|
||||
if not any(allowed_type in content_type.lower() for allowed_type in allowed_types):
|
||||
return jsonify({
|
||||
"error": f"Nicht unterstütztes Bildformat: {content_type}. Erlaubte Formate: JPG, JPEG, PNG, GIF"
|
||||
}), 400
|
||||
|
||||
# Check content length header
|
||||
content_length = response.headers.get('Content-Length')
|
||||
if content_length:
|
||||
try:
|
||||
if int(content_length) > 5 * 1024 * 1024:
|
||||
return jsonify({"error": "Image is too large"}), 413
|
||||
return jsonify({"error": "Image is too large (max 5MB)"}), 413
|
||||
except ValueError:
|
||||
pass
|
||||
|
||||
# Generate a fully unique filename
|
||||
|
||||
unique_id = str(uuid.uuid4())
|
||||
timestamp = time.strftime("%Y%m%d%H%M%S")
|
||||
|
||||
|
||||
extension = '.jpg' # default
|
||||
if 'image/png' in content_type.lower():
|
||||
extension = '.png'
|
||||
elif 'image/gif' in content_type.lower():
|
||||
extension = '.gif'
|
||||
|
||||
|
||||
filename = f"book_cover_{unique_id}_{timestamp}{extension}"
|
||||
filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename)
|
||||
|
||||
# Save image in chunks (prevents memory exhaustion and enforces size limits)
|
||||
with open(filepath, 'wb') as f:
|
||||
written = 0
|
||||
for chunk in response.iter_content(chunk_size=8192):
|
||||
written += len(chunk)
|
||||
if written > 5 * 1024 * 1024:
|
||||
# Clean up the partial file before aborting
|
||||
os.remove(filepath)
|
||||
return jsonify({"error": "Image is too large"}), 413
|
||||
f.write(chunk)
|
||||
|
||||
|
||||
image_data = io.BytesIO()
|
||||
written = 0
|
||||
|
||||
for chunk in response.iter_content(chunk_size=8192):
|
||||
written += len(chunk)
|
||||
if written > 5 * 1024 * 1024:
|
||||
return jsonify({"error": "Image is too large (max 5MB)"}), 413
|
||||
image_data.write(chunk)
|
||||
|
||||
image_data.seek(0)
|
||||
|
||||
fs = get_gridfs()
|
||||
fs.put(
|
||||
image_data,
|
||||
filename=filename,
|
||||
content_type=content_type
|
||||
)
|
||||
|
||||
return jsonify({
|
||||
"success": True,
|
||||
"filename": filename,
|
||||
"message": "Image downloaded successfully"
|
||||
"message": "Image downloaded and stored directly in database"
|
||||
})
|
||||
|
||||
|
||||
except requests.exceptions.RequestException as e:
|
||||
app.logger.error(f"Network error downloading book cover: {e}")
|
||||
return jsonify({"error": "Netzwerkfehler beim Herunterladen des Bildes."}), 500
|
||||
except Exception as e:
|
||||
app.logger.error(f"Error downloading book cover: {e}")
|
||||
# Fixed syntax here: Removed the injected HTML that was appended to this line
|
||||
return jsonify({"error": f"Failed to download image"}), 500
|
||||
return jsonify({"error": "Failed to download image"}), 500
|
||||
|
||||
"""
|
||||
@app.route('/proxy_image')
|
||||
def proxy_image():
|
||||
|
||||
@@ -25,6 +25,7 @@ import datetime
|
||||
import Web.modules.database.settings as cfg
|
||||
from Web.modules.database.settings import MongoClient
|
||||
import Web.modules.inventarsystem.data_protection as dp
|
||||
import logging
|
||||
|
||||
|
||||
def is_library_item(item):
|
||||
@@ -1292,4 +1293,137 @@ def sync_group_codes(primary_obj_id, base_code, individual_codes_list):
|
||||
return True
|
||||
except Exception as e:
|
||||
print(f"Error syncing group codes: {e}")
|
||||
return False
|
||||
return False
|
||||
|
||||
|
||||
logging.basicConfig(level=logging.INFO, format='%(levelname)s: %(message)s')
|
||||
|
||||
|
||||
def cleanup_orphaned_images(fs, dry_run=True):
|
||||
"""
|
||||
Finds images in GridFS that are no longer referenced by any item
|
||||
and optionally deletes them.
|
||||
|
||||
Supported item fields:
|
||||
- book_cover_image
|
||||
- image
|
||||
- images
|
||||
|
||||
The fields are expected to contain GridFS file ObjectIds.
|
||||
|
||||
:param fs: GridFS instance, e.g. gridfs.GridFS(db)
|
||||
:param dry_run: If True, only reports what would be deleted.
|
||||
If False, actually deletes the files.
|
||||
"""
|
||||
|
||||
logging.info("Starte Cleanup-Skript...")
|
||||
|
||||
client = MongoClient(cfg.MONGODB_HOST, cfg.MONGODB_PORT)
|
||||
|
||||
try:
|
||||
db = client[cfg.MONGODB_DB]
|
||||
items_collection = db["items"]
|
||||
|
||||
referenced_files = set()
|
||||
|
||||
for item in items_collection.find(
|
||||
{},
|
||||
{
|
||||
"Images": 1
|
||||
}
|
||||
):
|
||||
images = item.get("Images")
|
||||
|
||||
if isinstance(images, list):
|
||||
for img in images:
|
||||
if img:
|
||||
referenced_files.add(img)
|
||||
|
||||
referenced_files.discard(None)
|
||||
|
||||
logging.info(
|
||||
f"{len(referenced_files)} referenzierte GridFS-Dateien gefunden."
|
||||
)
|
||||
|
||||
orphaned_files = []
|
||||
|
||||
for grid_file in fs.find():
|
||||
file_id = grid_file._id
|
||||
filename = grid_file.filename or ""
|
||||
|
||||
if not filename.lower().endswith(
|
||||
(".jpg", ".jpeg", ".png", ".gif", ".webp")
|
||||
):
|
||||
continue
|
||||
|
||||
if file_id not in referenced_files:
|
||||
orphaned_files.append(
|
||||
{
|
||||
"_id": file_id,
|
||||
"filename": filename,
|
||||
"upload_date": grid_file.upload_date,
|
||||
}
|
||||
)
|
||||
|
||||
logging.info(
|
||||
f"Gefundene verwaiste Bilder: {len(orphaned_files)}"
|
||||
)
|
||||
|
||||
if dry_run:
|
||||
logging.info(
|
||||
"--- DRY RUN AKTIV - Es wird nichts gelöscht ---"
|
||||
)
|
||||
|
||||
for file in orphaned_files:
|
||||
logging.info(
|
||||
f"Würde löschen: "
|
||||
f"{file['filename']} "
|
||||
f"(ID: {file['_id']}, "
|
||||
f"Hochgeladen: {file['upload_date']})"
|
||||
)
|
||||
|
||||
logging.info(
|
||||
"--- Setze dry_run=False, um physisch zu löschen ---"
|
||||
)
|
||||
|
||||
else:
|
||||
logging.warning("--- LÖSCHVORGANG AKTIV ---")
|
||||
|
||||
deleted_count = 0
|
||||
failed_count = 0
|
||||
|
||||
for file in orphaned_files:
|
||||
try:
|
||||
fs.delete(file["_id"])
|
||||
|
||||
deleted_count += 1
|
||||
|
||||
logging.info(
|
||||
f"Gelöscht: {file['filename']} "
|
||||
f"(ID: {file['_id']})"
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
failed_count += 1
|
||||
|
||||
logging.error(
|
||||
f"Fehler beim Löschen von "
|
||||
f"{file['filename']} "
|
||||
f"(ID: {file['_id']}): {e}"
|
||||
)
|
||||
|
||||
logging.info(
|
||||
f"Cleanup beendet. "
|
||||
f"{deleted_count} Bilder gelöscht, "
|
||||
f"{failed_count} Fehler."
|
||||
)
|
||||
|
||||
return {
|
||||
"status": "success",
|
||||
"referenced_count": len(referenced_files),
|
||||
"orphaned_count": len(orphaned_files),
|
||||
"dry_run": dry_run,
|
||||
}
|
||||
|
||||
finally:
|
||||
client.close()
|
||||
@@ -704,6 +704,41 @@ def get_user_by_student_card(student_card_id):
|
||||
# Do not call dp.decrypt_text() here because found_user is a MongoDB dictionary.
|
||||
return found_user
|
||||
|
||||
def get_user_by_student_ident(student_ident):
|
||||
"""Return user dict by student ident by decrypting all cards and matching."""
|
||||
if not student_ident:
|
||||
return None
|
||||
|
||||
# Normalisiere den Suchbegriff, den wir finden wollen
|
||||
normalized_target = str(student_ident).strip()
|
||||
if not normalized_target:
|
||||
return None
|
||||
|
||||
client = MongoClient(cfg.MONGODB_HOST, cfg.MONGODB_PORT)
|
||||
try:
|
||||
db = _get_tenant_db(client)
|
||||
all_student_cards = db['student_cards'].find()
|
||||
|
||||
for user_doc in all_student_cards:
|
||||
encrypted_ident = user_doc.get('AusweisIdent')
|
||||
|
||||
if encrypted_ident:
|
||||
try:
|
||||
decrypted_ident = dp.decrypt_text(encrypted_ident)
|
||||
|
||||
if decrypted_ident and str(decrypted_ident).strip() == normalized_target:
|
||||
return user_doc
|
||||
|
||||
except Exception as e:
|
||||
app.logger.error(f"Entschlüsselungsfehler bei ID {user_doc.get('_id')}: {e}")
|
||||
continue
|
||||
|
||||
except Exception as exc:
|
||||
app.logger.error(f"Datenbankfehler in get_user_by_student_ident: {exc}")
|
||||
finally:
|
||||
client.close()
|
||||
|
||||
return None
|
||||
|
||||
def make_admin(username):
|
||||
"""Grant administrator privileges to a user."""
|
||||
|
||||
@@ -1342,7 +1342,7 @@
|
||||
<ul class="navbar-nav me-auto mb-2 mb-lg-0" id="libraryNavList">
|
||||
{% if current_permissions.pages.get('library_view', False) %}
|
||||
<li class="nav-item" data-nav-fixed="true">
|
||||
<a class="nav-link {% if current_path == url_for('library_view') %}nav-active{% endif %}" href="{{ url_for('library_view') }}" data-tutorial-tip="Die Bibliothek zeigt Ihnen alle Medien und verfügbaren Bücher.">Medien</a>
|
||||
<a class="nav-link {% if current_path == url_for('library_view') %}nav-active{% endif %}" href="{{ url_for('library_view') }}" data-tutorial-tip="Die Bibliothek zeigt Ihnen alle Medien und verfügbaren Bücher.">Medien/Ausleihe</a>
|
||||
</li>
|
||||
{% endif %}
|
||||
{% if 'username' in session %}
|
||||
|
||||
@@ -135,21 +135,6 @@
|
||||
.library-scan-status.warn { color: #9a6700; }
|
||||
.library-scan-status.error { color: #b42318; }
|
||||
|
||||
.library-scan-reader-wrap {
|
||||
display: none;
|
||||
margin-top: 12px;
|
||||
max-width: 460px;
|
||||
background: var(--ui-surface);
|
||||
border: 1px solid #d9dde4;
|
||||
border-radius: 8px;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.library-scan-reader {
|
||||
width: 100%;
|
||||
min-height: 280px;
|
||||
}
|
||||
|
||||
/* Filters */
|
||||
.library-filter-toggle-btn {
|
||||
padding: 10px 16px;
|
||||
@@ -431,6 +416,71 @@
|
||||
|
||||
.library-scan-reader-wrap { max-width: 100%; }
|
||||
}
|
||||
.library-scan-reader-wrap {
|
||||
display: none;
|
||||
margin-top: 15px;
|
||||
max-width: 640px;
|
||||
margin-left: auto;
|
||||
margin-right: auto;
|
||||
background: #000;
|
||||
border: 1px solid #d9dde4;
|
||||
border-radius: 8px;
|
||||
overflow: hidden;
|
||||
grid-column: 1 / -1;
|
||||
}
|
||||
|
||||
.library-scan-reader {
|
||||
width: 100%;
|
||||
min-height: 280px;
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.library-scan-reader video {
|
||||
width: 100%;
|
||||
height: auto;
|
||||
display: block;
|
||||
object-fit: cover;
|
||||
}
|
||||
|
||||
.library-scan-reader canvas.drawing,
|
||||
.library-scan-reader canvas.drawingBuffer {
|
||||
position: absolute;
|
||||
top: 0;
|
||||
left: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
|
||||
.detail-gallery-container {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 15px;
|
||||
margin: 15px 0 20px 0;
|
||||
width: 100%;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.item-image-wrapper {
|
||||
background-color: #f8fafc;
|
||||
border: 1px solid #e2e8f0;
|
||||
border-radius: 8px;
|
||||
padding: 6px;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.04);
|
||||
}
|
||||
|
||||
.item-image {
|
||||
max-width: 160px;
|
||||
max-height: 200px;
|
||||
width: auto;
|
||||
height: auto;
|
||||
display: block;
|
||||
object-fit: contain;
|
||||
border-radius: 4px;
|
||||
}
|
||||
</style>
|
||||
|
||||
<div class="library-table-container" id="libraryTableContainer" data-can-edit="{{ 1 if current_permissions.actions.get('can_edit', False) else 0 }}">
|
||||
@@ -457,7 +507,6 @@
|
||||
🔍 Filter
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div class="library-scan-controls">
|
||||
<select id="scanModeSelect" aria-label="Scan-Modus">
|
||||
<option value="card_only">Nur Ausweis erfassen</option>
|
||||
@@ -475,6 +524,10 @@
|
||||
</label>
|
||||
<button id="manualActionBtn" class="button" type="button" style="margin-left:6px; background:#4f46e5; color:white;">Code verarbeiten</button>
|
||||
</div>
|
||||
<div class="library-scan-reader-wrap" id="scanReaderWrap" style="display: none; margin-top: 15px;">
|
||||
<div class="library-scan-reader" style="width: 100%; max-width: 640px; margin: 0 auto; overflow: hidden; border-radius: 8px; border: 2px solid #ccc;">
|
||||
</div>
|
||||
</div>
|
||||
<div id="filterPanel" class="library-filter-panel">
|
||||
<div class="filter-row">
|
||||
<div class="filter-item">
|
||||
@@ -1306,69 +1359,75 @@
|
||||
const detailContent = document.getElementById('detailContent');
|
||||
const detailModal = document.getElementById('detailModal');
|
||||
|
||||
// Lade-Status anzeigen und Modal öffnen
|
||||
detailContent.innerHTML = '<p>Lade Details...</p>';
|
||||
detailModal.style.display = 'flex';
|
||||
|
||||
const item = libraryItems.find(i => i._id === itemId);
|
||||
let mediaHtml = '';
|
||||
|
||||
// Robuste Prüfung: Wir testen gängige Benennungen aus deinem Backend
|
||||
const imageArray = item.Images || item.Bilder || item.images;
|
||||
|
||||
if (item && Array.isArray(imageArray) && imageArray.length > 0) {
|
||||
const imagesHtml = imageArray.map((image, index) => {
|
||||
|
||||
// Dein neuer Code für die exakte Routen-Generierung
|
||||
const imageSrc = image.startsWith('/uploads/') || image.startsWith('http') ?
|
||||
image :
|
||||
`{{ url_for('uploaded_file', filename='') }}${image}`;
|
||||
|
||||
const thumbnailInfo = item.ThumbnailInfo && item.ThumbnailInfo[index];
|
||||
const isVideo = isVideoFile(image);
|
||||
|
||||
if (isVideo) {
|
||||
const videoSrc = thumbnailInfo && thumbnailInfo.has_thumbnail
|
||||
? thumbnailInfo.thumbnail_url
|
||||
: imageSrc;
|
||||
|
||||
if (thumbnailInfo && thumbnailInfo.has_thumbnail) {
|
||||
return `
|
||||
<div class="video-container" style="position: relative; width: 120px; height: 120px; display: inline-block; margin-right: 15px; margin-bottom: 15px;">
|
||||
<img src="${videoSrc}" alt="${escapeHtml(item.Name || 'Medium')}" class="item-image" style="width: 100%; height: 100%; object-fit: cover; border-radius: 8px; border: 1px solid #ddd;">
|
||||
<div class="video-preview-overlay" style="position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); color: white; background: rgba(0,0,0,0.6); border-radius: 50%; width: 36px; height: 36px; display: flex; align-items: center; justify-content: center; font-size: 16px;">
|
||||
▶
|
||||
</div>
|
||||
</div>`;
|
||||
} else {
|
||||
return `<div style="width: 120px; height: 120px; background: #333; color: #fff; display: inline-flex; align-items: center; justify-content: center; border-radius: 8px; margin-right: 15px; margin-bottom: 15px;">VIDEO</div>`;
|
||||
}
|
||||
} else {
|
||||
const imageSrcFinal = thumbnailInfo && thumbnailInfo.has_thumbnail
|
||||
? thumbnailInfo.thumbnail_url
|
||||
: imageSrc;
|
||||
|
||||
return `<img src="${imageSrcFinal}" alt="${escapeHtml(item.Name || 'Medium')}" class="item-image" style="width: 120px; height: 120px; object-fit: cover; border-radius: 8px; border: 1px solid #ddd; margin-right: 15px; margin-bottom: 15px;">`;
|
||||
}
|
||||
}).join('');
|
||||
|
||||
mediaHtml = `<div class="detail-gallery-container" style="margin-bottom: 20px; padding-bottom: 15px; border-bottom: 1px solid #eee; display: flex; flex-wrap: wrap;">${imagesHtml}</div>`;
|
||||
}
|
||||
|
||||
// Daten vom Backend-API-Endpoint abrufen
|
||||
fetch(`/api/item_detail/${itemId}`)
|
||||
.then(response => {
|
||||
if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
|
||||
return response.text();
|
||||
if (!response.ok) {
|
||||
throw new Error('Fehler beim Laden der Artikeldetails');
|
||||
}
|
||||
return response.json();
|
||||
})
|
||||
.then(html => {
|
||||
detailContent.innerHTML = mediaHtml + DOMPurify.sanitize(html);
|
||||
.then(data => {
|
||||
detailContent.innerHTML = data.html;
|
||||
|
||||
const imageArray = data.images || [];
|
||||
const thumbnailInfoMap = data.thumbnailInfo || [];
|
||||
|
||||
if (Array.isArray(imageArray) && imageArray.length > 0) {
|
||||
const imagesHtml = imageArray.map((image, index) => {
|
||||
const isVideo = typeof isVideoFile === 'function' ? isVideoFile(image) : /\.(mp4|webm|ogg|mov)$/i.test(image);
|
||||
const thumbnailInfo = thumbnailInfoMap[index];
|
||||
|
||||
if (isVideo) {
|
||||
const videoSrc = image.startsWith('/uploads/') || image.startsWith('http')
|
||||
? image
|
||||
: `/uploads/${image}`;
|
||||
|
||||
return `
|
||||
<div class="item-image-wrapper" style="width: 100%; height: auto;">
|
||||
<video src="${videoSrc}" class="item-image ${index === 0 ? 'active-image' : ''}" id="modal-image-${index}" controls preload="metadata" style="width: 100%; height: auto; max-height: 300px;"></video>
|
||||
</div>`;
|
||||
} else {
|
||||
const imageSrc = thumbnailInfo && thumbnailInfo.has_preview
|
||||
? thumbnailInfo.preview_url
|
||||
: (image.startsWith('/uploads/') || image.startsWith('http')
|
||||
? image
|
||||
: `/uploads/${image}`);
|
||||
|
||||
return `
|
||||
<div class="item-image-wrapper">
|
||||
<img src="${imageSrc}"
|
||||
alt="Buchcover / Bild"
|
||||
class="item-image ${index === 0 ? 'active-image' : ''}"
|
||||
id="modal-image-${index}"
|
||||
loading="lazy"
|
||||
onload="console.log('Bild geladen:', '${imageSrc}')"
|
||||
onerror="console.error('FEHLER beim Laden des Bildes im DOM:', '${imageSrc}')">
|
||||
</div>`;
|
||||
}
|
||||
}).join('');
|
||||
|
||||
const mediaHtml = `<div class="detail-gallery-container">${imagesHtml}</div>`;
|
||||
|
||||
const h2Tag = detailContent.querySelector('h2');
|
||||
if (h2Tag) {
|
||||
h2Tag.insertAdjacentHTML('afterend', mediaHtml);
|
||||
} else {
|
||||
detailContent.insertAdjacentHTML('afterbegin', mediaHtml);
|
||||
}
|
||||
}
|
||||
})
|
||||
.catch(err => {
|
||||
console.error('Error loading detail:', err);
|
||||
detailContent.innerHTML = '<p style="color: red;">Entschuldigung, die Details konnten nicht geladen werden.</p>';
|
||||
.catch(error => {
|
||||
console.error('Error fetching item detail:', error);
|
||||
detailContent.innerHTML = '<p style="color: red;">Fehler beim Laden der Artikeldetails.</p>';
|
||||
});
|
||||
}
|
||||
|
||||
// Closes the modal via the 'x' button
|
||||
// Schließt das Modal über den 'x'-Button
|
||||
function closeDetailModal() {
|
||||
document.getElementById('detailModal').style.display = 'none';
|
||||
}
|
||||
|
||||
@@ -18,14 +18,58 @@
|
||||
align-items: center;
|
||||
margin-bottom: 20px;
|
||||
flex-wrap: wrap;
|
||||
gap: 10px;
|
||||
gap: 15px;
|
||||
}
|
||||
|
||||
/* Neu strukturiertes Layout für Formular & Import */
|
||||
.dashboard-grid {
|
||||
display: grid;
|
||||
grid-template-columns: 2fr 1fr;
|
||||
gap: 20px;
|
||||
margin-bottom: 30px;
|
||||
}
|
||||
|
||||
.student-card-form {
|
||||
background: var(--ui-bg);
|
||||
padding: 20px;
|
||||
border-radius: 8px;
|
||||
margin-bottom: 30px;
|
||||
}
|
||||
|
||||
.import-card {
|
||||
border: 1px solid #dbe4ee;
|
||||
border-radius: 8px;
|
||||
padding: 20px;
|
||||
background: #f8fbff;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
justify-content: space-between;
|
||||
}
|
||||
|
||||
.rollover-box {
|
||||
background: #fff3cd;
|
||||
border: 1px solid #ffeeba;
|
||||
border-radius: 6px;
|
||||
padding: 10px 12px;
|
||||
margin-top: 4px;
|
||||
}
|
||||
|
||||
.rollover-label {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
cursor: pointer;
|
||||
font-size: 13px;
|
||||
color: #856404;
|
||||
font-weight: 700;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.rollover-hint {
|
||||
display: block;
|
||||
margin-top: 4px;
|
||||
font-size: 11px;
|
||||
color: #856404;
|
||||
line-height: 1.3;
|
||||
}
|
||||
|
||||
.form-row {
|
||||
@@ -35,6 +79,10 @@
|
||||
margin-bottom: 15px;
|
||||
}
|
||||
|
||||
.form-row.full-width {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
|
||||
.form-group {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
@@ -47,7 +95,8 @@
|
||||
}
|
||||
|
||||
.form-group input,
|
||||
.form-group select {
|
||||
.form-group select,
|
||||
.form-group textarea {
|
||||
padding: 10px;
|
||||
border: 1px solid #ddd;
|
||||
border-radius: 4px;
|
||||
@@ -55,7 +104,8 @@
|
||||
}
|
||||
|
||||
.form-group input:focus,
|
||||
.form-group select:focus {
|
||||
.form-group select:focus,
|
||||
.form-group textarea:focus {
|
||||
outline: none;
|
||||
border-color: #007bff;
|
||||
box-shadow: 0 0 5px rgba(0, 123, 255, 0.3);
|
||||
@@ -65,14 +115,16 @@
|
||||
display: flex;
|
||||
gap: 10px;
|
||||
justify-content: flex-end;
|
||||
margin-top: 10px;
|
||||
}
|
||||
|
||||
.form-actions button {
|
||||
.form-actions button, .form-actions a {
|
||||
padding: 10px 20px;
|
||||
border: none;
|
||||
border-radius: 4px;
|
||||
cursor: pointer;
|
||||
font-weight: 600;
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
.btn-save {
|
||||
@@ -126,15 +178,18 @@
|
||||
.card-actions {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.btn-edit, .btn-delete {
|
||||
.btn-edit, .btn-delete, .btn-export {
|
||||
padding: 6px 12px;
|
||||
border: none;
|
||||
border-radius: 4px;
|
||||
cursor: pointer;
|
||||
font-size: 13px;
|
||||
font-weight: 600;
|
||||
text-decoration: none;
|
||||
display: inline-block;
|
||||
}
|
||||
|
||||
.btn-edit {
|
||||
@@ -164,9 +219,6 @@
|
||||
font-weight: 600;
|
||||
text-decoration: none;
|
||||
display: inline-block;
|
||||
}
|
||||
|
||||
.btn-print {
|
||||
background: #17a2b8;
|
||||
color: white;
|
||||
}
|
||||
@@ -188,6 +240,7 @@
|
||||
display: flex;
|
||||
gap: 10px;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.empty-state {
|
||||
@@ -201,6 +254,12 @@
|
||||
margin: 10px 0;
|
||||
}
|
||||
|
||||
@media (max-width: 992px) {
|
||||
.dashboard-grid {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
.form-row {
|
||||
grid-template-columns: 1fr;
|
||||
@@ -222,14 +281,16 @@
|
||||
|
||||
.card-actions {
|
||||
flex-direction: column;
|
||||
align-items: stretch;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
|
||||
<div class="container">
|
||||
<!-- Header mit Aktionen -->
|
||||
<div class="student-card-header">
|
||||
<div>
|
||||
<h1>📚 Bibliotheksausweise (Bibliothek)</h1>
|
||||
<h1 style="margin: 0;">📚 Bibliotheksausweise</h1>
|
||||
</div>
|
||||
<div class="export-buttons">
|
||||
<form method="GET" action="{{ url_for('student_card_class_barcode_download') }}" style="display: inline-flex; gap: 5px; align-items: center; background: white; padding: 2px; border-radius: 4px; border: 1px solid #ddd;">
|
||||
@@ -239,7 +300,7 @@
|
||||
<option value="{{ cls }}">{{ cls }}</option>
|
||||
{% endfor %}
|
||||
</select>
|
||||
<button type="submit" class="btn-print" style="background: #17a2b8; padding: 8px 12px; margin: 0;">📤 PDF</button>
|
||||
<button type="submit" class="btn-print" style="padding: 8px 12px; margin: 0;">📤 PDF</button>
|
||||
</form>
|
||||
|
||||
<a href="{{ url_for('student_card_barcode_download') }}" class="btn-print" style="background: #28a745;">📥 Alle Ausweise (PDF)</a>
|
||||
@@ -247,81 +308,118 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div style="border:1px solid #dbe4ee; border-radius:8px; padding:14px; margin-bottom:16px; background:#f8fbff;">
|
||||
<h3 style="margin:0 0 8px 0;">Excel-Import Bibliotheksausweise</h3>
|
||||
<p style="margin:0 0 10px 0; color:#555;">Laden Sie eine <strong>.xlsx</strong>- oder <strong>.csv</strong>-Datei hoch, zum Beispiel aus <strong>ASV (Amtliche Schuldaten)</strong>. Erkannt werden automatisch Spalten wie <strong>Name</strong>, <strong>Klasse</strong>, <strong>Ausweis-ID</strong>, <strong>Notizen</strong> und <strong>Standard-Ausleihdauer</strong>. Fehlt die Ausweis-ID, wird sie automatisch aus Name und Klasse erzeugt.</p>
|
||||
<form method="POST" action="{{ url_for('upload_student_cards_excel') }}" enctype="multipart/form-data" style="display:flex; gap:10px; flex-wrap:wrap; align-items:center;">
|
||||
<input type="file" name="student_cards_excel" accept=".xlsx,.csv" required>
|
||||
<button type="submit" class="btn btn-secondary" name="excel_action" value="validate">Nur validieren</button>
|
||||
<button type="submit" class="btn btn-primary" name="excel_action" value="import">Ausweise importieren</button>
|
||||
</form>
|
||||
</div>
|
||||
<!-- Hauptbereich Grid: Formular + Import -->
|
||||
<div class="dashboard-grid">
|
||||
<!-- Add/Edit Form -->
|
||||
<div class="student-card-form">
|
||||
<h2 style="margin-top:0;">{% if edit_mode %}Ausweis bearbeiten{% else %}Neuer Bibliotheksausweis{% endif %}</h2>
|
||||
|
||||
<!-- Add/Edit Form -->
|
||||
<div class="student-card-form">
|
||||
<h2>{% if edit_mode %}Ausweis bearbeiten{% else %}Neuer Bibliotheksausweis{% endif %}</h2>
|
||||
|
||||
<form method="POST" action="{{ url_for('student_cards_admin') }}">
|
||||
{% if edit_mode %}
|
||||
<input type="hidden" name="action" value="edit">
|
||||
<input type="hidden" name="card_id" value="{{ form_data.get('card_id', '') }}">
|
||||
{% else %}
|
||||
<input type="hidden" name="action" value="add">
|
||||
{% endif %}
|
||||
|
||||
<div class="form-row">
|
||||
<div class="form-group">
|
||||
<label for="ausweis_id">Ausweis-ID *</label>
|
||||
<input type="text" id="ausweis_id" name="ausweis_id" required
|
||||
value="{{ form_data.get('ausweis_id', '') }}"
|
||||
placeholder="z.B. SIS2024001">
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label for="student_name">Schüler Name *</label>
|
||||
<input type="text" id="student_name" name="student_name" required
|
||||
value="{{ form_data.get('student_name', '') }}"
|
||||
placeholder="z.B. Max Mustermann">
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="form-row">
|
||||
<div class="form-group">
|
||||
<label for="default_borrow_days">Standard Ausleihdauer (Tage) *</label>
|
||||
<input type="number" id="default_borrow_days" name="default_borrow_days"
|
||||
min="1" max="365" required
|
||||
value="{{ form_data.get('default_borrow_days', config.get('default', 14)) }}">
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label for="class_name">Klasse</label>
|
||||
<input type="text" id="class_name" name="class_name"
|
||||
value="{{ form_data.get('class_name', '') }}"
|
||||
placeholder="z.B. 10A">
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="form-row">
|
||||
<div class="form-group">
|
||||
<label for="notes">Notizen</label>
|
||||
<textarea id="notes" name="notes" rows="3"
|
||||
placeholder="Optionale Notizen..."
|
||||
style="padding: 10px; border: 1px solid #ddd; border-radius: 4px;">{{ form_data.get('notes', '') }}</textarea>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="form-actions">
|
||||
<form method="POST" action="{{ url_for('student_cards_admin') }}">
|
||||
{% if edit_mode %}
|
||||
<a href="{{ url_for('student_cards_admin') }}" class="btn-cancel">Abbrechen</a>
|
||||
<input type="hidden" name="action" value="edit">
|
||||
<input type="hidden" name="card_id" value="{{ form_data.get('card_id', '') }}">
|
||||
{% else %}
|
||||
<input type="hidden" name="action" value="add">
|
||||
{% endif %}
|
||||
<button type="submit" class="btn-save">
|
||||
{% if edit_mode %}Speichern{% else %}Hinzufügen{% endif %}
|
||||
</button>
|
||||
|
||||
<div class="form-row">
|
||||
<div class="form-group">
|
||||
<label for="student_name">Schüler Name *</label>
|
||||
<input type="text" id="student_name" name="student_name" required
|
||||
value="{{ form_data.get('student_name', '') }}"
|
||||
placeholder="z.B. Max Mustermann">
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label for="class_name">Klasse</label>
|
||||
<input type="text" id="class_name" name="class_name" list="class_list"
|
||||
value="{{ form_data.get('class_name', '') }}"
|
||||
placeholder="z.B. 10A (Tippen oder Auswählen)">
|
||||
|
||||
<datalist id="class_list">
|
||||
{% for cls in available_classes %}
|
||||
<option value="{{ cls }}">
|
||||
{% endfor %}
|
||||
</datalist>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="form-row">
|
||||
<div class="form-group">
|
||||
<label for="ausweis_id">Ausweis-ID</label>
|
||||
<input type="text" id="ausweis_id" name="ausweis_id"
|
||||
value="{{ form_data.get('ausweis_id', '') }}"
|
||||
placeholder="z.B. SIS2024001">
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label for="ausweis_ident">Lokales Differenzierungsmerkmal</label>
|
||||
<input type="text" id="ausweis_ident" name="ausweis_ident"
|
||||
value="{{ form_data.get('ausweis_ident', '') }}"
|
||||
placeholder="z.B. xw5oo123bbe">
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="form-row">
|
||||
<div class="form-group">
|
||||
<label for="default_borrow_days">Standard Ausleihdauer (Tage) *</label>
|
||||
<input type="number" id="default_borrow_days" name="default_borrow_days"
|
||||
min="1" max="365" required
|
||||
value="{{ form_data.get('default_borrow_days', config.get('default', 14)) }}">
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="form-row full-width">
|
||||
<div class="form-group">
|
||||
<label for="notes">Notizen</label>
|
||||
<textarea id="notes" name="notes" rows="2"
|
||||
placeholder="Optionale Notizen...">{{ form_data.get('notes', '') }}</textarea>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="form-actions">
|
||||
{% if edit_mode %}
|
||||
<a href="{{ url_for('student_cards_admin') }}" class="btn-cancel">Abbrechen</a>
|
||||
{% endif %}
|
||||
<button type="submit" class="btn-save">
|
||||
{% if edit_mode %}Speichern{% else %}Hinzufügen{% endif %}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
<!-- Excel-Import mit Abgleich (Rollover-Modus) -->
|
||||
<div class="import-card">
|
||||
<div>
|
||||
<h3 style="margin:0 0 8px 0;">Excel-Import</h3>
|
||||
<p style="margin:0 0 12px 0; color:#555; font-size:13px; line-height:1.4;">
|
||||
Laden Sie eine <strong>.xlsx</strong>- oder <strong>.csv</strong>-Datei hoch (z. B. aus <strong>ASV</strong>). Erkannt werden Name, Nachname, Klasse, Ausweis-ID, lokales Differenzierungsmerkmal, Notizen & Ausleihdauer.
|
||||
</p>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
<form method="POST" action="{{ url_for('upload_student_cards_excel') }}" enctype="multipart/form-data" style="display:flex; flex-direction:column; gap:12px;">
|
||||
<input type="file" name="student_cards_excel" accept=".xlsx,.csv" required style="font-size:13px;">
|
||||
|
||||
<!-- Rollover / Abgleich Option -->
|
||||
<div class="rollover-box">
|
||||
<label class="rollover-label">
|
||||
<input type="checkbox" name="rollover_mode" value="true">
|
||||
<span>Rollover-Modus (Abgleich / Destruktiv)</span>
|
||||
</label>
|
||||
<span class="rollover-hint">
|
||||
⚠️ <strong>Warnung:</strong> Nicht mehr vorhandene Ausweise/Schüler werden beim Import entfernt bzw. abgeglichen.
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div style="display:flex; gap:8px;">
|
||||
<button type="submit" class="btn btn-secondary" name="excel_action" value="validate" style="flex:1;">Validieren</button>
|
||||
<button type="submit" class="btn btn-primary" name="excel_action" value="import" style="flex:1;">Importieren</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Cards List -->
|
||||
<div>
|
||||
<h2>Registrierte Ausweise</h2>
|
||||
<h2 style="margin-bottom: 15px;">Registrierte Ausweise</h2>
|
||||
{% if student_cards %}
|
||||
<table class="cards-table">
|
||||
<thead>
|
||||
@@ -348,7 +446,7 @@
|
||||
<input type="hidden" name="edit" value="{{ card._id }}">
|
||||
<button type="submit" class="btn-edit">Bearbeiten</button>
|
||||
</form>
|
||||
<a href="{{ url_for('student_card_single_barcode_download', card_id=card._id) }}" class="btn-export" style="text-decoration: none; display: inline-block;">📥 PDF</a>
|
||||
<a href="{{ url_for('student_card_single_barcode_download', card_id=card._id) }}" class="btn-export">📥 PDF</a>
|
||||
<form method="POST" style="display: inline;" onsubmit="return confirm('Wirklich löschen?');">
|
||||
<input type="hidden" name="action" value="delete">
|
||||
<input type="hidden" name="card_id" value="{{ card._id }}">
|
||||
@@ -374,5 +472,4 @@
|
||||
// All PDF exports now go through backend routes
|
||||
</script>
|
||||
|
||||
{% endblock %}
|
||||
|
||||
{% endblock %}
|
||||
@@ -876,12 +876,14 @@
|
||||
</div>
|
||||
|
||||
|
||||
<!-- Image upload -->
|
||||
<div class="form-group">
|
||||
<label for="images">Bilder:</label>
|
||||
<label>Buchcover (automatisch):</label>
|
||||
<div id="book-cover-preview-container"></div>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label for="images"> Bilder hinzufügen:</label>
|
||||
<input type="file" id="images" name="images" accept=".jpg, .jpeg, .png, .gif" multiple>
|
||||
<div class="allowed-formats">Erlaubte Formate: JPG, JPEG, PNG, GIF</div>
|
||||
<!-- Add image preview area -->
|
||||
<div class="image-preview-container" id="image-preview-container"></div>
|
||||
</div>
|
||||
|
||||
@@ -1669,23 +1671,24 @@
|
||||
}, 3000);
|
||||
}
|
||||
|
||||
// Function to download book cover image
|
||||
function downloadBookCover(imageUrl) {
|
||||
if (!imageUrl) {
|
||||
console.log('No image URL provided');
|
||||
return;
|
||||
}
|
||||
|
||||
// Show loading indicator for image download
|
||||
const imagePreviewContainer = document.getElementById('image-preview-container');
|
||||
if (imagePreviewContainer) {
|
||||
const loadingDiv = document.createElement('div');
|
||||
loadingDiv.className = 'image-loading';
|
||||
loadingDiv.innerHTML = '<div class="loading-spinner">Buchcover wird heruntergeladen...</div>';
|
||||
imagePreviewContainer.appendChild(loadingDiv);
|
||||
|
||||
const coverPreviewContainer = document.getElementById('book-cover-preview-container');
|
||||
|
||||
if (!coverPreviewContainer) {
|
||||
console.error('Error: "book-cover-preview-container" not found in the DOM.');
|
||||
return;
|
||||
}
|
||||
|
||||
// Download the image via backend
|
||||
|
||||
const loadingDiv = document.createElement('div');
|
||||
loadingDiv.className = 'image-loading';
|
||||
loadingDiv.innerHTML = '<div class="loading-spinner">Buchcover wird heruntergeladen...</div>';
|
||||
coverPreviewContainer.appendChild(loadingDiv);
|
||||
|
||||
fetch('/download_book_cover', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
@@ -1693,78 +1696,63 @@
|
||||
},
|
||||
body: JSON.stringify({ url: imageUrl })
|
||||
})
|
||||
.then(response => response.json())
|
||||
.then(data => {
|
||||
// Remove loading indicator
|
||||
const loadingDiv = imagePreviewContainer?.querySelector('.image-loading');
|
||||
if (loadingDiv) {
|
||||
loadingDiv.remove();
|
||||
}
|
||||
|
||||
if (data.success) {
|
||||
// Create a preview of the downloaded image
|
||||
const imagePreview = document.createElement('div');
|
||||
imagePreview.className = 'book-cover-preview';
|
||||
imagePreview.innerHTML = `
|
||||
<div class="preview-item">
|
||||
<img src="{{ url_for('uploaded_file', filename='') }}${data.filename}"
|
||||
alt="Buchcover" class="book-cover-thumbnail">
|
||||
<p class="book-cover-caption">Buchcover automatisch heruntergeladen</p>
|
||||
<input type="hidden" name="book_cover_image" value="${data.filename}">
|
||||
<button type="button" onclick="removeBookCover(this)"
|
||||
class="remove-book-cover-button">
|
||||
Entfernen
|
||||
</button>
|
||||
</div>
|
||||
`;
|
||||
|
||||
if (imagePreviewContainer) {
|
||||
imagePreviewContainer.appendChild(imagePreview);
|
||||
.then(response => response.json())
|
||||
.then(data => {
|
||||
const currentLoadingDiv = coverPreviewContainer.querySelector('.image-loading');
|
||||
if (currentLoadingDiv) {
|
||||
currentLoadingDiv.remove();
|
||||
}
|
||||
|
||||
console.log('Book cover downloaded successfully:', data.filename);
|
||||
} else {
|
||||
console.error('Failed to download book cover:', data.error);
|
||||
// Show error message to user
|
||||
if (imagePreviewContainer) {
|
||||
const errorDiv = document.createElement('div');
|
||||
errorDiv.className = 'error-message';
|
||||
errorDiv.textContent = 'Fehler beim Herunterladen des Buchcovers: ' + data.error;
|
||||
errorDiv.style.fontSize = '0.8em';
|
||||
errorDiv.style.padding = '5px';
|
||||
errorDiv.style.marginTop = '5px';
|
||||
imagePreviewContainer.appendChild(errorDiv);
|
||||
|
||||
// Remove error message after 5 seconds
|
||||
setTimeout(() => errorDiv.remove(), 5000);
|
||||
|
||||
if (data.success) {
|
||||
coverPreviewContainer.innerHTML = '';
|
||||
|
||||
const imagePreview = document.createElement('div');
|
||||
imagePreview.className = 'book-cover-preview';
|
||||
imagePreview.innerHTML = `
|
||||
<div class="preview-item">
|
||||
<img src="/uploads/${data.filename}"
|
||||
alt="Buchcover" class="book-cover-thumbnail" style="max-width: 150px; border-radius: 4px;">
|
||||
<p class="book-cover-caption" style="font-size: 0.9em; color: #555;">Buchcover automatisch heruntergeladen</p>
|
||||
<input type="hidden" name="book_cover_image" value="${data.filename}">
|
||||
<button type="button" onclick="removeBookCover(this)"
|
||||
class="remove-book-cover-button btn btn-sm btn-danger">
|
||||
Entfernen
|
||||
</button>
|
||||
</div>
|
||||
`;
|
||||
|
||||
coverPreviewContainer.appendChild(imagePreview);
|
||||
console.log('Book cover downloaded successfully:', data.filename);
|
||||
} else {
|
||||
console.error('Failed to download book cover:', data.error);
|
||||
showCoverError(coverPreviewContainer, 'Fehler beim Herunterladen des Buchcovers: ' + data.error);
|
||||
}
|
||||
}
|
||||
})
|
||||
.catch(error => {
|
||||
console.error('Error downloading book cover:', error);
|
||||
// Remove loading indicator
|
||||
const loadingDiv = imagePreviewContainer?.querySelector('.image-loading');
|
||||
if (loadingDiv) {
|
||||
loadingDiv.remove();
|
||||
}
|
||||
|
||||
// Show error message
|
||||
if (imagePreviewContainer) {
|
||||
const errorDiv = document.createElement('div');
|
||||
errorDiv.className = 'error-message';
|
||||
errorDiv.textContent = 'Netzwerkfehler beim Herunterladen des Buchcovers';
|
||||
errorDiv.style.fontSize = '0.8em';
|
||||
errorDiv.style.padding = '5px';
|
||||
errorDiv.style.marginTop = '5px';
|
||||
imagePreviewContainer.appendChild(errorDiv);
|
||||
|
||||
// Remove error message after 5 seconds
|
||||
setTimeout(() => errorDiv.remove(), 5000);
|
||||
}
|
||||
});
|
||||
})
|
||||
.catch(error => {
|
||||
console.error('Error downloading book cover:', error);
|
||||
|
||||
const currentLoadingDiv = coverPreviewContainer.querySelector('.image-loading');
|
||||
if (currentLoadingDiv) {
|
||||
currentLoadingDiv.remove();
|
||||
}
|
||||
|
||||
showCoverError(coverPreviewContainer, 'Netzwerkfehler beim Herunterladen des Buchcovers');
|
||||
});
|
||||
}
|
||||
|
||||
// Function to remove downloaded book cover
|
||||
|
||||
function showCoverError(container, message) {
|
||||
const errorDiv = document.createElement('div');
|
||||
errorDiv.className = 'error-message';
|
||||
errorDiv.textContent = message;
|
||||
errorDiv.style.fontSize = '0.8em';
|
||||
errorDiv.style.color = 'red';
|
||||
errorDiv.style.padding = '5px';
|
||||
errorDiv.style.marginTop = '5px';
|
||||
container.appendChild(errorDiv);
|
||||
|
||||
setTimeout(() => errorDiv.remove(), 5000);
|
||||
}
|
||||
|
||||
function removeBookCover(button) {
|
||||
const previewItem = button.closest('.preview-item');
|
||||
if (previewItem) {
|
||||
@@ -1772,7 +1760,6 @@
|
||||
}
|
||||
}
|
||||
|
||||
// Code validation functions
|
||||
function checkCodeUnique(code, excludeId, callback) {
|
||||
if (!code || code.trim() === '') {
|
||||
callback(true);
|
||||
|
||||
Reference in New Issue
Block a user