Compare commits
36
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
58dd957315 | ||
|
|
3afec10346 | ||
|
|
9f0d514c38 | ||
|
|
1a32a078bc | ||
|
|
5c4ab6f0fc | ||
|
|
79cf958c3c | ||
|
|
826db109c3 | ||
|
|
f9b991d991 | ||
|
|
363f0df530 | ||
|
|
34bb3cf4c3 | ||
|
|
18706c6d1c | ||
|
|
9771b98075 | ||
|
|
e380ad6092 | ||
|
|
d6e8e08b10 | ||
|
|
ddb6ab82ad | ||
|
|
baefc55257 | ||
|
|
6c359089cd | ||
|
|
479cf3d98c | ||
|
|
f00e7d8f74 | ||
|
|
7af729ac88 | ||
|
|
847349b419 | ||
|
|
91a80c6330 | ||
|
|
530d71ac8f | ||
|
|
64991326e7 | ||
|
|
dffcfdcba7 | ||
|
|
b3e79a65c1 | ||
|
|
b33b4eadc6 | ||
|
|
07a1cdb063 | ||
|
|
2942bcc380 | ||
|
|
349337e75f | ||
|
|
9bdd8261fe | ||
|
|
04c8505531 | ||
|
|
c9edf4a4c8 | ||
|
|
0e0a99569e | ||
|
|
6e94ca20c4 | ||
|
|
72fdfb0898 |
No files matched your search
@@ -20,13 +20,19 @@ pytest test_ausleihung.py -vv --tb=long
|
|||||||
|
|
||||||
## Test Coverage
|
## Test Coverage
|
||||||
|
|
||||||
### ✅ Status Determination (5 tests)
|
### ✅ Status Determination
|
||||||
- Future borrowings marked as 'planned'
|
- Future borrowings marked as 'planned'
|
||||||
- Current borrowings marked as 'active'
|
- 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
|
- Cancelled status never changes
|
||||||
- Active borrowings without end time
|
- 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 Operations (2 tests)
|
||||||
- Create immediately active borrowing
|
- Create immediately active borrowing
|
||||||
- Create planned/future borrowing
|
- Create planned/future borrowing
|
||||||
|
|||||||
+383
-111
@@ -158,6 +158,70 @@ def print(*args, **kwargs):
|
|||||||
STUDENT_CARD_ENCRYPTED_FIELDS = ('ausweis_ident', 'SchülerName', 'Klasse', 'Notizen')
|
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()
|
||||||
|
decrypted_value = decrypt_text(raw_value)
|
||||||
|
lookup_values = [raw_value]
|
||||||
|
if decrypted_value and decrypted_value not in lookup_values:
|
||||||
|
lookup_values.append(str(decrypted_value).strip())
|
||||||
|
|
||||||
|
for lookup_value in lookup_values:
|
||||||
|
user_doc = us.get_user_by_id(lookup_value)
|
||||||
|
if not user_doc:
|
||||||
|
user_doc = us.get_user_by_student_card(lookup_value)
|
||||||
|
if not user_doc:
|
||||||
|
user_doc = us.get_user_by_student_card_record_id(lookup_value)
|
||||||
|
if not user_doc:
|
||||||
|
user_doc = us.get_user(lookup_value)
|
||||||
|
if user_doc:
|
||||||
|
return str(user_doc.get('Username') or user_doc.get('username') or lookup_value)
|
||||||
|
|
||||||
|
client = None
|
||||||
|
try:
|
||||||
|
client = MongoClient(MONGODB_HOST, MONGODB_PORT)
|
||||||
|
cards = get_tenant_db(client)['student_cards']
|
||||||
|
card_queries = [{'AusweisId': lookup_value} for lookup_value in lookup_values]
|
||||||
|
if ObjectId.is_valid(raw_value):
|
||||||
|
card_queries.insert(0, {'_id': ObjectId(raw_value)})
|
||||||
|
card = cards.find_one({'$or': card_queries}) if card_queries else None
|
||||||
|
if card:
|
||||||
|
card = _decrypt_student_card_doc(card)
|
||||||
|
card_name = str(card.get('SchülerName') or '').strip()
|
||||||
|
if card_name:
|
||||||
|
return card_name
|
||||||
|
finally:
|
||||||
|
if client:
|
||||||
|
client.close()
|
||||||
|
|
||||||
|
return str(decrypted_value or 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_id(decrypted_value)
|
||||||
|
if not user_doc:
|
||||||
|
user_doc = us.get_user_by_student_card(decrypted_value)
|
||||||
|
if not user_doc:
|
||||||
|
user_doc = us.get_user_by_student_card_record_id(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):
|
def _decrypt_student_card_doc(card_doc):
|
||||||
if not card_doc:
|
if not card_doc:
|
||||||
return card_doc
|
return card_doc
|
||||||
@@ -468,6 +532,10 @@ def _enforce_active_session_user():
|
|||||||
return None
|
return None
|
||||||
|
|
||||||
username = session.get('username')
|
username = session.get('username')
|
||||||
|
current_user_id = session.get('user_id')
|
||||||
|
if not current_user_id:
|
||||||
|
current_user = us.get_user(username)
|
||||||
|
current_user_id = str(current_user['_id']) if current_user and current_user.get('_id') else None
|
||||||
if not username:
|
if not username:
|
||||||
return None
|
return None
|
||||||
|
|
||||||
@@ -1208,7 +1276,7 @@ def create_return_reminders():
|
|||||||
|
|
||||||
# Falls der Benutzername verschlüsselt ist, hier entschlüsseln,
|
# Falls der Benutzername verschlüsselt ist, hier entschlüsseln,
|
||||||
# damit der Admin den echten Namen/Ausweis lesen kann.
|
# 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_id = str(borrow_doc.get('Item', '')).strip()
|
||||||
item_doc = item_docs.get(item_id, {})
|
item_doc = item_docs.get(item_id, {})
|
||||||
@@ -1378,6 +1446,10 @@ def update_appointment_statuses():
|
|||||||
for appointment in appointments_to_check:
|
for appointment in appointments_to_check:
|
||||||
old_status = appointment.get('Status')
|
old_status = appointment.get('Status')
|
||||||
activation_user = str(appointment.get('User') or '').strip()
|
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')
|
activation_item_name = str(appointment.get('Item') or 'Termin')
|
||||||
|
|
||||||
# is_library_item expects an item document, not the stored item id.
|
# is_library_item expects an item document, not the stored item id.
|
||||||
@@ -1400,9 +1472,107 @@ def update_appointment_statuses():
|
|||||||
)
|
)
|
||||||
item_is_library = it.is_library_item(item_doc_for_status)
|
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')
|
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
|
# Wenn sich der Status geändert hat, aktualisiere in der Datenbank
|
||||||
if new_status != old_status and not item_is_library:
|
if new_status != old_status and not item_is_library:
|
||||||
extra_fields = {}
|
extra_fields = {}
|
||||||
@@ -1477,32 +1647,48 @@ def update_appointment_statuses():
|
|||||||
except Exception as e:
|
except Exception as e:
|
||||||
app.logger.warning(f"Could not update item status to True for {appointment['_id']}: {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:
|
# Endzeitpunkt erreicht: nur einen deutlich sichtbaren
|
||||||
try:
|
# Rückgabehinweis setzen, niemals automatisch abschließen.
|
||||||
_create_notification(
|
if (
|
||||||
db,
|
old_status == 'active'
|
||||||
audience='user',
|
and isinstance(appointment.get('End'), datetime.datetime)
|
||||||
notif_type='appointment_activated',
|
and au.ensure_timezone_aware(appointment['End']) <= current_time
|
||||||
title='Reservierung ist jetzt aktiv',
|
):
|
||||||
message=f"Deine geplante Ausleihe für {activation_item_name} startet jetzt.",
|
ausleihungen.update_one(
|
||||||
target_user=activation_user,
|
{'_id': appointment['_id'], 'Status': 'active'},
|
||||||
reference={
|
{'$set': {
|
||||||
'appointment_id': str(appointment.get('_id')),
|
'ReturnPending': True,
|
||||||
'item_id': str(appointment.get('Item') or ''),
|
'ReturnReminderAt': current_time,
|
||||||
'event': 'activated',
|
'LastUpdated': current_time,
|
||||||
},
|
}}
|
||||||
unique_key=f"appointment:activated:{appointment.get('_id')}",
|
)
|
||||||
severity='info',
|
|
||||||
)
|
if old_status == 'planned' and new_status == 'active' and activation_user:
|
||||||
except Exception as notif_err:
|
try:
|
||||||
app.logger.warning(
|
_create_notification(
|
||||||
f"Failed to create activation notification for {appointment.get('_id')}: {notif_err}"
|
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)
|
# 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
|
appt = appointment # Verwende das aktuelle Dokument aus der Schleife
|
||||||
if appt.get('Status') != 'active':
|
if appt.get('Status') != 'active':
|
||||||
continue
|
continue
|
||||||
@@ -1525,8 +1711,7 @@ def update_appointment_statuses():
|
|||||||
raw_user = str(appt.get('User', '')).strip()
|
raw_user = str(appt.get('User', '')).strip()
|
||||||
|
|
||||||
# Entschlüsselung der AusweisId
|
# Entschlüsselung der AusweisId
|
||||||
decrypted_user = decrypt_text(raw_user) if 'decrypt_text' in globals() else raw_user
|
target_ausweis_id = _resolve_library_card_id(raw_user)
|
||||||
target_ausweis_id = decrypted_user if decrypted_user else raw_user
|
|
||||||
item_id = appt.get('Item')
|
item_id = appt.get('Item')
|
||||||
|
|
||||||
if not target_ausweis_id:
|
if not target_ausweis_id:
|
||||||
@@ -1560,7 +1745,7 @@ def update_appointment_statuses():
|
|||||||
pass
|
pass
|
||||||
|
|
||||||
# STUFE 2: >= 2 * student_ausleih_dauer Tage überfällig -> Ausweis sperren, Stufe 2 setzen & Admins benachrichtigen
|
# STUFE 2: >= 2 * student_ausleih_dauer Tage überfällig -> Ausweis sperren, Stufe 2 setzen & Admins benachrichtigen
|
||||||
if days_overdue >= (int(student_ausleih_dauer) * 2) and mahnstufe < 2:
|
if days_overdue >= (int(student_ausleih_dauer) * 2) and mahnstufe == 1 and card.get('is_blocked') is not True:
|
||||||
ausleihungen.update_one(
|
ausleihungen.update_one(
|
||||||
{'_id': appt['_id']},
|
{'_id': appt['_id']},
|
||||||
{'$set': {'Mahnstufe': 2, 'LastUpdated': current_time}}
|
{'$set': {'Mahnstufe': 2, 'LastUpdated': current_time}}
|
||||||
@@ -3419,7 +3604,7 @@ def library_loans_admin():
|
|||||||
fmt_reports, fmt_repairs = format_damage_history(raw_reports, raw_repairs)
|
fmt_reports, fmt_repairs = format_damage_history(raw_reports, raw_repairs)
|
||||||
|
|
||||||
raw_user = record.get('User', '')
|
raw_user = record.get('User', '')
|
||||||
decrypted_user = safe_decrypt(raw_user)
|
decrypted_user = _display_username(raw_user)
|
||||||
|
|
||||||
user_class = (
|
user_class = (
|
||||||
safe_decrypt(record.get('Klasse'))
|
safe_decrypt(record.get('Klasse'))
|
||||||
@@ -3580,8 +3765,7 @@ def mahnungen_admin():
|
|||||||
item_code = item_doc.get('Code_4', '')
|
item_code = item_doc.get('Code_4', '')
|
||||||
|
|
||||||
raw_user = str(record.get('User') or '')
|
raw_user = str(record.get('User') or '')
|
||||||
decrypted_user = decrypt_text(raw_user)
|
ausweis_id = _resolve_library_card_id(raw_user)
|
||||||
ausweis_id = (decrypted_user if decrypted_user else raw_user).strip().upper()
|
|
||||||
|
|
||||||
student_card = card_map.get(ausweis_id, {})
|
student_card = card_map.get(ausweis_id, {})
|
||||||
student_name = student_card.get('SchülerName', ausweis_id if ausweis_id else 'Unbekannt')
|
student_name = student_card.get('SchülerName', ausweis_id if ausweis_id else 'Unbekannt')
|
||||||
@@ -3668,8 +3852,7 @@ def mahnungen_reset(days):
|
|||||||
|
|
||||||
# 3. Schülerausweis ermitteln und entsperren
|
# 3. Schülerausweis ermitteln und entsperren
|
||||||
raw_user = str(record.get('User', ''))
|
raw_user = str(record.get('User', ''))
|
||||||
decrypted_user = decrypt_text(raw_user)
|
ausweis_id = _resolve_library_card_id(raw_user)
|
||||||
ausweis_id = decrypted_user if decrypted_user else raw_user
|
|
||||||
|
|
||||||
card = student_cards_col.find_one({'AusweisId': ausweis_id})
|
card = student_cards_col.find_one({'AusweisId': ausweis_id})
|
||||||
if not card and raw_user != ausweis_id:
|
if not card and raw_user != ausweis_id:
|
||||||
@@ -3730,8 +3913,7 @@ def mahnungen_send_email():
|
|||||||
|
|
||||||
# Gegenstand und Schülerausweis ermitteln
|
# Gegenstand und Schülerausweis ermitteln
|
||||||
raw_user = str(record.get('User', ''))
|
raw_user = str(record.get('User', ''))
|
||||||
decrypted_user = decrypt_text(raw_user)
|
ausweis_id = _resolve_library_card_id(raw_user)
|
||||||
ausweis_id = decrypted_user if decrypted_user else raw_user
|
|
||||||
|
|
||||||
card = student_cards_col.find_one({'AusweisId': ausweis_id})
|
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 (
|
student_card = _decrypt_student_card_doc(card) if card and '_decrypt_student_card_doc' in globals() else (
|
||||||
@@ -4083,8 +4265,7 @@ def api_library_return_by_code():
|
|||||||
continue
|
continue
|
||||||
|
|
||||||
# AusweisId entschlüsseln
|
# AusweisId entschlüsseln
|
||||||
decrypted_user = decrypt_text(raw_user) if 'safe_decrypt' in globals() else raw_user
|
ausweis_id = _resolve_library_card_id(raw_user)
|
||||||
ausweis_id = decrypted_user if decrypted_user else raw_user
|
|
||||||
|
|
||||||
# Prüfen, ob der Schüler noch andere eskalierte Ausleihungen hat
|
# 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!
|
# Da die aktuelle Ausleihe oben auf 'completed' gesetzt wurde, wird sie hier nicht mitgezählt!
|
||||||
@@ -4227,10 +4408,17 @@ def api_library_scan_action():
|
|||||||
|
|
||||||
due_date = now + datetime.timedelta(days=borrow_duration_days)
|
due_date = now + datetime.timedelta(days=borrow_duration_days)
|
||||||
|
|
||||||
|
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)
|
it.update_item_status(item_id, False, borrower_name)
|
||||||
au.add_ausleihung(
|
au.add_ausleihung(
|
||||||
item_id,
|
item_id,
|
||||||
borrower_name,
|
str(borrower_user['_id']),
|
||||||
now,
|
now,
|
||||||
end_date=due_date,
|
end_date=due_date,
|
||||||
due_date=due_date,
|
due_date=due_date,
|
||||||
@@ -4242,7 +4430,7 @@ def api_library_scan_action():
|
|||||||
'channel': 'library_scan',
|
'channel': 'library_scan',
|
||||||
'item_id': item_id,
|
'item_id': item_id,
|
||||||
'item_name': item_doc.get('Name', ''),
|
'item_name': item_doc.get('Name', ''),
|
||||||
'borrower':borrower_name,
|
'borrower': borrower_name,
|
||||||
'student_card_id': student_card_id,
|
'student_card_id': student_card_id,
|
||||||
'borrow_duration_days': borrow_duration_days,
|
'borrow_duration_days': borrow_duration_days,
|
||||||
}
|
}
|
||||||
@@ -4368,23 +4556,24 @@ def api_item_detail(item_id):
|
|||||||
else:
|
else:
|
||||||
status_label = 'Verfügbar'
|
status_label = 'Verfügbar'
|
||||||
|
|
||||||
|
# Helper function to get borrower display name
|
||||||
|
def get_borrower_name(user_raw):
|
||||||
|
if not user_raw:
|
||||||
|
return ''
|
||||||
|
return _display_username(user_raw)
|
||||||
|
|
||||||
# Prefer the most recent active borrower across the group
|
# Prefer the most recent active borrower across the group
|
||||||
borrower_value = ''
|
borrower_value = ''
|
||||||
for rec in borrow_records:
|
for rec in borrow_records:
|
||||||
if rec.get('Status') == 'active' and rec.get('User'):
|
if rec.get('Status') == 'active' and rec.get('User'):
|
||||||
try:
|
borrower_value = get_borrower_name(rec.get('User'))
|
||||||
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', ''))
|
|
||||||
break
|
break
|
||||||
|
|
||||||
if not borrower_value and item.get('User'):
|
if not borrower_value and item.get('User'):
|
||||||
try:
|
try:
|
||||||
item_user = item.get('User')
|
item_user = item.get('User')
|
||||||
if item_user is not None:
|
if item_user is not None:
|
||||||
borrower_value = decrypt_text(str(item_user))
|
borrower_value = _display_username(item_user)
|
||||||
except Exception:
|
except Exception:
|
||||||
borrower_value = str(item.get('User', ''))
|
borrower_value = str(item.get('User', ''))
|
||||||
|
|
||||||
@@ -4400,17 +4589,13 @@ def api_item_detail(item_id):
|
|||||||
rows = []
|
rows = []
|
||||||
|
|
||||||
for rec in borrow_records[:3]:
|
for rec in borrow_records[:3]:
|
||||||
user_raw = rec.get('User')
|
rec_borrower_name = get_borrower_name(rec.get('User')) or '-'
|
||||||
try:
|
|
||||||
user = decrypt_text(user_raw) if user_raw is not None else ''
|
|
||||||
except Exception:
|
|
||||||
user = user_raw
|
|
||||||
status = rec.get('Status', '')
|
status = rec.get('Status', '')
|
||||||
start = fmt_dt(rec.get('Start'))
|
start = fmt_dt(rec.get('Start'))
|
||||||
end = fmt_dt(rec.get('End'))
|
end = fmt_dt(rec.get('End'))
|
||||||
notes = html.escape(str(rec.get('Notes') or ''))
|
notes = html.escape(str(rec.get('Notes') or ''))
|
||||||
rows.append(
|
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(status))} — "
|
||||||
f"{html.escape(str(start))} → {html.escape(str(end))}"
|
f"{html.escape(str(start))} → {html.escape(str(end))}"
|
||||||
f"{(' — ' + notes) if notes else ''}</li>"
|
f"{(' — ' + notes) if notes else ''}</li>"
|
||||||
@@ -5467,6 +5652,7 @@ def login():
|
|||||||
if user:
|
if user:
|
||||||
app.logger.info(f"Login success: username={encrypt_text(username)!r} tenant={current_tenant_id or 'default'} db={current_tenant_db} host={request.host} ip={encrypt_text(request.remote_addr)}")
|
app.logger.info(f"Login success: username={encrypt_text(username)!r} tenant={current_tenant_id or 'default'} db={current_tenant_db} host={request.host} ip={encrypt_text(request.remote_addr)}")
|
||||||
session['username'] = username
|
session['username'] = username
|
||||||
|
session['user_id'] = str(user.get('_id'))
|
||||||
is_admin_user = bool(user.get('Admin', False))
|
is_admin_user = bool(user.get('Admin', False))
|
||||||
session['admin'] = is_admin_user
|
session['admin'] = is_admin_user
|
||||||
session['is_admin'] = is_admin_user
|
session['is_admin'] = is_admin_user
|
||||||
@@ -5597,6 +5783,8 @@ def get_items():
|
|||||||
favorites = set(session.get('favorites', []))
|
favorites = set(session.get('favorites', []))
|
||||||
|
|
||||||
available_only = str(request.args.get('available_only', '')).strip().lower() in ('1', 'true', 'yes', 'on')
|
available_only = str(request.args.get('available_only', '')).strip().lower() in ('1', 'true', 'yes', 'on')
|
||||||
|
search_term = str(request.args.get('search', '')).strip()
|
||||||
|
search_scope = str(request.args.get('search_scope', 'all')).strip().lower()
|
||||||
offset_raw = request.args.get('offset')
|
offset_raw = request.args.get('offset')
|
||||||
limit_raw = request.args.get('limit')
|
limit_raw = request.args.get('limit')
|
||||||
light_mode_param = str(request.args.get('light_mode', '')).strip().lower()
|
light_mode_param = str(request.args.get('light_mode', '')).strip().lower()
|
||||||
@@ -5632,6 +5820,42 @@ def get_items():
|
|||||||
'Deleted': {'$ne': True},
|
'Deleted': {'$ne': True},
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if search_term:
|
||||||
|
search_pattern = re.escape(search_term[:200])
|
||||||
|
if search_scope in ('description', 'title_description'):
|
||||||
|
search_fields = ['Name', 'Beschreibung']
|
||||||
|
else:
|
||||||
|
search_fields = [
|
||||||
|
'Name', 'Beschreibung', 'Code_4', 'ISBN',
|
||||||
|
'Author', 'Autor',
|
||||||
|
]
|
||||||
|
|
||||||
|
direct_matches = [{field: {'$regex': search_pattern, '$options': 'i'}}
|
||||||
|
for field in search_fields]
|
||||||
|
if search_scope not in ('description', 'title_description') and search_term.isdigit():
|
||||||
|
direct_matches.append({'Code_4': int(search_term)})
|
||||||
|
grouped_parent_ids = [
|
||||||
|
child.get('ParentItemId')
|
||||||
|
for child in items_col.find(
|
||||||
|
{
|
||||||
|
'IsGroupedSubItem': True,
|
||||||
|
'Deleted': {'$ne': True},
|
||||||
|
'$or': direct_matches,
|
||||||
|
},
|
||||||
|
{'ParentItemId': 1},
|
||||||
|
)
|
||||||
|
if child.get('ParentItemId')
|
||||||
|
]
|
||||||
|
if grouped_parent_ids:
|
||||||
|
direct_matches.append({'_id': {'$in': grouped_parent_ids}})
|
||||||
|
|
||||||
|
base_query = {
|
||||||
|
'$and': [
|
||||||
|
base_query,
|
||||||
|
{'$or': direct_matches},
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
total_count = items_col.count_documents(base_query)
|
total_count = items_col.count_documents(base_query)
|
||||||
|
|
||||||
light_projection = {
|
light_projection = {
|
||||||
@@ -5698,6 +5922,7 @@ def get_items():
|
|||||||
'ParentItemId': 1,
|
'ParentItemId': 1,
|
||||||
'Code_4': 1,
|
'Code_4': 1,
|
||||||
'Verfuegbar': 1,
|
'Verfuegbar': 1,
|
||||||
|
'User': 1,
|
||||||
'Name': 1,
|
'Name': 1,
|
||||||
}
|
}
|
||||||
# Full mode: complete child data with all details
|
# Full mode: complete child data with all details
|
||||||
@@ -5706,6 +5931,7 @@ def get_items():
|
|||||||
'ParentItemId': 1,
|
'ParentItemId': 1,
|
||||||
'Code_4': 1,
|
'Code_4': 1,
|
||||||
'Verfuegbar': 1,
|
'Verfuegbar': 1,
|
||||||
|
'User': 1,
|
||||||
'Name': 1,
|
'Name': 1,
|
||||||
'Images': 1,
|
'Images': 1,
|
||||||
'ThumbnailInfo': 1,
|
'ThumbnailInfo': 1,
|
||||||
@@ -5733,13 +5959,26 @@ def get_items():
|
|||||||
grouped_units = [itm] + grouped_children
|
grouped_units = [itm] + grouped_children
|
||||||
available_units = []
|
available_units = []
|
||||||
grouped_all_codes = []
|
grouped_all_codes = []
|
||||||
|
grouped_unit_states = []
|
||||||
for unit in grouped_units:
|
for unit in grouped_units:
|
||||||
|
unit_id = str(unit['_id']) if not isinstance(unit['_id'], str) else unit['_id']
|
||||||
unit_code = unit.get('Code_4')
|
unit_code = unit.get('Code_4')
|
||||||
if unit_code is not None and str(unit_code).strip() != '':
|
if unit_code is not None and str(unit_code).strip() != '':
|
||||||
grouped_all_codes.append(str(unit_code).strip())
|
normalized_code = str(unit_code).strip()
|
||||||
|
grouped_all_codes.append(normalized_code)
|
||||||
|
else:
|
||||||
|
normalized_code = ''
|
||||||
|
|
||||||
|
grouped_unit_states.append({
|
||||||
|
'id': unit_id,
|
||||||
|
'code': normalized_code,
|
||||||
|
'available': bool(unit.get('Verfuegbar', True)),
|
||||||
|
'borrowed_by_current_user': bool(
|
||||||
|
username and str(unit.get('User') or '') == str(username)
|
||||||
|
),
|
||||||
|
})
|
||||||
|
|
||||||
if unit.get('Verfuegbar', True):
|
if unit.get('Verfuegbar', True):
|
||||||
unit_id = str(unit['_id']) if not isinstance(unit['_id'], str) else unit['_id']
|
|
||||||
code = unit.get('Code_4') or '-'
|
code = unit.get('Code_4') or '-'
|
||||||
available_units.append({
|
available_units.append({
|
||||||
'id': unit_id,
|
'id': unit_id,
|
||||||
@@ -5752,6 +5991,7 @@ def get_items():
|
|||||||
itm['AvailableGroupedCount'] = len(available_units)
|
itm['AvailableGroupedCount'] = len(available_units)
|
||||||
itm['GroupedAvailableUnits'] = available_units
|
itm['GroupedAvailableUnits'] = available_units
|
||||||
itm['GroupedAllCodes'] = grouped_all_codes
|
itm['GroupedAllCodes'] = grouped_all_codes
|
||||||
|
itm['GroupedUnitStates'] = grouped_unit_states
|
||||||
if grouped_count > 1:
|
if grouped_count > 1:
|
||||||
itm['Verfuegbar'] = len(available_units) > 0
|
itm['Verfuegbar'] = len(available_units) > 0
|
||||||
if available_only and not itm.get('Verfuegbar', False):
|
if available_only and not itm.get('Verfuegbar', False):
|
||||||
@@ -5813,10 +6053,7 @@ def get_bookings():
|
|||||||
result = []
|
result = []
|
||||||
for booking in bookings:
|
for booking in bookings:
|
||||||
raw_booking_user = booking.get('User') or ''
|
raw_booking_user = booking.get('User') or ''
|
||||||
try:
|
booking_user = str(raw_booking_user)
|
||||||
booking_user = decrypt_text(raw_booking_user) if raw_booking_user else ''
|
|
||||||
except Exception:
|
|
||||||
booking_user = str(raw_booking_user)
|
|
||||||
start_dt = booking.get('Start')
|
start_dt = booking.get('Start')
|
||||||
if not start_dt:
|
if not start_dt:
|
||||||
continue
|
continue
|
||||||
@@ -5862,7 +6099,7 @@ def get_bookings():
|
|||||||
'userName': str(booking_user),
|
'userName': str(booking_user),
|
||||||
'notes': str(booking.get('Notes') or ''),
|
'notes': str(booking.get('Notes') or ''),
|
||||||
'period': period,
|
'period': period,
|
||||||
'isCurrentUser': str(booking_user) == username,
|
'isCurrentUser': str(booking_user) == str(current_user_id),
|
||||||
'itemBorrower': item_borrower,
|
'itemBorrower': item_borrower,
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -5982,7 +6219,10 @@ def api_booking_conflicts():
|
|||||||
current_permissions = us.get_effective_permissions(session['username'])
|
current_permissions = us.get_effective_permissions(session['username'])
|
||||||
|
|
||||||
if not current_permissions['actions'].get('can_view_logs', False):
|
if not current_permissions['actions'].get('can_view_logs', False):
|
||||||
query['User'] = session['username']
|
current_user = us.get_user(session['username'])
|
||||||
|
if not current_user or not current_user.get('_id'):
|
||||||
|
return jsonify({'error': 'User account could not be resolved'}), 401
|
||||||
|
query['User'] = str(current_user['_id'])
|
||||||
|
|
||||||
conflicts = list(ausleihungen.find(query))
|
conflicts = list(ausleihungen.find(query))
|
||||||
result = []
|
result = []
|
||||||
@@ -7323,6 +7563,11 @@ def ausleihen(id):
|
|||||||
return redirect(url_for('login'))
|
return redirect(url_for('login'))
|
||||||
|
|
||||||
username = session['username']
|
username = session['username']
|
||||||
|
current_user = us.get_user(username)
|
||||||
|
if not current_user or not current_user.get('_id'):
|
||||||
|
flash('Benutzerkonto konnte nicht eindeutig ermittelt werden.', 'error')
|
||||||
|
return redirect(url_for('login'))
|
||||||
|
effective_borrower_id = str(current_user['_id'])
|
||||||
requested_return_to = (request.form.get('return_to') or '').strip().lower()
|
requested_return_to = (request.form.get('return_to') or '').strip().lower()
|
||||||
if requested_return_to == 'library' and cfg.MODULES.is_enabled('library'):
|
if requested_return_to == 'library' and cfg.MODULES.is_enabled('library'):
|
||||||
redirect_target = 'library_view'
|
redirect_target = 'library_view'
|
||||||
@@ -7396,6 +7641,7 @@ def ausleihen(id):
|
|||||||
flash('Keine Schülerin/kein Schüler mit dieser Ausweis-ID gefunden.', 'error')
|
flash('Keine Schülerin/kein Schüler mit dieser Ausweis-ID gefunden.', 'error')
|
||||||
return redirect(url_for('library_view'))
|
return redirect(url_for('library_view'))
|
||||||
effective_borrower = student_user.get('Username') or student_user.get('username') or username
|
effective_borrower = student_user.get('Username') or student_user.get('username') or username
|
||||||
|
effective_borrower_id = str(student_user['_id'])
|
||||||
if borrow_duration_days is None:
|
if borrow_duration_days is None:
|
||||||
try:
|
try:
|
||||||
card_default = int(student_user.get('MaxBorrowDays', cfg.STUDENT_DEFAULT_BORROW_DAYS))
|
card_default = int(student_user.get('MaxBorrowDays', cfg.STUDENT_DEFAULT_BORROW_DAYS))
|
||||||
@@ -7470,7 +7716,7 @@ def ausleihen(id):
|
|||||||
it.update_item_status(unit_id, False, effective_borrower)
|
it.update_item_status(unit_id, False, effective_borrower)
|
||||||
au.add_ausleihung(
|
au.add_ausleihung(
|
||||||
unit_id,
|
unit_id,
|
||||||
effective_borrower,
|
effective_borrower_id,
|
||||||
start_date,
|
start_date,
|
||||||
end_date=end_date,
|
end_date=end_date,
|
||||||
due_date=end_date if is_library_item else None,
|
due_date=end_date if is_library_item else None,
|
||||||
@@ -7567,7 +7813,7 @@ def ausleihen(id):
|
|||||||
start_date = datetime.datetime.now(ZoneInfo("Europe/Berlin"))
|
start_date = datetime.datetime.now(ZoneInfo("Europe/Berlin"))
|
||||||
au.add_ausleihung(
|
au.add_ausleihung(
|
||||||
id,
|
id,
|
||||||
effective_borrower,
|
effective_borrower_id,
|
||||||
start_date,
|
start_date,
|
||||||
end_date=end_date,
|
end_date=end_date,
|
||||||
due_date=end_date if is_library_item else None,
|
due_date=end_date if is_library_item else None,
|
||||||
@@ -7618,7 +7864,7 @@ def ausleihen(id):
|
|||||||
exemplar_id = f"{id}_{exemplar['number']}"
|
exemplar_id = f"{id}_{exemplar['number']}"
|
||||||
au.add_ausleihung(
|
au.add_ausleihung(
|
||||||
exemplar_id,
|
exemplar_id,
|
||||||
effective_borrower,
|
effective_borrower_id,
|
||||||
start_date,
|
start_date,
|
||||||
end_date=end_date,
|
end_date=end_date,
|
||||||
due_date=end_date if is_library_item else None,
|
due_date=end_date if is_library_item else None,
|
||||||
@@ -7669,7 +7915,13 @@ def zurueckgeben(id):
|
|||||||
|
|
||||||
current_permissions = us.get_effective_permissions(session['username'])
|
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:
|
try:
|
||||||
# Get ALL active borrowing records for this item and complete them
|
# Get ALL active borrowing records for this item and complete them
|
||||||
client = MongoClient(MONGODB_HOST, MONGODB_PORT)
|
client = MongoClient(MONGODB_HOST, MONGODB_PORT)
|
||||||
@@ -7678,7 +7930,7 @@ def zurueckgeben(id):
|
|||||||
|
|
||||||
# Find all active records for this item
|
# Find all active records for this item
|
||||||
active_records = ausleihungen.find({
|
active_records = ausleihungen.find({
|
||||||
'Item': id,
|
'$or': [{'Item': id}, {'Item': ObjectId(id) if ObjectId.is_valid(id) else id}],
|
||||||
'Status': 'active'
|
'Status': 'active'
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -7694,6 +7946,7 @@ def zurueckgeben(id):
|
|||||||
{'$set': {
|
{'$set': {
|
||||||
'Status': 'completed',
|
'Status': 'completed',
|
||||||
'End': end_date,
|
'End': end_date,
|
||||||
|
'ReturnPending': False,
|
||||||
'LastUpdated': datetime.datetime.now(ZoneInfo("Europe/Berlin"))
|
'LastUpdated': datetime.datetime.now(ZoneInfo("Europe/Berlin"))
|
||||||
}}
|
}}
|
||||||
)
|
)
|
||||||
@@ -7779,7 +8032,12 @@ def get_ausleihung_by_item_route(id):
|
|||||||
|
|
||||||
current_permissions = us.get_effective_permissions(session['username'])
|
current_permissions = us.get_effective_permissions(session['username'])
|
||||||
|
|
||||||
if ausleihung and (current_permissions['actions'].get('can_manage_users')) or ausleihung.get('User') == session['username']:
|
current_user = us.get_user(session['username'])
|
||||||
|
current_user_id = str(current_user['_id']) if current_user and current_user.get('_id') else ''
|
||||||
|
if ausleihung and (
|
||||||
|
current_permissions['actions'].get('can_manage_users')
|
||||||
|
or ausleihung.get('User') == current_user_id
|
||||||
|
):
|
||||||
return {'ausleihung': ausleihung, 'status': 'success'}
|
return {'ausleihung': ausleihung, 'status': 'success'}
|
||||||
|
|
||||||
item = it.get_item(id)
|
item = it.get_item(id)
|
||||||
@@ -7811,10 +8069,7 @@ def get_planned_bookings(item_id):
|
|||||||
bookings = []
|
bookings = []
|
||||||
for r in cursor:
|
for r in cursor:
|
||||||
raw_user = r.get('User') or ''
|
raw_user = r.get('User') or ''
|
||||||
try:
|
booking_user = _display_username(raw_user)
|
||||||
booking_user = decrypt_text(raw_user) if raw_user else ''
|
|
||||||
except Exception:
|
|
||||||
booking_user = str(raw_user)
|
|
||||||
bookings.append({
|
bookings.append({
|
||||||
'id': str(r.get('_id')),
|
'id': str(r.get('_id')),
|
||||||
'user': booking_user,
|
'user': booking_user,
|
||||||
@@ -7845,10 +8100,7 @@ def get_planned_bookings_public(item_id):
|
|||||||
bookings = []
|
bookings = []
|
||||||
for r in cursor:
|
for r in cursor:
|
||||||
raw_user = r.get('User') or ''
|
raw_user = r.get('User') or ''
|
||||||
try:
|
booking_user = _display_username(raw_user)
|
||||||
booking_user = decrypt_text(raw_user) if raw_user else ''
|
|
||||||
except Exception:
|
|
||||||
booking_user = str(raw_user)
|
|
||||||
bookings.append({
|
bookings.append({
|
||||||
'user': booking_user,
|
'user': booking_user,
|
||||||
'period': r.get('Period'),
|
'period': r.get('Period'),
|
||||||
@@ -8061,7 +8313,7 @@ def plan_booking():
|
|||||||
try:
|
try:
|
||||||
for _, period, period_times in requested_slots:
|
for _, period, period_times in requested_slots:
|
||||||
booking_id = au.add_planned_booking(
|
booking_id = au.add_planned_booking(
|
||||||
item_id, session['username'], period_times['start'],
|
item_id, session.get('user_id') or str(us.get_user(session['username'])['_id']), period_times['start'],
|
||||||
period_times['end'], notes, period=period
|
period_times['end'], notes, period=period
|
||||||
)
|
)
|
||||||
if not booking_id:
|
if not booking_id:
|
||||||
@@ -8114,7 +8366,7 @@ def process_day_bookings(item_id, booking_date, periods, notes):
|
|||||||
# Create the booking
|
# Create the booking
|
||||||
booking_id = au.add_planned_booking(
|
booking_id = au.add_planned_booking(
|
||||||
item_id,
|
item_id,
|
||||||
session['username'],
|
session.get('user_id') or str(us.get_user(session['username'])['_id']),
|
||||||
start_time,
|
start_time,
|
||||||
end_time,
|
end_time,
|
||||||
notes,
|
notes,
|
||||||
@@ -8181,7 +8433,7 @@ def add_booking():
|
|||||||
# Continue with adding the booking
|
# Continue with adding the booking
|
||||||
booking_id = au.add_planned_booking(
|
booking_id = au.add_planned_booking(
|
||||||
item_id=item_id,
|
item_id=item_id,
|
||||||
user=session['username'],
|
user_id=session.get('user_id') or str(us.get_user(session['username'])['_id']),
|
||||||
start_date=start_date,
|
start_date=start_date,
|
||||||
end_date=end_date,
|
end_date=end_date,
|
||||||
notes=notes,
|
notes=notes,
|
||||||
@@ -8212,8 +8464,10 @@ def cancel_booking(id):
|
|||||||
current_permissions = us.get_effective_permissions(session['username'])
|
current_permissions = us.get_effective_permissions(session['username'])
|
||||||
|
|
||||||
# Check if user owns this booking
|
# Check if user owns this booking
|
||||||
booking_user = au.dp.decrypt_text(booking.get('User')) if booking.get('User') else ''
|
current_user = us.get_user(session['username'])
|
||||||
if booking_user != session['username'] and not current_permissions['actions'].get('can_manage_users', False):
|
current_user_id = str(current_user['_id']) if current_user and current_user.get('_id') else ''
|
||||||
|
booking_user_id = str(booking.get('User') or '')
|
||||||
|
if booking_user_id != current_user_id and not current_permissions['actions'].get('can_manage_users', False):
|
||||||
return {"success": False, "error": "Not authorized to cancel this booking"}, 403
|
return {"success": False, "error": "Not authorized to cancel this booking"}, 403
|
||||||
|
|
||||||
# Cancel the booking
|
# Cancel the booking
|
||||||
@@ -8690,7 +8944,7 @@ def user_del():
|
|||||||
fullname = None
|
fullname = None
|
||||||
|
|
||||||
users_list.append({
|
users_list.append({
|
||||||
'username': decrypt_text(username),
|
'username': _display_username(username),
|
||||||
'admin': user.get('Admin', False),
|
'admin': user.get('Admin', False),
|
||||||
'fullname': fullname,
|
'fullname': fullname,
|
||||||
'name': name,
|
'name': name,
|
||||||
@@ -8831,7 +9085,8 @@ def admin_borrowings():
|
|||||||
has_damage = False
|
has_damage = False
|
||||||
|
|
||||||
raw_user = r.get('User', '')
|
raw_user = r.get('User', '')
|
||||||
decrypted_user = decrypt_text(raw_user) if raw_user else ''
|
decrypted_user = _display_username(raw_user)
|
||||||
|
|
||||||
|
|
||||||
entries.append({
|
entries.append({
|
||||||
'id': str(r.get('_id')),
|
'id': str(r.get('_id')),
|
||||||
@@ -10065,8 +10320,8 @@ def library_item_invoices(item_id):
|
|||||||
entries.append({
|
entries.append({
|
||||||
'borrow_id': str(borrow_doc.get('_id')),
|
'borrow_id': str(borrow_doc.get('_id')),
|
||||||
'borrow_status': borrow_doc.get('Status', ''),
|
'borrow_status': borrow_doc.get('Status', ''),
|
||||||
'borrow_user': decrypt_text(borrow_doc.get('User', '')) if hasattr(borrow_doc,
|
'borrow_user': _display_username(borrow_doc.get('User', '')) if hasattr(borrow_doc,
|
||||||
'get') and borrow_doc.get(
|
'get') and borrow_doc.get(
|
||||||
'User') else '',
|
'User') else '',
|
||||||
'borrow_start': borrow_doc.get('Start').strftime('%d.%m.%Y %H:%M') if isinstance(
|
'borrow_start': borrow_doc.get('Start').strftime('%d.%m.%Y %H:%M') if isinstance(
|
||||||
borrow_doc.get('Start'), datetime.datetime) else '',
|
borrow_doc.get('Start'), datetime.datetime) else '',
|
||||||
@@ -10166,7 +10421,7 @@ def library_item_invoices(item_id):
|
|||||||
))
|
))
|
||||||
|
|
||||||
for b in damage_borrow_docs:
|
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 {}
|
d_data = b.get('DamageData') or {}
|
||||||
if not isinstance(d_data, dict): d_data = {}
|
if not isinstance(d_data, dict): d_data = {}
|
||||||
@@ -10456,7 +10711,7 @@ def logs():
|
|||||||
|
|
||||||
formatted_items.append({
|
formatted_items.append({
|
||||||
'Item': item_name,
|
'Item': item_name,
|
||||||
'User': decrypt_text(username),
|
'User': _display_username(username),
|
||||||
'Start': start_date,
|
'Start': start_date,
|
||||||
'End': end_date,
|
'End': end_date,
|
||||||
'Duration': duration,
|
'Duration': duration,
|
||||||
@@ -10498,7 +10753,7 @@ def logs():
|
|||||||
note = log_item.get('note', '')
|
note = log_item.get('note', '')
|
||||||
formatted_items.append({
|
formatted_items.append({
|
||||||
'Item': item_name,
|
'Item': item_name,
|
||||||
'User': decrypt_text(log_item.get('user', 'Unknown User')),
|
'User': _display_username(log_item.get('user', 'Unknown User')),
|
||||||
'Start': ts_display,
|
'Start': ts_display,
|
||||||
'End': '-',
|
'End': '-',
|
||||||
'Duration': '-',
|
'Duration': '-',
|
||||||
@@ -10512,7 +10767,7 @@ def logs():
|
|||||||
resolved_count = log_item.get('resolved_count', 0)
|
resolved_count = log_item.get('resolved_count', 0)
|
||||||
formatted_items.append({
|
formatted_items.append({
|
||||||
'Item': item_name,
|
'Item': item_name,
|
||||||
'User': decrypt_text(log_item.get('user', 'Unknown User')),
|
'User': _display_username(log_item.get('user', 'Unknown User')),
|
||||||
'Start': ts_display,
|
'Start': ts_display,
|
||||||
'End': '-',
|
'End': '-',
|
||||||
'Duration': '-',
|
'Duration': '-',
|
||||||
@@ -10775,7 +11030,9 @@ def search_word(word):
|
|||||||
if (term_lower in text.lower()) or (term_lower in title_text.lower()):
|
if (term_lower in text.lower()) or (term_lower in title_text.lower()):
|
||||||
_id = i.get("_id")
|
_id = i.get("_id")
|
||||||
if _id is not None:
|
if _id is not None:
|
||||||
id_set.add(str(_id))
|
item_id = str(_id)
|
||||||
|
parent_id = i.get('ParentItemId')
|
||||||
|
id_set.add(str(parent_id or item_id))
|
||||||
|
|
||||||
return jsonify({"success": True, "response": list(id_set)})
|
return jsonify({"success": True, "response": list(id_set)})
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
@@ -11308,6 +11565,14 @@ def my_borrowed_items():
|
|||||||
return redirect(url_for('login', next=request.path))
|
return redirect(url_for('login', next=request.path))
|
||||||
|
|
||||||
username = session['username']
|
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)
|
client = MongoClient(MONGODB_HOST, MONGODB_PORT)
|
||||||
db = client[MONGODB_DB]
|
db = client[MONGODB_DB]
|
||||||
@@ -11324,31 +11589,28 @@ def my_borrowed_items():
|
|||||||
|
|
||||||
for appointment in all_ausleihungen:
|
for appointment in all_ausleihungen:
|
||||||
raw_user = appointment.get('User', '')
|
raw_user = appointment.get('User', '')
|
||||||
|
user_values = {str(raw_user).strip()} if raw_user else set()
|
||||||
try:
|
try:
|
||||||
decrypted_user = decrypt_text(raw_user) if raw_user else ''
|
if raw_user:
|
||||||
except Exception as e:
|
user_values.add(str(decrypt_text(raw_user)).strip())
|
||||||
app.logger.error(f"Entschlüsselungsfehler: {e}")
|
user_values.add(_resolve_library_card_id(raw_user))
|
||||||
decrypted_user = ''
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
if decrypted_user != username:
|
if not user_values.intersection(user_ids):
|
||||||
continue
|
continue
|
||||||
|
|
||||||
item_id = appointment.get('Item')
|
item_id = appointment.get('Item')
|
||||||
if not item_id:
|
if not item_id:
|
||||||
continue
|
continue
|
||||||
|
|
||||||
try:
|
item_queries = [{'_id': item_id}]
|
||||||
if isinstance(item_id, str):
|
if isinstance(item_id, str) and ObjectId.is_valid(item_id):
|
||||||
query_id = ObjectId(item_id)
|
item_queries.insert(0, {'_id': ObjectId(item_id)})
|
||||||
else:
|
item_obj = items_collection.find_one({
|
||||||
query_id = item_id
|
'$or': item_queries,
|
||||||
|
'Deleted': {'$ne': True}
|
||||||
item_obj = items_collection.find_one({
|
})
|
||||||
'_id': query_id,
|
|
||||||
'Deleted': {'$ne': True}
|
|
||||||
})
|
|
||||||
except Exception:
|
|
||||||
item_obj = None
|
|
||||||
|
|
||||||
if item_obj:
|
if item_obj:
|
||||||
item_obj['_id'] = str(item_obj['_id'])
|
item_obj['_id'] = str(item_obj['_id'])
|
||||||
@@ -11360,14 +11622,21 @@ def my_borrowed_items():
|
|||||||
'notes': appointment.get('Notes'),
|
'notes': appointment.get('Notes'),
|
||||||
'period': appointment.get('Period'),
|
'period': appointment.get('Period'),
|
||||||
'status': appointment.get('VerifiedStatus', appointment.get('Status')),
|
'status': appointment.get('VerifiedStatus', appointment.get('Status')),
|
||||||
|
'return_pending': bool(appointment.get('ReturnPending')),
|
||||||
}
|
}
|
||||||
|
|
||||||
status = appointment.get('Status')
|
status = appointment.get('Status')
|
||||||
if status == 'active':
|
if status == 'active':
|
||||||
item_obj['ActiveAppointment'] = True
|
item_obj['ActiveAppointment'] = True
|
||||||
|
item_obj['ReturnPending'] = bool(appointment.get('ReturnPending'))
|
||||||
if str(item_obj['_id']) not in processed_item_ids:
|
if str(item_obj['_id']) not in processed_item_ids:
|
||||||
active_items.append(item_obj)
|
active_items.append(item_obj)
|
||||||
processed_item_ids.add(str(item_obj['_id']))
|
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':
|
elif status == 'planned':
|
||||||
planned_items.append(item_obj)
|
planned_items.append(item_obj)
|
||||||
|
|
||||||
@@ -11378,12 +11647,15 @@ def my_borrowed_items():
|
|||||||
|
|
||||||
for item in all_borrowed_items:
|
for item in all_borrowed_items:
|
||||||
raw_item_user = item.get('User', '')
|
raw_item_user = item.get('User', '')
|
||||||
|
item_user_values = {str(raw_item_user).strip()} if raw_item_user else set()
|
||||||
try:
|
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:
|
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['_id'] = str(item['_id'])
|
||||||
item['ActiveAppointment'] = True
|
item['ActiveAppointment'] = True
|
||||||
item['AppointmentData'] = {'status': 'active (no document)'}
|
item['AppointmentData'] = {'status': 'active (no document)'}
|
||||||
@@ -11703,10 +11975,10 @@ def admin_damaged_items():
|
|||||||
|
|
||||||
# Benutzernamen der Ausleihe entschlüsseln
|
# Benutzernamen der Ausleihe entschlüsseln
|
||||||
if active_borrow and active_borrow.get('User'):
|
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
|
# 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
|
# Datenstruktur exakt für dein Jinja2 Template aufbauen
|
||||||
damaged_items.append({
|
damaged_items.append({
|
||||||
@@ -12143,7 +12415,7 @@ def schedule_appointment():
|
|||||||
# Use add_ausleihung directly to set the correct initial status
|
# Use add_ausleihung directly to set the correct initial status
|
||||||
appointment_id = au.add_ausleihung(
|
appointment_id = au.add_ausleihung(
|
||||||
item_id=item_id,
|
item_id=item_id,
|
||||||
user=session['username'],
|
user_id=session.get('user_id') or str(us.get_user(session['username'])['_id']),
|
||||||
start_date=start_datetime,
|
start_date=start_datetime,
|
||||||
end_date=end_datetime,
|
end_date=end_datetime,
|
||||||
notes=notes,
|
notes=notes,
|
||||||
@@ -12279,7 +12551,7 @@ def cancel_ausleihung_route(id):
|
|||||||
ausleihung_status = ausleihung.get('Status', 'unknown')
|
ausleihung_status = ausleihung.get('Status', 'unknown')
|
||||||
raw_ausleihung_user = ausleihung.get('User', '')
|
raw_ausleihung_user = ausleihung.get('User', '')
|
||||||
try:
|
try:
|
||||||
ausleihung_user = decrypt_text(raw_ausleihung_user) if raw_ausleihung_user else ''
|
ausleihung_user = _display_username(raw_ausleihung_user)
|
||||||
except Exception:
|
except Exception:
|
||||||
ausleihung_user = str(raw_ausleihung_user or '')
|
ausleihung_user = str(raw_ausleihung_user or '')
|
||||||
print(f"Found ausleihung: ID={id}, Status={ausleihung_status}")
|
print(f"Found ausleihung: ID={id}, Status={ausleihung_status}")
|
||||||
|
|||||||
@@ -15,7 +15,8 @@ Hauptfunktionen:
|
|||||||
|
|
||||||
Sammlungsstruktur:
|
Sammlungsstruktur:
|
||||||
- ausleihungen: Speichert alle Ausleihungsdatensätze mit ihrem Status
|
- 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
|
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]
|
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")
|
print(f"[DEBUG] Ausleihe {ausleihung_id} startet in {time_until_start/3600:.1f} Stunden ({start_time}), noch geplant")
|
||||||
new_status = 'planned'
|
new_status = 'planned'
|
||||||
# Wenn kein Enddatum gesetzt ist oder die aktuelle Zeit vor dem Enddatum liegt,
|
# Eine aktive Ausleihe bleibt aktiv, bis die Rückgabe ausdrücklich bestätigt
|
||||||
# ist die Ausleihung aktiv
|
# wurde. Das geplante Ende löst nur einen Rückgabehinweis aus.
|
||||||
elif not end_time or current_time < end_time:
|
|
||||||
new_status = 'active'
|
|
||||||
# Wenn die aktuelle Zeit nach dem Enddatum liegt, ist die Ausleihung beendet
|
|
||||||
else:
|
else:
|
||||||
new_status = 'completed'
|
new_status = 'active'
|
||||||
|
|
||||||
# Protokollieren Sie Statusänderungen, wenn aktiviert und eine Änderung stattgefunden hat
|
# Protokollieren Sie Statusänderungen, wenn aktiviert und eine Änderung stattgefunden hat
|
||||||
if log_changes and new_status != original_status and '_id' in ausleihung:
|
if log_changes and new_status != original_status and '_id' in ausleihung:
|
||||||
@@ -185,13 +183,13 @@ def create_backup_database():
|
|||||||
|
|
||||||
# === AUSLEIHUNG MANAGEMENT ===
|
# === AUSLEIHUNG MANAGEMENT ===
|
||||||
|
|
||||||
def add_ausleihung(item_id, user, start_date, end_date=None, notes="", status="active", period=None, exemplar_data=None, due_date=None):
|
def add_ausleihung(item_id, user_id, start_date, end_date=None, notes="", status="active", period=None, exemplar_data=None, due_date=None):
|
||||||
"""
|
"""
|
||||||
Add a new borrowing record for an item.
|
Add a new borrowing record for an item.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
item_id (str): ID of the item borrowed
|
item_id (str): ID of the item borrowed
|
||||||
user (str): Username of the borrower
|
user_id (str): ID of the borrower
|
||||||
start_date (datetime): Start date and time of the borrowing
|
start_date (datetime): Start date and time of the borrowing
|
||||||
end_date (datetime, optional): End date and time if already returned
|
end_date (datetime, optional): End date and time if already returned
|
||||||
notes (str, optional): Additional notes about the borrowing
|
notes (str, optional): Additional notes about the borrowing
|
||||||
@@ -209,7 +207,7 @@ def add_ausleihung(item_id, user, start_date, end_date=None, notes="", status="a
|
|||||||
|
|
||||||
ausleihung = {
|
ausleihung = {
|
||||||
'Item': item_id,
|
'Item': item_id,
|
||||||
'User': dp.encrypt_text(user),
|
'User': str(user_id),
|
||||||
'Start': start_date,
|
'Start': start_date,
|
||||||
'Status': status
|
'Status': status
|
||||||
}
|
}
|
||||||
@@ -256,8 +254,7 @@ def update_ausleihung(id, item_id=None, user_id=None, start=None, end=None, note
|
|||||||
if item_id is not None:
|
if item_id is not None:
|
||||||
update_data['Item'] = item_id
|
update_data['Item'] = item_id
|
||||||
if user_id is not None:
|
if user_id is not None:
|
||||||
# WICHTIG: Gleiche Verschlüsselung wie in add_ausleihung nutzen!
|
update_data['User'] = str(user_id)
|
||||||
update_data['User'] = dp.encrypt_text(user_id) if hasattr(dp, 'encrypt_text') else user_id
|
|
||||||
if start is not None:
|
if start is not None:
|
||||||
update_data['Start'] = ensure_timezone_aware(start)
|
update_data['Start'] = ensure_timezone_aware(start)
|
||||||
if end is not None:
|
if end is not None:
|
||||||
@@ -556,9 +553,7 @@ def get_ausleihung_by_user(user_id, status=None, use_client_side_verification=Tr
|
|||||||
db = client[cfg.MONGODB_DB]
|
db = client[cfg.MONGODB_DB]
|
||||||
ausleihungen = db['ausleihungen']
|
ausleihungen = db['ausleihungen']
|
||||||
|
|
||||||
# Ensure proper encrypted query string if user IDs are encrypted in DB
|
query = {'User': str(user_id), 'Status': {'$ne': 'deleted'}}
|
||||||
search_user = dp.encrypt_text(user_id) if hasattr(dp, 'encrypt_text') else user_id
|
|
||||||
query = {'User': search_user, 'Status': {'$ne': 'deleted'}}
|
|
||||||
|
|
||||||
if not use_client_side_verification:
|
if not use_client_side_verification:
|
||||||
if status is not None:
|
if status is not None:
|
||||||
@@ -864,8 +859,8 @@ def reset_item_completely(item_id):
|
|||||||
|
|
||||||
# === KOMPATIBILITÄTSFUNKTIONEN ===
|
# === KOMPATIBILITÄTSFUNKTIONEN ===
|
||||||
|
|
||||||
def add_planned_booking(item_id, user, start_date, end_date, notes="", period=None):
|
def add_planned_booking(item_id, user_id, start_date, end_date, notes="", period=None):
|
||||||
return add_ausleihung(item_id, user, start_date, end_date, notes, status='planned', period=period)
|
return add_ausleihung(item_id, user_id, start_date, end_date, notes, status='planned', period=period)
|
||||||
|
|
||||||
|
|
||||||
def check_booking_conflict(item_id, start_date, end_date, period=None):
|
def check_booking_conflict(item_id, start_date, end_date, period=None):
|
||||||
|
|||||||
@@ -695,13 +695,42 @@ def get_user_by_student_card(student_card_id):
|
|||||||
if not normalized:
|
if not normalized:
|
||||||
return None
|
return None
|
||||||
client = MongoClient(cfg.MONGODB_HOST, cfg.MONGODB_PORT)
|
client = MongoClient(cfg.MONGODB_HOST, cfg.MONGODB_PORT)
|
||||||
db = _get_tenant_db(client)
|
try:
|
||||||
users = db['student_cards']
|
db = _get_tenant_db(client)
|
||||||
found_user = users.find_one({'SchülerName': normalized})
|
users = db['users']
|
||||||
client.close()
|
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):
|
def get_user_by_student_ident(student_ident):
|
||||||
"""Return user dict by student ident by decrypting all cards and matching."""
|
"""Return user dict by student ident by decrypting all cards and matching."""
|
||||||
@@ -874,6 +903,42 @@ def get_user(username):
|
|||||||
client.close()
|
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):
|
def check_admin(username):
|
||||||
"""Check if a user has administrator privileges."""
|
"""Check if a user has administrator privileges."""
|
||||||
user = get_user(username)
|
user = get_user(username)
|
||||||
|
|||||||
@@ -921,6 +921,42 @@ html, body {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* iPad layout: keep content airy while using the available tablet width. */
|
||||||
|
@media screen and (min-width: 768px) and (max-width: 1180px) {
|
||||||
|
.container {
|
||||||
|
width: min(100% - 32px, 1120px);
|
||||||
|
margin: 16px auto;
|
||||||
|
padding: 20px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.form-control,
|
||||||
|
.form-select,
|
||||||
|
textarea,
|
||||||
|
input,
|
||||||
|
select {
|
||||||
|
min-height: 44px;
|
||||||
|
font-size: 16px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn,
|
||||||
|
button,
|
||||||
|
input[type="submit"],
|
||||||
|
input[type="button"] {
|
||||||
|
min-height: 44px;
|
||||||
|
touch-action: manipulation;
|
||||||
|
}
|
||||||
|
|
||||||
|
.table-responsive {
|
||||||
|
border: 1px solid var(--ui-border);
|
||||||
|
border-radius: var(--ui-radius);
|
||||||
|
-webkit-overflow-scrolling: touch;
|
||||||
|
}
|
||||||
|
|
||||||
|
.table-responsive > .table {
|
||||||
|
margin-bottom: 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/* ========================================================= */
|
/* ========================================================= */
|
||||||
/* UNIVERSAL DARK MODE OVERRIDES FOR HARDCODED HTML STYLES */
|
/* UNIVERSAL DARK MODE OVERRIDES FOR HARDCODED HTML STYLES */
|
||||||
/* ========================================================= */
|
/* ========================================================= */
|
||||||
|
|||||||
@@ -1301,8 +1301,6 @@
|
|||||||
<button class="function-search-btn" type="submit">Los</button>
|
<button class="function-search-btn" type="submit">Los</button>
|
||||||
</form>
|
</form>
|
||||||
</div>
|
</div>
|
||||||
{% if current_tenant_db %}
|
|
||||||
<span class="navbar-text tenant-badge" title="Aktive Tenant-Datenbank">{{ current_tenant_db }}</span>
|
|
||||||
{% endif %}
|
{% endif %}
|
||||||
<span class="navbar-text text-light me-3">{{ session['username'] }}</span>
|
<span class="navbar-text text-light me-3">{{ session['username'] }}</span>
|
||||||
<div class="dropdown me-2 user-menu-wrap">
|
<div class="dropdown me-2 user-menu-wrap">
|
||||||
@@ -1332,7 +1330,6 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</nav>
|
</nav>
|
||||||
{% endif %}
|
|
||||||
|
|
||||||
{% if library_module_enabled and CURRENT_MODULE == 'library' %}
|
{% if library_module_enabled and CURRENT_MODULE == 'library' %}
|
||||||
<nav class="navbar navbar-expand-lg navbar-dark" id="libraryNavbar">
|
<nav class="navbar navbar-expand-lg navbar-dark" id="libraryNavbar">
|
||||||
|
|||||||
@@ -214,7 +214,7 @@
|
|||||||
|
|
||||||
<!-- E-Mail Modal -->
|
<!-- E-Mail Modal -->
|
||||||
<div class="modal fade" id="emailModal" tabindex="-1" aria-labelledby="emailModalLabel" aria-hidden="true">
|
<div class="modal fade" id="emailModal" tabindex="-1" aria-labelledby="emailModalLabel" aria-hidden="true">
|
||||||
<div class="modal-dialog">
|
<div class="modal-dialog modal-dialog-centered">
|
||||||
<div class="modal-content">
|
<div class="modal-content">
|
||||||
<div class="modal-header">
|
<div class="modal-header">
|
||||||
<h5 class="modal-title" id="emailModalLabel">Mahnungs-E-Mail senden</h5>
|
<h5 class="modal-title" id="emailModalLabel">Mahnungs-E-Mail senden</h5>
|
||||||
@@ -247,7 +247,7 @@
|
|||||||
|
|
||||||
<!-- Custom Reset Days Modal -->
|
<!-- Custom Reset Days Modal -->
|
||||||
<div class="modal fade" id="customResetModal" tabindex="-1" aria-labelledby="customResetModalLabel" aria-hidden="true">
|
<div class="modal fade" id="customResetModal" tabindex="-1" aria-labelledby="customResetModalLabel" aria-hidden="true">
|
||||||
<div class="modal-dialog">
|
<div class="modal-dialog modal-dialog-centered">
|
||||||
<div class="modal-content">
|
<div class="modal-content">
|
||||||
<div class="modal-header">
|
<div class="modal-header">
|
||||||
<h5 class="modal-title" id="customResetModalLabel">Mahnung zurücksetzen</h5>
|
<h5 class="modal-title" id="customResetModalLabel">Mahnung zurücksetzen</h5>
|
||||||
|
|||||||
+263
-52
@@ -266,6 +266,11 @@
|
|||||||
border-radius: 4px;
|
border-radius: 4px;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.code-search-label {
|
||||||
|
color: #b93845;
|
||||||
|
font-weight: 700;
|
||||||
|
}
|
||||||
|
|
||||||
.search-button {
|
.search-button {
|
||||||
padding: 8px 12px;
|
padding: 8px 12px;
|
||||||
background-color: #007bff;
|
background-color: #007bff;
|
||||||
@@ -284,10 +289,10 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
#code-search.searching {
|
#code-search.searching {
|
||||||
background-color: #fff3cd;
|
background-color: #fff5f5;
|
||||||
transition: background-color 0.3s;
|
transition: background-color 0.3s;
|
||||||
border: 2px solid #ffc107;
|
border: 2px solid #d65a62;
|
||||||
box-shadow: 0 0 8px rgba(255, 193, 7, 0.5);
|
box-shadow: 0 0 8px rgba(190, 55, 66, 0.28);
|
||||||
}
|
}
|
||||||
|
|
||||||
/* QR Scanner styles */
|
/* QR Scanner styles */
|
||||||
@@ -562,26 +567,55 @@
|
|||||||
align-items: center;
|
align-items: center;
|
||||||
}
|
}
|
||||||
|
|
||||||
.navigation-buttons {
|
.items-navigation {
|
||||||
display: flex;
|
display: grid;
|
||||||
justify-content: center;
|
grid-template-columns: 42px minmax(0, 1fr) 42px;
|
||||||
gap: 10px;
|
align-items: center;
|
||||||
|
column-gap: 16px;
|
||||||
|
width: calc(100% + 116px);
|
||||||
|
margin-left: -58px;
|
||||||
margin-top: 20px;
|
margin-top: 20px;
|
||||||
}
|
}
|
||||||
|
|
||||||
.navigation-buttons .prev-button,
|
.navigation-button-slot {
|
||||||
.navigation-buttons .next-button {
|
display: flex;
|
||||||
background-color: #007bff;
|
justify-content: center;
|
||||||
color: #fff;
|
|
||||||
border: none;
|
|
||||||
cursor: pointer;
|
|
||||||
padding: 10px;
|
|
||||||
border-radius: 5px;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.navigation-buttons .prev-button:hover,
|
.navigation-button {
|
||||||
.navigation-buttons .next-button:hover {
|
display: inline-flex;
|
||||||
background-color: #0056b3;
|
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 */
|
/* Modal styles */
|
||||||
@@ -744,15 +778,15 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
.code-match {
|
.code-match {
|
||||||
border: 2px solid #17a2b8 !important;
|
border: 2px solid #d65a62 !important;
|
||||||
box-shadow: 0 0 15px rgba(23, 162, 184, 0.5) !important;
|
box-shadow: 0 0 15px rgba(190, 55, 66, 0.28) !important;
|
||||||
position: relative;
|
position: relative;
|
||||||
z-index: 5;
|
z-index: 5;
|
||||||
}
|
}
|
||||||
|
|
||||||
.exact-code-match {
|
.exact-code-match {
|
||||||
border: 3px solid #28a745 !important;
|
border: 3px solid #b93845 !important;
|
||||||
box-shadow: 0 0 20px rgba(40, 167, 69, 0.7) !important;
|
box-shadow: 0 0 20px rgba(185, 56, 69, 0.42) !important;
|
||||||
position: relative;
|
position: relative;
|
||||||
z-index: 11;
|
z-index: 11;
|
||||||
}
|
}
|
||||||
@@ -1633,7 +1667,13 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
/* Navigation buttons mobile */
|
/* 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 */
|
display: none !important; /* Hide horizontal navigation on mobile */
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1946,7 +1986,7 @@
|
|||||||
/* Standardized button styles across the application */
|
/* Standardized button styles across the application */
|
||||||
.search-button, .scan-button, .filter-toggle, .clear-filter,
|
.search-button, .scan-button, .filter-toggle, .clear-filter,
|
||||||
.add-new-btn, .popup-close-button, .prev-image-button, .next-image-button,
|
.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;
|
display: inline-flex;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
justify-content: center;
|
justify-content: center;
|
||||||
@@ -1971,6 +2011,122 @@
|
|||||||
box-sizing: border-box;
|
box-sizing: border-box;
|
||||||
white-space: nowrap;
|
white-space: nowrap;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* iPad: use the wider canvas for cards, filters, forms, and image previews. */
|
||||||
|
@media screen and (min-width: 768px) and (max-width: 1180px) {
|
||||||
|
.admin-content-container {
|
||||||
|
width: min(100%, 1120px) !important;
|
||||||
|
max-width: 1120px !important;
|
||||||
|
margin: 0 auto !important;
|
||||||
|
padding: 20px 24px 28px !important;
|
||||||
|
box-sizing: border-box !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
.filter-container {
|
||||||
|
display: grid !important;
|
||||||
|
grid-template-columns: repeat(2, minmax(0, 1fr)) !important;
|
||||||
|
align-items: start;
|
||||||
|
gap: 14px !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
.filter-group {
|
||||||
|
min-width: 0 !important;
|
||||||
|
width: auto !important;
|
||||||
|
padding: 14px !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
.filter-group.search-field {
|
||||||
|
grid-column: span 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
.search-container {
|
||||||
|
gap: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.search-container input,
|
||||||
|
.form-group input,
|
||||||
|
.form-group select,
|
||||||
|
.form-group textarea {
|
||||||
|
min-height: 44px;
|
||||||
|
font-size: 16px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.items-container {
|
||||||
|
display: grid !important;
|
||||||
|
grid-template-columns: repeat(2, minmax(0, 1fr)) !important;
|
||||||
|
gap: 18px !important;
|
||||||
|
padding: 14px 0 24px !important;
|
||||||
|
overflow: visible !important;
|
||||||
|
scroll-snap-type: none !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
.item-card {
|
||||||
|
width: auto !important;
|
||||||
|
max-width: none !important;
|
||||||
|
min-width: 0 !important;
|
||||||
|
padding: 16px !important;
|
||||||
|
scroll-snap-align: none !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
.item-card .image-container {
|
||||||
|
width: 100% !important;
|
||||||
|
max-width: none !important;
|
||||||
|
height: auto !important;
|
||||||
|
aspect-ratio: 4 / 3;
|
||||||
|
margin: 10px 0 14px !important;
|
||||||
|
overflow: hidden !important;
|
||||||
|
border: 1px solid var(--ui-border);
|
||||||
|
border-radius: 12px !important;
|
||||||
|
background: var(--ui-surface-soft);
|
||||||
|
}
|
||||||
|
|
||||||
|
.item-card .image-container .item-image,
|
||||||
|
.item-card .image-container .video-container {
|
||||||
|
width: 100% !important;
|
||||||
|
height: 100% !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
.item-card .image-container .item-image {
|
||||||
|
object-fit: contain !important;
|
||||||
|
object-position: center;
|
||||||
|
background: var(--ui-surface-soft);
|
||||||
|
}
|
||||||
|
|
||||||
|
.item-card .image-container .item-image[data-index="0"] {
|
||||||
|
display: block !important;
|
||||||
|
position: relative !important;
|
||||||
|
opacity: 1 !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
.item-card .image-container .item-image:not([data-index="0"]) {
|
||||||
|
display: none !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
.item-card .image-container .video-container {
|
||||||
|
position: relative;
|
||||||
|
display: block !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
.form-row {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||||
|
gap: 16px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.form-actions {
|
||||||
|
flex-wrap: wrap;
|
||||||
|
gap: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.form-actions > * {
|
||||||
|
min-height: 44px;
|
||||||
|
}
|
||||||
|
|
||||||
|
#item-modal .modal-content {
|
||||||
|
width: min(92vw, 880px);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
</style>
|
</style>
|
||||||
<style>
|
<style>
|
||||||
.bookmark-btn { position:absolute; top:8px; right:8px; width:46px; height:46px; background:rgba(255,255,255,.92); border:2px solid #ffc107; border-radius:50%; font-size:1.65rem; line-height:1; display:flex; align-items:center; justify-content:center; cursor:pointer; color:#ffc107; box-shadow:0 2px 6px rgba(0,0,0,.18); transition:background .2s, transform .15s, color .2s; z-index:6; pointer-events:auto; }
|
.bookmark-btn { position:absolute; top:8px; right:8px; width:46px; height:46px; background:rgba(255,255,255,.92); border:2px solid #ffc107; border-radius:50%; font-size:1.65rem; line-height:1; display:flex; align-items:center; justify-content:center; cursor:pointer; color:#ffc107; box-shadow:0 2px 6px rgba(0,0,0,.18); transition:background .2s, transform .15s, color .2s; z-index:6; pointer-events:auto; }
|
||||||
@@ -2385,7 +2541,7 @@ document.addEventListener('DOMContentLoaded', ()=>{
|
|||||||
|
|
||||||
<div class="filter-group search-field">
|
<div class="filter-group search-field">
|
||||||
<div class="filter-header">
|
<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>
|
<button type="button" class="clear-filter" onclick="clearCodeSearch()">Clear</button>
|
||||||
</div>
|
</div>
|
||||||
<div class="search-container">
|
<div class="search-container">
|
||||||
@@ -2427,12 +2583,16 @@ document.addEventListener('DOMContentLoaded', ()=>{
|
|||||||
<span>Anzahl</span>
|
<span>Anzahl</span>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div id="items-container" class="items-container">
|
<div class="items-navigation">
|
||||||
<!-- Items will be dynamically loaded here -->
|
<div class="navigation-button-slot">
|
||||||
</div>
|
<button class="navigation-button prev-button" type="button" onclick="scrollPrev()" aria-label="Vorherige Elemente">❮</button>
|
||||||
<div class="navigation-buttons">
|
</div>
|
||||||
<button class="prev-button" onclick="scrollPrev()">❮</button>
|
<div id="items-container" class="items-container">
|
||||||
<button class="next-button" onclick="scrollNext()">❯</button>
|
<!-- 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">❯</button>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div id="item-modal" class="item-modal">
|
<div id="item-modal" class="item-modal">
|
||||||
@@ -3206,9 +3366,13 @@ document.addEventListener('DOMContentLoaded', ()=>{
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
function loadItems(offset = 0, append = false) {
|
function loadItems(offset = 0, append = false, searchTerm = '', searchScope = 'all') {
|
||||||
// Keep list payload lightweight; full details are fetched on-demand in openItemQuick.
|
// Keep list payload lightweight; full details are fetched on-demand in openItemQuick.
|
||||||
return fetch(`{{ url_for('get_items') }}?offset=${offset}&limit=${MAIN_ADMIN_ITEMS_PAGE_SIZE}&light_mode=true`)
|
const searchParams = searchTerm && searchScope === 'title_description'
|
||||||
|
? `&search=${encodeURIComponent(searchTerm)}&search_scope=${encodeURIComponent(searchScope)}`
|
||||||
|
: '';
|
||||||
|
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(response => response.json())
|
||||||
.then(data => {
|
.then(data => {
|
||||||
const itemsContainer = document.querySelector('#items-container');
|
const itemsContainer = document.querySelector('#items-container');
|
||||||
@@ -3227,8 +3391,7 @@ document.addEventListener('DOMContentLoaded', ()=>{
|
|||||||
if (!append && (!pageItems || pageItems.length === 0)) {
|
if (!append && (!pageItems || pageItems.length === 0)) {
|
||||||
itemsContainer.innerHTML = `
|
itemsContainer.innerHTML = `
|
||||||
<div class="no-items-message">
|
<div class="no-items-message">
|
||||||
<div>Keine Objekte gefunden</div>
|
<div>Kein Item gefunden</div>
|
||||||
<a class="empty-state-cta" href="{{ url_for('upload_admin') }}">Erstellen sie hier ihr erstes Item</a>
|
|
||||||
</div>
|
</div>
|
||||||
`;
|
`;
|
||||||
if (itemsIndicator) {
|
if (itemsIndicator) {
|
||||||
@@ -3241,7 +3404,7 @@ document.addEventListener('DOMContentLoaded', ()=>{
|
|||||||
}
|
}
|
||||||
pageItems.sort((a, b) => {
|
pageItems.sort((a, b) => {
|
||||||
const nameA = a.Name ? a.Name.toLowerCase() : '';
|
const nameA = a.Name ? a.Name.toLowerCase() : '';
|
||||||
const nameB = a.Name ? a.Name.toLowerCase() : '';
|
const nameB = b.Name ? b.Name.toLowerCase() : '';
|
||||||
return nameA.localeCompare(nameB);
|
return nameA.localeCompare(nameB);
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -3285,6 +3448,7 @@ document.addEventListener('DOMContentLoaded', ()=>{
|
|||||||
card.dataset.code = (item.Code_4 !== undefined && item.Code_4 !== null) ?
|
card.dataset.code = (item.Code_4 !== undefined && item.Code_4 !== null) ?
|
||||||
String(item.Code_4).trim() : '';
|
String(item.Code_4).trim() : '';
|
||||||
card.dataset.groupCodes = JSON.stringify(Array.isArray(item.GroupedAllCodes) ? item.GroupedAllCodes : []);
|
card.dataset.groupCodes = JSON.stringify(Array.isArray(item.GroupedAllCodes) ? item.GroupedAllCodes : []);
|
||||||
|
card.dataset.groupedUnits = JSON.stringify(Array.isArray(item.GroupedUnitStates) ? item.GroupedUnitStates : []);
|
||||||
|
|
||||||
// Add filter values to their respective sets
|
// Add filter values to their respective sets
|
||||||
filter1Array.forEach(value => {
|
filter1Array.forEach(value => {
|
||||||
@@ -3415,7 +3579,7 @@ document.addEventListener('DOMContentLoaded', ()=>{
|
|||||||
</div>
|
</div>
|
||||||
{% if current_permissions.actions.get('can_borrow', False) %}
|
{% if current_permissions.actions.get('can_borrow', False) %}
|
||||||
${isAvailableForBorrow && !item.BlockedNow ?
|
${isAvailableForBorrow && !item.BlockedNow ?
|
||||||
`<form method="POST" action="{{ url_for('ausleihen', id='') }}${item._id}">
|
`<form method="POST" action="{{ url_for('ausleihen', id='') }}${item._id}" data-grouped-borrow-form>
|
||||||
${isGroupedItem ? `
|
${isGroupedItem ? `
|
||||||
<div class="grouped-borrow-controls" style="display:flex; gap:8px; flex-wrap:wrap; margin-bottom:8px; align-items:center;">
|
<div class="grouped-borrow-controls" style="display:flex; gap:8px; flex-wrap:wrap; margin-bottom:8px; align-items:center;">
|
||||||
<label style="font-size:0.85rem; margin:0;">Anzahl:</label>
|
<label style="font-size:0.85rem; margin:0;">Anzahl:</label>
|
||||||
@@ -3445,6 +3609,7 @@ document.addEventListener('DOMContentLoaded', ()=>{
|
|||||||
:
|
:
|
||||||
`<button class="ausleihen disabled-button" disabled>${item.BlockedNow ? 'Reserviert' : 'Ausgeliehen'}</button>`
|
`<button class="ausleihen disabled-button" disabled>${item.BlockedNow ? 'Reserviert' : 'Ausgeliehen'}</button>`
|
||||||
}
|
}
|
||||||
|
${isGroupedItem ? '<div class="grouped-searched-action" data-grouped-searched-action style="display:none;"></div>' : ''}
|
||||||
{% endif %}
|
{% endif %}
|
||||||
{% if current_permissions.actions.get('can_delete', False) %}
|
{% if current_permissions.actions.get('can_delete', False) %}
|
||||||
<form method="POST" action="{{ url_for('delete_item', id='') }}${item._id}" style="display:inline;" onsubmit="return confirm('Sind Sie sicher, dass Sie dieses Objekt löschen möchten?')">
|
<form method="POST" action="{{ url_for('delete_item', id='') }}${item._id}" style="display:inline;" onsubmit="return confirm('Sind Sie sicher, dass Sie dieses Objekt löschen möchten?')">
|
||||||
@@ -3679,13 +3844,66 @@ document.addEventListener('DOMContentLoaded', ()=>{
|
|||||||
card.classList.remove('highlight-item', 'code-match', 'exact-code-match');
|
card.classList.remove('highlight-item', 'code-match', 'exact-code-match');
|
||||||
});
|
});
|
||||||
|
|
||||||
applyFilters(true);
|
if (codeSearchTerm) {
|
||||||
|
loadItems(0, false, codeSearchTerm, 'all');
|
||||||
|
} else {
|
||||||
|
loadItems();
|
||||||
|
}
|
||||||
|
|
||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
searchInput.classList.remove('searching');
|
searchInput.classList.remove('searching');
|
||||||
}, 500);
|
}, 500);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function syncSearchedGroupedAction(card, searchTerm, exactCodeMatch) {
|
||||||
|
const searchedAction = card.querySelector('[data-grouped-searched-action]');
|
||||||
|
if (!searchedAction) return;
|
||||||
|
|
||||||
|
const borrowForm = card.querySelector('[data-grouped-borrow-form]');
|
||||||
|
searchedAction.style.display = 'none';
|
||||||
|
searchedAction.innerHTML = '';
|
||||||
|
|
||||||
|
if (!exactCodeMatch || !searchTerm) {
|
||||||
|
if (borrowForm) borrowForm.style.display = '';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
let groupedUnits = [];
|
||||||
|
try {
|
||||||
|
groupedUnits = JSON.parse(card.dataset.groupedUnits || '[]');
|
||||||
|
} catch {
|
||||||
|
groupedUnits = [];
|
||||||
|
}
|
||||||
|
|
||||||
|
const matchedUnit = groupedUnits.find(unit =>
|
||||||
|
String(unit.code || '').trim().toLowerCase() === searchTerm
|
||||||
|
);
|
||||||
|
if (!matchedUnit) return;
|
||||||
|
|
||||||
|
if (matchedUnit.available) {
|
||||||
|
if (borrowForm) borrowForm.style.display = '';
|
||||||
|
const specificSelect = borrowForm?.querySelector('[name="specific_item_id"]');
|
||||||
|
if (specificSelect) {
|
||||||
|
specificSelect.value = matchedUnit.id;
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (borrowForm) borrowForm.style.display = 'none';
|
||||||
|
searchedAction.style.display = 'block';
|
||||||
|
if (matchedUnit.borrowed_by_current_user) {
|
||||||
|
searchedAction.innerHTML = `
|
||||||
|
<form method="POST" action="/zurueckgeben/${encodeURIComponent(matchedUnit.id)}">
|
||||||
|
<button class="ausleihen" type="submit">Zurückgeben (${escapeHtml(matchedUnit.code || 'Code')})</button>
|
||||||
|
</form>`;
|
||||||
|
} else {
|
||||||
|
searchedAction.innerHTML = `
|
||||||
|
<button class="ausleihen disabled-button" type="button" disabled>
|
||||||
|
${escapeHtml(matchedUnit.code || 'Code')} ausgeliehen
|
||||||
|
</button>`;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
function applyFilters(isDirectSearch = false) {
|
function applyFilters(isDirectSearch = false) {
|
||||||
const itemsContainer = document.querySelector('#items-container');
|
const itemsContainer = document.querySelector('#items-container');
|
||||||
const items = itemsContainer.querySelectorAll('.item-card');
|
const items = itemsContainer.querySelectorAll('.item-card');
|
||||||
@@ -3732,6 +3950,7 @@ document.addEventListener('DOMContentLoaded', ()=>{
|
|||||||
if (passesAllFilters && matchesCodeSearch && matchesDesc && (!favoritesOnly || isFavoriteCard)) {
|
if (passesAllFilters && matchesCodeSearch && matchesDesc && (!favoritesOnly || isFavoriteCard)) {
|
||||||
item.style.display = 'block';
|
item.style.display = 'block';
|
||||||
visibleCount++;
|
visibleCount++;
|
||||||
|
syncSearchedGroupedAction(item, searchTerm, exactCodeMatch);
|
||||||
|
|
||||||
if (exactCodeMatch) {
|
if (exactCodeMatch) {
|
||||||
item.classList.add('highlight-item', 'exact-code-match');
|
item.classList.add('highlight-item', 'exact-code-match');
|
||||||
@@ -3756,6 +3975,7 @@ document.addEventListener('DOMContentLoaded', ()=>{
|
|||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
item.style.display = 'none';
|
item.style.display = 'none';
|
||||||
|
syncSearchedGroupedAction(item, '', false);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -3830,7 +4050,7 @@ document.addEventListener('DOMContentLoaded', ()=>{
|
|||||||
card.classList.remove('highlight-item', 'code-match', 'exact-code-match');
|
card.classList.remove('highlight-item', 'code-match', 'exact-code-match');
|
||||||
});
|
});
|
||||||
|
|
||||||
applyFilters();
|
loadItems();
|
||||||
}
|
}
|
||||||
|
|
||||||
// Description search using backend substring match
|
// Description search using backend substring match
|
||||||
@@ -3839,21 +4059,12 @@ document.addEventListener('DOMContentLoaded', ()=>{
|
|||||||
const term = (input?.value || '').trim();
|
const term = (input?.value || '').trim();
|
||||||
if (!term){
|
if (!term){
|
||||||
descSearchIds = null;
|
descSearchIds = null;
|
||||||
applyFilters(true);
|
loadItems(0, false, codeSearchTerm, 'all');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
input?.classList.add('searching');
|
input?.classList.add('searching');
|
||||||
fetch(`/search_word/${encodeURIComponent(term)}`)
|
descSearchIds = null;
|
||||||
.then(r=>r.json())
|
loadItems(0, false, term, 'title_description')
|
||||||
.then(data=>{
|
|
||||||
if (data && data.success && Array.isArray(data.response)){
|
|
||||||
descSearchIds = new Set(data.response.map(String));
|
|
||||||
} else {
|
|
||||||
descSearchIds = new Set();
|
|
||||||
}
|
|
||||||
applyFilters(true);
|
|
||||||
})
|
|
||||||
.catch(()=>{ descSearchIds = new Set(); applyFilters(true); })
|
|
||||||
.finally(()=>{ setTimeout(()=> input?.classList.remove('searching'), 300); });
|
.finally(()=>{ setTimeout(()=> input?.classList.remove('searching'), 300); });
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -3861,7 +4072,7 @@ document.addEventListener('DOMContentLoaded', ()=>{
|
|||||||
const input = document.getElementById('desc-search');
|
const input = document.getElementById('desc-search');
|
||||||
if (input) input.value = '';
|
if (input) input.value = '';
|
||||||
descSearchIds = null;
|
descSearchIds = null;
|
||||||
applyFilters();
|
loadItems(0, false, codeSearchTerm, 'all');
|
||||||
}
|
}
|
||||||
|
|
||||||
// Open item modal with fresh details from backend.
|
// Open item modal with fresh details from backend.
|
||||||
|
|||||||
@@ -21,9 +21,8 @@
|
|||||||
<div class="card shadow-sm border-0 h-100 rounded-3">
|
<div class="card shadow-sm border-0 h-100 rounded-3">
|
||||||
<div class="card-header bg-white border-bottom py-3 d-flex justify-content-between align-items-center">
|
<div class="card-header bg-white border-bottom py-3 d-flex justify-content-between align-items-center">
|
||||||
<h2 class="card-title h5 mb-0 fw-semibold text-primary">
|
<h2 class="card-title h5 mb-0 fw-semibold text-primary">
|
||||||
<i class="bi bi-funnel me-2"></i>{{ filter_names.get('1', 'Jahrgangsstufe') }}
|
<i class="bi bi-funnel me-2"></i>{{ filter_names.get('2', 'Jahrgangsstufe') }}
|
||||||
</h2>
|
</h2>
|
||||||
<span class="badge bg-primary-subtle text-primary rounded-pill">Filter 1</span>
|
|
||||||
</div>
|
</div>
|
||||||
<div class="card-body p-4">
|
<div class="card-body p-4">
|
||||||
<form method="POST" action="{{ url_for('add_filter_value', filter_num=1) }}" class="mb-4">
|
<form method="POST" action="{{ url_for('add_filter_value', filter_num=1) }}" class="mb-4">
|
||||||
@@ -87,9 +86,8 @@
|
|||||||
<div class="card shadow-sm border-0 h-100 rounded-3">
|
<div class="card shadow-sm border-0 h-100 rounded-3">
|
||||||
<div class="card-header bg-white border-bottom py-3 d-flex justify-content-between align-items-center">
|
<div class="card-header bg-white border-bottom py-3 d-flex justify-content-between align-items-center">
|
||||||
<h2 class="card-title h5 mb-0 fw-semibold text-primary">
|
<h2 class="card-title h5 mb-0 fw-semibold text-primary">
|
||||||
<i class="bi bi-funnel me-2"></i>{{ filter_names.get('2', 'Fachgebiet') }}
|
<i class="bi bi-funnel me-2"></i>{{ filter_names.get('1', 'Fachgebiet') }}
|
||||||
</h2>
|
</h2>
|
||||||
<span class="badge bg-primary-subtle text-primary rounded-pill">Filter 2</span>
|
|
||||||
</div>
|
</div>
|
||||||
<div class="card-body p-4">
|
<div class="card-body p-4">
|
||||||
<form method="POST" action="{{ url_for('add_filter_value', filter_num=2) }}" class="mb-4">
|
<form method="POST" action="{{ url_for('add_filter_value', filter_num=2) }}" class="mb-4">
|
||||||
|
|||||||
@@ -142,6 +142,9 @@
|
|||||||
{% if item.ActiveAppointment %}
|
{% if item.ActiveAppointment %}
|
||||||
<span class="appointment-status status-active">Aktiv</span>
|
<span class="appointment-status status-active">Aktiv</span>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
|
{% if item.ReturnPending %}
|
||||||
|
<span class="return-due-badge">RÜCKGABE ERFORDERLICH</span>
|
||||||
|
{% endif %}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="item-details">
|
<div class="item-details">
|
||||||
@@ -202,7 +205,9 @@
|
|||||||
<div class="action-buttons-container">
|
<div class="action-buttons-container">
|
||||||
<form method="POST" action="{{ url_for('zurueckgeben', id=item._id) }}">
|
<form method="POST" action="{{ url_for('zurueckgeben', id=item._id) }}">
|
||||||
<input type="hidden" name="source_page" value="my_borrowed_items">
|
<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>
|
||||||
<form method="POST" action="{{ url_for('cancel_ausleihung_route', id=item.AppointmentData.id) }}" onsubmit="return confirm('Möchten Sie diese aktive Ausleihung wirklich stornieren?');">
|
<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>
|
<button class="cancel-button" type="submit">Stornieren</button>
|
||||||
@@ -497,6 +502,30 @@ document.addEventListener('DOMContentLoaded', function() {
|
|||||||
.return-button:hover {
|
.return-button:hover {
|
||||||
background-color: #0069d9;
|
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 {
|
.return-count-group {
|
||||||
display: flex;
|
display: flex;
|
||||||
|
|||||||
Reference in new issue
Block a user