Compare commits

...

36 Commits

Author SHA1 Message Date
Aiirondev_dev 78c215b234 slight database mixup fix
Release Inventarsystem / release-docker (push) Successful in 2m44s
2026-08-19 20:14:23 +02:00
Aiirondev_dev 9e77b4604d slight database mixup fix
Release Inventarsystem / release-docker (push) Successful in 2m14s
2026-08-19 19:57:13 +02:00
Aiirondev_dev c06473644a slight database mixup fix
Release Inventarsystem / release-docker (push) Successful in 2m14s
2026-08-19 18:55:30 +02:00
Aiirondev_dev 6c855ed9d9 slight database mixup fix
Release Inventarsystem / release-docker (push) Successful in 2m15s
2026-08-19 18:49:36 +02:00
Aiirondev_dev b09a6f7720 slight database mixup fix
Release Inventarsystem / release-docker (push) Successful in 3m25s
2026-08-19 18:42:01 +02:00
Aiirondev_dev 8c5185bd8c Spelling mistakes and renaming done.
Release Inventarsystem / release-docker (push) Successful in 2m16s
2026-08-18 21:52:45 +02:00
Aiirondev_dev 0b30f8463f Renamed from Ausleihen, to Alle Ausleihen. in base.html
Release Inventarsystem / release-docker (push) Successful in 2m14s
2026-08-18 21:43:00 +02:00
Aiirondev_dev 671a9e8e85 Renaming of the ResetCardBtn to Feld zurücksetzen in regards to user comprehension.
Release Inventarsystem / release-docker (push) Successful in 2m26s
2026-08-18 21:31:52 +02:00
Aiirondev_dev 3d9e5c470a Fix of an issue with the data being use for the button insert
Release Inventarsystem / release-docker (push) Successful in 2m16s
2026-08-18 21:12:47 +02:00
Aiirondev_dev e636242542 fix for the cost button in the damaged items cost
Release Inventarsystem / release-docker (push) Successful in 2m16s
2026-08-18 21:00:14 +02:00
Aiirondev_dev d61aeebb8f Implementation of a extra button to add the complete replacement for the Bibliotheks item
Release Inventarsystem / release-docker (push) Successful in 2m14s
2026-08-18 20:37:04 +02:00
Aiirondev_dev 375e9c46eb slight fix of an import dubbeling
Release Inventarsystem / release-docker (push) Successful in 2m14s
2026-08-18 20:33:17 +02:00
Aiirondev 8dc773d202 README.md aktualisiert
Release Inventarsystem / release-docker (push) Successful in 2m45s
2026-08-18 17:59:25 +00:00
Aiirondev_dev 1b2b462c52 changes to the _upload student to have the field encryptet
Release Inventarsystem / release-docker (push) Successful in 2m17s
2026-08-18 18:51:49 +02:00
Aiirondev_dev bd7ef61f5a Initial implementation of a studentcard abgleich.
Release Inventarsystem / release-docker (push) Successful in 2m15s
2026-08-18 18:10:44 +02:00
Aiirondev_dev df0f7d3066 Style changes to the student Cards admin
Release Inventarsystem / release-docker (push) Successful in 2m18s
2026-08-18 17:06:24 +02:00
Aiirondev_dev 2215fc76d8 Style changes to the student Cards admin
Release Inventarsystem / release-docker (push) Successful in 2m14s
2026-08-18 17:01:09 +02:00
Aiirondev_dev e177936359 Renaming of Medien to Medien/Asuleihe
Release Inventarsystem / release-docker (push) Successful in 2m14s
2026-08-18 16:19:50 +02:00
Aiirondev_dev ae4a7226fa Changes to implement the ausweis_ident variable to correctly idententify students with the same name
Release Inventarsystem / release-docker (push) Successful in 2m15s
2026-08-18 14:46:55 +02:00
Aiirondev_dev 16a10a8c09 fix of breaking error
Release Inventarsystem / release-docker (push) Successful in 2m14s
2026-08-18 12:35:15 +02:00
Aiirondev_dev 3d4048d23b esential bugs being fixed and some new adjustemnets for the student card functionality
Release Inventarsystem / release-docker (push) Failing after 1m2s
2026-08-18 12:28:55 +02:00
Aiirondev_dev 6985f32fe9 fix(scheduler): eliminate worker race conditions using MongoDB lock
Release Inventarsystem / release-docker (push) Successful in 3m20s
- Replace fragile .scheduler_lock file mechanism with atomic MongoDB operations
- Prevent multiple background schedulers from starting across web workers
- Add heartbeat task to renew lock periodically and handle crash recovery
- Release lock cleanly on application shutdown
2026-08-17 15:49:51 +02:00
Aiirondev_dev ab7a369b6e removal of automatic return of files
Release Inventarsystem / release-docker (push) Failing after 34s
2026-08-17 15:31:22 +02:00
Aiirondev_dev 27be38dfc9 Spelling enhancements
Release Inventarsystem / release-docker (push) Successful in 2m17s
2026-08-17 13:33:51 +02:00
Aiirondev_dev 140fb5f743 Implementation of an automatic code generation and generation of an excel.
Release Inventarsystem / release-docker (push) Successful in 2m14s
2026-08-17 12:18:19 +02:00
Aiirondev_dev 9ea0ae6157 Implementation of an automatic id code generation.
Release Inventarsystem / release-docker (push) Successful in 3m12s
2026-08-17 11:50:35 +02:00
Aiirondev_dev bb89b434ed Error fixing and debugging implementation.
Release Inventarsystem / release-docker (push) Successful in 2m15s
2026-08-17 01:07:38 +02:00
Aiirondev_dev ac4d125d73 Error fixing and debugging implementation.
Release Inventarsystem / release-docker (push) Successful in 2m15s
2026-08-17 00:57:18 +02:00
Aiirondev_dev 3f6830e8c8 Error fixing and debugging implementation.
Release Inventarsystem / release-docker (push) Successful in 2m14s
2026-08-17 00:50:35 +02:00
Aiirondev_dev 0ea5d2db26 Error fixing and debugging implementation.
Release Inventarsystem / release-docker (push) Successful in 2m17s
2026-08-17 00:39:38 +02:00
Aiirondev_dev 41d9c0a848 Style fix for the detailed galery view.
Release Inventarsystem / release-docker (push) Successful in 2m15s
2026-08-17 00:19:07 +02:00
Aiirondev_dev f6e3db9b4a Style fix for the detailed galery view.
Release Inventarsystem / release-docker (push) Successful in 2m15s
2026-08-17 00:11:39 +02:00
Aiirondev_dev 7e5ee7b5ea Slight fix of the displaying of the detailed view, for the bibliothek focusing on the style
Release Inventarsystem / release-docker (push) Successful in 2m15s
2026-08-17 00:02:49 +02:00
Aiirondev_dev 2528e79895 Slight fix of the displaying of the detailed view, for the bibliothek
Release Inventarsystem / release-docker (push) Successful in 2m14s
2026-08-16 23:50:24 +02:00
Aiirondev_dev 542caa520f fix of a redirect error
Release Inventarsystem / release-docker (push) Successful in 2m15s
2026-08-16 23:21:31 +02:00
Aiirondev_dev 5136e40587 Implementation of a clean up function for a stray collection processing
Release Inventarsystem / release-docker (push) Successful in 2m15s
2026-08-16 23:08:10 +02:00
8 changed files with 789 additions and 328 deletions
+1 -1
View File
@@ -1,6 +1,6 @@
# Inventarsystem
[![https://github.com/AIIrondev/legendary-octo-garbanzo](https://github.com/AIIrondev/legendary-octo-garbanzo/actions/workflows/release-docker.yml/badge.svg)](https://github.com/AIIrondev/legendary-octo-garbanzo/actions/workflows/release-docker.yml)
[![https://git.invario-software.eu/Invario/Inventarsystem](https://git.invario-software.eu/Invario/Inventarsystem/actions/workflows/release-docker.yml/badge.svg)](https://git.invario-software.eu/Invario/Inventarsystem/actions/workflows/release-docker.yml)
[![wakatime](https://wakatime.com/badge/user/30b8509f-5e17-4d16-b6b8-3ca0f3f936d3/project/8a380b7f-389f-4a7e-8877-0fe9e1a4c243.svg)](https://wakatime.com/badge/user/30b8509f-5e17-4d16-b6b8-3ca0f3f936d3/project/8a380b7f-389f-4a7e-8877-0fe9e1a4c243)
+287 -172
View File
@@ -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,8 +2137,21 @@ 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 from Excel with automatic name/class mapping, rollover support, and encryption."""
if 'username' not in session:
flash('Nicht angemeldet.', 'error')
return redirect(url_for('login'))
@@ -2127,6 +2176,8 @@ def _upload_student_cards_excel():
flash('Nur .xlsx oder .csv Dateien werden unterstützt.', 'error')
return redirect(url_for('student_cards_admin'))
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'),
@@ -2167,7 +2220,7 @@ def _upload_student_cards_excel():
}
validation_only = (request.form.get('excel_action') or '').strip().lower() == 'validate'
max_rows = 15000
max_rows = 1500
planned_rows = []
validation_errors = []
@@ -2177,10 +2230,12 @@ 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())
student_cards_col = db['student_cards']
student_cards_cursor = student_cards_col.find({}, {'AusweisId': 1})
existing_ids.update(
str(card.get('AusweisId', '')).strip().upper()
for card in student_cards.find({}, {'AusweisId': 1})
for card in student_cards_cursor
if card.get('AusweisId')
)
@@ -2198,34 +2253,37 @@ 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')
row_errors.append('Vorname und Nachname fehlen')
if not ausweis_id and student_name:
ausweis_id = _build_student_card_excel_id(student_name, class_name, row_number, existing_ids)
ausweis_id = generate_ausweis_id(existing_ids)
validation_warnings.append((row_number, f'Ausweis-ID wurde automatisch erzeugt: {ausweis_id}'))
elif ausweis_id:
existing_ids.add(ausweis_id.upper())
elif ausweis_id and not rollover_mode:
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)
if not ausweis_ident:
ausweis_ident = ausweis_id
if row_errors:
validation_errors.append((row_number, '; '.join(row_errors)))
continue
@@ -2233,65 +2291,134 @@ def _upload_student_cards_excel():
planned_rows.append({
'row_number': row_number,
'ausweis_id': ausweis_id,
'ausweis_ident': ausweis_ident,
'student_name': student_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:
raw_db_cards = list(student_cards_col.find())
decrypted_db_cards = []
for doc in raw_db_cards:
dec_name = decrypt_text(doc.get('SchülerName')) if doc.get('SchülerName') else ""
dec_class = decrypt_text(doc.get('Klasse')) if doc.get('Klasse') else ""
raw_ident = doc.get('ausweis_ident') or doc.get('AusweisIdent') or ""
dec_ident = raw_ident
if raw_ident and str(raw_ident).startswith("gAAAAA"):
try:
dec_ident = decrypt_text(raw_ident)
except Exception:
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:
warning_text = f" Hinweise: {'; '.join([f'Zeile {n}: {msg}' for n, msg in validation_warnings[:10]])}" if validation_warnings else ""
if rollover_mode:
flash(
f'Validierung erfolgreich ({len(planned_rows)} Excel-Zeilen). '
f'Abgleich-Vorschau: {matched_count} unverändert, {len(rows_to_create)} neu, {len(db_ids_to_delete)} zum Löschen.{warning_text}',
'success'
)
else:
flash(f'Validierung erfolgreich: {len(planned_rows)} Ausweise würden importiert.{warning_text}',
'success')
return redirect(url_for('student_cards_admin'))
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:
encrypted_payload = encrypt_document_fields(
{
'ausweis_ident': row['ausweis_ident'],
'SchülerName': row['student_name'],
'Klasse': row['class_name'],
'Notizen': row['notes'],
},
STUDENT_CARD_ENCRYPTED_FIELDS
)
student_cards.insert_one({
student_cards_col.insert_one({
'AusweisId': row['ausweis_id'],
'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')
flash('Fehler beim Import 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')
warning_details = f" Hinweise: {'; '.join([f'Zeile {n}: {msg}' for n, msg in validation_warnings[:10]])}" if validation_warnings else ""
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.{warning_details}',
'success'
)
else:
flash(f'Excel-Import erfolgreich: {created_total} Ausweise importiert.', 'success')
flash(f'Excel-Import erfolgreich: {created_total} Ausweise importiert.{warning_details}', '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:
@@ -3199,9 +3326,6 @@ def library_loans_admin():
_ensure_audit_indexes_once()
# IMPORT HINZUGEFÜGT: Entschlüsselungs-Tool importieren
from modules.inventarsystem.data_protection import decrypt_text
def fmt_dt(dt):
try:
return dt.strftime('%d.%m.%Y %H:%M') if dt else ''
@@ -3258,6 +3382,7 @@ def library_loans_admin():
'item_code': item_doc.get('Code_4', ''),
'item_author': item_doc.get('Author', ''),
'item_isbn': item_doc.get('ISBN', ''),
'item_cost_raw': item_doc.get('Anschaffungskosten', ''),
'user': decrypted_user,
'status': record.get('Status', ''),
'start': fmt_dt(record.get('Start')),
@@ -3826,11 +3951,14 @@ 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 jsonify({
'html': detail_html,
'images': item.get('Images', item.get('Bilder', []))
'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}")
@@ -3982,6 +4110,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():
@@ -4018,6 +4159,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),
@@ -4032,6 +4174,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)
@@ -4057,9 +4200,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,
@@ -4082,17 +4228,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,
@@ -5484,7 +5638,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'
@@ -5828,7 +5982,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(
@@ -7242,62 +7398,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():
"""
@@ -9008,13 +9108,17 @@ def admin_add_invoice_correction(borrow_id):
def library_item_invoices(item_id):
"""Show all stored invoices for one specific library item."""
if 'username' not in session:
flash('Ihnen ist es nicht gestattet auf dieser Internetanwendung, die eben besuchte Adrrese zu nutzen, versuchen sie es erneut nach dem sie sich mit einem berechtigten Nutzer angemeldet haben!', 'error')
flash(
'Ihnen ist es nicht gestattet auf dieser Internetanwendung, die eben besuchte Adrrese zu nutzen, versuchen sie es erneut nach dem sie sich mit einem berechtigten Nutzer angemeldet haben!',
'error')
return redirect(url_for('login'))
if not cfg.MODULES.is_enabled('library'):
flash('Bibliotheks-Modul ist deaktiviert.', 'error')
return redirect(url_for('home_admin'))
current_permissions = us.get_effective_permissions(session['username'])
if not current_permissions['pages'].get('library_loans_admin', False):
flash('Ihnen fehlen die nötigen Berechtigungen, um diese Aktion auszuführen.', 'error')
return redirect(url_for('library_view'))
@@ -9035,9 +9139,12 @@ def library_item_invoices(item_id):
flash('Bibliotheksmedium nicht gefunden.', 'error')
return redirect(url_for('library_loans_admin'))
item_id_obj = item_doc.get('_id')
item_id_str = str(item_id_obj)
borrow_docs = list(ausleihungen.find(
{
'Item': str(item_doc.get('_id')),
'Item': {'$in': [item_id_str, item_id_obj]},
'InvoiceData': {'$exists': True, '$ne': {}}
},
{
@@ -9052,19 +9159,27 @@ def library_item_invoices(item_id):
entries = []
for borrow_doc in borrow_docs:
invoice_data = borrow_doc.get('InvoiceData') or {}
created_at = invoice_data.get('created_at')
created_at_display = created_at.strftime('%d.%m.%Y %H:%M') if isinstance(created_at, datetime.datetime) else (str(created_at) if created_at else '')
created_at_display = created_at.strftime('%d.%m.%Y %H:%M') if isinstance(created_at,
datetime.datetime) else (
str(created_at) if created_at else '')
paid_at = invoice_data.get('paid_at')
paid_at_display = paid_at.strftime('%d.%m.%Y %H:%M') if isinstance(paid_at, datetime.datetime) else (str(paid_at) if paid_at else '')
paid_at_display = paid_at.strftime('%d.%m.%Y %H:%M') if isinstance(paid_at, datetime.datetime) else (
str(paid_at) if paid_at else '')
entries.append({
'borrow_id': str(borrow_doc.get('_id')),
'borrow_status': borrow_doc.get('Status', ''),
'borrow_user': borrow_doc.get('User', ''),
'borrow_start': borrow_doc.get('Start').strftime('%d.%m.%Y %H:%M') if isinstance(borrow_doc.get('Start'), datetime.datetime) else '',
'borrow_end': borrow_doc.get('End').strftime('%d.%m.%Y %H:%M') if isinstance(borrow_doc.get('End'), datetime.datetime) else '',
'borrow_start': borrow_doc.get('Start').strftime('%d.%m.%Y %H:%M') if isinstance(
borrow_doc.get('Start'), datetime.datetime) else '',
'borrow_end': borrow_doc.get('End').strftime('%d.%m.%Y %H:%M') if isinstance(borrow_doc.get('End'),
datetime.datetime) else '',
'invoice_number': invoice_data.get('invoice_number', ''),
'invoice_amount': _format_money_value(invoice_data.get('amount')),
'invoice_amount': _format_money_value(invoice_data.get('amount')) if hasattr(invoice_data,
'get') else '0,00',
'invoice_reason': invoice_data.get('damage_reason', ''),
'invoice_created_at': created_at_display,
'invoice_created_by': invoice_data.get('created_by', ''),
@@ -9087,6 +9202,7 @@ def library_item_invoices(item_id):
student_cards_module_enabled=cfg.MODULES.is_enabled('student_cards'),
mail_module_enabled=cfg.MODULES.is_enabled('mail')
)
except Exception as e:
app.logger.error(f"Error loading invoice history for item {item_id}: {e}")
flash('Fehler beim Laden der Rechnungshistorie.', 'error')
@@ -9095,7 +9211,6 @@ def library_item_invoices(item_id):
if client:
client.close()
@app.route('/admin_reset_user_password', methods=['POST'])
def admin_reset_user_password():
"""
+135 -1
View File
@@ -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()
+35
View File
@@ -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."""
+4 -4
View File
@@ -1261,10 +1261,10 @@
<li><a class="dropdown-item" href="{{ url_for('admin_school_settings') }}">Schulstammdaten</a></li>
{% endif %}
{% if current_permissions.pages.get('admin_borrowings', False) %}
<li><a class="dropdown-item" href="{{ url_for('admin_borrowings') }}">Ausleihen</a></li>
<li><a class="dropdown-item" href="{{ url_for('admin_borrowings') }}">Alle Ausleihen</a></li>
{% endif %}
{% if current_permissions.pages.get('admin_damaged_items', False) %}
<li><a class="dropdown-item" href="{{ url_for('admin_damaged_items') }}">Defekte Items</a></li>
<li><a class="dropdown-item" href="{{ url_for('admin_damaged_items') }}">Alle defekten Items</a></li>
{% endif %}
{% if current_permissions.actions.get('can_view_logs', False) and current_permissions.pages.get('admin_audit_dashboard', False) %}
<li><a class="dropdown-item" href="{{ url_for('admin_audit_dashboard') }}">Audit Dashboard</a></li>
@@ -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 %}
@@ -1372,7 +1372,7 @@
{% if 'username' in session and current_permissions.actions.get('can_manage_settings', False) %}
<li><h6 class="dropdown-header">Bibliotheks-Verwaltung</h6></li>
{% if current_permissions.pages.get('library_loans_admin', False) %}
<li><a class="dropdown-item" href="{{ url_for('library_loans_admin') }}">Ausleihen / Defekte Items</a></li>
<li><a class="dropdown-item" href="{{ url_for('library_loans_admin') }}">Alle Ausleihen/Alle Defekten Items</a></li>
{% endif %}
{% if student_cards_module_enabled %}
{% if current_permissions.actions.get('can_manage_users', False) %}
+59 -32
View File
@@ -407,14 +407,14 @@
</div>
</div>
<div id="damage-invoice-modal" style="display:none; position:fixed; inset:0; background:rgba(15,23,42,0.72); z-index:9999; padding:20px; overflow:auto;">
<div id="damage-invoice-modal" role="dialog" aria-modal="true" aria-labelledby="modal-title" style="display:none; position:fixed; inset:0; background:rgba(15,23,42,0.72); z-index:9999; padding:20px; overflow:auto;">
<div style="max-width:760px; margin:40px auto; background: var(--ui-surface); border-radius:12px; padding:24px; box-shadow:0 20px 60px rgba(0,0,0,0.3);">
<div style="display:flex; justify-content:space-between; align-items:center; gap:12px; margin-bottom:18px;">
<div>
<h2 style="margin:0;">Rechnung erstellen</h2>
<h2 id="modal-title" style="margin:0;">Rechnung erstellen</h2>
<p style="margin:6px 0 0; color:#666;">Die Rechnung nutzt das bestehende Rechnungssystem und kann direkt nach der Schadensmeldung erstellt werden.</p>
</div>
<button type="button" class="btn btn-secondary" onclick="closeDamageInvoiceModal()">Schließen</button>
<button type="button" class="btn btn-secondary" onclick="closeDamageInvoiceModal()" aria-label="Modal schließen">Schließen</button>
</div>
<form id="damage-invoice-form" method="post" action="">
@@ -432,7 +432,10 @@
<input id="damage-invoice-code" type="text" readonly style="width:100%; padding:10px; border:1px solid #ddd; border-radius:6px; background: var(--ui-surface-soft);">
</div>
<div>
<label for="damage-invoice-amount" style="display:block; font-weight:700; margin-bottom:6px;">Preis</label>
<div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:6px;">
<label for="damage-invoice-amount" style="font-weight:700; margin:0;">Preis</label>
<button type="button" id="damage-invoice-replace-btn" class="btn btn-outline-secondary btn-sm" style="padding: 2px 8px; font-size: 0.75rem;">Komplett ersetzen</button>
</div>
<input id="damage-invoice-amount" name="invoice_amount" type="text" required style="width:100%; padding:10px; border:1px solid #ddd; border-radius:6px;" placeholder="z.B. 12,50">
</div>
</div>
@@ -477,6 +480,7 @@
const damageInvoiceCode = document.getElementById('damage-invoice-code');
const damageInvoiceAmount = document.getElementById('damage-invoice-amount');
const damageInvoiceReason = document.getElementById('damage-invoice-reason');
const damageInvoiceReplaceBtn = document.getElementById('damage-invoice-replace-btn');
function openDamageReportPrompt(button) {
const row = button.closest('.loan-row');
@@ -494,41 +498,48 @@
const description = noteInput.trim() || 'Schaden erneut gemeldet';
// Visuelles Feedback: Button deaktivieren und Text ändern
const originalText = button.textContent;
button.disabled = true;
button.textContent = 'Speichere...';
fetch(`/report_damage/${itemId}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ description })
})
.then(response => response.json().then(data => ({ ok: response.ok, data })))
.then(({ ok, data }) => {
if (!ok || !data.success) {
.then(async response => {
// Robustes JSON-Parsing (verhindert Absturz, falls der Server kein JSON zurückgibt)
const data = await response.json().catch(() => ({}));
if (!response.ok || !data.success) {
throw new Error(data.message || 'Fehler beim Speichern der Schadensmeldung.');
}
return data;
})
.then(data => {
if (confirm('Schaden gespeichert. Soll direkt eine Rechnung erstellt werden?')) {
openDamageInvoiceModal(row, description);
// Button wieder zurücksetzen, da die Seite nicht neu geladen wird
button.disabled = false;
button.textContent = originalText;
return;
}
// Bei "Abbrechen" im Confirm -> Neuladen der Tabelle
window.location.reload();
})
.catch(error => {
alert(error.message || 'Fehler beim Speichern der Schadensmeldung.');
alert(error.message || 'Ein unbekannter Fehler ist aufgetreten.');
// Fehlerbehandlung: Button wieder aktiv schalten
button.disabled = false;
button.textContent = originalText;
});
}
window.openDamageReportPrompt = openDamageReportPrompt;
function openDamageInvoiceModal(row, description) {
const modal = document.getElementById('damage-invoice-modal');
const form = document.getElementById('damage-invoice-form');
const inputItem = document.getElementById('damage-invoice-item');
const inputBorrower = document.getElementById('damage-invoice-borrower');
const inputCode = document.getElementById('damage-invoice-code');
const inputAmount = document.getElementById('damage-invoice-amount');
const inputReason = document.getElementById('damage-invoice-reason');
if (!modal || !form) {
if (!damageInvoiceModal || !damageInvoiceForm) {
console.error("Modal oder Formular nicht gefunden.");
return;
}
@@ -537,29 +548,47 @@
const itemName = row.dataset.itemName || '';
const borrower = row.dataset.userName || '';
const itemCode = row.dataset.itemCode || '';
// KORREKTUR: Jetzt greifen wir auf das richtige dataset-Attribut zu
const itemCost = row.dataset.itemCost || '';
form.action = "{{ url_for('admin_create_invoice', borrow_id='__BORROW_ID__') }}".replace('__BORROW_ID__', borrowId);
damageInvoiceForm.action = "{{ url_for('admin_create_invoice', borrow_id='__BORROW_ID__') }}".replace('__BORROW_ID__', borrowId);
inputItem.value = itemName;
inputBorrower.value = borrower;
inputCode.value = itemCode;
damageInvoiceItem.value = itemName;
damageInvoiceBorrower.value = borrower;
damageInvoiceCode.value = itemCode;
inputAmount.value = String(itemCost).replace(' EUR', '').trim();
// Feld zunächst leeren, damit der Ersetzen-Button genutzt werden kann
damageInvoiceAmount.value = '';
inputReason.value = description || `Schaden gemeldet für ${itemName}`;
// Original-Preis im Button als data-Attribut hinterlegen
if (damageInvoiceReplaceBtn) {
damageInvoiceReplaceBtn.dataset.acquisition_costs = String(itemCost).replace(' EUR', '').trim();
}
modal.style.display = 'block';
inputAmount.focus();
damageInvoiceReason.value = description || `Schaden gemeldet für ${itemName}`;
damageInvoiceModal.style.display = 'block';
// Accessibility: Fokus ins erste aktivierbare Feld setzen
damageInvoiceAmount.focus();
}
function closeDamageInvoiceModal() {
const modal = document.getElementById('damage-invoice-modal');
if (modal) {
modal.style.display = 'none';
if (damageInvoiceModal) {
damageInvoiceModal.style.display = 'none';
}
}
// Event-Listener für den Ersetzen-Button
if (damageInvoiceReplaceBtn) {
damageInvoiceReplaceBtn.addEventListener('click', function() {
if (this.dataset.acquisition_costs) {
damageInvoiceAmount.value = this.dataset.acquisition_costs;
}
});
}
window.openDamageInvoiceModal = openDamageInvoiceModal;
window.closeDamageInvoiceModal = closeDamageInvoiceModal;
@@ -571,8 +600,6 @@
});
}
window.closeDamageInvoiceModal = closeDamageInvoiceModal;
function applyFilters() {
const search = (searchInput.value || '').trim().toLowerCase();
const status = statusFilter.value;
@@ -613,4 +640,4 @@
applyFilters();
})();
</script>
{% endblock %}
{% endblock %}
+90 -31
View File
@@ -450,6 +450,37 @@
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 }}">
@@ -485,7 +516,7 @@
</select>
<input type="text" id="activeStudentCard" placeholder="Aktiver Ausweis (gescannt)">
<input type="text" id="manualItemCode" placeholder="Manueller Mediencode (optional)" style="min-width:180px;">
<button id="resetCardBtn" class="button" type="button">Ausweis löschen</button>
<button id="resetCardBtn" class="button" type="button">Feld zurücksetzen</button>
<button id="toggleScannerBtn" class="button" type="button">Scanner starten</button>
<label style="display:flex; align-items:center; gap:8px; margin-left:6px;">
<input type="checkbox" id="keyboardScannerToggle">
@@ -1328,43 +1359,71 @@
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';
// Sicherer Zugriff auf das Item mit Fallback
const item = libraryItems.find(i => i._id === itemId);
let mediaHtml = '';
if (item) {
// Prüfe gängige Array-Namen aus dem Backend
const imageArray = item.Images || item.Bilder || item.images;
if (Array.isArray(imageArray) && imageArray.length > 0) {
const imagesHtml = imageArray.map(image => {
// Direkter, robuster Pfad zur Upload-Route
const imageSrc = image.startsWith('/uploads/') || image.startsWith('http')
? image
: `/uploads/${image}`;
return `<img src="${imageSrc}" 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>`;
}
}
// Zusätzliche Details vom Backend laden
// 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>';
});
}
+178 -87
View File
@@ -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,87 +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" 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="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>
@@ -354,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 }}">
@@ -380,5 +472,4 @@
// All PDF exports now go through backend routes
</script>
{% endblock %}
{% endblock %}