Compare commits
13 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| b94fb1cd97 | |||
| ce20f569a3 | |||
| ec7f32994c | |||
| 8358bf257f | |||
| 193495d6a2 | |||
| 5afcaa5e19 | |||
| 3aa44b64b8 | |||
| 86d8f19313 | |||
| e74798f252 | |||
| 31c3d700a8 | |||
| a3c114e4b5 | |||
| 170a2a53ab | |||
| a8ac08d5b0 |
+1
-1
@@ -32,4 +32,4 @@ RUN if [ "$NUITKA_BUILD" = "1" ]; then \
|
||||
WORKDIR /app/Web
|
||||
EXPOSE 8000
|
||||
|
||||
CMD ["gunicorn", "app:app", "--bind", "0.0.0.0:8000", "--workers", "3", "--timeout", "60", "--graceful-timeout", "20", "--max-requests", "1000", "--max-requests-jitter", "100", "--log-level", "info", "--access-logfile", "-", "--error-logfile", "-"]
|
||||
CMD ["gunicorn", "app:app", "--bind", "0.0.0.0:8000", "--workers", "2", "--timeout", "30", "--graceful-timeout", "20", "--max-requests", "200", "--max-requests-jitter", "50", "--log-level", "info", "--access-logfile", "-", "--error-logfile", "-"]
|
||||
|
||||
+2
-1
@@ -6,9 +6,10 @@ The latest version will allways be supported the rest are old version that are n
|
||||
|
||||
| Version | Supported |
|
||||
| ------- | ------------------ |
|
||||
| 0.2.17 | ✅ |
|
||||
| 3.2.x | :white_check_mark: |
|
||||
| 3.1.x | :x: |
|
||||
| 3.0.x | :white_check_mark: |
|
||||
| 3.0.x | :x: |
|
||||
| 2.6.x | :x: |
|
||||
| 2.4.x | :x: |
|
||||
| 1.8.x | :x: |
|
||||
|
||||
+610
-78
@@ -27,6 +27,7 @@ Features:
|
||||
|
||||
from flask import Flask, render_template, request, redirect, url_for, session, flash, send_from_directory, get_flashed_messages, jsonify, Response, make_response, send_file
|
||||
from werkzeug.utils import secure_filename
|
||||
from werkzeug.middleware.proxy_fix import ProxyFix
|
||||
import user as us
|
||||
import items as it
|
||||
import ausleihung as au
|
||||
@@ -44,6 +45,7 @@ import traceback
|
||||
import re
|
||||
import io
|
||||
import html
|
||||
import logging
|
||||
# QR Code functionality deactivated
|
||||
# import qrcode
|
||||
# from qrcode.constants import ERROR_CORRECT_L
|
||||
@@ -62,13 +64,34 @@ from settings import MongoClient
|
||||
|
||||
|
||||
app = Flask(__name__, static_folder='static') # Correctly set static folder
|
||||
app.logger.setLevel(logging.WARNING)
|
||||
app.secret_key = cfg.SECRET_KEY
|
||||
app.debug = cfg.DEBUG
|
||||
app.config['UPLOAD_FOLDER'] = cfg.UPLOAD_FOLDER
|
||||
app.config['THUMBNAIL_FOLDER'] = cfg.THUMBNAIL_FOLDER
|
||||
app.config['PREVIEW_FOLDER'] = cfg.PREVIEW_FOLDER
|
||||
app.config['ALLOWED_EXTENSIONS'] = set(cfg.ALLOWED_EXTENSIONS)
|
||||
app.config['MAX_CONTENT_LENGTH'] = max(cfg.MAX_UPLOAD_MB, cfg.IMAGE_MAX_UPLOAD_MB, cfg.VIDEO_MAX_UPLOAD_MB) * 1024 * 1024
|
||||
app.config['SESSION_COOKIE_HTTPONLY'] = True
|
||||
app.config['SESSION_COOKIE_SAMESITE'] = 'Lax'
|
||||
app.config['SESSION_COOKIE_SECURE'] = cfg.SSL_ENABLED if os.getenv('INVENTAR_SESSION_COOKIE_SECURE') is None else os.getenv('INVENTAR_SESSION_COOKIE_SECURE', '').strip().lower() in ('1', 'true', 'yes', 'on')
|
||||
app.config['PREFERRED_URL_SCHEME'] = 'https' if app.config['SESSION_COOKIE_SECURE'] else 'http'
|
||||
# app.config['QR_CODE_FOLDER'] = cfg.QR_CODE_FOLDER # QR Code storage deactivated
|
||||
app.wsgi_app = ProxyFix(app.wsgi_app, x_for=1, x_proto=1, x_host=1, x_port=1)
|
||||
|
||||
|
||||
def print(*args, **kwargs):
|
||||
if not args:
|
||||
return None
|
||||
|
||||
message = " ".join(str(arg) for arg in args)
|
||||
stripped = message.lstrip()
|
||||
if stripped.startswith(('Error', 'Fehler', 'Warning', 'Warnung', '[WARN]', '[KONFLIKT]', 'Failed', 'Fehl')):
|
||||
app.logger.warning(message)
|
||||
elif stripped.startswith(('Exception', 'Traceback')):
|
||||
app.logger.error(message)
|
||||
else:
|
||||
app.logger.info(message)
|
||||
|
||||
# Thumbnail sizes
|
||||
THUMBNAIL_SIZE = cfg.THUMBNAIL_SIZE
|
||||
@@ -96,6 +119,16 @@ APP_VERSION = __version__
|
||||
RELEASE_STATE_FILE = os.path.join(os.path.dirname(BASE_DIR), '.release-version')
|
||||
|
||||
|
||||
@app.after_request
|
||||
def _set_security_headers(response):
|
||||
response.headers.setdefault('X-Content-Type-Options', 'nosniff')
|
||||
response.headers.setdefault('X-Frame-Options', 'SAMEORIGIN')
|
||||
response.headers.setdefault('Referrer-Policy', 'strict-origin-when-cross-origin')
|
||||
if cfg.SSL_ENABLED:
|
||||
response.headers.setdefault('Strict-Transport-Security', 'max-age=31536000; includeSubDomains')
|
||||
return response
|
||||
|
||||
|
||||
def _get_asset_version():
|
||||
"""Return a cache-busting asset version tied to deployment state."""
|
||||
env_version = os.getenv('INVENTAR_ASSET_VERSION', '').strip()
|
||||
@@ -436,17 +469,183 @@ def _prepare_invoice_pdf_payload(invoice_data, borrow_doc=None, item_doc=None):
|
||||
'amount_text': amount_text or '-',
|
||||
}
|
||||
|
||||
|
||||
def _create_notification(db, *, audience, notif_type, title, message, target_user=None, reference=None, unique_key=None, severity='info'):
|
||||
"""Create a notification entry with optional deduplication via unique_key."""
|
||||
notifications_col = db['notifications']
|
||||
|
||||
if unique_key:
|
||||
existing = notifications_col.find_one({'UniqueKey': unique_key}, {'_id': 1})
|
||||
if existing:
|
||||
return False
|
||||
|
||||
now = datetime.datetime.now()
|
||||
payload = {
|
||||
'Audience': audience,
|
||||
'Type': notif_type,
|
||||
'Title': title,
|
||||
'Message': message,
|
||||
'TargetUser': target_user,
|
||||
'Reference': reference or {},
|
||||
'UniqueKey': unique_key,
|
||||
'Severity': severity,
|
||||
'ReadBy': [],
|
||||
'CreatedAt': now,
|
||||
'UpdatedAt': now,
|
||||
}
|
||||
notifications_col.insert_one(payload)
|
||||
return True
|
||||
|
||||
|
||||
def _get_notifications_for_user(db, username, is_admin=False, limit=150):
|
||||
"""Fetch notifications visible to the current user, newest first."""
|
||||
query = {
|
||||
'$or': [
|
||||
{'Audience': 'user', 'TargetUser': username},
|
||||
]
|
||||
}
|
||||
if is_admin:
|
||||
query['$or'].append({'Audience': 'admin'})
|
||||
|
||||
cursor = db['notifications'].find(query).sort('CreatedAt', -1).limit(limit)
|
||||
return list(cursor)
|
||||
|
||||
|
||||
def _get_unread_notification_count(db, username, is_admin=False):
|
||||
"""Count unread notifications for navbar badge rendering."""
|
||||
query = {
|
||||
'$and': [
|
||||
{
|
||||
'$or': [
|
||||
{'Audience': 'user', 'TargetUser': username},
|
||||
]
|
||||
},
|
||||
{'ReadBy': {'$ne': username}},
|
||||
]
|
||||
}
|
||||
if is_admin:
|
||||
query['$and'][0]['$or'].append({'Audience': 'admin'})
|
||||
|
||||
return db['notifications'].count_documents(query)
|
||||
|
||||
|
||||
def _build_reminder_message(item_name, start_dt=None, end_dt=None):
|
||||
"""Build a concise reminder text for borrowed items."""
|
||||
start_text = start_dt.strftime('%d.%m.%Y %H:%M') if isinstance(start_dt, datetime.datetime) else '-'
|
||||
end_text = end_dt.strftime('%d.%m.%Y %H:%M') if isinstance(end_dt, datetime.datetime) else '-'
|
||||
return (
|
||||
f"Bitte denke an die Rueckgabe von '{item_name}'. "
|
||||
f"Ausleihe seit: {start_text}. "
|
||||
f"Geplantes Ende: {end_text}."
|
||||
)
|
||||
|
||||
|
||||
def create_return_reminders():
|
||||
"""Create one-time reminders for day-1 and planned-end events."""
|
||||
now = datetime.datetime.now()
|
||||
one_day_ago = now - datetime.timedelta(days=1)
|
||||
|
||||
client = None
|
||||
try:
|
||||
client = MongoClient(MONGODB_HOST, MONGODB_PORT)
|
||||
db = client[MONGODB_DB]
|
||||
ausleihungen_col = db['ausleihungen']
|
||||
items_col = db['items']
|
||||
|
||||
candidates = list(ausleihungen_col.find(
|
||||
{
|
||||
'Status': {'$in': ['active', 'planned']},
|
||||
'User': {'$exists': True, '$ne': ''},
|
||||
'$or': [
|
||||
{'Start': {'$lte': one_day_ago}},
|
||||
{'End': {'$lte': now}},
|
||||
]
|
||||
},
|
||||
{'User': 1, 'Item': 1, 'Status': 1, 'Start': 1, 'End': 1}
|
||||
))
|
||||
|
||||
item_ids = []
|
||||
for entry in candidates:
|
||||
item_id = entry.get('Item')
|
||||
if item_id:
|
||||
item_ids.append(item_id)
|
||||
|
||||
item_docs = {}
|
||||
for raw_id in item_ids:
|
||||
try:
|
||||
doc = items_col.find_one({'_id': ObjectId(raw_id)}, {'Name': 1, 'Code_4': 1})
|
||||
if doc:
|
||||
item_docs[raw_id] = doc
|
||||
except Exception:
|
||||
continue
|
||||
|
||||
for borrow_doc in candidates:
|
||||
borrow_id = str(borrow_doc.get('_id'))
|
||||
username = str(borrow_doc.get('User', '')).strip()
|
||||
if not borrow_id or not username:
|
||||
continue
|
||||
|
||||
item_id = str(borrow_doc.get('Item', '')).strip()
|
||||
item_doc = item_docs.get(item_id, {})
|
||||
item_name = item_doc.get('Name') or f'Item {item_id}'
|
||||
|
||||
start_dt = borrow_doc.get('Start')
|
||||
end_dt = borrow_doc.get('End')
|
||||
|
||||
if isinstance(start_dt, datetime.datetime) and start_dt <= one_day_ago:
|
||||
_create_notification(
|
||||
db,
|
||||
audience='user',
|
||||
notif_type='return_day_1',
|
||||
title='Erinnerung: Rueckgabe nach 1 Tag',
|
||||
message=_build_reminder_message(item_name, start_dt=start_dt, end_dt=end_dt),
|
||||
target_user=username,
|
||||
reference={'borrow_id': borrow_id, 'item_id': item_id, 'event': 'day_1'},
|
||||
unique_key=f'reminder:day1:{borrow_id}',
|
||||
severity='warning',
|
||||
)
|
||||
|
||||
if isinstance(end_dt, datetime.datetime) and end_dt <= now:
|
||||
_create_notification(
|
||||
db,
|
||||
audience='user',
|
||||
notif_type='return_after_end',
|
||||
title='Erinnerung: Geplante Ausleihe ist beendet',
|
||||
message=_build_reminder_message(item_name, start_dt=start_dt, end_dt=end_dt),
|
||||
target_user=username,
|
||||
reference={'borrow_id': borrow_id, 'item_id': item_id, 'event': 'after_end'},
|
||||
unique_key=f'reminder:end:{borrow_id}',
|
||||
severity='warning',
|
||||
)
|
||||
except Exception as exc:
|
||||
app.logger.warning(f"Reminder creation failed: {exc}")
|
||||
finally:
|
||||
if client:
|
||||
client.close()
|
||||
|
||||
@app.context_processor
|
||||
def inject_version():
|
||||
"""Inject global template variables."""
|
||||
is_admin = False
|
||||
asset_version = _get_asset_version()
|
||||
unread_notification_count = 0
|
||||
if 'username' in session:
|
||||
try:
|
||||
is_admin = us.check_admin(session['username'])
|
||||
except Exception:
|
||||
is_admin = False
|
||||
|
||||
client = None
|
||||
try:
|
||||
client = MongoClient(MONGODB_HOST, MONGODB_PORT)
|
||||
db = client[MONGODB_DB]
|
||||
unread_notification_count = _get_unread_notification_count(db, session['username'], is_admin=is_admin)
|
||||
except Exception:
|
||||
unread_notification_count = 0
|
||||
finally:
|
||||
if client:
|
||||
client.close()
|
||||
|
||||
current_module = _get_current_module(request.path)
|
||||
|
||||
return {
|
||||
@@ -456,7 +655,8 @@ def inject_version():
|
||||
'school_periods': SCHOOL_PERIODS,
|
||||
'library_module_enabled': cfg.LIBRARY_MODULE_ENABLED,
|
||||
'student_cards_module_enabled': cfg.STUDENT_CARDS_MODULE_ENABLED,
|
||||
'is_admin': is_admin
|
||||
'is_admin': is_admin,
|
||||
'unread_notification_count': unread_notification_count,
|
||||
}
|
||||
|
||||
# Create necessary directories at startup
|
||||
@@ -486,14 +686,11 @@ def create_daily_backup():
|
||||
Erstellt täglich ein Backup der Ausleihungsdatenbank
|
||||
"""
|
||||
try:
|
||||
print(f"[{datetime.datetime.now()}] Erstelle Backup der Ausleihungsdatenbank...")
|
||||
result = au.create_backup_database()
|
||||
if result:
|
||||
print(f"[{datetime.datetime.now()}] Backup erfolgreich erstellt")
|
||||
else:
|
||||
print(f"[{datetime.datetime.now()}] Fehler beim Erstellen des Backups")
|
||||
if not result:
|
||||
app.logger.warning("Daily backup creation returned false")
|
||||
except Exception as e:
|
||||
print(f"[{datetime.datetime.now()}] Ausnahme beim Erstellen des Backups: {str(e)}")
|
||||
app.logger.error(f"Daily backup creation failed: {e}")
|
||||
|
||||
def update_appointment_statuses():
|
||||
"""
|
||||
@@ -503,17 +700,8 @@ def update_appointment_statuses():
|
||||
- Aktive Termine, die beendet werden sollten
|
||||
"""
|
||||
current_time = datetime.datetime.now()
|
||||
# Prepare logging early so it's available in exception paths
|
||||
log_dir = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'logs')
|
||||
os.makedirs(log_dir, exist_ok=True)
|
||||
log_file = os.path.join(log_dir, 'scheduler.log')
|
||||
|
||||
try:
|
||||
with open(log_file, 'a', encoding='utf-8') as f:
|
||||
f.write(f"[{current_time}] Starte automatische Statusaktualisierung...\n")
|
||||
|
||||
print(f"[{current_time}] Starte automatische Statusaktualisierung...")
|
||||
|
||||
# Hole alle Termine mit Status 'planned' oder 'active'
|
||||
client = MongoClient(MONGODB_HOST, MONGODB_PORT)
|
||||
db = client[MONGODB_DB]
|
||||
@@ -575,16 +763,15 @@ def update_appointment_statuses():
|
||||
f" [KONFLIKT] Termin {appointment['_id']}: "
|
||||
f"planned → active, aber {conflict_note}"
|
||||
)
|
||||
print(conflict_log)
|
||||
with open(log_file, 'a', encoding='utf-8') as f:
|
||||
f.write(f"[{current_time}] {conflict_log}\n")
|
||||
app.logger.warning(conflict_log)
|
||||
else:
|
||||
# No conflict — clear any previously stored conflict flag
|
||||
extra_fields['ConflictDetected'] = False
|
||||
extra_fields['ConflictNote'] = ''
|
||||
except Exception as conflict_err:
|
||||
print(f" [WARN] Konfliktprüfung fehlgeschlagen für Termin "
|
||||
f"{appointment['_id']}: {conflict_err}")
|
||||
app.logger.warning(
|
||||
f"Conflict check failed for appointment {appointment['_id']}: {conflict_err}"
|
||||
)
|
||||
|
||||
result = ausleihungen.update_one(
|
||||
{'_id': appointment['_id']},
|
||||
@@ -602,43 +789,22 @@ def update_appointment_statuses():
|
||||
elif new_status == 'completed':
|
||||
completed_count += 1
|
||||
|
||||
log_msg = f" - Termin {appointment['_id']}: {old_status} → {new_status}"
|
||||
print(log_msg)
|
||||
with open(log_file, 'a', encoding='utf-8') as f:
|
||||
f.write(f"[{current_time}] {log_msg}\n")
|
||||
|
||||
client.close()
|
||||
|
||||
if updated_count > 0:
|
||||
result_msg = f"Statusaktualisierung abgeschlossen: {updated_count} Termine aktualisiert"
|
||||
detail_msg = f" - {activated_count} aktiviert, {completed_count} abgeschlossen"
|
||||
print(f"[{current_time}] {result_msg}")
|
||||
print(f"[{current_time}] {detail_msg}")
|
||||
with open(log_file, 'a', encoding='utf-8') as f:
|
||||
f.write(f"[{current_time}] {result_msg}\n")
|
||||
f.write(f"[{current_time}] {detail_msg}\n")
|
||||
else:
|
||||
result_msg = "Statusaktualisierung abgeschlossen: Keine Änderungen erforderlich"
|
||||
print(f"[{current_time}] {result_msg}")
|
||||
with open(log_file, 'a', encoding='utf-8') as f:
|
||||
f.write(f"[{current_time}] {result_msg}\n")
|
||||
app.logger.warning(
|
||||
f"Appointment status update finished: {updated_count} changed ({activated_count} active, {completed_count} completed)"
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
error_msg = f"Fehler bei der automatischen Statusaktualisierung: {str(e)}"
|
||||
print(f"[{datetime.datetime.now()}] {error_msg}")
|
||||
try:
|
||||
with open(log_file, 'a', encoding='utf-8') as f:
|
||||
f.write(f"[{datetime.datetime.now()}] {error_msg}\n")
|
||||
except Exception:
|
||||
pass
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
app.logger.error(f"Automatic appointment status update failed: {e}")
|
||||
|
||||
# Schedule jobs
|
||||
scheduler = BackgroundScheduler()
|
||||
if cfg.SCHEDULER_ENABLED:
|
||||
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.start()
|
||||
|
||||
# Register shutdown handler to stop scheduler when app is terminated
|
||||
@@ -1316,7 +1482,7 @@ def uploaded_file(filename):
|
||||
# Default placeholder from static folder
|
||||
return send_from_directory(app.static_folder, 'favicon.ico')
|
||||
except Exception as e:
|
||||
print(f"Error serving file {filename}: {str(e)}")
|
||||
app.logger.error(f"Error serving file {filename}: {str(e)}")
|
||||
return Response("Image not found", status=404)
|
||||
|
||||
|
||||
@@ -1351,7 +1517,7 @@ def thumbnail_file(filename):
|
||||
else:
|
||||
return send_from_directory(app.static_folder, 'favicon.ico')
|
||||
except Exception as e:
|
||||
print(f"Error serving thumbnail {filename}: {str(e)}")
|
||||
app.logger.error(f"Error serving thumbnail {filename}: {str(e)}")
|
||||
return Response("Thumbnail not found", status=404)
|
||||
|
||||
|
||||
@@ -1386,7 +1552,7 @@ def preview_file(filename):
|
||||
else:
|
||||
return send_from_directory(app.static_folder, 'favicon.ico')
|
||||
except Exception as e:
|
||||
print(f"Error serving preview {filename}: {str(e)}")
|
||||
app.logger.error(f"Error serving preview {filename}: {str(e)}")
|
||||
return Response("Preview not found", status=404)
|
||||
|
||||
|
||||
@@ -1849,7 +2015,7 @@ def api_library_items():
|
||||
'has_more': (offset + count) < total_count
|
||||
}), 200
|
||||
except Exception as e:
|
||||
print(f"Error fetching library items: {e}")
|
||||
app.logger.error(f"Error fetching library items: {e}")
|
||||
return jsonify({'error': str(e)}), 500
|
||||
|
||||
|
||||
@@ -2059,7 +2225,7 @@ def api_item_detail(item_id):
|
||||
"""
|
||||
return detail_html, 200
|
||||
except Exception as e:
|
||||
print(f"Error fetching item detail: {e}")
|
||||
app.logger.error(f"Error fetching item detail: {e}")
|
||||
return jsonify({'error': str(e)}), 500
|
||||
|
||||
|
||||
@@ -2162,11 +2328,6 @@ def upload_admin():
|
||||
try:
|
||||
original_item = it.get_item(duplicate_from)
|
||||
if original_item:
|
||||
# Enhanced debug logging for images
|
||||
images = original_item.get('Images', [])
|
||||
print(f"DEBUG: Original item: {original_item.get('_id')} has these images: {images}")
|
||||
print(f"DEBUG: Images type: {type(images)}, count: {len(images) if isinstance(images, list) else 'not a list'}")
|
||||
|
||||
duplicate_data = {
|
||||
'name': original_item.get('Name', ''),
|
||||
'description': original_item.get('Beschreibung', ''),
|
||||
@@ -2192,7 +2353,7 @@ def upload_admin():
|
||||
else:
|
||||
flash('Ursprungs-Element für Duplizierung nicht gefunden.', 'error')
|
||||
except Exception as e:
|
||||
print(f"Error loading item for duplication: {e}")
|
||||
app.logger.warning(f"Error loading item for duplication: {e}")
|
||||
flash('Fehler beim Laden der Duplizierungsdaten.', 'error')
|
||||
|
||||
# Handle the new method (sessionStorage-based duplication)
|
||||
@@ -2261,7 +2422,7 @@ def library_admin():
|
||||
else:
|
||||
flash('Ursprungs-Element für Duplizierung nicht gefunden.', 'error')
|
||||
except Exception as e:
|
||||
print(f"Error loading item for duplication: {e}")
|
||||
app.logger.warning(f"Error loading item for duplication: {e}")
|
||||
flash('Fehler beim Laden der Duplizierungsdaten.', 'error')
|
||||
elif duplicate_flag == 'true':
|
||||
flash('Buch wird dupliziert. Die Daten werden aus dem Session-Speicher geladen.', 'info')
|
||||
@@ -2282,7 +2443,7 @@ def library_admin():
|
||||
@app.route('/student_cards_admin', methods=['GET', 'POST'])
|
||||
def student_cards_admin():
|
||||
"""
|
||||
Admin page for managing student library cards (Schülerausweise).
|
||||
Admin page for managing student library cards (Bibliotheksausweis).
|
||||
Only accessible by admins and only when the student cards module is enabled.
|
||||
"""
|
||||
if 'username' not in session:
|
||||
@@ -2318,7 +2479,7 @@ def student_cards_admin():
|
||||
'notes': card.get('Notizen', '')
|
||||
}
|
||||
except Exception as e:
|
||||
print(f"Error loading student card for edit: {e}")
|
||||
app.logger.error(f"Error loading student card for edit: {e}")
|
||||
flash('Fehler beim Laden des Ausweises.', 'error')
|
||||
|
||||
# Handle POST request (add or edit)
|
||||
@@ -2336,7 +2497,7 @@ def student_cards_admin():
|
||||
student_cards.delete_one({'_id': ObjectId(card_id)})
|
||||
flash('Ausweis wurde gelöscht.', 'success')
|
||||
except Exception as e:
|
||||
print(f"Error deleting student card: {e}")
|
||||
app.logger.error(f"Error deleting student card: {e}")
|
||||
flash('Fehler beim Löschen des Ausweises.', 'error')
|
||||
|
||||
elif action == 'edit':
|
||||
@@ -2364,7 +2525,7 @@ def student_cards_admin():
|
||||
flash('Ausweis wurde aktualisiert.', 'success')
|
||||
return redirect(url_for('student_cards_admin'))
|
||||
except Exception as e:
|
||||
print(f"Error updating student card: {e}")
|
||||
app.logger.error(f"Error updating student card: {e}")
|
||||
flash('Fehler beim Aktualisieren des Ausweises.', 'error')
|
||||
|
||||
elif action == 'add':
|
||||
@@ -2388,7 +2549,7 @@ def student_cards_admin():
|
||||
flash('Neuer Ausweis wurde hinzugefügt.', 'success')
|
||||
return redirect(url_for('student_cards_admin'))
|
||||
except Exception as e:
|
||||
print(f"Error adding student card: {e}")
|
||||
app.logger.error(f"Error adding student card: {e}")
|
||||
flash('Fehler beim Hinzufügen des Ausweises.', 'error')
|
||||
|
||||
# Get all student cards
|
||||
@@ -2410,7 +2571,7 @@ def student_cards_admin():
|
||||
@app.route('/student_cards_print', methods=['GET'])
|
||||
def student_cards_print():
|
||||
"""
|
||||
Generate a printable template for all student library cards (Schülerausweise).
|
||||
Generate a printable template for all student library cards (Bibliotheksausweis).
|
||||
Only accessible by admins and only when the student cards module is enabled.
|
||||
"""
|
||||
if 'username' not in session:
|
||||
@@ -2950,6 +3111,7 @@ def get_items():
|
||||
available_only = str(request.args.get('available_only', '')).strip().lower() in ('1', 'true', 'yes', 'on')
|
||||
offset_raw = request.args.get('offset')
|
||||
limit_raw = request.args.get('limit')
|
||||
light_mode_param = str(request.args.get('light_mode', '')).strip().lower()
|
||||
pagination_requested = offset_raw is not None or limit_raw is not None
|
||||
|
||||
if pagination_requested:
|
||||
@@ -2966,6 +3128,13 @@ def get_items():
|
||||
offset = 0
|
||||
limit = None
|
||||
|
||||
if light_mode_param in ('1', 'true', 'yes', 'on'):
|
||||
light_mode = True
|
||||
elif light_mode_param in ('0', 'false', 'no', 'off'):
|
||||
light_mode = False
|
||||
else:
|
||||
light_mode = (offset == 0)
|
||||
|
||||
client = MongoClient(MONGODB_HOST, MONGODB_PORT)
|
||||
db = client[MONGODB_DB]
|
||||
items_col = db['items']
|
||||
@@ -2977,18 +3146,97 @@ def get_items():
|
||||
|
||||
total_count = items_col.count_documents(base_query)
|
||||
|
||||
items_cur = items_col.find(base_query).sort([('Name', 1), ('_id', 1)])
|
||||
light_projection = {
|
||||
'Name': 1,
|
||||
'Code_4': 1,
|
||||
'Images': 1,
|
||||
'ThumbnailInfo': 1,
|
||||
'Verfuegbar': 1,
|
||||
'Filter': 1,
|
||||
'Filter2': 1,
|
||||
'Filter3': 1,
|
||||
'Ort': 1,
|
||||
'User': 1,
|
||||
'ItemType': 1,
|
||||
}
|
||||
|
||||
# Full projection: all details for detailed view
|
||||
full_projection = {
|
||||
'Name': 1,
|
||||
'Ort': 1,
|
||||
'Beschreibung': 1,
|
||||
'Filter': 1,
|
||||
'Filter2': 1,
|
||||
'Filter3': 1,
|
||||
'Code_4': 1,
|
||||
'Images': 1,
|
||||
'ThumbnailInfo': 1,
|
||||
'Verfuegbar': 1,
|
||||
'User': 1,
|
||||
'BorrowerInfo': 1,
|
||||
'appointments': 1,
|
||||
'BlockedNow': 1,
|
||||
'Reservierbar': 1,
|
||||
'DamageReports': 1,
|
||||
'ISBN': 1,
|
||||
'Author': 1,
|
||||
'Autor': 1,
|
||||
'Anschaffungsjahr': 1,
|
||||
'Anschaffungskosten': 1,
|
||||
'Condition': 1,
|
||||
'HasDamage': 1,
|
||||
'ItemType': 1,
|
||||
'SeriesGroupId': 1,
|
||||
'LastUpdated': 1,
|
||||
}
|
||||
|
||||
parent_projection = light_projection if light_mode else full_projection
|
||||
|
||||
items_cur = items_col.find(base_query, parent_projection).sort([('Name', 1), ('_id', 1)])
|
||||
if pagination_requested:
|
||||
items_cur = items_cur.skip(offset).limit(limit)
|
||||
|
||||
items = []
|
||||
for itm in items_cur:
|
||||
item_id_str = str(itm['_id'])
|
||||
grouped_children = list(items_col.find({
|
||||
'ParentItemId': item_id_str,
|
||||
parent_items = list(items_cur)
|
||||
parent_ids = [str(item.get('_id')) for item in parent_items if item.get('_id') is not None]
|
||||
|
||||
children_by_parent = {}
|
||||
if parent_ids:
|
||||
# Light mode: minimal child data for counting only
|
||||
light_child_projection = {
|
||||
'_id': 1,
|
||||
'ParentItemId': 1,
|
||||
'Code_4': 1,
|
||||
'Verfuegbar': 1,
|
||||
'Name': 1,
|
||||
}
|
||||
# Full mode: complete child data with all details
|
||||
full_child_projection = {
|
||||
'_id': 1,
|
||||
'ParentItemId': 1,
|
||||
'Code_4': 1,
|
||||
'Verfuegbar': 1,
|
||||
'Name': 1,
|
||||
'Images': 1,
|
||||
'ThumbnailInfo': 1,
|
||||
'Beschreibung': 1,
|
||||
}
|
||||
child_projection = light_child_projection if light_mode else full_child_projection
|
||||
|
||||
child_cursor = items_col.find({
|
||||
'ParentItemId': {'$in': parent_ids},
|
||||
'IsGroupedSubItem': True,
|
||||
'Deleted': {'$ne': True},
|
||||
}))
|
||||
}, child_projection)
|
||||
for child in child_cursor:
|
||||
parent_id = str(child.get('ParentItemId') or '')
|
||||
if not parent_id:
|
||||
continue
|
||||
children_by_parent.setdefault(parent_id, []).append(child)
|
||||
|
||||
items = []
|
||||
for itm in parent_items:
|
||||
item_id_str = str(itm['_id'])
|
||||
grouped_children = children_by_parent.get(item_id_str, [])
|
||||
grouped_count = 1 + len(grouped_children)
|
||||
|
||||
grouped_units = [itm] + grouped_children
|
||||
@@ -3028,6 +3276,7 @@ def get_items():
|
||||
'limit': limit if limit is not None else count,
|
||||
'count': count,
|
||||
'total': total_count,
|
||||
'light_mode': light_mode,
|
||||
'has_more': pagination_requested and ((offset + count) < total_count)
|
||||
})
|
||||
except Exception as e:
|
||||
@@ -4587,6 +4836,19 @@ def report_damage(id):
|
||||
updated_item = items_col.find_one({'_id': ObjectId(id)}, {'DamageReports': 1})
|
||||
damage_count = len(updated_item.get('DamageReports', [])) if updated_item else 0
|
||||
|
||||
_create_notification(
|
||||
db,
|
||||
audience='admin',
|
||||
notif_type='damage_reported',
|
||||
title='Defekt gemeldet',
|
||||
message=(
|
||||
f"Fuer das Item '{item_doc.get('Name', id)}' wurde ein Defekt gemeldet. "
|
||||
f"Meldung von {session.get('username', '-')}: {description}"
|
||||
),
|
||||
reference={'item_id': id, 'damage_count': damage_count},
|
||||
severity='danger',
|
||||
)
|
||||
|
||||
# Best-effort system log entry for auditability
|
||||
try:
|
||||
logs_collection = db['system_logs']
|
||||
@@ -4927,7 +5189,7 @@ def ausleihen(id):
|
||||
flash('Alle Exemplare sind aufgrund geplanter Reservierungen heute belegt.', 'error')
|
||||
return redirect(url_for(redirect_target))
|
||||
except Exception as e:
|
||||
print(f"Warning: could not enforce planned booking guard: {e}")
|
||||
app.logger.warning(f"Could not enforce planned booking guard: {e}")
|
||||
|
||||
# Get number of exemplars to borrow (default to 1)
|
||||
exemplare_count = request.form.get('exemplare_count', 1)
|
||||
@@ -5048,10 +5310,7 @@ def zurueckgeben(id):
|
||||
|
||||
username = session['username']
|
||||
|
||||
print("Code 1169: zurueckgeben called with item ID:", id)
|
||||
|
||||
if not item.get('Verfuegbar', True) and (us.check_admin(session['username']) or item.get('User') == username):
|
||||
print("Code 1172: Item is not available, proceeding with return")
|
||||
try:
|
||||
# Get ALL active borrowing records for this item and complete them
|
||||
client = MongoClient(MONGODB_HOST, MONGODB_PORT)
|
||||
@@ -5070,8 +5329,6 @@ def zurueckgeben(id):
|
||||
updated_count = 0
|
||||
for record in active_records:
|
||||
ausleihung_id = str(record['_id'])
|
||||
print(f"Completing active ausleihung {ausleihung_id} for item {id}")
|
||||
|
||||
# Update each active record
|
||||
result = ausleihungen.update_one(
|
||||
{'_id': ObjectId(ausleihung_id)},
|
||||
@@ -7484,6 +7741,281 @@ def my_borrowed_items():
|
||||
user_is_admin=user_is_admin
|
||||
)
|
||||
|
||||
|
||||
@app.route('/notifications')
|
||||
def notifications_view():
|
||||
"""Notification center for users and admins."""
|
||||
if 'username' not in session:
|
||||
flash('Bitte melden Sie sich an, um Benachrichtigungen zu sehen.', 'error')
|
||||
return redirect(url_for('login'))
|
||||
|
||||
username = session['username']
|
||||
is_admin_user = False
|
||||
try:
|
||||
is_admin_user = us.check_admin(username)
|
||||
except Exception:
|
||||
is_admin_user = False
|
||||
|
||||
client = None
|
||||
try:
|
||||
client = MongoClient(MONGODB_HOST, MONGODB_PORT)
|
||||
db = client[MONGODB_DB]
|
||||
notifications = _get_notifications_for_user(db, username, is_admin=is_admin_user, limit=200)
|
||||
|
||||
user_notifications = []
|
||||
admin_notifications = []
|
||||
for notif in notifications:
|
||||
is_read = username in (notif.get('ReadBy') or [])
|
||||
row = {
|
||||
'id': str(notif.get('_id')),
|
||||
'title': notif.get('Title', 'Benachrichtigung'),
|
||||
'message': notif.get('Message', ''),
|
||||
'severity': notif.get('Severity', 'info'),
|
||||
'type': notif.get('Type', ''),
|
||||
'created_at': notif.get('CreatedAt'),
|
||||
'is_read': is_read,
|
||||
'reference': notif.get('Reference', {}) or {},
|
||||
}
|
||||
if notif.get('Audience') == 'admin':
|
||||
admin_notifications.append(row)
|
||||
else:
|
||||
user_notifications.append(row)
|
||||
|
||||
return render_template(
|
||||
'notifications.html',
|
||||
user_notifications=user_notifications,
|
||||
admin_notifications=admin_notifications,
|
||||
is_admin_user=is_admin_user,
|
||||
library_module_enabled=cfg.LIBRARY_MODULE_ENABLED,
|
||||
student_cards_module_enabled=cfg.STUDENT_CARDS_MODULE_ENABLED,
|
||||
)
|
||||
except Exception as exc:
|
||||
app.logger.error(f"Error loading notifications: {exc}")
|
||||
flash('Fehler beim Laden der Benachrichtigungen.', 'error')
|
||||
return redirect(url_for('home'))
|
||||
finally:
|
||||
if client:
|
||||
client.close()
|
||||
|
||||
|
||||
@app.route('/notifications/mark_read/<notification_id>', methods=['POST'])
|
||||
def mark_notification_read(notification_id):
|
||||
"""Mark a single notification as read for the current user."""
|
||||
if 'username' not in session:
|
||||
return redirect(url_for('login'))
|
||||
|
||||
username = session['username']
|
||||
client = None
|
||||
try:
|
||||
client = MongoClient(MONGODB_HOST, MONGODB_PORT)
|
||||
db = client[MONGODB_DB]
|
||||
db['notifications'].update_one(
|
||||
{'_id': ObjectId(notification_id)},
|
||||
{
|
||||
'$addToSet': {'ReadBy': username},
|
||||
'$set': {'UpdatedAt': datetime.datetime.now()}
|
||||
}
|
||||
)
|
||||
except Exception as exc:
|
||||
app.logger.warning(f"Could not mark notification as read {notification_id}: {exc}")
|
||||
finally:
|
||||
if client:
|
||||
client.close()
|
||||
|
||||
return redirect(url_for('notifications_view'))
|
||||
|
||||
|
||||
@app.route('/notifications/mark_all_read', methods=['POST'])
|
||||
def mark_all_notifications_read():
|
||||
"""Mark all visible notifications as read for the current user."""
|
||||
if 'username' not in session:
|
||||
return redirect(url_for('login'))
|
||||
|
||||
username = session['username']
|
||||
is_admin_user = False
|
||||
try:
|
||||
is_admin_user = us.check_admin(username)
|
||||
except Exception:
|
||||
is_admin_user = False
|
||||
|
||||
query = {
|
||||
'$or': [
|
||||
{'Audience': 'user', 'TargetUser': username},
|
||||
]
|
||||
}
|
||||
if is_admin_user:
|
||||
query['$or'].append({'Audience': 'admin'})
|
||||
|
||||
client = None
|
||||
try:
|
||||
client = MongoClient(MONGODB_HOST, MONGODB_PORT)
|
||||
db = client[MONGODB_DB]
|
||||
db['notifications'].update_many(
|
||||
query,
|
||||
{
|
||||
'$addToSet': {'ReadBy': username},
|
||||
'$set': {'UpdatedAt': datetime.datetime.now()}
|
||||
}
|
||||
)
|
||||
except Exception as exc:
|
||||
app.logger.warning(f"Could not mark all notifications as read for {username}: {exc}")
|
||||
finally:
|
||||
if client:
|
||||
client.close()
|
||||
|
||||
return redirect(url_for('notifications_view'))
|
||||
|
||||
|
||||
@app.route('/notifications/unread_status', methods=['GET'])
|
||||
def notifications_unread_status():
|
||||
"""Return unread notification count and latest unread message metadata."""
|
||||
if 'username' not in session:
|
||||
return jsonify({'ok': False, 'error': 'not_authenticated'}), 401
|
||||
|
||||
username = session['username']
|
||||
is_admin_user = False
|
||||
try:
|
||||
is_admin_user = us.check_admin(username)
|
||||
except Exception:
|
||||
is_admin_user = False
|
||||
|
||||
client = None
|
||||
try:
|
||||
client = MongoClient(MONGODB_HOST, MONGODB_PORT)
|
||||
db = client[MONGODB_DB]
|
||||
|
||||
visibility_query = {
|
||||
'$or': [
|
||||
{'Audience': 'user', 'TargetUser': username},
|
||||
]
|
||||
}
|
||||
if is_admin_user:
|
||||
visibility_query['$or'].append({'Audience': 'admin'})
|
||||
|
||||
unread_query = {
|
||||
'$and': [
|
||||
visibility_query,
|
||||
{'ReadBy': {'$ne': username}},
|
||||
]
|
||||
}
|
||||
|
||||
unread_count = db['notifications'].count_documents(unread_query)
|
||||
latest_unread = db['notifications'].find_one(
|
||||
unread_query,
|
||||
{
|
||||
'Title': 1,
|
||||
'Message': 1,
|
||||
'CreatedAt': 1,
|
||||
'Type': 1,
|
||||
'Severity': 1,
|
||||
},
|
||||
sort=[('CreatedAt', -1)]
|
||||
)
|
||||
|
||||
latest_payload = None
|
||||
if latest_unread:
|
||||
latest_payload = {
|
||||
'title': latest_unread.get('Title', 'Benachrichtigung'),
|
||||
'message': latest_unread.get('Message', ''),
|
||||
'created_at': latest_unread.get('CreatedAt').isoformat() if isinstance(latest_unread.get('CreatedAt'), datetime.datetime) else '',
|
||||
'type': latest_unread.get('Type', ''),
|
||||
'severity': latest_unread.get('Severity', 'info'),
|
||||
}
|
||||
|
||||
return jsonify({
|
||||
'ok': True,
|
||||
'unread_count': unread_count,
|
||||
'latest_unread': latest_payload,
|
||||
})
|
||||
except Exception as exc:
|
||||
app.logger.warning(f"Could not fetch unread notification status for {username}: {exc}")
|
||||
return jsonify({'ok': False, 'error': 'status_fetch_failed'}), 500
|
||||
finally:
|
||||
if client:
|
||||
client.close()
|
||||
|
||||
|
||||
@app.route('/admin/damaged_items')
|
||||
def admin_damaged_items():
|
||||
"""Dedicated admin management window for damaged items."""
|
||||
if 'username' not in session or not us.check_admin(session['username']):
|
||||
flash('Administratorrechte erforderlich.', 'error')
|
||||
return redirect(url_for('login'))
|
||||
|
||||
client = None
|
||||
try:
|
||||
client = MongoClient(MONGODB_HOST, MONGODB_PORT)
|
||||
db = client[MONGODB_DB]
|
||||
items_col = db['items']
|
||||
ausleihungen_col = db['ausleihungen']
|
||||
|
||||
items = list(items_col.find(
|
||||
{
|
||||
'Deleted': {'$ne': True},
|
||||
'$or': [
|
||||
{'HasDamage': True},
|
||||
{'Condition': 'destroyed'},
|
||||
{'DamageReports.0': {'$exists': True}},
|
||||
]
|
||||
},
|
||||
{
|
||||
'Name': 1,
|
||||
'Code_4': 1,
|
||||
'ItemType': 1,
|
||||
'Author': 1,
|
||||
'ISBN': 1,
|
||||
'Condition': 1,
|
||||
'DamageReports': 1,
|
||||
'DamageRepairs': 1,
|
||||
'Verfuegbar': 1,
|
||||
'User': 1,
|
||||
'LastUpdated': 1,
|
||||
}
|
||||
).sort('LastUpdated', -1))
|
||||
|
||||
damaged_rows = []
|
||||
for item_doc in items:
|
||||
item_id = str(item_doc.get('_id'))
|
||||
active_borrow = ausleihungen_col.find_one(
|
||||
{'Item': item_id, 'Status': {'$in': ['active', 'planned']}},
|
||||
{'_id': 1, 'User': 1, 'Status': 1, 'End': 1}
|
||||
)
|
||||
reports = item_doc.get('DamageReports', []) or []
|
||||
latest_report = reports[0] if reports else {}
|
||||
|
||||
damaged_rows.append({
|
||||
'id': item_id,
|
||||
'name': item_doc.get('Name', ''),
|
||||
'code': item_doc.get('Code_4', ''),
|
||||
'item_type': item_doc.get('ItemType', ''),
|
||||
'author': item_doc.get('Author', ''),
|
||||
'isbn': item_doc.get('ISBN', ''),
|
||||
'condition': item_doc.get('Condition', ''),
|
||||
'available': bool(item_doc.get('Verfuegbar', False)),
|
||||
'borrow_user': item_doc.get('User', ''),
|
||||
'damage_count': len(reports),
|
||||
'damage_reports': reports,
|
||||
'latest_damage_description': latest_report.get('description', ''),
|
||||
'latest_damage_by': latest_report.get('reported_by', ''),
|
||||
'latest_damage_at': latest_report.get('reported_at'),
|
||||
'active_borrow': active_borrow,
|
||||
'last_updated': item_doc.get('LastUpdated'),
|
||||
})
|
||||
|
||||
return render_template(
|
||||
'admin_damaged_items.html',
|
||||
damaged_items=damaged_rows,
|
||||
library_module_enabled=cfg.LIBRARY_MODULE_ENABLED,
|
||||
student_cards_module_enabled=cfg.STUDENT_CARDS_MODULE_ENABLED,
|
||||
)
|
||||
except Exception as exc:
|
||||
app.logger.error(f"Error loading damaged-items admin view: {exc}")
|
||||
flash('Fehler beim Laden der Defekte-Items-Verwaltung.', 'error')
|
||||
return redirect(url_for('home_admin'))
|
||||
finally:
|
||||
if client:
|
||||
client.close()
|
||||
|
||||
@app.route('/favicon.ico')
|
||||
def favicon():
|
||||
"""
|
||||
|
||||
+100
-12
@@ -12,6 +12,8 @@ defaults for the web application and helper modules.
|
||||
"""
|
||||
import os
|
||||
import json
|
||||
import atexit
|
||||
from threading import Lock
|
||||
from pymongo import MongoClient as _PyMongoClient
|
||||
|
||||
# Base directory of this Web package
|
||||
@@ -99,10 +101,27 @@ def _get(conf, path, default):
|
||||
return default
|
||||
return cur
|
||||
|
||||
|
||||
def _get_bool_env(name, default):
|
||||
value = os.getenv(name)
|
||||
if value is None:
|
||||
return default
|
||||
return value.strip().lower() in ('1', 'true', 'yes', 'on')
|
||||
|
||||
|
||||
def _get_int_env(name, default):
|
||||
value = os.getenv(name)
|
||||
if value is None or not value.strip():
|
||||
return int(default)
|
||||
try:
|
||||
return int(value)
|
||||
except ValueError:
|
||||
return int(default)
|
||||
|
||||
# Expose settings
|
||||
APP_VERSION = _get(_conf, ['ver'], DEFAULTS['version'])
|
||||
DEBUG = _get(_conf, ['dbg'], DEFAULTS['debug'])
|
||||
SECRET_KEY = str(_get(_conf, ['key'], DEFAULTS['secret_key']))
|
||||
DEBUG = _get_bool_env('INVENTAR_DEBUG', _get(_conf, ['dbg'], DEFAULTS['debug']))
|
||||
SECRET_KEY = str(os.getenv('INVENTAR_SECRET_KEY', _get(_conf, ['key'], DEFAULTS['secret_key'])))
|
||||
HOST = _get(_conf, ['host'], DEFAULTS['host'])
|
||||
PORT = _get(_conf, ['port'], DEFAULTS['port'])
|
||||
|
||||
@@ -115,6 +134,13 @@ MONGODB_DB = _get(_conf, ['mongodb', 'db'], DEFAULTS['mongodb']['db'])
|
||||
MONGODB_HOST = os.getenv('INVENTAR_MONGODB_HOST', MONGODB_HOST)
|
||||
MONGODB_PORT = int(os.getenv('INVENTAR_MONGODB_PORT', str(MONGODB_PORT)))
|
||||
MONGODB_DB = os.getenv('INVENTAR_MONGODB_DB', MONGODB_DB)
|
||||
MONGODB_MAX_POOL_SIZE = _get_int_env('INVENTAR_MONGODB_MAX_POOL_SIZE', 20)
|
||||
MONGODB_MIN_POOL_SIZE = _get_int_env('INVENTAR_MONGODB_MIN_POOL_SIZE', 0)
|
||||
MONGODB_MAX_IDLE_TIME_MS = _get_int_env('INVENTAR_MONGODB_MAX_IDLE_TIME_MS', 300000)
|
||||
MONGODB_CONNECT_TIMEOUT_MS = _get_int_env('INVENTAR_MONGODB_CONNECT_TIMEOUT_MS', 5000)
|
||||
MONGODB_SERVER_SELECTION_TIMEOUT_MS = _get_int_env('INVENTAR_MONGODB_SERVER_SELECTION_TIMEOUT_MS', 5000)
|
||||
MONGODB_SOCKET_TIMEOUT_MS = _get_int_env('INVENTAR_MONGODB_SOCKET_TIMEOUT_MS', 30000)
|
||||
MONGODB_MAX_CONNECTING = _get_int_env('INVENTAR_MONGODB_MAX_CONNECTING', 2)
|
||||
|
||||
# Scheduler
|
||||
SCHEDULER_INTERVAL_MIN = _get(_conf, ['scheduler', 'interval_minutes'], DEFAULTS['scheduler']['interval_minutes'])
|
||||
@@ -176,19 +202,81 @@ if not os.path.isabs(LOGS_FOLDER):
|
||||
LOGS_FOLDER = os.path.join(PROJECT_ROOT, LOGS_FOLDER)
|
||||
|
||||
|
||||
_MONGO_CLIENT_CACHE = {}
|
||||
_MONGO_CLIENT_LOCK = Lock()
|
||||
|
||||
|
||||
class _MongoClientProxy:
|
||||
def __init__(self, client):
|
||||
self._client = client
|
||||
|
||||
def __getattr__(self, name):
|
||||
return getattr(self._client, name)
|
||||
|
||||
def __getitem__(self, name):
|
||||
return self._client[name]
|
||||
|
||||
def __enter__(self):
|
||||
return self
|
||||
|
||||
def __exit__(self, exc_type, exc, tb):
|
||||
return False
|
||||
|
||||
def close(self):
|
||||
return None
|
||||
|
||||
|
||||
def _close_cached_mongo_clients():
|
||||
with _MONGO_CLIENT_LOCK:
|
||||
clients = list(_MONGO_CLIENT_CACHE.values())
|
||||
_MONGO_CLIENT_CACHE.clear()
|
||||
|
||||
for proxy in clients:
|
||||
try:
|
||||
proxy._client.close()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
atexit.register(_close_cached_mongo_clients)
|
||||
|
||||
|
||||
def MongoClient(*args, **kwargs):
|
||||
"""Return a lightweight MongoDB client configured from this settings module."""
|
||||
"""Return a process-local MongoDB client configured from this settings module."""
|
||||
explicit_host = 'host' in kwargs
|
||||
explicit_port = 'port' in kwargs
|
||||
host = args[0] if len(args) >= 1 else kwargs.pop('host', MONGODB_HOST)
|
||||
port = args[1] if len(args) >= 2 else kwargs.pop('port', MONGODB_PORT)
|
||||
client_kwargs = {
|
||||
'maxPoolSize': 10,
|
||||
'minPoolSize': 0,
|
||||
'connectTimeoutMS': 5000,
|
||||
'serverSelectionTimeoutMS': 5000,
|
||||
'maxPoolSize': MONGODB_MAX_POOL_SIZE,
|
||||
'minPoolSize': MONGODB_MIN_POOL_SIZE,
|
||||
'maxIdleTimeMS': MONGODB_MAX_IDLE_TIME_MS,
|
||||
'connectTimeoutMS': MONGODB_CONNECT_TIMEOUT_MS,
|
||||
'serverSelectionTimeoutMS': MONGODB_SERVER_SELECTION_TIMEOUT_MS,
|
||||
'socketTimeoutMS': MONGODB_SOCKET_TIMEOUT_MS,
|
||||
'maxConnecting': MONGODB_MAX_CONNECTING,
|
||||
'retryWrites': True,
|
||||
'retryReads': True,
|
||||
}
|
||||
client_kwargs.update(kwargs)
|
||||
|
||||
# Preserve caller-provided positional host/port arguments.
|
||||
# If none are passed, use configured defaults.
|
||||
if args:
|
||||
return _PyMongoClient(*args, **client_kwargs)
|
||||
return _PyMongoClient(MONGODB_HOST, MONGODB_PORT, **client_kwargs)
|
||||
if len(args) >= 2 and not explicit_host and not explicit_port:
|
||||
mongo_args = args
|
||||
else:
|
||||
mongo_args = (host, port)
|
||||
|
||||
cache_key = (
|
||||
mongo_args,
|
||||
tuple(sorted((key, repr(value)) for key, value in client_kwargs.items())),
|
||||
)
|
||||
|
||||
with _MONGO_CLIENT_LOCK:
|
||||
cached_client = _MONGO_CLIENT_CACHE.get(cache_key)
|
||||
if cached_client is not None:
|
||||
return cached_client
|
||||
|
||||
client = _PyMongoClient(*mongo_args, **client_kwargs)
|
||||
|
||||
cached_client = _MongoClientProxy(client)
|
||||
_MONGO_CLIENT_CACHE[cache_key] = cached_client
|
||||
return cached_client
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
{% extends "base.html" %}
|
||||
|
||||
{% block title %}Defekte Items verwalten{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<div class="container" style="max-width: 1250px; margin: 18px auto 32px;">
|
||||
<div style="display:flex; justify-content:space-between; align-items:flex-start; gap:12px; flex-wrap:wrap; margin-bottom:16px;">
|
||||
<div>
|
||||
<h1 style="margin:0;">Defekte Items</h1>
|
||||
<p style="margin:6px 0 0; color:#64748b;">Eigenes Verwaltungsfenster fuer gemeldete Defekte mit schneller Reparatur-Funktion.</p>
|
||||
</div>
|
||||
<div style="display:flex; gap:8px; flex-wrap:wrap;">
|
||||
<a class="btn btn-outline-secondary" href="{{ url_for('admin_borrowings') }}">Ausleihen</a>
|
||||
{% if library_module_enabled %}
|
||||
<a class="btn btn-outline-secondary" href="{{ url_for('library_loans_admin') }}">Bibliothek</a>
|
||||
{% endif %}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div style="background:#fff; border:1px solid #e2e8f0; border-radius:14px; padding:14px; margin-bottom:12px;">
|
||||
<input id="damage-search" type="text" placeholder="Suche nach Name, Code, Typ, Benutzer oder Schaden..." style="width:100%; padding:10px 12px; border:1px solid #d1d5db; border-radius:10px;">
|
||||
</div>
|
||||
|
||||
<div style="background:#fff; border:1px solid #e2e8f0; border-radius:14px; padding:0; overflow:hidden;">
|
||||
<table id="damage-table" style="width:100%; border-collapse:collapse;">
|
||||
<thead>
|
||||
<tr style="background:#f8fafc;">
|
||||
<th style="text-align:left; padding:11px; border-bottom:1px solid #e5e7eb;">Item</th>
|
||||
<th style="text-align:left; padding:11px; border-bottom:1px solid #e5e7eb;">Status</th>
|
||||
<th style="text-align:left; padding:11px; border-bottom:1px solid #e5e7eb;">Letzte Meldung</th>
|
||||
<th style="text-align:left; padding:11px; border-bottom:1px solid #e5e7eb;">Ausleihe</th>
|
||||
<th style="text-align:left; padding:11px; border-bottom:1px solid #e5e7eb;">Aktion</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{% for item in damaged_items %}
|
||||
<tr class="damage-row" data-search="{{ (item.name ~ ' ' ~ item.code ~ ' ' ~ item.item_type ~ ' ' ~ item.borrow_user ~ ' ' ~ item.latest_damage_description)|lower }}">
|
||||
<td style="padding:11px; border-bottom:1px solid #eef2f7; vertical-align:top;">
|
||||
<div style="font-weight:700;">{{ item.name }}</div>
|
||||
<div style="font-size:0.86rem; color:#64748b;">{{ item.code or '-' }} | {{ item.item_type or '-' }}</div>
|
||||
{% if item.author %}<div style="font-size:0.82rem; color:#64748b;">{{ item.author }}</div>{% endif %}
|
||||
{% if item.isbn %}<div style="font-size:0.82rem; color:#64748b;">ISBN: {{ item.isbn }}</div>{% endif %}
|
||||
</td>
|
||||
<td style="padding:11px; border-bottom:1px solid #eef2f7; vertical-align:top;">
|
||||
<div style="display:inline-block; padding:3px 9px; border-radius:999px; background:#fee2e2; color:#991b1b; font-size:0.75rem; font-weight:700;">Defekt</div>
|
||||
<div style="font-size:0.84rem; color:#475569; margin-top:6px;">Meldungen: {{ item.damage_count }}</div>
|
||||
<div style="font-size:0.84rem; color:#475569;">Condition: {{ item.condition or '-' }}</div>
|
||||
<div style="font-size:0.84rem; color:#475569;">Verfuegbar: {{ 'Ja' if item.available else 'Nein' }}</div>
|
||||
</td>
|
||||
<td style="padding:11px; border-bottom:1px solid #eef2f7; vertical-align:top;">
|
||||
<div style="font-size:0.9rem; color:#1f2937;">{{ item.latest_damage_description or '-' }}</div>
|
||||
<div style="font-size:0.82rem; color:#64748b; margin-top:4px;">
|
||||
Gemeldet von {{ item.latest_damage_by or '-' }}
|
||||
{% if item.latest_damage_at %} am {{ item.latest_damage_at.strftime('%d.%m.%Y %H:%M') }}{% endif %}
|
||||
</div>
|
||||
</td>
|
||||
<td style="padding:11px; border-bottom:1px solid #eef2f7; vertical-align:top;">
|
||||
{% if item.active_borrow %}
|
||||
<div style="display:inline-block; padding:3px 9px; border-radius:999px; background:#dbeafe; color:#1d4ed8; font-size:0.75rem; font-weight:700;">Aktiv/Geplant</div>
|
||||
<div style="font-size:0.84rem; color:#475569; margin-top:6px;">User: {{ item.active_borrow.User or item.borrow_user or '-' }}</div>
|
||||
{% if item.active_borrow.End %}
|
||||
<div style="font-size:0.84rem; color:#475569;">Ende: {{ item.active_borrow.End.strftime('%d.%m.%Y %H:%M') }}</div>
|
||||
{% endif %}
|
||||
{% else %}
|
||||
<div style="display:inline-block; padding:3px 9px; border-radius:999px; background:#dcfce7; color:#166534; font-size:0.75rem; font-weight:700;">Keine offene Ausleihe</div>
|
||||
{% endif %}
|
||||
</td>
|
||||
<td style="padding:11px; border-bottom:1px solid #eef2f7; vertical-align:top;">
|
||||
<button class="btn btn-success btn-sm" onclick="repairDamage('{{ item.id }}', this)">Als repariert markieren</button>
|
||||
</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
{% if not damaged_items %}
|
||||
<div style="padding:24px; color:#64748b; text-align:center;">Keine defekten Items vorhanden.</div>
|
||||
{% endif %}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
(function() {
|
||||
const searchInput = document.getElementById('damage-search');
|
||||
if (searchInput) {
|
||||
searchInput.addEventListener('input', function() {
|
||||
const q = (searchInput.value || '').toLowerCase();
|
||||
document.querySelectorAll('.damage-row').forEach(function(row) {
|
||||
const text = row.getAttribute('data-search') || '';
|
||||
row.style.display = text.includes(q) ? '' : 'none';
|
||||
});
|
||||
});
|
||||
}
|
||||
})();
|
||||
|
||||
function repairDamage(itemId, button) {
|
||||
if (!itemId) return;
|
||||
if (!confirm('Alle offenen Defektmeldungen fuer dieses Item als repariert markieren?')) {
|
||||
return;
|
||||
}
|
||||
|
||||
button.disabled = true;
|
||||
fetch('/mark_damage_repaired/' + itemId, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({})
|
||||
})
|
||||
.then(function(res) { return res.json(); })
|
||||
.then(function(data) {
|
||||
if (!data.success) {
|
||||
throw new Error(data.message || 'Reparatur fehlgeschlagen');
|
||||
}
|
||||
window.location.reload();
|
||||
})
|
||||
.catch(function(err) {
|
||||
button.disabled = false;
|
||||
alert(err.message || 'Fehler beim Markieren als repariert.');
|
||||
});
|
||||
}
|
||||
</script>
|
||||
{% endblock %}
|
||||
+470
-14
@@ -7,7 +7,7 @@
|
||||
For commercial licensing inquiries: https://github.com/AIIrondev
|
||||
-->
|
||||
<!DOCTYPE html>
|
||||
<html lang="en" data-module="{{ CURRENT_MODULE }}">
|
||||
<html lang="de" data-module="{{ CURRENT_MODULE }}">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, user-scalable=yes">
|
||||
@@ -63,6 +63,9 @@
|
||||
.navbar {
|
||||
box-shadow: 0 4px 14px rgba(2, 6, 23, 0.24);
|
||||
background-color: var(--module-primary-color) !important;
|
||||
position: sticky;
|
||||
top: 0;
|
||||
z-index: 1900;
|
||||
}
|
||||
|
||||
.navbar-brand {
|
||||
@@ -82,6 +85,65 @@
|
||||
border-radius: 8px;
|
||||
}
|
||||
|
||||
.navbar-nav .nav-link.nav-active {
|
||||
background-color: rgba(255, 255, 255, 0.2);
|
||||
box-shadow: inset 0 0 0 1px rgba(255, 255, 255, 0.35);
|
||||
}
|
||||
|
||||
.function-search-wrap {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
margin-right: 10px;
|
||||
width: min(420px, 42vw);
|
||||
}
|
||||
|
||||
.function-search-form {
|
||||
width: 100%;
|
||||
display: flex;
|
||||
gap: 6px;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.function-search-input {
|
||||
width: 100%;
|
||||
min-height: 38px;
|
||||
border-radius: 10px;
|
||||
border: 1px solid rgba(255, 255, 255, 0.3);
|
||||
background: rgba(255, 255, 255, 0.12);
|
||||
color: #ffffff;
|
||||
padding: 8px 12px;
|
||||
outline: none;
|
||||
}
|
||||
|
||||
.function-search-input::placeholder {
|
||||
color: rgba(255, 255, 255, 0.78);
|
||||
}
|
||||
|
||||
.function-search-input:focus {
|
||||
border-color: #93c5fd;
|
||||
box-shadow: 0 0 0 2px rgba(147, 197, 253, 0.35);
|
||||
background: rgba(255, 255, 255, 0.18);
|
||||
}
|
||||
|
||||
.function-search-btn {
|
||||
min-height: 38px;
|
||||
border-radius: 10px;
|
||||
border: 1px solid rgba(255, 255, 255, 0.45);
|
||||
background: rgba(255, 255, 255, 0.15);
|
||||
color: #ffffff;
|
||||
padding: 7px 12px;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.function-search-btn:hover {
|
||||
background: rgba(255, 255, 255, 0.26);
|
||||
}
|
||||
|
||||
.quick-link-pill {
|
||||
border: 1px solid rgba(255, 255, 255, 0.35);
|
||||
background: rgba(255, 255, 255, 0.08);
|
||||
}
|
||||
|
||||
.navbar-nav .nav-link:hover,
|
||||
.navbar-nav .nav-link:focus {
|
||||
background-color: rgba(255, 255, 255, 0.12);
|
||||
@@ -255,6 +317,27 @@
|
||||
.nav-item.dropdown .dropdown-toggle {
|
||||
padding: 8px 12px;
|
||||
}
|
||||
|
||||
.navbar-toggler {
|
||||
padding: 0.5rem 0.65rem;
|
||||
border-width: 2px;
|
||||
}
|
||||
|
||||
.function-search-wrap {
|
||||
width: 100%;
|
||||
margin: 8px 0 10px;
|
||||
}
|
||||
|
||||
.navbar-nav .nav-item {
|
||||
margin-right: 0;
|
||||
margin-bottom: 6px;
|
||||
}
|
||||
|
||||
.navbar-nav .nav-link {
|
||||
min-height: 44px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
/* Better touch targets for mobile */
|
||||
.dropdown-toggle::after {
|
||||
@@ -363,6 +446,7 @@
|
||||
{% endblock %}
|
||||
</head>
|
||||
<body>
|
||||
{% set current_path = request.path %}
|
||||
<!-- Module Selector Bar -->
|
||||
{% if 'username' in session %}
|
||||
<div class="module-selector-bar" id="moduleBar">
|
||||
@@ -396,16 +480,24 @@
|
||||
<div class="collapse navbar-collapse" id="inventoryNavContent">
|
||||
<ul class="navbar-nav me-auto mb-2 mb-lg-0" id="inventoryNavList">
|
||||
<li class="nav-item" data-nav-fixed="true">
|
||||
<a class="nav-link" href="{{ url_for('home') }}">Artikel</a>
|
||||
<a class="nav-link {% if current_path == url_for('home') %}nav-active{% endif %}" href="{{ url_for('home') }}">Artikel</a>
|
||||
</li>
|
||||
{% if 'username' in session %}
|
||||
<li class="nav-item" data-nav-fixed="true">
|
||||
<a class="nav-link quick-link-pill {% if current_path == url_for('my_borrowed_items') %}nav-active{% endif %}" href="{{ url_for('my_borrowed_items') }}">Meine Ausleihen</a>
|
||||
</li>
|
||||
<li class="nav-item" data-nav-fixed="true">
|
||||
<a class="nav-link quick-link-pill {% if current_path == url_for('tutorial_page') %}nav-active{% endif %}" href="{{ url_for('tutorial_page') }}">Tutorial</a>
|
||||
</li>
|
||||
{% endif %}
|
||||
{% if 'username' in session and (session.get('admin', False) or is_admin) %}
|
||||
<li class="nav-item">
|
||||
<a class="nav-link nav-priority-link" href="{{ url_for('upload_admin') }}">➕ Hochladen</a>
|
||||
<a class="nav-link nav-priority-link {% if current_path == url_for('upload_admin') %}nav-active{% endif %}" href="{{ url_for('upload_admin') }}">➕ Hochladen</a>
|
||||
</li>
|
||||
{% endif %}
|
||||
<li class="nav-item dropdown ms-lg-auto">
|
||||
<a class="nav-link dropdown-toggle" href="#" id="invMoreDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false">
|
||||
⋯ Mehr
|
||||
<a class="nav-link dropdown-toggle" href="#" id="invMoreDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false" title="Weitere Optionen">
|
||||
Mehr Optionen
|
||||
</a>
|
||||
<ul class="dropdown-menu dropdown-menu-end" aria-labelledby="invMoreDropdown">
|
||||
{% if 'username' in session %}
|
||||
@@ -418,6 +510,7 @@
|
||||
<li><a class="dropdown-item" href="{{ url_for('manage_filters') }}">Filter verwalten</a></li>
|
||||
<li><a class="dropdown-item" href="{{ url_for('manage_locations') }}">Orte verwalten</a></li>
|
||||
<li><a class="dropdown-item" href="{{ url_for('admin_borrowings') }}">Ausleihen</a></li>
|
||||
<li><a class="dropdown-item" href="{{ url_for('admin_damaged_items') }}">Defekte Items</a></li>
|
||||
<li><a class="dropdown-item" href="{{ url_for('admin_audit_dashboard') }}">Audit Dashboard</a></li>
|
||||
<li><a class="dropdown-item" href="{{ url_for('logs') }}">Logs</a></li>
|
||||
<li><hr class="dropdown-divider"></li>
|
||||
@@ -434,12 +527,28 @@
|
||||
</ul>
|
||||
<div class="d-flex">
|
||||
{% if 'username' in session %}
|
||||
<div class="function-search-wrap">
|
||||
<form class="function-search-form" data-function-search="true">
|
||||
<input
|
||||
class="function-search-input"
|
||||
type="search"
|
||||
name="function_search"
|
||||
placeholder="Funktion suchen..."
|
||||
list="function-search-options"
|
||||
autocomplete="off"
|
||||
>
|
||||
<button class="function-search-btn" type="submit">Los</button>
|
||||
</form>
|
||||
</div>
|
||||
<span class="navbar-text text-light me-3">{{ session['username'] }}</span>
|
||||
<div class="dropdown me-2">
|
||||
<button class="btn btn-secondary dropdown-toggle" type="button" id="invUserMenuDropdown" data-bs-toggle="dropdown" aria-expanded="false">
|
||||
<div class="dropdown me-2 user-menu-wrap">
|
||||
<button class="btn btn-secondary dropdown-toggle user-menu-btn" type="button" id="invUserMenuDropdown" data-bs-toggle="dropdown" aria-expanded="false" data-notification-button="true">
|
||||
👤
|
||||
<span class="user-notification-dot {% if unread_notification_count and unread_notification_count > 0 %}visible{% endif %}" aria-hidden="true"></span>
|
||||
</button>
|
||||
<ul class="dropdown-menu dropdown-menu-end" aria-labelledby="invUserMenuDropdown">
|
||||
<li><a class="dropdown-item" href="{{ url_for('notifications_view') }}">Benachrichtigungen</a></li>
|
||||
<li><hr class="dropdown-divider"></li>
|
||||
<li><a class="dropdown-item" href="{{ url_for('change_password') }}">Passwort ändern</a></li>
|
||||
<li><hr class="dropdown-divider"></li>
|
||||
<li><a class="dropdown-item" href="{{ url_for('logout') }}">Logout</a></li>
|
||||
@@ -462,16 +571,24 @@
|
||||
<div class="collapse navbar-collapse" id="libraryNavContent">
|
||||
<ul class="navbar-nav me-auto mb-2 mb-lg-0" id="libraryNavList">
|
||||
<li class="nav-item" data-nav-fixed="true">
|
||||
<a class="nav-link" href="{{ url_for('library_view') }}">Medien</a>
|
||||
<a class="nav-link {% if current_path == url_for('library_view') %}nav-active{% endif %}" href="{{ url_for('library_view') }}">Medien</a>
|
||||
</li>
|
||||
{% if 'username' in session %}
|
||||
<li class="nav-item" data-nav-fixed="true">
|
||||
<a class="nav-link quick-link-pill {% if current_path == url_for('my_borrowed_items') %}nav-active{% endif %}" href="{{ url_for('my_borrowed_items') }}">Meine Medien</a>
|
||||
</li>
|
||||
<li class="nav-item" data-nav-fixed="true">
|
||||
<a class="nav-link quick-link-pill {% if current_path == url_for('tutorial_page') %}nav-active{% endif %}" href="{{ url_for('tutorial_page') }}">Tutorial</a>
|
||||
</li>
|
||||
{% endif %}
|
||||
{% if 'username' in session and (session.get('admin', False) or is_admin) %}
|
||||
<li class="nav-item">
|
||||
<a class="nav-link nav-priority-link" href="{{ url_for('library_admin') }}">📖 Hochladen</a>
|
||||
<a class="nav-link nav-priority-link {% if current_path == url_for('library_admin') %}nav-active{% endif %}" href="{{ url_for('library_admin') }}">📖 Hochladen</a>
|
||||
</li>
|
||||
{% endif %}
|
||||
<li class="nav-item dropdown ms-lg-auto">
|
||||
<a class="nav-link dropdown-toggle" href="#" id="libMoreDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false">
|
||||
⋯ Mehr
|
||||
<a class="nav-link dropdown-toggle" href="#" id="libMoreDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false" title="Weitere Optionen">
|
||||
Mehr Optionen
|
||||
</a>
|
||||
<ul class="dropdown-menu dropdown-menu-end" aria-labelledby="libMoreDropdown">
|
||||
{% if 'username' in session %}
|
||||
@@ -482,8 +599,9 @@
|
||||
{% if 'username' in session and (session.get('admin', False) or is_admin) %}
|
||||
<li><h6 class="dropdown-header">Bibliotheks-Verwaltung</h6></li>
|
||||
<li><a class="dropdown-item" href="{{ url_for('library_loans_admin') }}">Ausleihen</a></li>
|
||||
<li><a class="dropdown-item" href="{{ url_for('admin_damaged_items') }}">Defekte Items</a></li>
|
||||
{% if student_cards_module_enabled %}
|
||||
<li><a class="dropdown-item" href="{{ url_for('student_cards_admin') }}">Schülerausweise</a></li>
|
||||
<li><a class="dropdown-item" href="{{ url_for('student_cards_admin') }}">Bibliotheksausweis</a></li>
|
||||
{% endif %}
|
||||
<li><hr class="dropdown-divider"></li>
|
||||
<li><h6 class="dropdown-header">System</h6></li>
|
||||
@@ -499,12 +617,28 @@
|
||||
</ul>
|
||||
<div class="d-flex">
|
||||
{% if 'username' in session %}
|
||||
<div class="function-search-wrap">
|
||||
<form class="function-search-form" data-function-search="true">
|
||||
<input
|
||||
class="function-search-input"
|
||||
type="search"
|
||||
name="function_search"
|
||||
placeholder="Funktion suchen..."
|
||||
list="function-search-options"
|
||||
autocomplete="off"
|
||||
>
|
||||
<button class="function-search-btn" type="submit">Los</button>
|
||||
</form>
|
||||
</div>
|
||||
<span class="navbar-text text-light me-3">{{ session['username'] }}</span>
|
||||
<div class="dropdown me-2">
|
||||
<button class="btn btn-secondary dropdown-toggle" type="button" id="libUserMenuDropdown" data-bs-toggle="dropdown" aria-expanded="false">
|
||||
<div class="dropdown me-2 user-menu-wrap">
|
||||
<button class="btn btn-secondary dropdown-toggle user-menu-btn" type="button" id="libUserMenuDropdown" data-bs-toggle="dropdown" aria-expanded="false" data-notification-button="true">
|
||||
👤
|
||||
<span class="user-notification-dot {% if unread_notification_count and unread_notification_count > 0 %}visible{% endif %}" aria-hidden="true"></span>
|
||||
</button>
|
||||
<ul class="dropdown-menu dropdown-menu-end" aria-labelledby="libUserMenuDropdown">
|
||||
<li><a class="dropdown-item" href="{{ url_for('notifications_view') }}">Benachrichtigungen</a></li>
|
||||
<li><hr class="dropdown-divider"></li>
|
||||
<li><a class="dropdown-item" href="{{ url_for('change_password') }}">Passwort ändern</a></li>
|
||||
<li><hr class="dropdown-divider"></li>
|
||||
<li><a class="dropdown-item" href="{{ url_for('logout') }}">Logout</a></li>
|
||||
@@ -597,6 +731,73 @@
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.04em;
|
||||
}
|
||||
|
||||
.notif-badge {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
min-width: 20px;
|
||||
height: 20px;
|
||||
border-radius: 999px;
|
||||
background: #dc2626;
|
||||
color: #fff;
|
||||
font-size: 0.72rem;
|
||||
font-weight: 800;
|
||||
padding: 0 6px;
|
||||
margin-left: 8px;
|
||||
line-height: 1;
|
||||
}
|
||||
|
||||
.user-menu-wrap {
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.user-menu-btn {
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.user-notification-dot {
|
||||
position: absolute;
|
||||
top: 6px;
|
||||
right: 10px;
|
||||
width: 10px;
|
||||
height: 10px;
|
||||
border-radius: 50%;
|
||||
background: #dc2626;
|
||||
border: 2px solid #ffffff;
|
||||
box-shadow: 0 0 0 1px rgba(220, 38, 38, 0.35);
|
||||
display: none;
|
||||
}
|
||||
|
||||
.user-notification-dot.visible {
|
||||
display: block;
|
||||
}
|
||||
|
||||
.notification-toast {
|
||||
position: fixed;
|
||||
right: 16px;
|
||||
bottom: 18px;
|
||||
z-index: 2300;
|
||||
max-width: 360px;
|
||||
background: #0f172a;
|
||||
color: #fff;
|
||||
border-radius: 10px;
|
||||
border: 1px solid rgba(148, 163, 184, 0.35);
|
||||
box-shadow: 0 18px 35px rgba(2, 6, 23, 0.4);
|
||||
padding: 12px 14px;
|
||||
font-size: 0.9rem;
|
||||
line-height: 1.35;
|
||||
display: none;
|
||||
}
|
||||
|
||||
.notification-toast strong {
|
||||
display: block;
|
||||
margin-bottom: 2px;
|
||||
}
|
||||
|
||||
.notification-toast.show {
|
||||
display: block;
|
||||
}
|
||||
</style>
|
||||
<div id="cookie-banner" role="dialog" aria-live="polite" aria-label="Cookie-Hinweis">
|
||||
<div class="cb-inner">
|
||||
@@ -624,6 +825,38 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="notification-toast" class="notification-toast" role="status" aria-live="polite">
|
||||
<strong id="notification-toast-title">Neue Benachrichtigung</strong>
|
||||
<span id="notification-toast-message"></span>
|
||||
</div>
|
||||
|
||||
<datalist id="function-search-options">
|
||||
<option value="Artikel"></option>
|
||||
<option value="Meine Ausleihen"></option>
|
||||
<option value="Benachrichtigungen"></option>
|
||||
<option value="Tutorial"></option>
|
||||
<option value="Impressum"></option>
|
||||
<option value="Lizenz"></option>
|
||||
{% if library_module_enabled %}
|
||||
<option value="Bibliothek"></option>
|
||||
<option value="Meine Medien"></option>
|
||||
{% endif %}
|
||||
{% if 'username' in session and (session.get('admin', False) or is_admin) %}
|
||||
<option value="Hochladen"></option>
|
||||
<option value="Ausleihen Verwaltung"></option>
|
||||
<option value="Defekte Items"></option>
|
||||
<option value="Filter verwalten"></option>
|
||||
<option value="Orte verwalten"></option>
|
||||
<option value="Audit Dashboard"></option>
|
||||
<option value="Logs"></option>
|
||||
<option value="Benutzer verwalten"></option>
|
||||
<option value="Neuer Benutzer"></option>
|
||||
{% if student_cards_module_enabled %}
|
||||
<option value="Bibliotheksausweis"></option>
|
||||
{% endif %}
|
||||
{% endif %}
|
||||
</datalist>
|
||||
|
||||
<script>
|
||||
(function(){
|
||||
function getCookie(name){
|
||||
@@ -657,8 +890,231 @@
|
||||
const username = {{ (session['username'] if 'username' in session else '')|tojson }};
|
||||
const isTutorialPage = window.location.pathname === {{ url_for('tutorial_page')|tojson }};
|
||||
const isLoginPage = window.location.pathname === {{ url_for('login')|tojson }};
|
||||
const notificationsPagePath = {{ url_for('notifications_view')|tojson }};
|
||||
const onboardingKey = username ? ('inventarsystem_tutorial_prompt_v1_' + username) : null;
|
||||
const onboardingOverlay = document.getElementById('onboarding-overlay');
|
||||
const notificationButtons = Array.from(document.querySelectorAll('[data-notification-button="true"]'));
|
||||
const notificationToast = document.getElementById('notification-toast');
|
||||
const notificationToastTitle = document.getElementById('notification-toast-title');
|
||||
const notificationToastMessage = document.getElementById('notification-toast-message');
|
||||
let lastUnreadCount = Number({{ unread_notification_count|default(0)|int }});
|
||||
const loginHintKey = username ? ('inventarsystem_notification_login_hint_v1_' + username) : null;
|
||||
|
||||
const functionSearchEntries = [
|
||||
{ label: 'Artikel', keywords: ['artikel', 'inventar', 'home'], url: {{ url_for('home')|tojson }} },
|
||||
{ label: 'Meine Ausleihen', keywords: ['meine ausleihen', 'ausleihen', 'borrowed'], url: {{ url_for('my_borrowed_items')|tojson }} },
|
||||
{ label: 'Benachrichtigungen', keywords: ['benachrichtigungen', 'nachrichten', 'notifications'], url: {{ url_for('notifications_view')|tojson }} },
|
||||
{ label: 'Tutorial', keywords: ['tutorial', 'hilfe', 'anleitung'], url: {{ url_for('tutorial_page')|tojson }} },
|
||||
{ label: 'Impressum', keywords: ['impressum'], url: {{ url_for('impressum')|tojson }} },
|
||||
{ label: 'Lizenz', keywords: ['lizenz', 'license'], url: {{ url_for('license')|tojson }} },
|
||||
{% if library_module_enabled %}
|
||||
{ label: 'Bibliothek', keywords: ['bibliothek', 'medien'], url: {{ url_for('library_view')|tojson }} },
|
||||
{% endif %}
|
||||
{% if 'username' in session and (session.get('admin', False) or is_admin) %}
|
||||
{ label: 'Hochladen', keywords: ['hochladen', 'upload'], url: {{ url_for('upload_admin')|tojson }} },
|
||||
{ label: 'Ausleihen Verwaltung', keywords: ['ausleihen verwaltung', 'admin borrowings'], url: {{ url_for('admin_borrowings')|tojson }} },
|
||||
{ label: 'Defekte Items', keywords: ['defekte items', 'defekt', 'schaden'], url: {{ url_for('admin_damaged_items')|tojson }} },
|
||||
{ label: 'Filter verwalten', keywords: ['filter verwalten', 'filter'], url: {{ url_for('manage_filters')|tojson }} },
|
||||
{ label: 'Orte verwalten', keywords: ['orte verwalten', 'orte', 'location'], url: {{ url_for('manage_locations')|tojson }} },
|
||||
{ label: 'Audit Dashboard', keywords: ['audit', 'audit dashboard'], url: {{ url_for('admin_audit_dashboard')|tojson }} },
|
||||
{ label: 'Logs', keywords: ['logs', 'protokoll'], url: {{ url_for('logs')|tojson }} },
|
||||
{ label: 'Benutzer verwalten', keywords: ['benutzer verwalten', 'user'], url: {{ url_for('user_del')|tojson }} },
|
||||
{ label: 'Neuer Benutzer', keywords: ['neuer benutzer', 'register'], url: {{ url_for('register')|tojson }} },
|
||||
{% if library_module_enabled %}
|
||||
{ label: 'Bibliotheks-Ausleihen', keywords: ['bibliotheks ausleihen', 'library loans'], url: {{ url_for('library_loans_admin')|tojson }} },
|
||||
{% endif %}
|
||||
{% if student_cards_module_enabled %}
|
||||
{ label: 'Bibliotheksausweis', keywords: ['bibliotheksausweis', 'student card'], url: {{ url_for('student_cards_admin')|tojson }} },
|
||||
{% endif %}
|
||||
{% endif %}
|
||||
];
|
||||
|
||||
function normalizeSearchText(value) {
|
||||
return String(value || '')
|
||||
.toLowerCase()
|
||||
.replace(/[ä]/g, 'ae')
|
||||
.replace(/[ö]/g, 'oe')
|
||||
.replace(/[ü]/g, 'ue')
|
||||
.replace(/[ß]/g, 'ss')
|
||||
.trim();
|
||||
}
|
||||
|
||||
function findFunctionRoute(rawValue) {
|
||||
const input = normalizeSearchText(rawValue);
|
||||
if (!input) {
|
||||
return null;
|
||||
}
|
||||
|
||||
let exact = null;
|
||||
for (const entry of functionSearchEntries) {
|
||||
const candidates = [entry.label].concat(entry.keywords || []);
|
||||
for (const candidate of candidates) {
|
||||
if (normalizeSearchText(candidate) === input) {
|
||||
exact = entry;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (exact) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (exact) {
|
||||
return exact.url;
|
||||
}
|
||||
|
||||
for (const entry of functionSearchEntries) {
|
||||
const candidates = [entry.label].concat(entry.keywords || []);
|
||||
for (const candidate of candidates) {
|
||||
if (normalizeSearchText(candidate).includes(input) || input.includes(normalizeSearchText(candidate))) {
|
||||
return entry.url;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function bindFunctionSearchForms() {
|
||||
const forms = document.querySelectorAll('form[data-function-search="true"]');
|
||||
forms.forEach(function(form) {
|
||||
form.addEventListener('submit', function(event) {
|
||||
event.preventDefault();
|
||||
const input = form.querySelector('input[name="function_search"]');
|
||||
const targetUrl = findFunctionRoute(input ? input.value : '');
|
||||
if (targetUrl) {
|
||||
window.location.href = targetUrl;
|
||||
return;
|
||||
}
|
||||
showInAppNotification('Keine Funktion gefunden', 'Bitte Suche verfeinern, z.B. "Defekte Items" oder "Benachrichtigungen".');
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
bindFunctionSearchForms();
|
||||
|
||||
function maybeShowLoginNotificationHint() {
|
||||
if (!username || !loginHintKey) {
|
||||
return;
|
||||
}
|
||||
if (window.location.pathname === notificationsPagePath) {
|
||||
return;
|
||||
}
|
||||
|
||||
const alreadyShown = sessionStorage.getItem(loginHintKey);
|
||||
if (alreadyShown) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (lastUnreadCount > 0) {
|
||||
const hintTitle = 'Neue Benachrichtigungen';
|
||||
const hintMessage =
|
||||
lastUnreadCount === 1
|
||||
? 'Sie haben 1 neue Benachrichtigung. Im Nutzer-Menue finden Sie den Eintrag Benachrichtigungen.'
|
||||
: 'Sie haben ' + lastUnreadCount + ' neue Benachrichtigungen. Im Nutzer-Menue finden Sie den Eintrag Benachrichtigungen.';
|
||||
showInAppNotification(hintTitle, hintMessage);
|
||||
}
|
||||
|
||||
sessionStorage.setItem(loginHintKey, 'shown');
|
||||
}
|
||||
|
||||
maybeShowLoginNotificationHint();
|
||||
|
||||
function updateNotificationDots(unreadCount) {
|
||||
const hasUnread = Number(unreadCount) > 0;
|
||||
notificationButtons.forEach(function(btn) {
|
||||
const dot = btn.querySelector('.user-notification-dot');
|
||||
if (!dot) {
|
||||
return;
|
||||
}
|
||||
if (hasUnread) {
|
||||
dot.classList.add('visible');
|
||||
} else {
|
||||
dot.classList.remove('visible');
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function showInAppNotification(title, message) {
|
||||
if (!notificationToast || !notificationToastTitle || !notificationToastMessage) {
|
||||
return;
|
||||
}
|
||||
notificationToastTitle.textContent = title || 'Neue Benachrichtigung';
|
||||
notificationToastMessage.textContent = message || '';
|
||||
notificationToast.classList.add('show');
|
||||
window.setTimeout(function() {
|
||||
notificationToast.classList.remove('show');
|
||||
}, 5000);
|
||||
}
|
||||
|
||||
function showBrowserNotification(title, message) {
|
||||
if (!('Notification' in window)) {
|
||||
showInAppNotification(title, message);
|
||||
return;
|
||||
}
|
||||
if (Notification.permission === 'granted') {
|
||||
new Notification(title || 'Neue Benachrichtigung', {
|
||||
body: message || '',
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (Notification.permission === 'default') {
|
||||
Notification.requestPermission().then(function(permission) {
|
||||
if (permission === 'granted') {
|
||||
new Notification(title || 'Neue Benachrichtigung', {
|
||||
body: message || '',
|
||||
});
|
||||
} else {
|
||||
showInAppNotification(title, message);
|
||||
}
|
||||
}).catch(function() {
|
||||
showInAppNotification(title, message);
|
||||
});
|
||||
return;
|
||||
}
|
||||
showInAppNotification(title, message);
|
||||
}
|
||||
|
||||
function pollNotificationStatus() {
|
||||
if (!username) {
|
||||
return;
|
||||
}
|
||||
|
||||
fetch('/notifications/unread_status', {
|
||||
method: 'GET',
|
||||
headers: {
|
||||
'Accept': 'application/json'
|
||||
}
|
||||
})
|
||||
.then(function(response) {
|
||||
if (!response.ok) {
|
||||
throw new Error('status request failed');
|
||||
}
|
||||
return response.json();
|
||||
})
|
||||
.then(function(data) {
|
||||
if (!data || !data.ok) {
|
||||
return;
|
||||
}
|
||||
|
||||
const unreadCount = Number(data.unread_count || 0);
|
||||
updateNotificationDots(unreadCount);
|
||||
|
||||
if (unreadCount > lastUnreadCount && window.location.pathname !== notificationsPagePath) {
|
||||
const latest = data.latest_unread || {};
|
||||
showBrowserNotification(latest.title || 'Neue Nachricht', latest.message || 'Es gibt neue Benachrichtigungen.');
|
||||
}
|
||||
|
||||
lastUnreadCount = unreadCount;
|
||||
})
|
||||
.catch(function() {
|
||||
// Silent fail; polling retries automatically.
|
||||
});
|
||||
}
|
||||
|
||||
updateNotificationDots(lastUnreadCount);
|
||||
if (username) {
|
||||
window.setInterval(pollNotificationStatus, 30000);
|
||||
}
|
||||
|
||||
function showOnboarding(){
|
||||
if (onboardingOverlay) {
|
||||
|
||||
@@ -14,20 +14,21 @@
|
||||
<div class="container my-4">
|
||||
<div class="impressum-content bg-white p-4 shadow rounded">
|
||||
<h1 class="mb-4 text-center">Impressum</h1>
|
||||
<p class="text-center mb-5">(Angaben gemäß § 5 TMG)</p>
|
||||
<p class="text-center mb-5">(Angaben gemäß § 5 DDG)</p>
|
||||
|
||||
<div class="impressum-section mb-4">
|
||||
<h3 class="mb-3">Kontaktinformationen</h3>
|
||||
<p><strong>Name:</strong> . ..</p>
|
||||
<p><strong>Adresse:</strong> Musterstraße 123<br>12345 Musterstadt<br>Deutschland</p>
|
||||
<p><strong>E-Mail:</strong> <a href="mailto:kontakt@example.com">kontakt@example.com</a></p>
|
||||
<p><strong>Telefon:</strong> +49 123 456789</p>
|
||||
<address class="mb-0">
|
||||
<p><strong>Name:</strong> Invario UG</p>
|
||||
<p><strong>Adresse:</strong> Musterstraße 123<br>12345 Musterstadt<br>Deutschland</p>
|
||||
</address>
|
||||
<p><strong>E-Mail:</strong> <a href="mailto:info@invario.eu">info@invario.eu</a></p>
|
||||
</div>
|
||||
|
||||
<div class="impressum-section mb-4">
|
||||
<h3 class="mb-3">Verantwortlich für den Inhalt</h3>
|
||||
<p>(nach § 55 Abs. 2 RStV)</p>
|
||||
<p>...<br>
|
||||
<p>(nach § 18 Abs. 2 MStV)</p>
|
||||
<p>Invario UG<br>
|
||||
Musterstraße 123<br>
|
||||
12345 Musterstadt<br>
|
||||
Deutschland</p>
|
||||
@@ -37,7 +38,7 @@
|
||||
<h3 class="mb-3">Haftungsausschluss</h3>
|
||||
|
||||
<h4 class="mb-2">Haftung für Inhalte</h4>
|
||||
<p>Die Inhalte unserer Seiten wurden mit größter Sorgfalt erstellt. Für die Richtigkeit, Vollständigkeit und Aktualität der Inhalte können wir jedoch keine Gewähr übernehmen. Als Diensteanbieter sind wir gemäß § 7 Abs.1 TMG für eigene Inhalte auf diesen Seiten nach den allgemeinen Gesetzen verantwortlich. Nach §§ 8 bis 10 TMG sind wir als Diensteanbieter jedoch nicht verpflichtet, übermittelte oder gespeicherte fremde Informationen zu überwachen oder nach Umständen zu forschen, die auf eine rechtswidrige Tätigkeit hinweisen.</p>
|
||||
<p>Die Inhalte unserer Seiten wurden mit größter Sorgfalt erstellt. Für die Richtigkeit, Vollständigkeit und Aktualität der Inhalte können wir jedoch keine Gewähr übernehmen. Als Diensteanbieter sind wir gemäß § 7 Abs. 1 DDG für eigene Inhalte auf diesen Seiten nach den allgemeinen Gesetzen verantwortlich. Nach §§ 8 bis 10 DDG sind wir als Diensteanbieter jedoch nicht verpflichtet, übermittelte oder gespeicherte fremde Informationen zu überwachen oder nach Umständen zu forschen, die auf eine rechtswidrige Tätigkeit hinweisen.</p>
|
||||
|
||||
<h4 class="mb-2">Haftung für Links</h4>
|
||||
<p>Unser Angebot enthält Links zu externen Websites Dritter, auf deren Inhalte wir keinen Einfluss haben. Deshalb können wir für diese fremden Inhalte auch keine Gewähr übernehmen. Für die Inhalte der verlinkten Seiten ist stets der jeweilige Anbieter oder Betreiber der Seiten verantwortlich. Die verlinkten Seiten wurden zum Zeitpunkt der Verlinkung auf mögliche Rechtsverstöße überprüft. Rechtswidrige Inhalte waren zum Zeitpunkt der Verlinkung nicht erkennbar.</p>
|
||||
|
||||
@@ -321,11 +321,6 @@
|
||||
<li><strong>Einwilligung:</strong> Falls private Daten der Nutzer erfasst werden, muss eine explizite
|
||||
Einwilligung vorliegen (Art. 6 Abs. 1 lit. a DSGVO).</li>
|
||||
</ol>
|
||||
<div class="license-exception-notice" style="background-color:#f8d7da; border-color:#f5c2c7; border-left-color:#dc3545;">
|
||||
<h3 style="color:#842029;">⚠️ Hinweis</h3>
|
||||
<p>Dieses Dokument stellt <strong>keine Rechtsberatung</strong> dar. Bitte konsultieren Sie im Zweifelsfall
|
||||
einen Fachanwalt für Datenschutzrecht.</p>
|
||||
</div>
|
||||
</div>
|
||||
</div><!-- /#pane-legal -->
|
||||
|
||||
|
||||
@@ -728,6 +728,7 @@
|
||||
let mainItemsNextOffset = 0;
|
||||
let mainItemsHasMore = false;
|
||||
let mainItemsLoadingMore = false;
|
||||
let mainItemsLightMode = true; // Track if we're in light mode to gradually request full data
|
||||
let mainItemsObserver = null;
|
||||
let mainItemsSentinel = null;
|
||||
let mainItemsLoadingIndicator = null;
|
||||
@@ -788,7 +789,10 @@
|
||||
}
|
||||
|
||||
function loadItems(offset = 0, append = false) {
|
||||
return fetch(`{{ url_for('get_items') }}?offset=${offset}&limit=${MAIN_ITEMS_PAGE_SIZE}`)
|
||||
// Für Pages nach der ersten: Explizit vollständige Daten laden (light_mode=false)
|
||||
// Erste Page: light_mode wird automatisch enablet
|
||||
const lightModeParam = offset > 0 ? '&light_mode=false' : '';
|
||||
return fetch(`{{ url_for('get_items') }}?offset=${offset}&limit=${MAIN_ITEMS_PAGE_SIZE}${lightModeParam}`)
|
||||
.then(response => response.json())
|
||||
.then(data => {
|
||||
const itemsContainer = document.querySelector('#items-container');
|
||||
|
||||
@@ -415,13 +415,17 @@
|
||||
}
|
||||
|
||||
.bulk-delete-row {
|
||||
display: flex;
|
||||
display: none;
|
||||
justify-content: flex-start;
|
||||
align-items: center;
|
||||
margin-bottom: 8px;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.bulk-delete-mode-active .bulk-delete-row {
|
||||
display: flex;
|
||||
}
|
||||
|
||||
.bulk-delete-toggle {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
@@ -3056,6 +3060,7 @@ document.addEventListener('DOMContentLoaded', ()=>{
|
||||
bulkDeleteDrawerOpen = Boolean(open);
|
||||
const drawer = document.getElementById('bulk-delete-drawer');
|
||||
const toggle = document.getElementById('bulk-delete-drawer-toggle');
|
||||
const itemsContainer = document.querySelector('#items-container');
|
||||
if (drawer) {
|
||||
drawer.classList.toggle('open', bulkDeleteDrawerOpen);
|
||||
drawer.setAttribute('aria-hidden', bulkDeleteDrawerOpen ? 'false' : 'true');
|
||||
@@ -3065,6 +3070,10 @@ document.addEventListener('DOMContentLoaded', ()=>{
|
||||
toggle.innerHTML = bulkDeleteDrawerOpen ? '<span class="drawer-icon">✕</span>' : '<span class="drawer-icon">⚙</span>';
|
||||
toggle.title = bulkDeleteDrawerOpen ? 'Massenlöschung schließen' : 'Massenlöschung öffnen';
|
||||
}
|
||||
// Toggle checkbox visibility: show checkboxes only when bulk delete mode is active
|
||||
if (itemsContainer) {
|
||||
itemsContainer.classList.toggle('bulk-delete-mode-active', bulkDeleteDrawerOpen);
|
||||
}
|
||||
}
|
||||
|
||||
function toggleBulkDeleteDrawer() {
|
||||
@@ -3310,6 +3319,7 @@ document.addEventListener('DOMContentLoaded', ()=>{
|
||||
let mainAdminItemsNextOffset = 0;
|
||||
let mainAdminItemsHasMore = false;
|
||||
let mainAdminItemsLoadingMore = false;
|
||||
let mainAdminLightMode = true; // Track if we're in light mode to gradually request full data
|
||||
let mainAdminItemsObserver = null;
|
||||
let mainAdminItemsSentinel = null;
|
||||
let mainAdminItemsLoadingIndicator = null;
|
||||
@@ -3371,7 +3381,10 @@ document.addEventListener('DOMContentLoaded', ()=>{
|
||||
}
|
||||
|
||||
function loadItems(offset = 0, append = false) {
|
||||
return fetch(`{{ url_for('get_items') }}?offset=${offset}&limit=${MAIN_ADMIN_ITEMS_PAGE_SIZE}`)
|
||||
// Für Pages nach der ersten: Explizit vollständige Daten laden (light_mode=false)
|
||||
// Erste Page: light_mode wird automatisch enablet
|
||||
const lightModeParam = offset > 0 ? '&light_mode=false' : '';
|
||||
return fetch(`{{ url_for('get_items') }}?offset=${offset}&limit=${MAIN_ADMIN_ITEMS_PAGE_SIZE}${lightModeParam}`)
|
||||
.then(response => response.json())
|
||||
.then(data => {
|
||||
const itemsContainer = document.querySelector('#items-container');
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
{% extends "base.html" %}
|
||||
|
||||
{% block title %}Benachrichtigungen{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<div class="container" style="max-width: 1080px; margin: 18px auto 32px;">
|
||||
<div style="display:flex; justify-content:space-between; gap:12px; align-items:center; margin-bottom:16px; flex-wrap:wrap;">
|
||||
<div>
|
||||
<h1 style="margin:0;">Benachrichtigungen</h1>
|
||||
<p style="margin:6px 0 0; color:#64748b;">Rueckgabe-Erinnerungen und wichtige Hinweise fuer Benutzer und Verwaltung.</p>
|
||||
</div>
|
||||
<form method="post" action="{{ url_for('mark_all_notifications_read') }}">
|
||||
<button class="btn btn-outline-secondary" type="submit">Alle als gelesen markieren</button>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
<div style="display:grid; grid-template-columns:1fr; gap:14px;">
|
||||
<section style="background:#fff; border:1px solid #e2e8f0; border-radius:14px; padding:16px;">
|
||||
<h2 style="margin:0 0 12px; font-size:1.15rem;">Meine Benachrichtigungen</h2>
|
||||
{% if user_notifications %}
|
||||
<div style="display:grid; gap:10px;">
|
||||
{% for n in user_notifications %}
|
||||
<article style="border:1px solid #e5e7eb; border-left:5px solid {% if n.severity == 'danger' %}#dc2626{% elif n.severity == 'warning' %}#d97706{% else %}#2563eb{% endif %}; border-radius:10px; padding:12px 12px 10px; background:{% if n.is_read %}#f8fafc{% else %}#ffffff{% endif %};">
|
||||
<div style="display:flex; justify-content:space-between; gap:10px; align-items:flex-start; flex-wrap:wrap;">
|
||||
<div>
|
||||
<div style="font-weight:800; color:#0f172a;">{{ n.title }}</div>
|
||||
<div style="font-size:0.9rem; color:#475569; margin-top:2px;">{{ n.message }}</div>
|
||||
{% if n.type == 'damage_reported' %}
|
||||
<div style="margin-top:8px;">
|
||||
<a class="btn btn-sm btn-outline-danger" href="{{ url_for('admin_damaged_items') }}">Zu Defekte-Items Verwaltung</a>
|
||||
</div>
|
||||
{% endif %}
|
||||
<div style="font-size:0.78rem; color:#64748b; margin-top:6px;">
|
||||
{% if n.created_at %}{{ n.created_at.strftime('%d.%m.%Y %H:%M') }}{% else %}-{% endif %}
|
||||
</div>
|
||||
</div>
|
||||
{% if not n.is_read %}
|
||||
<form method="post" action="{{ url_for('mark_notification_read', notification_id=n.id) }}">
|
||||
<button class="btn btn-sm btn-primary" type="submit">Als gelesen</button>
|
||||
</form>
|
||||
{% else %}
|
||||
<span style="font-size:0.8rem; color:#16a34a; font-weight:700;">Gelesen</span>
|
||||
{% endif %}
|
||||
</div>
|
||||
</article>
|
||||
{% endfor %}
|
||||
</div>
|
||||
{% else %}
|
||||
<p style="color:#64748b; margin:0;">Keine Benachrichtigungen vorhanden.</p>
|
||||
{% endif %}
|
||||
</section>
|
||||
|
||||
{% if is_admin_user %}
|
||||
<section style="background:#fff; border:1px solid #e2e8f0; border-radius:14px; padding:16px;">
|
||||
<h2 style="margin:0 0 12px; font-size:1.15rem;">Admin-Benachrichtigungen</h2>
|
||||
{% if admin_notifications %}
|
||||
<div style="display:grid; gap:10px;">
|
||||
{% for n in admin_notifications %}
|
||||
<article style="border:1px solid #e5e7eb; border-left:5px solid {% if n.severity == 'danger' %}#dc2626{% elif n.severity == 'warning' %}#d97706{% else %}#2563eb{% endif %}; border-radius:10px; padding:12px 12px 10px; background:{% if n.is_read %}#f8fafc{% else %}#ffffff{% endif %};">
|
||||
<div style="display:flex; justify-content:space-between; gap:10px; align-items:flex-start; flex-wrap:wrap;">
|
||||
<div>
|
||||
<div style="font-weight:800; color:#0f172a;">{{ n.title }}</div>
|
||||
<div style="font-size:0.9rem; color:#475569; margin-top:2px;">{{ n.message }}</div>
|
||||
<div style="font-size:0.78rem; color:#64748b; margin-top:6px;">
|
||||
{% if n.created_at %}{{ n.created_at.strftime('%d.%m.%Y %H:%M') }}{% else %}-{% endif %}
|
||||
</div>
|
||||
</div>
|
||||
{% if not n.is_read %}
|
||||
<form method="post" action="{{ url_for('mark_notification_read', notification_id=n.id) }}">
|
||||
<button class="btn btn-sm btn-primary" type="submit">Als gelesen</button>
|
||||
</form>
|
||||
{% else %}
|
||||
<span style="font-size:0.8rem; color:#16a34a; font-weight:700;">Gelesen</span>
|
||||
{% endif %}
|
||||
</div>
|
||||
</article>
|
||||
{% endfor %}
|
||||
</div>
|
||||
{% else %}
|
||||
<p style="color:#64748b; margin:0;">Keine Admin-Benachrichtigungen vorhanden.</p>
|
||||
{% endif %}
|
||||
</section>
|
||||
{% endif %}
|
||||
</div>
|
||||
</div>
|
||||
{% endblock %}
|
||||
@@ -124,12 +124,12 @@
|
||||
<div class="container">
|
||||
<div class="icon">📇</div>
|
||||
<h1>Schülerausweis-Download</h1>
|
||||
<p>Generieren Sie eine PDF mit Barcodes aller Schülerausweise zum direkten Drucken</p>
|
||||
<p>Generieren Sie eine PDF mit Barcodes aller Bibliotheksausweise zum direkten Drucken</p>
|
||||
|
||||
<div class="info-box">
|
||||
<strong>📌 Was wird heruntergeladen?</strong>
|
||||
<p>Eine druckfertige PDF mit:</p>
|
||||
<p>✓ Alle Schülerausweise</p>
|
||||
<p>✓ Alle Bibliotheksausweise</p>
|
||||
<p>✓ Scanbare CODE128 Barcodes</p>
|
||||
<p>✓ Optimiert für A4-Druck (2 Karten pro Seite)</p>
|
||||
<p>✓ Professionelle Qualität</p>
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
-->
|
||||
{% extends "base.html" %}
|
||||
|
||||
{% block title %}Schülerausweise - Inventarsystem{% endblock %}
|
||||
{% block title %}Bibliotheksausweise - Inventarsystem{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<style>
|
||||
@@ -229,7 +229,7 @@
|
||||
<div class="container">
|
||||
<div class="student-card-header">
|
||||
<div>
|
||||
<h1>📚 Schülerausweise (Bibliotek)</h1>
|
||||
<h1>📚 Bibliotheksausweise (Bibliotek)</h1>
|
||||
</div>
|
||||
<div class="export-buttons">
|
||||
<a href="{{ url_for('student_card_barcode_download') }}" class="btn-print" style="background: #28a745;">📥 Alle Ausweise (PDF)</a>
|
||||
@@ -342,7 +342,7 @@
|
||||
</table>
|
||||
{% else %}
|
||||
<div class="empty-state">
|
||||
<p>Keine Schülerausweise registriert.</p>
|
||||
<p>Keine Bibliotheksausweise registriert.</p>
|
||||
<p>Fügen Sie ein neues Ausweis oben hinzu.</p>
|
||||
</div>
|
||||
{% endif %}
|
||||
|
||||
+3
-1
@@ -30,6 +30,8 @@ services:
|
||||
dockerfile: Dockerfile
|
||||
container_name: inventarsystem-app
|
||||
restart: unless-stopped
|
||||
security_opt:
|
||||
- no-new-privileges:true
|
||||
depends_on:
|
||||
mongodb:
|
||||
condition: service_healthy
|
||||
@@ -43,7 +45,7 @@ services:
|
||||
- "8000"
|
||||
volumes:
|
||||
- ./config.json:/app/config.json:ro
|
||||
- ./Web:/app/Web
|
||||
- ./Web:/app/Web:ro
|
||||
- app_uploads:/app/Web/uploads
|
||||
- app_thumbnails:/app/Web/thumbnails
|
||||
- app_previews:/app/Web/previews
|
||||
|
||||
Reference in New Issue
Block a user