Compare commits

...

22 Commits

Author SHA1 Message Date
Aiirondev_dev 1a32a078bc changes to the Bibliotheks system ame Displayment 2026-11-02 14:03:45 +01:00
Aiirondev_dev 5c4ab6f0fc Biblitoheksid is also convertet 2026-11-01 17:08:22 +01:00
Aiirondev_dev 79cf958c3c changes to the DIsplayment of the name ussage 2026-11-01 16:56:01 +01:00
Aiirondev_dev 826db109c3 Changes to the Formating 2026-11-01 16:48:28 +01:00
Aiirondev f9b991d991 Changes to fix the Barcode Search 2026-10-27 10:03:00 +00:00
Aiirondev_dev 363f0df530 changes to the student Name Processing 2026-10-20 20:07:23 +02:00
Aiirondev_dev 34bb3cf4c3 changes to the user processing in the api_item_datail Function 2026-10-20 19:20:36 +02:00
Aiirondev_dev 18706c6d1c slight change to get the right information out of a database record 2026-10-20 19:08:58 +02:00
Aiirondev_dev 9771b98075 logging implementatiion for the user displayment 2026-10-20 18:56:59 +02:00
Aiirondev_dev e380ad6092 Implementation of a nother user decryption detail displayment 2026-10-20 18:44:58 +02:00
Aiirondev_dev d6e8e08b10 Debug logging implementation and changes to the User entcryption 2026-10-20 18:32:23 +02:00
Aiirondev_dev ddb6ab82ad change of the last borrowing user displayment to correctly change the encryption to have the unencryptet name 2026-10-20 17:46:51 +02:00
Aiirondev_dev baefc55257 changes to the get_user_by_student_card function because of a faulty update regarding the searching of the student Cars 2026-10-20 17:29:07 +02:00
Aiirondev_dev 6c359089cd Including of logging information 2026-10-20 17:13:29 +02:00
Aiirondev_dev 479cf3d98c changes to the formating 2026-10-20 16:37:31 +02:00
Aiirondev_dev f00e7d8f74 changes with the Color of the Code suchen Box to red 2026-10-18 22:02:59 +02:00
Aiirondev_dev 7af729ac88 Changes tot the style and formating of the Website especialy when Highlighting the important Search fields 2026-10-18 21:46:18 +02:00
Aiirondev_dev 847349b419 changes to the style and formating of the Buttons 2026-10-18 21:35:13 +02:00
Aiirondev_dev 91a80c6330 Changes to the Button style for non mobile devices to have a smohter 2026-10-18 21:30:16 +02:00
Aiirondev_dev 530d71ac8f changes to the design 2026-10-18 21:10:56 +02:00
Aiirondev_dev 64991326e7 Die Ursache wurde behoben: Die Ausleihungen speichern den Benutzer teilweise als Benutzer-ObjectId, während das Fenster „Meine Ausleihungen“ nur den Session-Benutzernamen verglichen hat. Dadurch wurden die Datensätze herausgefiltert.
Zusätzlich wurde die Item-Suche robuster gemacht:

Vergleich gegen Benutzername
Vergleich gegen Benutzer-ObjectId
Vergleich gegen session['user_id']
Unterstützung für verschlüsselte und unverschlüsselte Benutzerwerte
Unterstützung für Item-IDs als String und als MongoDB-ObjectId
Geändert wurde:

Web/app.py
2026-10-15 22:01:23 +02:00
Aiirondev_dev dffcfdcba7 Die blockierende Ausleihverarbeitung wurde korrigiert.
Änderungen
Geplante Inventar-Ausleihen werden zum Startzeitpunkt automatisch aktiviert, wenn ein Exemplar verfügbar ist.
Bei fehlender Verfügbarkeit bleibt die Reservierung geplant.
Der reservierende Benutzer und der aktuelle Ausleiher erhalten jeweils eine Benachrichtigung.
Die automatische Aktivierung wird beim nächsten Scheduler-Lauf erneut versucht, sobald der Gegenstand zurückgegeben wurde.
Das geplante Ende beendet eine aktive Ausleihe nicht mehr automatisch.
Nach Ablauf erscheint bei „Meine Ausleihungen“ ein deutlich roter Hinweis:
RÜCKGABE ERFORDERLICH
roter, hervorgehobener Button Rückgabe bestätigen
Eine Ausleihe wird erst nach dem expliziten Bestätigen der Rückgabe auf completed gesetzt und wieder verfügbar gemacht.
Rückgabeaktionen unterstützen nun auch Datensätze, bei denen die Item-ID als ObjectId gespeichert ist.
Die Dokumentation des Ausleih-Workflows wurde aktualisiert.
Geänderte Dateien:

Web/app.py
Web/modules/database/ausleihung.py
Web/templates/my_borrowed_items.html
Legal/TEST_AUSLEIHUNG.md
Validiert mit:

Python-Syntaxprüfung erfolgreich
git diff --check erfolgreich
Im Repository wurden keine ausführbaren Python-Testdateien gefunden
2026-10-15 21:33:41 +02:00
6 changed files with 459 additions and 142 deletions
+8 -2
View File
@@ -20,13 +20,19 @@ pytest test_ausleihung.py -vv --tb=long
## Test Coverage
### ✅ Status Determination (5 tests)
### ✅ Status Determination
- Future borrowings marked as 'planned'
- Current borrowings marked as 'active'
- Past borrowings marked as 'completed'
- Active borrowings remain 'active' after the planned end until return confirmation
- Cancelled status never changes
- Active borrowings without end time
### ✅ Inventory borrowing workflow
- Planned inventory borrowings activate automatically at their start when the item is available
- Unavailable items remain planned and notify the requester and current holder
- Reaching the planned end creates a return warning instead of an automatic return
- The item is completed and made available only after the user confirms the return
### ✅ Create Operations (2 tests)
- Create immediately active borrowing
- Create planned/future borrowing
+266 -91
View File
@@ -158,6 +158,41 @@ def print(*args, **kwargs):
STUDENT_CARD_ENCRYPTED_FIELDS = ('ausweis_ident', 'SchülerName', 'Klasse', 'Notizen')
def _display_username(user_value):
"""Return a username for a stored user ID, with legacy value support."""
if user_value is None or str(user_value).strip() == '':
return ''
raw_value = str(user_value).strip()
user_doc = us.get_user_by_id(raw_value)
if not user_doc:
user_doc = us.get_user_by_student_card(raw_value)
if not user_doc:
user_doc = us.get_user_by_student_card_record_id(raw_value)
if user_doc:
return str(user_doc.get('Username') or user_doc.get('username') or raw_value)
return decrypt_text(raw_value)
def _resolve_library_card_id(user_value):
"""Return the card ID for a stored user reference."""
if user_value is None or str(user_value).strip() == '':
return ''
raw_value = str(user_value).strip()
user_doc = us.get_user_by_id(raw_value)
if user_doc:
return str(user_doc.get('StudentCardId') or raw_value).strip().upper()
decrypted_value = decrypt_text(raw_value)
user_doc = us.get_user_by_student_card(decrypted_value)
if user_doc:
return str(user_doc.get('StudentCardId') or decrypted_value).strip().upper()
return str(decrypted_value or raw_value).strip().upper()
def _decrypt_student_card_doc(card_doc):
if not card_doc:
return card_doc
@@ -1212,7 +1247,7 @@ def create_return_reminders():
# Falls der Benutzername verschlüsselt ist, hier entschlüsseln,
# damit der Admin den echten Namen/Ausweis lesen kann.
display_user = decrypt_text(username) if 'decrypt_text' in globals() else username
display_user = _display_username(username)
item_id = str(borrow_doc.get('Item', '')).strip()
item_doc = item_docs.get(item_id, {})
@@ -1382,6 +1417,10 @@ def update_appointment_statuses():
for appointment in appointments_to_check:
old_status = appointment.get('Status')
activation_user = str(appointment.get('User') or '').strip()
try:
activation_user = _display_username(activation_user)
except Exception:
pass
activation_item_name = str(appointment.get('Item') or 'Termin')
# is_library_item expects an item document, not the stored item id.
@@ -1404,9 +1443,107 @@ def update_appointment_statuses():
)
item_is_library = it.is_library_item(item_doc_for_status)
# Aktuellen Status bestimmen
# Aktuellen Status bestimmen. Eine aktive Ausleihe bleibt bis zur
# bestätigten Rückgabe aktiv, auch wenn ihr Endzeitpunkt erreicht ist.
new_status = au.get_current_status(appointment, log_changes=True, user='scheduler')
# Inventarreservierungen werden erst beim tatsächlichen Start aktiviert.
# Ist kein Exemplar frei, bleibt die Reservierung geplant und beide
# betroffenen Nutzer werden einmalig benachrichtigt.
if (
old_status == 'planned'
and new_status == 'active'
and not item_is_library
and appointment.get('Item')
):
item_id = appointment.get('Item')
item_doc = None
item_queries = [{'_id': item_id}]
try:
item_queries.insert(0, {'_id': ObjectId(str(item_id))})
except (InvalidId, TypeError):
pass
item_doc = items_col.find_one({'$or': item_queries})
available = bool(item_doc and item_doc.get('Verfuegbar', True))
if item_doc and int(item_doc.get('Exemplare', 1) or 1) > 1:
total_exemplare = int(item_doc.get('Exemplare', 1) or 1)
borrowed_exemplare = len(item_doc.get('ExemplareStatus') or [])
available = borrowed_exemplare < total_exemplare
if item_doc:
active_query = {
'Status': 'active',
'_id': {'$ne': appointment['_id']},
'$or': [{'Item': item_id}, {'Item': str(item_id)}],
}
total_exemplare = int(item_doc.get('Exemplare', 1) or 1)
active_count = ausleihungen.count_documents(active_query)
available = available and active_count < total_exemplare
if not available:
holder = ''
if item_doc and item_doc.get('User'):
try:
holder = _display_username(item_doc['User'])
except Exception:
holder = str(item_doc['User'])
if not holder:
active_holder = ausleihungen.find_one(
{
'Status': 'active',
'$or': [{'Item': item_id}, {'Item': str(item_id)}],
'_id': {'$ne': appointment['_id']},
},
{'User': 1},
)
if active_holder and active_holder.get('User'):
try:
holder = _display_username(active_holder['User'])
except Exception:
holder = str(active_holder['User'])
requested_user = str(appointment.get('User') or '').strip()
try:
requested_user = _display_username(requested_user)
except Exception:
pass
item_name = (item_doc or {}).get('Name') or str(item_id)
conflict_fields = {
'ConflictDetected': True,
'ConflictNote': f'Keine Verfügbarkeit für "{item_name}" zum Startzeitpunkt.',
'ConflictAt': current_time,
'WaitingForAvailability': True,
}
ausleihungen.update_one(
{'_id': appointment['_id'], 'Status': 'planned'},
{'$set': {**conflict_fields, 'LastUpdated': current_time}}
)
if requested_user:
_create_notification(
db,
audience='user',
notif_type='borrowing_waiting_for_availability',
title='Ausleihe wartet auf Verfügbarkeit',
message=f'"{item_name}" ist zum geplanten Start noch ausgeliehen. Deine Reservierung bleibt aktiv und wird automatisch gestartet, sobald es zurückgegeben wurde.',
target_user=requested_user,
reference={'borrow_id': str(appointment['_id']), 'item_id': str(item_id)},
unique_key=f'borrowing:waiting:{appointment["_id"]}:requester',
severity='warning',
)
if holder and holder != requested_user:
_create_notification(
db,
audience='user',
notif_type='borrowing_blocking_return',
title='Rückgabe benötigt',
message=f'"{item_name}" wird für eine geplante Ausleihe benötigt. Bitte gib den Gegenstand zurück und bestätige die Rückgabe.',
target_user=holder,
reference={'borrow_id': str(appointment['_id']), 'item_id': str(item_id)},
unique_key=f'borrowing:waiting:{appointment["_id"]}:holder',
severity='warning',
)
continue
# Wenn sich der Status geändert hat, aktualisiere in der Datenbank
if new_status != old_status and not item_is_library:
extra_fields = {}
@@ -1481,32 +1618,48 @@ def update_appointment_statuses():
except Exception as e:
app.logger.warning(f"Could not update item status to True for {appointment['_id']}: {e}")
if old_status == 'planned' and new_status == 'active' and activation_user:
try:
_create_notification(
db,
audience='user',
notif_type='appointment_activated',
title='Reservierung ist jetzt aktiv',
message=f"Deine geplante Ausleihe für {activation_item_name} startet jetzt.",
target_user=activation_user,
reference={
'appointment_id': str(appointment.get('_id')),
'item_id': str(appointment.get('Item') or ''),
'event': 'activated',
},
unique_key=f"appointment:activated:{appointment.get('_id')}",
severity='info',
)
except Exception as notif_err:
app.logger.warning(
f"Failed to create activation notification for {appointment.get('_id')}: {notif_err}"
)
# Endzeitpunkt erreicht: nur einen deutlich sichtbaren
# Rückgabehinweis setzen, niemals automatisch abschließen.
if (
old_status == 'active'
and isinstance(appointment.get('End'), datetime.datetime)
and au.ensure_timezone_aware(appointment['End']) <= current_time
):
ausleihungen.update_one(
{'_id': appointment['_id'], 'Status': 'active'},
{'$set': {
'ReturnPending': True,
'ReturnReminderAt': current_time,
'LastUpdated': current_time,
}}
)
if old_status == 'planned' and new_status == 'active' and activation_user:
try:
_create_notification(
db,
audience='user',
notif_type='appointment_activated',
title='Reservierung ist jetzt aktiv',
message=f"Deine geplante Ausleihe für {activation_item_name} startet jetzt.",
target_user=activation_user,
reference={
'appointment_id': str(appointment.get('_id')),
'item_id': str(appointment.get('Item') or ''),
'event': 'activated',
},
unique_key=f"appointment:activated:{appointment.get('_id')}",
severity='info',
)
except Exception as notif_err:
app.logger.warning(
f"Failed to create activation notification for {appointment.get('_id')}: {notif_err}"
)
# -----------------------------------------------------------------
# Mahnlauf für Bibliotheksartikel (Prüfung auf Überfälligkeit)
# -----------------------------------------------------------------
elif item_is_library:
if item_is_library:
appt = appointment # Verwende das aktuelle Dokument aus der Schleife
if appt.get('Status') != 'active':
continue
@@ -1529,8 +1682,7 @@ def update_appointment_statuses():
raw_user = str(appt.get('User', '')).strip()
# Entschlüsselung der AusweisId
decrypted_user = decrypt_text(raw_user) if 'decrypt_text' in globals() else raw_user
target_ausweis_id = decrypted_user if decrypted_user else raw_user
target_ausweis_id = _resolve_library_card_id(raw_user)
item_id = appt.get('Item')
if not target_ausweis_id:
@@ -3423,7 +3575,7 @@ def library_loans_admin():
fmt_reports, fmt_repairs = format_damage_history(raw_reports, raw_repairs)
raw_user = record.get('User', '')
decrypted_user = safe_decrypt(raw_user)
decrypted_user = _display_username(raw_user)
user_class = (
safe_decrypt(record.get('Klasse'))
@@ -3584,8 +3736,7 @@ def mahnungen_admin():
item_code = item_doc.get('Code_4', '')
raw_user = str(record.get('User') or '')
decrypted_user = decrypt_text(raw_user)
ausweis_id = (decrypted_user if decrypted_user else raw_user).strip().upper()
ausweis_id = _resolve_library_card_id(raw_user)
student_card = card_map.get(ausweis_id, {})
student_name = student_card.get('SchülerName', ausweis_id if ausweis_id else 'Unbekannt')
@@ -3672,8 +3823,7 @@ def mahnungen_reset(days):
# 3. Schülerausweis ermitteln und entsperren
raw_user = str(record.get('User', ''))
decrypted_user = decrypt_text(raw_user)
ausweis_id = decrypted_user if decrypted_user else raw_user
ausweis_id = _resolve_library_card_id(raw_user)
card = student_cards_col.find_one({'AusweisId': ausweis_id})
if not card and raw_user != ausweis_id:
@@ -3734,8 +3884,7 @@ def mahnungen_send_email():
# Gegenstand und Schülerausweis ermitteln
raw_user = str(record.get('User', ''))
decrypted_user = decrypt_text(raw_user)
ausweis_id = decrypted_user if decrypted_user else raw_user
ausweis_id = _resolve_library_card_id(raw_user)
card = student_cards_col.find_one({'AusweisId': ausweis_id})
student_card = _decrypt_student_card_doc(card) if card and '_decrypt_student_card_doc' in globals() else (
@@ -4087,8 +4236,7 @@ def api_library_return_by_code():
continue
# AusweisId entschlüsseln
decrypted_user = decrypt_text(raw_user) if 'safe_decrypt' in globals() else raw_user
ausweis_id = decrypted_user if decrypted_user else raw_user
ausweis_id = _resolve_library_card_id(raw_user)
# Prüfen, ob der Schüler noch andere eskalierte Ausleihungen hat
# Da die aktuelle Ausleihe oben auf 'completed' gesetzt wurde, wird sie hier nicht mitgezählt!
@@ -4231,10 +4379,14 @@ def api_library_scan_action():
due_date = now + datetime.timedelta(days=borrow_duration_days)
it.update_item_status(item_id, False, borrower_name)
app.logger.info(f"Library scan action: borrowing item {item_id} for student card {student_card_id} until {due_date.isoformat()}")
borrower_user = us.get_user_by_student_card(student_card_id)
app.logger.info(f"Found borrower user: {borrower_user}")
if not borrower_user or not borrower_user.get('_id'):
app.logger.warning(f"No user found for student card {student_card_id}. Cannot record borrowing in ausleihungen.")
return jsonify({'ok': False, 'message': 'Kein Benutzer für diesen Schülerausweis gefunden.'}), 404
it.update_item_status(item_id, False, borrower_name)
au.add_ausleihung(
item_id,
str(borrower_user['_id']),
@@ -4249,7 +4401,7 @@ def api_library_scan_action():
'channel': 'library_scan',
'item_id': item_id,
'item_name': item_doc.get('Name', ''),
'borrower':borrower_name,
'borrower': borrower_name,
'student_card_id': student_card_id,
'borrow_duration_days': borrow_duration_days,
}
@@ -4339,6 +4491,7 @@ def api_item_detail(item_id):
db = client[MONGODB_DB]
ausleihungen_col = db['ausleihungen']
items_col = db['items']
student_cards_col = db['student_cards']
# Determine parent/group id (if this is a child, use its ParentItemId)
parent_id = str(item.get('ParentItemId') or str(item.get('_id')))
@@ -4375,23 +4528,32 @@ def api_item_detail(item_id):
else:
status_label = 'Verfügbar'
# Helper function to get borrower display name
def get_borrower_name(user_raw):
if not user_raw:
return ''
try:
user_doc = student_cards_col.find_one({'_id': ObjectId(user_raw)})
if user_doc:
if user_doc.get('SchülerName'):
return decrypt_text(str(user_doc.get('SchülerName', '')))
return str(user_doc.get('AusweisId', ''))
except Exception:
pass
return str(user_raw)
# Prefer the most recent active borrower across the group
borrower_value = ''
for rec in borrow_records:
if rec.get('Status') == 'active' and rec.get('User'):
try:
user_raw = rec.get('User')
if user_raw is not None:
borrower_value = decrypt_text(str(user_raw))
except Exception:
borrower_value = str(rec.get('User', ''))
borrower_value = get_borrower_name(rec.get('User'))
break
if not borrower_value and item.get('User'):
try:
item_user = item.get('User')
if item_user is not None:
borrower_value = decrypt_text(str(item_user))
borrower_value = _display_username(item_user)
except Exception:
borrower_value = str(item.get('User', ''))
@@ -4407,17 +4569,13 @@ def api_item_detail(item_id):
rows = []
for rec in borrow_records[:3]:
user_raw = rec.get('User')
try:
user = decrypt_text(user_raw) if user_raw is not None else ''
except Exception:
user = user_raw
rec_borrower_name = get_borrower_name(rec.get('User')) or '-'
status = rec.get('Status', '')
start = fmt_dt(rec.get('Start'))
end = fmt_dt(rec.get('End'))
notes = html.escape(str(rec.get('Notes') or ''))
rows.append(
f"<li><strong>{html.escape(str(user or '-'))}</strong> — "
f"<li><strong>{html.escape(rec_borrower_name)}</strong> — "
f"{html.escape(str(status))} — "
f"{html.escape(str(start))} → {html.escape(str(end))}"
f"{(' — ' + notes) if notes else ''}</li>"
@@ -7737,7 +7895,13 @@ def zurueckgeben(id):
current_permissions = us.get_effective_permissions(session['username'])
if not item.get('Verfuegbar', True) and (current_permissions['actions'].get('can_manage_users', False)) or item.get('User') == username:
if (
not item.get('Verfuegbar', True)
and (
current_permissions['actions'].get('can_manage_users', False)
or item.get('User') == username
)
):
try:
# Get ALL active borrowing records for this item and complete them
client = MongoClient(MONGODB_HOST, MONGODB_PORT)
@@ -7746,7 +7910,7 @@ def zurueckgeben(id):
# Find all active records for this item
active_records = ausleihungen.find({
'Item': id,
'$or': [{'Item': id}, {'Item': ObjectId(id) if ObjectId.is_valid(id) else id}],
'Status': 'active'
})
@@ -7762,6 +7926,7 @@ def zurueckgeben(id):
{'$set': {
'Status': 'completed',
'End': end_date,
'ReturnPending': False,
'LastUpdated': datetime.datetime.now(ZoneInfo("Europe/Berlin"))
}}
)
@@ -7884,10 +8049,7 @@ def get_planned_bookings(item_id):
bookings = []
for r in cursor:
raw_user = r.get('User') or ''
try:
booking_user = decrypt_text(raw_user) if raw_user else ''
except Exception:
booking_user = str(raw_user)
booking_user = _display_username(raw_user)
bookings.append({
'id': str(r.get('_id')),
'user': booking_user,
@@ -7918,10 +8080,7 @@ def get_planned_bookings_public(item_id):
bookings = []
for r in cursor:
raw_user = r.get('User') or ''
try:
booking_user = decrypt_text(raw_user) if raw_user else ''
except Exception:
booking_user = str(raw_user)
booking_user = _display_username(raw_user)
bookings.append({
'user': booking_user,
'period': r.get('Period'),
@@ -8765,7 +8924,7 @@ def user_del():
fullname = None
users_list.append({
'username': decrypt_text(username),
'username': _display_username(username),
'admin': user.get('Admin', False),
'fullname': fullname,
'name': name,
@@ -8906,7 +9065,8 @@ def admin_borrowings():
has_damage = False
raw_user = r.get('User', '')
decrypted_user = decrypt_text(raw_user) if raw_user else ''
decrypted_user = _display_username(raw_user)
entries.append({
'id': str(r.get('_id')),
@@ -10140,8 +10300,8 @@ def library_item_invoices(item_id):
entries.append({
'borrow_id': str(borrow_doc.get('_id')),
'borrow_status': borrow_doc.get('Status', ''),
'borrow_user': decrypt_text(borrow_doc.get('User', '')) if hasattr(borrow_doc,
'get') and borrow_doc.get(
'borrow_user': _display_username(borrow_doc.get('User', '')) if hasattr(borrow_doc,
'get') and borrow_doc.get(
'User') else '',
'borrow_start': borrow_doc.get('Start').strftime('%d.%m.%Y %H:%M') if isinstance(
borrow_doc.get('Start'), datetime.datetime) else '',
@@ -10241,7 +10401,7 @@ def library_item_invoices(item_id):
))
for b in damage_borrow_docs:
borrow_user = decrypt_text(b.get('User', '')) if b.get('User') else '—'
borrow_user = _display_username(b.get('User', '')) if b.get('User') else '—'
d_data = b.get('DamageData') or {}
if not isinstance(d_data, dict): d_data = {}
@@ -10531,7 +10691,7 @@ def logs():
formatted_items.append({
'Item': item_name,
'User': decrypt_text(username),
'User': _display_username(username),
'Start': start_date,
'End': end_date,
'Duration': duration,
@@ -10573,7 +10733,7 @@ def logs():
note = log_item.get('note', '')
formatted_items.append({
'Item': item_name,
'User': decrypt_text(log_item.get('user', 'Unknown User')),
'User': _display_username(log_item.get('user', 'Unknown User')),
'Start': ts_display,
'End': '-',
'Duration': '-',
@@ -10587,7 +10747,7 @@ def logs():
resolved_count = log_item.get('resolved_count', 0)
formatted_items.append({
'Item': item_name,
'User': decrypt_text(log_item.get('user', 'Unknown User')),
'User': _display_username(log_item.get('user', 'Unknown User')),
'Start': ts_display,
'End': '-',
'Duration': '-',
@@ -11385,6 +11545,14 @@ def my_borrowed_items():
return redirect(url_for('login', next=request.path))
username = session['username']
current_user = us.get_user(username) or {}
user_ids = {
username,
str(current_user.get('_id')) if current_user.get('_id') else '',
str(session.get('user_id') or ''),
str(current_user.get('StudentCardId') or '').strip().upper(),
}
user_ids.discard('')
client = MongoClient(MONGODB_HOST, MONGODB_PORT)
db = client[MONGODB_DB]
@@ -11401,31 +11569,28 @@ def my_borrowed_items():
for appointment in all_ausleihungen:
raw_user = appointment.get('User', '')
user_values = {str(raw_user).strip()} if raw_user else set()
try:
decrypted_user = decrypt_text(raw_user) if raw_user else ''
except Exception as e:
app.logger.error(f"Entschlüsselungsfehler: {e}")
decrypted_user = ''
if raw_user:
user_values.add(str(decrypt_text(raw_user)).strip())
user_values.add(_resolve_library_card_id(raw_user))
except Exception:
pass
if decrypted_user != username:
if not user_values.intersection(user_ids):
continue
item_id = appointment.get('Item')
if not item_id:
continue
try:
if isinstance(item_id, str):
query_id = ObjectId(item_id)
else:
query_id = item_id
item_obj = items_collection.find_one({
'_id': query_id,
'Deleted': {'$ne': True}
})
except Exception:
item_obj = None
item_queries = [{'_id': item_id}]
if isinstance(item_id, str) and ObjectId.is_valid(item_id):
item_queries.insert(0, {'_id': ObjectId(item_id)})
item_obj = items_collection.find_one({
'$or': item_queries,
'Deleted': {'$ne': True}
})
if item_obj:
item_obj['_id'] = str(item_obj['_id'])
@@ -11437,14 +11602,21 @@ def my_borrowed_items():
'notes': appointment.get('Notes'),
'period': appointment.get('Period'),
'status': appointment.get('VerifiedStatus', appointment.get('Status')),
'return_pending': bool(appointment.get('ReturnPending')),
}
status = appointment.get('Status')
if status == 'active':
item_obj['ActiveAppointment'] = True
item_obj['ReturnPending'] = bool(appointment.get('ReturnPending'))
if str(item_obj['_id']) not in processed_item_ids:
active_items.append(item_obj)
processed_item_ids.add(str(item_obj['_id']))
elif item_obj['ReturnPending']:
for existing_item in active_items:
if str(existing_item.get('_id')) == str(item_obj['_id']):
existing_item['ReturnPending'] = True
break
elif status == 'planned':
planned_items.append(item_obj)
@@ -11455,12 +11627,15 @@ def my_borrowed_items():
for item in all_borrowed_items:
raw_item_user = item.get('User', '')
item_user_values = {str(raw_item_user).strip()} if raw_item_user else set()
try:
dec_item_user = decrypt_text(raw_item_user) if raw_item_user else ''
if raw_item_user:
item_user_values.add(str(decrypt_text(raw_item_user)).strip())
item_user_values.add(_resolve_library_card_id(raw_item_user))
except Exception:
dec_item_user = ''
pass
if dec_item_user == username and str(item['_id']) not in processed_item_ids:
if item_user_values.intersection(user_ids) and str(item['_id']) not in processed_item_ids:
item['_id'] = str(item['_id'])
item['ActiveAppointment'] = True
item['AppointmentData'] = {'status': 'active (no document)'}
@@ -11780,10 +11955,10 @@ def admin_damaged_items():
# Benutzernamen der Ausleihe entschlüsseln
if active_borrow and active_borrow.get('User'):
active_borrow['User'] = decrypt_text(active_borrow['User'])
active_borrow['User'] = _display_username(active_borrow['User'])
# Direkt am Item hinterlegten Nutzer entschlüsseln
item_user = decrypt_text(item.get('User')) if item.get('User') else ''
item_user = _display_username(item.get('User')) if item.get('User') else ''
# Datenstruktur exakt für dein Jinja2 Template aufbauen
damaged_items.append({
@@ -12356,7 +12531,7 @@ def cancel_ausleihung_route(id):
ausleihung_status = ausleihung.get('Status', 'unknown')
raw_ausleihung_user = ausleihung.get('User', '')
try:
ausleihung_user = decrypt_text(raw_ausleihung_user) if raw_ausleihung_user else ''
ausleihung_user = _display_username(raw_ausleihung_user)
except Exception:
ausleihung_user = str(raw_ausleihung_user or '')
print(f"Found ausleihung: ID={id}, Status={ausleihung_status}")
+5 -7
View File
@@ -15,7 +15,8 @@ Hauptfunktionen:
Sammlungsstruktur:
- ausleihungen: Speichert alle Ausleihungsdatensätze mit ihrem Status
- Status-Werte: 'planned' (geplant), 'active' (aktiv), 'completed' (abgeschlossen), 'cancelled' (storniert)
- Status-Werte: 'planned' (geplant), 'active' (aktiv), 'completed' (nach bestätigter Rückgabe), 'cancelled' (storniert)
- Das geplante Ende beendet eine aktive Ausleihe nicht automatisch; es erzeugt einen Rückgabehinweis.
"""
'''
Copyright 2025-2026 AIIrondev
@@ -96,13 +97,10 @@ def get_current_status(ausleihung, log_changes=False, user=None):
ausleihung_id = str(ausleihung.get('_id', 'unknown'))[:12]
print(f"[DEBUG] Ausleihe {ausleihung_id} startet in {time_until_start/3600:.1f} Stunden ({start_time}), noch geplant")
new_status = 'planned'
# Wenn kein Enddatum gesetzt ist oder die aktuelle Zeit vor dem Enddatum liegt,
# ist die Ausleihung aktiv
elif not end_time or current_time < end_time:
new_status = 'active'
# Wenn die aktuelle Zeit nach dem Enddatum liegt, ist die Ausleihung beendet
# Eine aktive Ausleihe bleibt aktiv, bis die Rückgabe ausdrücklich bestätigt
# wurde. Das geplante Ende löst nur einen Rückgabehinweis aus.
else:
new_status = 'completed'
new_status = 'active'
# Protokollieren Sie Statusänderungen, wenn aktiviert und eine Änderung stattgefunden hat
if log_changes and new_status != original_status and '_id' in ausleihung:
+71 -6
View File
@@ -695,13 +695,42 @@ def get_user_by_student_card(student_card_id):
if not normalized:
return None
client = MongoClient(cfg.MONGODB_HOST, cfg.MONGODB_PORT)
db = _get_tenant_db(client)
users = db['student_cards']
found_user = users.find_one({'SchülerName': normalized})
client.close()
try:
db = _get_tenant_db(client)
users = db['users']
return users.find_one({
'$or': [
{'StudentCardId': normalized},
{'StudentCardId': student_card_id},
]
})
finally:
client.close()
def get_user_by_student_card_record_id(card_id):
"""Return the user assigned to a student-card document ID."""
if card_id is None:
return None
client = MongoClient(cfg.MONGODB_HOST, cfg.MONGODB_PORT)
try:
db = _get_tenant_db(client)
card = None
if isinstance(card_id, ObjectId):
card = db['student_cards'].find_one({'_id': card_id})
elif ObjectId.is_valid(str(card_id)):
card = db['student_cards'].find_one({'_id': ObjectId(str(card_id))})
if not card:
return None
card_id_value = normalize_student_card_id(card.get('AusweisId'))
if not card_id_value:
return None
return db['users'].find_one({'StudentCardId': card_id_value})
finally:
client.close()
# 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."""
@@ -874,6 +903,42 @@ def get_user(username):
client.close()
def get_user_by_id(user_id):
"""Retrieve a user by MongoDB document ID."""
if user_id is None:
return None
lookup_values = [str(user_id)]
if ObjectId.is_valid(str(user_id)):
lookup_values.insert(0, ObjectId(str(user_id)))
client = MongoClient(cfg.MONGODB_HOST, cfg.MONGODB_PORT)
try:
def find_in_db(database_name):
users = client[database_name]['users']
for lookup_value in lookup_values:
user = users.find_one({'_id': lookup_value})
if user:
return user
return None
tenant_db, tenant_id = _resolve_request_tenant_db()
if tenant_db:
user = find_in_db(tenant_db)
if user:
return user
if _has_tenant_configs() and tenant_db is None:
logger.warning(
"Refusing default DB fallback for user ID lookup because tenant configs exist and no tenant was resolved."
)
return None
return find_in_db(cfg.MONGODB_DB)
finally:
client.close()
def check_admin(username):
"""Check if a user has administrator privileges."""
user = get_user(username)
+79 -35
View File
@@ -266,6 +266,11 @@
border-radius: 4px;
}
.code-search-label {
color: #b93845;
font-weight: 700;
}
.search-button {
padding: 8px 12px;
background-color: #007bff;
@@ -284,10 +289,10 @@
}
#code-search.searching {
background-color: #fff3cd;
background-color: #fff5f5;
transition: background-color 0.3s;
border: 2px solid #ffc107;
box-shadow: 0 0 8px rgba(255, 193, 7, 0.5);
border: 2px solid #d65a62;
box-shadow: 0 0 8px rgba(190, 55, 66, 0.28);
}
/* QR Scanner styles */
@@ -562,26 +567,55 @@
align-items: center;
}
.navigation-buttons {
display: flex;
justify-content: center;
gap: 10px;
.items-navigation {
display: grid;
grid-template-columns: 42px minmax(0, 1fr) 42px;
align-items: center;
column-gap: 16px;
width: calc(100% + 116px);
margin-left: -58px;
margin-top: 20px;
}
.navigation-buttons .prev-button,
.navigation-buttons .next-button {
background-color: #007bff;
color: #fff;
border: none;
cursor: pointer;
padding: 10px;
border-radius: 5px;
.navigation-button-slot {
display: flex;
justify-content: center;
}
.navigation-buttons .prev-button:hover,
.navigation-buttons .next-button:hover {
background-color: #0056b3;
.navigation-button {
display: inline-flex;
align-items: center;
justify-content: center;
width: 42px;
height: 42px;
padding: 0;
background: var(--ui-surface-soft);
color: var(--ui-title);
border: 1px solid var(--ui-border);
box-shadow: var(--ui-shadow-sm);
cursor: pointer;
border-radius: 10px;
font-size: 1.15rem;
font-weight: 700;
line-height: 1;
transition: transform 160ms ease, box-shadow 160ms ease, background-color 160ms ease, border-color 160ms ease;
z-index: 1;
}
.navigation-button:hover {
background: var(--ui-surface);
border-color: var(--module-accent-color);
box-shadow: var(--ui-shadow-md);
transform: translateY(-2px) scale(1.04);
}
.navigation-button:active {
transform: translateY(0) scale(0.96);
}
.navigation-button:focus-visible {
outline: 3px solid rgba(37, 99, 235, 0.35);
outline-offset: 3px;
}
/* Modal styles */
@@ -744,15 +778,15 @@
}
.code-match {
border: 2px solid #17a2b8 !important;
box-shadow: 0 0 15px rgba(23, 162, 184, 0.5) !important;
border: 2px solid #d65a62 !important;
box-shadow: 0 0 15px rgba(190, 55, 66, 0.28) !important;
position: relative;
z-index: 5;
}
.exact-code-match {
border: 3px solid #28a745 !important;
box-shadow: 0 0 20px rgba(40, 167, 69, 0.7) !important;
border: 3px solid #b93845 !important;
box-shadow: 0 0 20px rgba(185, 56, 69, 0.42) !important;
position: relative;
z-index: 11;
}
@@ -1633,7 +1667,13 @@
}
/* Navigation buttons mobile */
.navigation-buttons {
.items-navigation {
display: block !important;
width: 100% !important;
margin-left: 0 !important;
}
.navigation-button-slot {
display: none !important; /* Hide horizontal navigation on mobile */
}
@@ -1946,7 +1986,7 @@
/* Standardized button styles across the application */
.search-button, .scan-button, .filter-toggle, .clear-filter,
.add-new-btn, .popup-close-button, .prev-image-button, .next-image-button,
.navigation-buttons .prev-button, .navigation-buttons .next-button {
.navigation-button {
display: inline-flex;
align-items: center;
justify-content: center;
@@ -2501,7 +2541,7 @@ document.addEventListener('DOMContentLoaded', ()=>{
<div class="filter-group search-field">
<div class="filter-header">
<label for="code-search">Code suchen:</label>
<label class="code-search-label" for="code-search">Code suchen:</label>
<button type="button" class="clear-filter" onclick="clearCodeSearch()">Clear</button>
</div>
<div class="search-container">
@@ -2543,12 +2583,16 @@ document.addEventListener('DOMContentLoaded', ()=>{
<span>Anzahl</span>
</div>
<div id="items-container" class="items-container">
<!-- Items will be dynamically loaded here -->
</div>
<div class="navigation-buttons">
<button class="prev-button" onclick="scrollPrev()">&#10094;</button>
<button class="next-button" onclick="scrollNext()">&#10095;</button>
<div class="items-navigation">
<div class="navigation-button-slot">
<button class="navigation-button prev-button" type="button" onclick="scrollPrev()" aria-label="Vorherige Elemente">&#10094;</button>
</div>
<div id="items-container" class="items-container">
<!-- Items will be dynamically loaded here -->
</div>
<div class="navigation-button-slot">
<button class="navigation-button next-button" type="button" onclick="scrollNext()" aria-label="Nächste Elemente">&#10095;</button>
</div>
</div>
</div>
<div id="item-modal" class="item-modal">
@@ -3324,10 +3368,11 @@ document.addEventListener('DOMContentLoaded', ()=>{
function loadItems(offset = 0, append = false, searchTerm = '', searchScope = 'all') {
// Keep list payload lightweight; full details are fetched on-demand in openItemQuick.
const searchParams = searchTerm
const searchParams = searchTerm && searchScope === 'title_description'
? `&search=${encodeURIComponent(searchTerm)}&search_scope=${encodeURIComponent(searchScope)}`
: '';
return fetch(`{{ url_for('get_items') }}?offset=${offset}&limit=${MAIN_ADMIN_ITEMS_PAGE_SIZE}&light_mode=true${searchParams}`)
const limit = (searchTerm && searchScope === 'all') ? 5000 : MAIN_ADMIN_ITEMS_PAGE_SIZE;
return fetch(`{{ url_for('get_items') }}?offset=${offset}&limit=${limit}&light_mode=true${searchParams}`)
.then(response => response.json())
.then(data => {
const itemsContainer = document.querySelector('#items-container');
@@ -3346,8 +3391,7 @@ document.addEventListener('DOMContentLoaded', ()=>{
if (!append && (!pageItems || pageItems.length === 0)) {
itemsContainer.innerHTML = `
<div class="no-items-message">
<div>Keine Objekte gefunden</div>
<a class="empty-state-cta" href="{{ url_for('upload_admin') }}">Erstellen sie hier ihr erstes Item</a>
<div>Kein Item gefunden</div>
</div>
`;
if (itemsIndicator) {
+30 -1
View File
@@ -142,6 +142,9 @@
{% if item.ActiveAppointment %}
<span class="appointment-status status-active">Aktiv</span>
{% endif %}
{% if item.ReturnPending %}
<span class="return-due-badge">RÜCKGABE ERFORDERLICH</span>
{% endif %}
</div>
<div class="item-details">
@@ -202,7 +205,9 @@
<div class="action-buttons-container">
<form method="POST" action="{{ url_for('zurueckgeben', id=item._id) }}">
<input type="hidden" name="source_page" value="my_borrowed_items">
<button class="return-button" type="submit">Zurückgeben</button>
<button class="return-button{% if item.ReturnPending %} return-button-due{% endif %}" type="submit">
{% if item.ReturnPending %}Rückgabe bestätigen{% else %}Zurückgeben{% endif %}
</button>
</form>
<form method="POST" action="{{ url_for('cancel_ausleihung_route', id=item.AppointmentData.id) }}" onsubmit="return confirm('Möchten Sie diese aktive Ausleihung wirklich stornieren?');">
<button class="cancel-button" type="submit">Stornieren</button>
@@ -497,6 +502,30 @@ document.addEventListener('DOMContentLoaded', function() {
.return-button:hover {
background-color: #0069d9;
}
.return-due-badge {
background-color: #dc3545;
color: #fff;
padding: 4px 9px;
border-radius: 12px;
font-size: 0.75rem;
font-weight: 800;
margin-left: 10px;
}
.return-button-due {
background-color: #dc3545;
animation: return-due-pulse 1.8s ease-in-out infinite;
}
.return-button-due:hover {
background-color: #b02a37;
}
@keyframes return-due-pulse {
0%, 100% { box-shadow: 0 0 0 0 rgba(220, 53, 69, 0.45); }
50% { box-shadow: 0 0 0 7px rgba(220, 53, 69, 0); }
}
.return-count-group {
display: flex;