Compare commits

..
78 Commits
Author SHA1 Message Date
Aiirondev_dev b3e79a65c1 Umgesetzt:
Ausleihungen verwenden jetzt user_id statt Benutzername als Funktionsargument.
Das Feld User speichert nun die Benutzer-ID statt des Benutzernamens.
Login speichert zusätzlich session['user_id'].
Normale Ausleihen, Schülerausweis-Ausleihen und Reservierungen verwenden die Benutzer-ID.
Berechtigungsprüfungen für eigene Ausleihen/Buchungen vergleichen IDs.
Kalenderbuchungen erkennen den aktuellen Benutzer jetzt ebenfalls über die ID.
update_ausleihung() und get_ausleihung_by_user() wurden angepasst.
2026-10-15 20:58:40 +02:00
Aiirondev_dev b33b4eadc6 Implemented an iPad-focused responsive styling improvement.
Changes made
Added a dedicated iPad breakpoint for 768–1180px widths.
Improved inventory card layout:
Two-column card grid on iPads.
Cleaner spacing and card sizing.
Image previews now preserve aspect ratio with object-fit: contain.
Added consistent image backgrounds and rounded borders.
Fixed first-image visibility inside video/image containers.
Improved forms:
Two-column form layout on iPad.
Larger 44px touch-friendly controls.
Better spacing for filter groups and search fields.
Improved tables:
Rounded scroll container.
Better horizontal touch scrolling.
Preserved safe-area and touch interaction behavior.
2026-10-15 20:52:14 +02:00
Aiirondev_dev 07a1cdb063 changes to the filter preset 2026-10-07 16:30:13 +02:00
Aiirondev_dev 2942bcc380 Der Jinja-Fehler in base.html ist behoben. 2026-10-07 16:12:31 +02:00
Aiirondev_dev 349337e75f changes to dont reflekt the testing database name 2026-10-07 16:03:32 +02:00
Aiirondev_dev 9bdd8261fe changes to dont include the testing information 2026-10-07 16:02:39 +02:00
Aiirondev_dev 04c8505531 Die Suche wurde angepasst:Titel und Beschreibung werden jetzt direkt gemeinsam durchsucht.
Teiltreffer funktionieren, z. B.:
Rechen findet Rechenschiffchen
ein Fragment aus der Beschreibung findet den Artikel ebenfalls
Groß-/Kleinschreibung spielt keine Rolle
Die zusätzliche lokale ID-Filterung wurde entfernt, da sie Treffer teilweise wieder ausgeblendet hat.
Die Suche verwendet nun die serverseitige MongoDB-Abfrage mit regulären Teiltreffern.
2026-10-07 15:55:07 +02:00
Aiirondev_dev c9edf4a4c8 Die Inventarsuche wurde korrigiert. 2026-10-07 15:45:47 +02:00
Aiirondev_dev 0e0a99569e Implementation of the right Code ussage 2026-10-02 15:13:46 +02:00
Aiirondev_dev 6e94ca20c4 changes to the Mahnungssystem level fix 2026-09-27 14:40:21 +02:00
Aiirondev_dev 72fdfb0898 changes to the style of the mahnungs zurücksetzungs Modal 2026-09-27 14:35:01 +02:00
Aiirondev_dev 9de09a2f41 custom Mahnungs reset implementation 2026-09-27 14:20:44 +02:00
Aiirondev_dev 3d5a81824f changes to the Student Card clearing 2026-09-25 22:02:26 +02:00
Aiirondev_dev b0344627a7 removal of unused Code 2026-09-25 17:01:56 +02:00
Aiirondev_dev 8d07577220 changes to the asv export 2026-09-24 22:21:55 +02:00
Aiirondev_dev f3c7b6cd55 implementation of password visibility changing fuinction for the own password change 2026-09-24 17:26:25 +02:00
Aiirondev_dev c2bfed710d changes to the upload function 2026-09-24 16:46:32 +02:00
Aiirondev_dev 5d90eab154 changes to the edeting filter displaying 2026-09-24 16:40:21 +02:00
Aiirondev_dev 1eadfff9e1 slight changes 2026-09-24 16:33:18 +02:00
Aiirondev_dev 18f096b3f2 changes to the filter change 2026-09-24 16:29:05 +02:00
Aiirondev_dev 4b895a52ab changes to the Liught / Darkmode Toggle to move it to the personal settings 2026-09-23 22:23:42 +02:00
Aiirondev_dev 3a504afe37 Test change for the Darkmode and light mode toggle 2026-09-23 22:13:28 +02:00
Aiirondev_dev fb2ba86140 changes to be implementet to fix the crutial mistake of the variable passing 2026-09-23 21:36:44 +02:00
Aiirondev_dev 72e8a8cf5d fix for the issue implementet 2026-09-23 21:35:34 +02:00
Aiirondev_dev a158d16f62 changes to the passed variables 2026-09-23 21:20:53 +02:00
Aiirondev_dev b8347b80f2 Tryd some changes to the generate_ausweis_id() 2026-09-23 21:17:54 +02:00
Aiirondev_dev 31356e7178 chgange of the Titel Medien / Ausleihe to Ausleihe / Rückgabe 2026-09-23 21:05:52 +02:00
Aiirondev_dev 0409813cbe changes to the style for the Manuell input fields for the Libnrary borrowings. 2026-09-23 17:11:08 +02:00
Aiirondev_dev 95e02b7a75 changes to descriptors 2026-09-23 16:53:59 +02:00
Aiirondev_dev 3b0d499958 changes to implement a filter option for the student cards 2026-09-23 16:25:30 +02:00
Aiirondev_dev a7494648d8 changes to implement an option to view the password beeing typed in 2026-09-23 16:11:12 +02:00
Aiirondev_dev 8d8609fd70 removal of the debug 2026-09-21 15:57:54 +02:00
Aiirondev_dev 18c831eb42 debugging for the next function 2026-09-21 15:39:55 +02:00
Aiirondev_dev 8895283904 debugging for the user generation from the csv import 2026-09-21 15:26:57 +02:00
Aiirondev_dev a357881a20 changes to the upload of users process. 2026-09-21 15:12:07 +02:00
Aiirondev_dev b151dae3a8 changes to the descriptor 2026-09-21 14:51:15 +02:00
Aiirondev_dev 6167bfca82 changes to the main page 2026-09-21 14:36:03 +02:00
Aiirondev_dev c44a481382 changes to the beschriftungs presets 2026-09-20 13:02:54 +02:00
Aiirondev_dev 904972af53 changes to the item filter describtor 2026-09-20 12:33:02 +02:00
Aiirondev_dev de4098ebb2 Changes to the Timing of the removal of the Small Confirm 2026-09-20 11:42:39 +02:00
Aiirondev_dev 53b33afa80 Merge remote-tracking branch 'refs/remotes/origin/main' 2026-09-20 11:34:00 +02:00
Aiirondev_dev 0e9c7c6eb2 changes to the Name importing 2026-09-20 11:33:22 +02:00
Aiirondev_dev f442648dc9 changes to the mobile design to make it better fr the mobile view 2026-09-18 22:01:22 +02:00
Aiirondev_dev d2e2339d21 removal of test emial sending service 2026-09-18 16:01:37 +02:00
Aiirondev_dev e42d82fb62 allow to oush to 1.0.0 2026-09-18 15:53:21 +02:00
Aiirondev_dev c5726756d0 implementation of needet clarification 2026-09-17 21:29:24 +02:00
Aiirondev_dev 7d0147061a changes to the Email processing 2026-09-17 21:04:03 +02:00
Aiirondev_dev 76efa85419 changes to the sending test_mail profile 2026-09-17 20:39:10 +02:00
Aiirondev_dev a4cf9626cd changes to the send testmail 2026-09-17 20:30:48 +02:00
Aiirondev_dev fa55717f7f changes to have the test email function 2026-09-17 20:22:30 +02:00
Aiirondev_dev 4943aff944 changes to the email processing 2026-09-17 20:13:26 +02:00
Aiirondev_dev ee1683abe1 fix of faulty spelling 2026-09-17 19:59:35 +02:00
Aiirondev_dev 320acb5256 changes to the email sending 2026-09-17 19:36:48 +02:00
Aiirondev_dev 7b2a6d7bc1 test mail sender 2026-09-17 19:28:24 +02:00
Aiirondev_dev 027cef257d changes to the client building for the email requests 2026-09-17 17:42:00 +02:00
Aiirondev_dev cbacda34ca temporary removal of the tutorial Page 2026-09-17 16:46:31 +02:00
Aiirondev_dev cbc805919a changes to the Email behaivior 2026-09-16 17:45:16 +02:00
Aiirondev 31e8b7ccb4 revert 92c86334e9
revert Refactor email configuration handling and improve logging for email delivery
2026-09-16 15:37:25 +00:00
Aiirondev 5d908b6142 revert 92c86334e9
revert Refactor email configuration handling and improve logging for email delivery
2026-09-16 15:37:12 +00:00
Aiirondev aa9eb4996a revert eba20b7e2e
revert Fixes for the Secret deployment
2026-09-16 15:36:35 +00:00
Aiirondev 43f963d0d3 revert 7ab2899e92
revert changes to the Secret changes
2026-09-16 15:36:10 +00:00
Aiirondev 6589b8d275 revert 8673c0f05c
revert secrets processibg chanbged
2026-09-16 15:35:55 +00:00
Aiirondev 612ce2e6e6 revert d49ec9fd34
revert changes to the env processing
2026-09-16 15:35:36 +00:00
Aiirondev 210483d250 revert 6b3c35f895
revert changes tp implement the env file
2026-09-16 15:35:21 +00:00
Aiirondev 943b48ce16 revert 1dbe5709f5
revert changes to some settings
2026-09-16 15:35:12 +00:00
Aiirondev 476dfee0ff revert d002c5f9da
revert changes
2026-09-16 15:35:04 +00:00
Aiirondev_dev d002c5f9da changes 2026-09-16 17:14:37 +02:00
Aiirondev_dev 1dbe5709f5 changes to some settings 2026-09-16 15:43:17 +02:00
Aiirondev_dev 6b3c35f895 changes tp implement the env file 2026-09-16 15:27:07 +02:00
Aiirondev_dev d49ec9fd34 changes to the env processing 2026-09-16 15:16:31 +02:00
Aiirondev_dev 8673c0f05c secrets processibg chanbged 2026-09-16 15:02:00 +02:00
Aiirondev_dev 7ab2899e92 changes to the Secret changes 2026-09-16 14:36:04 +02:00
Aiirondev_dev eba20b7e2e Fixes for the Secret deployment 2026-09-16 14:16:13 +02:00
Aiirondev_dev 92c86334e9 Refactor email configuration handling and improve logging for email delivery
Release Inventarsystem / release-docker (push) Successful in 2m25s
2026-09-15 22:48:26 +02:00
Aiirondev_dev 98b1e39abb Improve modal scrolling behavior and height constraints for better usability
Release Inventarsystem / release-docker (push) Successful in 2m27s
2026-09-15 21:45:34 +02:00
Aiirondev_dev e9aea7e039 implementation of the Email add on
Release Inventarsystem / release-docker (push) Successful in 2m24s
2026-09-15 20:53:18 +02:00
Aiirondev_dev 00d45a9d1b Enhance booking user decryption and improve item modal styling
Release Inventarsystem / release-docker (push) Successful in 2m25s
2026-09-15 20:39:06 +02:00
Aiirondev_dev 9ad81d9b6d some more improvements for the appointment borrowing function
Release Inventarsystem / release-docker (push) Successful in 2m30s
2026-09-15 20:20:52 +02:00
25 changed files with 1600 additions and 585 deletions

No files matched your search

+1 -4
View File
@@ -150,10 +150,7 @@ jobs:
LATEST_MAJOR="0" LATEST_MAJOR="0"
fi fi
if [ "${BUMP_TYPE:-}" != "major" ] && [ "$TAG_MAJOR" != "$LATEST_MAJOR" ]; then
echo "Error: major version must stay v$LATEST_MAJOR.x.x (got $TAG)"
exit 1
fi
if git rev-parse -q --verify "refs/tags/$TAG" >/dev/null; then if git rev-parse -q --verify "refs/tags/$TAG" >/dev/null; then
i=1 i=1
+339 -244
View File
@@ -48,7 +48,7 @@ import Web.modules.log.audit_log as al
import push_notifications as pn import push_notifications as pn
import Web.modules.inventarsystem.pdf_export as pdf_export import Web.modules.inventarsystem.pdf_export as pdf_export
import Web.modules.inventarsystem.excel_export as excel_export import Web.modules.inventarsystem.excel_export as excel_export
from Web.modules.emailservice.email import send from Web.modules.emailservice.email import send, send_pdf
import datetime import datetime
from apscheduler.schedulers.background import BackgroundScheduler from apscheduler.schedulers.background import BackgroundScheduler
from bson.objectid import ObjectId, InvalidId from bson.objectid import ObjectId, InvalidId
@@ -468,6 +468,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
@@ -1560,7 +1564,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}}
@@ -2224,8 +2228,8 @@ def _upload_student_cards_excel():
'ausweis_id': ['ausweis_id', 'ausweisid', 'ausweis-id', 'karte', 'kartennummer', 'card_id', 'id'], 'ausweis_id': ['ausweis_id', 'ausweisid', 'ausweis-id', 'karte', 'kartennummer', 'card_id', 'id'],
'ausweis_ident': ['lokales differenzierungsmerkmal', 'lokales_differenzierungsmerkmal', 'ausweis_ident', 'ausweis_ident': ['lokales differenzierungsmerkmal', 'lokales_differenzierungsmerkmal', 'ausweis_ident',
'differenzierungsmerkmal'], 'differenzierungsmerkmal'],
'first_name': ['vorname', 'first_name', 'firstname', 'rufname'], 'first_name': ['name', 'vorname', 'first_name', 'firstname', 'rufname'],
'last_name': ['nachname', 'last_name', 'lastname'], 'last_name': ['nachname', 'last_name', 'lastname', 'familienname'],
'class_name': ['klasse', 'class', 'class_name', 'jahrgang', 'jahrgangsstufe', 'stufe', 'gruppe', 'asv_klasse'], 'class_name': ['klasse', 'class', 'class_name', 'jahrgang', 'jahrgangsstufe', 'stufe', 'gruppe', 'asv_klasse'],
'notes': ['notizen', 'notes', 'bemerkungen', 'bemerkung', 'hinweis', 'hinweise'], 'notes': ['notizen', 'notes', 'bemerkungen', 'bemerkung', 'hinweis', 'hinweise'],
'default_borrow_days': ['standard_ausleihdauer', 'ausleihdauer', 'borrow_days', 'tage', 'leihtage', 'default_borrow_days': ['standard_ausleihdauer', 'ausleihdauer', 'borrow_days', 'tage', 'leihtage',
@@ -2301,7 +2305,12 @@ def _upload_student_cards_excel():
row_errors.append('Vorname und Nachname fehlen') row_errors.append('Vorname und Nachname fehlen')
if not ausweis_id and student_name: if not ausweis_id and student_name:
ausweis_id = generate_ausweis_id(existing_ids) ausweis_id = generate_ausweis_id()
if ausweis_id in existing_ids:
row_errors.append(f'Automatisch erzeugte Ausweis-ID {ausweis_id} existiert bereits')
else:
while ausweis_id in existing_ids:
ausweis_id = generate_ausweis_id()
validation_warnings.append((row_number, f'Ausweis-ID wurde automatisch erzeugt: {ausweis_id}')) validation_warnings.append((row_number, f'Ausweis-ID wurde automatisch erzeugt: {ausweis_id}'))
existing_ids.add(ausweis_id.upper()) existing_ids.add(ausweis_id.upper())
elif ausweis_id and not rollover_mode: elif ausweis_id and not rollover_mode:
@@ -3490,6 +3499,8 @@ def library_loans_admin():
damaged_items=damaged_items, damaged_items=damaged_items,
library_module_enabled=cfg.MODULES.is_enabled('library'), library_module_enabled=cfg.MODULES.is_enabled('library'),
student_cards_module_enabled=cfg.MODULES.is_enabled('student_cards'), student_cards_module_enabled=cfg.MODULES.is_enabled('student_cards'),
mail_module_enabled=cfg.MODULES.is_enabled('mail'),
email_service_enabled=cfg.MODULES.is_enabled('mail')
) )
except Exception as e: except Exception as e:
app.logger.error(f"Error loading library loans admin view: {e}") app.logger.error(f"Error loading library loans admin view: {e}")
@@ -3499,144 +3510,6 @@ def library_loans_admin():
if client: if client:
client.close() client.close()
def generate_test_ausleihen():
"""
Generiert Testdaten für die Überprüfung der Mahnungs- und Sperrlogik.
Erstellt Dummy-Schülerausweise, Bibliotheks-Items und Ausleihungen mit manipulierten Daten (DueDate).
"""
current_time = datetime.datetime.now(ZoneInfo("Europe/Berlin"))
try:
client = MongoClient(MONGODB_HOST, MONGODB_PORT)
db = client[MONGODB_DB]
ausleihungen = db['ausleihungen']
student_cards_col = db['student_cards']
items_col = db['items']
print("Generiere Testdaten für das Mahnungssystem...")
# 1. Test-Schülerausweise erstellen oder aktualisieren (upsert)
# Wir nutzen AusweisIds, die im System als Identifikation dienen
test_students = [
{
"AusweisId": "TEST-AUSWEIS-01",
"SchülerName": encrypt_text("Max Mustermann (Stufe 1 Test)"),
"Klasse": "9a",
"is_blocked": False
},
{
"AusweisId": "TEST-AUSWEIS-02",
"SchülerName": encrypt_text("Erika Musterfrau (Stufe 2 Test)"),
"Klasse": "10b",
"is_blocked": False
},
{
"AusweisId": "TEST-AUSWEIS-03",
"SchülerName": encrypt_text("Tom Frisch (Keine Mahnung Test)"),
"Klasse": "8c",
"is_blocked": False
}
]
for s in test_students:
student_cards_col.update_one(
{'AusweisId': s['AusweisId']},
{'$set': s},
upsert=True
)
# 2. Test-Items als Bibliotheksartikel erstellen (ItemType wird gesetzt, damit it.is_library_itemgreift)
# Passe LIBRARY_ITEM_TYPES an deine verwendeten Typen an (hier beispielhaft 'Buch' / 'Medien')
item_type = LIBRARY_ITEM_TYPES[0] if 'LIBRARY_ITEM_TYPES' in globals() and LIBRARY_ITEM_TYPES else 'Buch'
item1_res = items_col.insert_one({
"Name": "Biologie Buch (Test Stufe 1)",
"ItemType": item_type,
"Verfuegbar": False,
"Exemplare": 1,
"Code_4": "TR-9988"
})
item2_res = items_col.insert_one({
"Name": "iPad Pro (Test Stufe 2)",
"ItemType": item_type,
"Verfuegbar": False,
"Exemplare": 1,
"Code_4": "TR-9988"
})
item3_res = items_col.insert_one({
"Name": "Taschenrechner (Test Frisch)",
"ItemType": item_type,
"Verfuegbar": False,
"Exemplare": 1,
"Code_4": "TR-9988"
})
# 3. Test-Ausleihungen generieren
# Fall 1: 15 Tage drüber, Mahnstufe 0 -> Sollte Stufe 1 triggern (>= 14 Tage)
due_date_stufe1 = current_time - datetime.timedelta(days=15)
# Fall 2: 29 Tage drüber, Mahnstufe 1 -> Sollte Stufe 2 triggern & Ausweis sperren (>= 28 Tage)
due_date_stufe2 = current_time - datetime.timedelta(days=29)
# Fall 3: 5 Tage drüber, Mahnstufe 0 -> Sollte NICHTS tun (da < 14 Tage)
due_date_frisch = current_time - datetime.timedelta(days=5)
# Je nachdem, ob dein System die User-Felder in Ausleihungen verschlüsselt speichert:
# Hier wird encrypt_text verwendet, falls die Funktion im Scope liegt.
user_val_1 = encrypt_text("TEST-AUSWEIS-01")
user_val_2 = encrypt_text("TEST-AUSWEIS-02")
user_val_3 = encrypt_text("TEST-AUSWEIS-03")
test_ausleihungen = [
{
"User": user_val_1,
"Item": str(item1_res.inserted_id),
"Status": "active",
"DueDate": due_date_stufe1,
"Mahnstufe": 0,
"LastUpdated": current_time
},
{
"User": user_val_2,
"Item": str(item2_res.inserted_id),
"Status": "active",
"DueDate": due_date_stufe2,
"Mahnstufe": 1, # Hat bereits Stufe 1, wartet auf Eskalation zu Stufe 2
"LastUpdated": due_date_stufe2
},
{
"User": user_val_3,
"Item": str(item3_res.inserted_id),
"Status": "active",
"DueDate": due_date_frisch,
"Mahnstufe": 2,
"LastUpdated": current_time
}
]
# In die Datenbank einfügen
ausleihungen.insert_many(test_ausleihungen)
print("Erfolgreich! Folgende Testdaten wurden für das Mahnungssystem in die DB geschrieben:")
print(f"- Fall 1 (Mahnstufe 1 Trigger): Ausweis 'TEST-AUSWEIS-01', fällig war am {due_date_stufe1.strftime('%Y-%m-%d')} (15 Tage überfällig)")
print(f"- Fall 2 (Mahnstufe 2 & Sperre): Ausweis 'TEST-AUSWEIS-02', fällig war am {due_date_stufe2.strftime('%Y-%m-%d')} (29 Tage überfällig)")
print(f"- Fall 3 (Zu früh / Ignorieren): Ausweis 'TEST-AUSWEIS-03', fällig war am {due_date_frisch.strftime('%Y-%m-%d')} (5 Tage überfällig)")
except Exception as e:
print(f"Fehler beim Erstellen der Testdaten: {e}")
finally:
if client:
client.close()
@app.route('/test_mahnungen')
def test_mahnungen():
# Testdaten (Mock-Daten), um alle if/else Bedingungen im HTML zu testen
generate_test_ausleihen()
create_return_reminders()
return redirect(url_for('mahnungen_admin'))
@app.route('/mahnungen_admin') @app.route('/mahnungen_admin')
def mahnungen_admin(): def mahnungen_admin():
"""Admin-Übersicht für überfällige Bibliotheks-Ausleihen.""" """Admin-Übersicht für überfällige Bibliotheks-Ausleihen."""
@@ -3756,8 +3629,8 @@ def mahnungen_admin():
email_service_enabled=cfg.EMAIL_ENABLED email_service_enabled=cfg.EMAIL_ENABLED
) )
@app.route('/mahnungen_reset', methods=['POST']) @app.route('/mahnungen_reset/<int:days>', methods=['POST'])
def mahnungen_reset(): def mahnungen_reset(days):
"""Setzt die Mahnstufe einer Ausleihe zurück, verlängert die Frist und entsperrt den Schülerausweis.""" """Setzt die Mahnstufe einer Ausleihe zurück, verlängert die Frist und entsperrt den Schülerausweis."""
if 'username' not in session: if 'username' not in session:
return jsonify({'success': False, 'message': 'Nicht angemeldet.'}), 401 return jsonify({'success': False, 'message': 'Nicht angemeldet.'}), 401
@@ -3785,7 +3658,7 @@ def mahnungen_reset():
return jsonify({'success': False, 'message': 'Ausleihe nicht gefunden.'}), 404 return jsonify({'success': False, 'message': 'Ausleihe nicht gefunden.'}), 404
current_time = datetime.datetime.now(ZoneInfo("Europe/Berlin")) current_time = datetime.datetime.now(ZoneInfo("Europe/Berlin"))
new_due_date = current_time + datetime.timedelta(days=14) # Frist um 14 Tage verlängern new_due_date = current_time + datetime.timedelta(days=days) # Frist um die angegebene Anzahl an Tagen verlängern
# 2. Mahnstufe zurücksetzen und Frist verlängern # 2. Mahnstufe zurücksetzen und Frist verlängern
ausleihungen_col.update_one( ausleihungen_col.update_one(
@@ -3819,7 +3692,7 @@ def mahnungen_reset():
return jsonify({ return jsonify({
'success': True, 'success': True,
'message': 'Mahnstufe zurückgesetzt, Frist um 14 Tage verlängert und Ausweis entsperrt.' 'message': f'Mahnstufe zurückgesetzt, Frist um {days} Tage verlängert und Ausweis entsperrt.'
}) })
except Exception as e: except Exception as e:
@@ -4359,9 +4232,12 @@ def api_library_scan_action():
due_date = now + datetime.timedelta(days=borrow_duration_days) due_date = now + datetime.timedelta(days=borrow_duration_days)
it.update_item_status(item_id, False, borrower_name) it.update_item_status(item_id, False, borrower_name)
borrower_user = us.get_user_by_student_card(student_card_id)
if not borrower_user or not borrower_user.get('_id'):
return jsonify({'ok': False, 'message': 'Kein Benutzer für diesen Schülerausweis gefunden.'}), 404
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,
@@ -4848,7 +4724,8 @@ def student_cards_admin():
if ausweis_id: if ausweis_id:
existing = student_cards.find_one({'AusweisId': ausweis_id}) existing = student_cards.find_one({'AusweisId': ausweis_id})
else: else:
ausweis_id = generate_ausweis_id() generated_ausweis_id = generate_ausweis_id()
ausweis_id = generated_ausweis_id
existing = False existing = False
if not ausweis_ident: if not ausweis_ident:
ausweis_ident = ausweis_id ausweis_ident = ausweis_id
@@ -4888,11 +4765,12 @@ def student_cards_admin():
return render_template( return render_template(
'student_cards_admin.html', 'student_cards_admin.html',
student_cards=all_cards, # Hier all_cards übergeben student_cards=all_cards,
edit_mode=edit_mode, edit_mode=edit_mode,
form_data=form_data, form_data=form_data,
available_classes=available_classes, # Enthält nun die lesbaren Klassen available_classes=available_classes,
config=cfg.get_school_info() config=cfg.get_school_info(),
email_service_enabled=cfg.MODULES.is_enabled('mail')
) )
@@ -5353,7 +5231,7 @@ def student_card_class_barcode_download():
flash('Fehler beim PDF-Download', 'error') flash('Fehler beim PDF-Download', 'error')
return redirect(url_for('student_cards_admin')) return redirect(url_for('student_cards_admin'))
@app.route('/student_card_single_barcode_download/<card_id>', methods=['GET']) @app.route('/student_card_single_barcode_download/<card_id>', methods=['GET', 'POST'])
def student_card_single_barcode_download(card_id): def student_card_single_barcode_download(card_id):
""" """
Download PDF with single student card barcode. Download PDF with single student card barcode.
@@ -5533,11 +5411,34 @@ def student_card_single_barcode_download(card_id):
c.save() c.save()
pdf_buffer.seek(0) pdf_buffer.seek(0)
pdf_filename = f'ausweis_{card["AusweisId"]}.pdf'
if request.method == 'POST':
recipient_email = (request.form.get('recipient_email') or '').strip()
if not recipient_email:
flash('Bitte eine Empfänger-E-Mail-Adresse eingeben oder nur PDF auswählen.', 'error')
return redirect(url_for('student_cards_admin'))
if not cfg.MODULES.is_enabled('mail'):
flash('Das E-Mail-Add-on ist deaktiviert. Der Ausweis kann weiterhin als PDF heruntergeladen werden.', 'warning')
return redirect(url_for('student_cards_admin'))
sent = send_pdf(
recipient_email,
f'Bibliotheksausweis {card["AusweisId"]}',
f'Anbei erhalten Sie den Bibliotheksausweis für {card.get("SchülerName", "")} als PDF.',
'Bibliotheksverwaltung',
pdf_buffer.getvalue(),
pdf_filename,
)
flash(
'Bibliotheksausweis wurde per E-Mail versendet.' if sent else 'Bibliotheksausweis konnte nicht per E-Mail versendet werden.',
'success' if sent else 'error',
)
return redirect(url_for('student_cards_admin'))
return send_file( return send_file(
pdf_buffer, pdf_buffer,
mimetype='application/pdf', mimetype='application/pdf',
as_attachment=True, as_attachment=True,
download_name=f'ausweis_{card["AusweisId"]}.pdf' download_name=pdf_filename
) )
except Exception as e: except Exception as e:
app.logger.error(f"Error occurred while generating PDF for card {card['AusweisId']}: {e}") app.logger.error(f"Error occurred while generating PDF for card {card['AusweisId']}: {e}")
@@ -5573,6 +5474,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
@@ -5703,6 +5605,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()
@@ -5738,6 +5642,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 = {
@@ -5804,6 +5744,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
@@ -5812,6 +5753,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,
@@ -5839,13 +5781,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,
@@ -5858,6 +5813,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):
@@ -5918,6 +5874,8 @@ def get_bookings():
result = [] result = []
for booking in bookings: for booking in bookings:
raw_booking_user = booking.get('User') or ''
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
@@ -5960,10 +5918,10 @@ def get_bookings():
'end': end_dt.isoformat() if isinstance(end_dt, datetime.datetime) else str(end_dt), 'end': end_dt.isoformat() if isinstance(end_dt, datetime.datetime) else str(end_dt),
'status': status, 'status': status,
'itemId': item_id, 'itemId': item_id,
'userName': str(booking.get('User') or ''), 'userName': str(booking_user),
'notes': str(booking.get('Notes') or ''), 'notes': str(booking.get('Notes') or ''),
'period': period, 'period': period,
'isCurrentUser': str(booking.get('User') or '') == username, 'isCurrentUser': str(booking_user) == str(current_user_id),
'itemBorrower': item_borrower, 'itemBorrower': item_borrower,
}) })
@@ -6083,7 +6041,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 = []
@@ -7424,6 +7385,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'
@@ -7497,6 +7463,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))
@@ -7571,7 +7538,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,
@@ -7668,7 +7635,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,
@@ -7719,7 +7686,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,
@@ -7880,7 +7847,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)
@@ -7911,9 +7883,14 @@ def get_planned_bookings(item_id):
cursor = ausleihungen.find({'Item': item_id, 'Status': 'planned'}).sort('Start', 1) cursor = ausleihungen.find({'Item': item_id, 'Status': 'planned'}).sort('Start', 1)
bookings = [] bookings = []
for r in cursor: for r in cursor:
raw_user = r.get('User') or ''
try:
booking_user = decrypt_text(raw_user) if raw_user else ''
except Exception:
booking_user = str(raw_user)
bookings.append({ bookings.append({
'id': str(r.get('_id')), 'id': str(r.get('_id')),
'user': r.get('User', ''), 'user': booking_user,
'period': r.get('Period'), 'period': r.get('Period'),
'start': r.get('Start').isoformat() if r.get('Start') else None, 'start': r.get('Start').isoformat() if r.get('Start') else None,
'end': r.get('End').isoformat() if r.get('End') else None, 'end': r.get('End').isoformat() if r.get('End') else None,
@@ -7940,7 +7917,13 @@ def get_planned_bookings_public(item_id):
cursor = ausleihungen.find({'Item': item_id, 'Status': 'planned'}).sort('Start', 1) cursor = ausleihungen.find({'Item': item_id, 'Status': 'planned'}).sort('Start', 1)
bookings = [] bookings = []
for r in cursor: for r in cursor:
raw_user = r.get('User') or ''
try:
booking_user = decrypt_text(raw_user) if raw_user else ''
except Exception:
booking_user = str(raw_user)
bookings.append({ bookings.append({
'user': booking_user,
'period': r.get('Period'), 'period': r.get('Period'),
'start': r.get('Start').isoformat() if r.get('Start') else None, 'start': r.get('Start').isoformat() if r.get('Start') else None,
'end': r.get('End').isoformat() if r.get('End') else None 'end': r.get('End').isoformat() if r.get('End') else None
@@ -8058,18 +8041,20 @@ def plan_booking():
# Validate inputs # Validate inputs
if not all([item_id, start_date_str, period_start]): if not all([item_id, start_date_str, period_start]):
return {"success": False, "error": "Missing required fields"}, 400 return {"success": False, "error": "Missing required fields"}, 400
if booking_type not in {'single', 'range'}:
return {"success": False, "error": "Invalid booking type"}, 400
if not end_date_str: if not end_date_str:
end_date_str = start_date_str end_date_str = start_date_str
# Parse dates # Parse dates
try: try:
if start_date_str: if start_date_str:
start_date = datetime.datetime.fromisoformat(start_date_str) start_date = datetime.datetime.fromisoformat(start_date_str).replace(tzinfo=None)
else: else:
return {"success": False, "error": "Missing start date"}, 400 return {"success": False, "error": "Missing start date"}, 400
if end_date_str: if end_date_str:
end_date = datetime.datetime.fromisoformat(end_date_str) end_date = datetime.datetime.fromisoformat(end_date_str).replace(tzinfo=None)
else: else:
return {"success": False, "error": "Missing end date"}, 400 return {"success": False, "error": "Missing end date"}, 400
@@ -8091,16 +8076,23 @@ def plan_booking():
# Handle period range # Handle period range
periods = [] periods = []
if period_start: try:
period_start_num = int(period_start) period_start_num = int(period_start)
else: except (TypeError, ValueError):
period_start_num = 1 # Default if None return {"success": False, "error": "Invalid start period"}, 400
if not 1 <= period_start_num <= 10:
return {"success": False, "error": "Invalid start period"}, 400
# If period_end is provided, it's a range of periods # If period_end is provided, it's a range of periods
if period_end: if period_end:
period_end_num = int(period_end) try:
period_end_num = int(period_end)
except (TypeError, ValueError):
return {"success": False, "error": "Invalid end period"}, 400
# Validate period range # Validate period range
if not 1 <= period_end_num <= 10:
return {"success": False, "error": "Invalid end period"}, 400
if period_end_num < period_start_num: if period_end_num < period_start_num:
return {"success": False, "error": "End period cannot be before start period"}, 400 return {"success": False, "error": "End period cannot be before start period"}, 400
@@ -8110,51 +8102,50 @@ def plan_booking():
# Single period booking # Single period booking
periods = [period_start_num] periods = [period_start_num]
# For date range bookings, we'll process each date separately if end_date < start_date:
booking_ids = [] return {"success": False, "error": "End date cannot be before start date"}, 400
errors = [] if booking_type == 'single' and start_date.date() != end_date.date():
return {"success": False, "error": "Single bookings must use one date"}, 400
# If it's a range of days requested_slots = []
if booking_type == 'range' and start_date != end_date: current_date = start_date
current_date = start_date last_date = end_date if booking_type == 'range' else start_date
while current_date <= end_date: while current_date.date() <= last_date.date():
# For each day in the range for period in periods:
day_booking_ids, day_errors = process_day_bookings( period_times = get_period_times(current_date, period)
item_id, if not period_times:
current_date, return {"success": False, "error": f"Invalid period {period}"}, 400
periods, requested_slots.append((current_date.date(), period, period_times))
notes current_date += datetime.timedelta(days=1)
)
booking_ids.extend(day_booking_ids)
errors.extend(day_errors)
# Move to next day # Preflight the complete request so conflicts never create partial ranges.
current_date += datetime.timedelta(days=1) for index, (booking_date, period, period_times) in enumerate(requested_slots):
else: if au.check_booking_conflict(item_id, period_times['start'], period_times['end'], period):
# Single day with multiple periods
booking_ids, errors = process_day_bookings(
item_id,
start_date,
periods,
notes
)
# Return results
if errors:
if booking_ids:
# Some succeeded, some failed
return { return {
"success": True, "success": False,
"partial": True, "error": "Booking conflict",
"booking_ids": booking_ids, "conflicts": [{"date": booking_date.isoformat(), "period": period}],
"errors": errors }, 409
} for previous_date, previous_period, _ in requested_slots[:index]:
else: if previous_date == booking_date and previous_period == period:
# All failed return {"success": False, "error": "Duplicate booking period"}, 400
return {"success": False}, 500
else: booking_ids = []
# All succeeded try:
return {"success": True, "booking_ids": booking_ids} for _, period, period_times in requested_slots:
booking_id = au.add_planned_booking(
item_id, session.get('user_id') or str(us.get_user(session['username'])['_id']), period_times['start'],
period_times['end'], notes, period=period
)
if not booking_id:
raise RuntimeError(f"Failed to create booking for period {period}")
booking_ids.append(str(booking_id))
except Exception:
for booking_id in booking_ids:
au.cancel_ausleihung(booking_id)
raise
return {"success": True, "booking_ids": booking_ids}
except Exception as e: except Exception as e:
import traceback import traceback
@@ -8196,7 +8187,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,
@@ -8214,7 +8205,7 @@ def add_booking():
if 'username' not in session: if 'username' not in session:
return jsonify({'success': False, 'error': 'Not logged in'}) return jsonify({'success': False, 'error': 'Not logged in'})
item_id = html.escape(request.form.get('item_id')) item_id = html.escape((request.form.get('item_id') or '').strip())
# Check if item exists and is reservable # Check if item exists and is reservable
item = it.get_item(item_id) item = it.get_item(item_id)
@@ -8243,21 +8234,39 @@ def add_booking():
end_date_str, '%Y-%m-%d %H:%M:%S' end_date_str, '%Y-%m-%d %H:%M:%S'
).replace(tzinfo=ZoneInfo("Europe/Berlin")) ).replace(tzinfo=ZoneInfo("Europe/Berlin"))
else: else:
end_date = None return jsonify({'success': False, 'error': 'Missing end date'}), 400
if end_date <= start_date:
return jsonify({'success': False, 'error': 'End date must be after start date'}), 400
period_value = None
if period not in (None, ''):
try:
period_value = int(period)
except (TypeError, ValueError):
return jsonify({'success': False, 'error': 'Invalid period'}), 400
if not 1 <= period_value <= 10:
return jsonify({'success': False, 'error': 'Invalid period'}), 400
if au.check_booking_conflict(item_id, start_date, end_date, period_value):
return jsonify({'success': False, 'error': 'Booking conflict'}), 409
# 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,
period=period period=period_value
) )
if not booking_id:
return jsonify({'success': False, 'error': 'Failed to create booking'}), 500
return jsonify({'success': True, 'booking_id': str(booking_id)}) return jsonify({'success': True, 'booking_id': str(booking_id)})
except Exception as e: except Exception as e:
return jsonify({'success': False}) app.logger.error(f"Error creating booking: {e}")
return jsonify({'success': False, 'error': 'Invalid booking data'}), 400
@app.route('/cancel_booking/<id>', methods=['POST']) @app.route('/cancel_booking/<id>', methods=['POST'])
def cancel_booking(id): def cancel_booking(id):
@@ -8276,11 +8285,14 @@ 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
if booking.get('User') != session['username'] and not current_permissions['actions'].get('can_manage_users', False): current_user = us.get_user(session['username'])
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
result = au.cancel_booking(id) result = au.cancel_ausleihung(id)
if result: if result:
return {"success": True} return {"success": True}
@@ -8460,20 +8472,18 @@ def parse_csv_users(file_bytes):
return parsed_users return parsed_users
def generate_compliant_password(length=16): def generate_compliant_password(length=6):
lowers = string.ascii_lowercase lowers = string.ascii_lowercase
uppers = string.ascii_uppercase uppers = string.ascii_uppercase
digits = string.digits digits = string.digits
symbols = "!@#$%^&*()_+~|}{[]:;?><,.-="
# Ensure at least one character from each required category # Ensure at least one character from each required category
pwd = [ pwd = [
secrets.choice(lowers), secrets.choice(lowers),
secrets.choice(uppers), secrets.choice(uppers),
secrets.choice(digits), secrets.choice(digits)
secrets.choice(symbols)
] ]
all_chars = lowers + uppers + digits + symbols all_chars = lowers + uppers + digits
pwd += [secrets.choice(all_chars) for _ in range(length - 4)] pwd += [secrets.choice(all_chars) for _ in range(length - 4)]
# Shuffle so guaranteed types aren't always at the start # Shuffle so guaranteed types aren't always at the start
@@ -8597,19 +8607,31 @@ def register_csv():
# Benutzernamen & Passwort generieren # Benutzernamen & Passwort generieren
username = us.build_unique_username_from_name(name, last_name) username = us.build_unique_username_from_name(name, last_name)
password = generate_compliant_password(16) password = generate_compliant_password(6)
# In DB speichern password = us.check_password_strength(password) and password or generate_compliant_password(6)
success = us.add_user(
username=username, action_permissions = None
password=password, page_permissions = None
name=name,
last_name=last_name, try:
is_student=False, us.add_user(
student_card_id=None, username,
max_borrow_days=None, password,
permission_preset=permission_preset, name,
) last_name,
is_student=False,
student_card_id=None,
max_borrow_days=None,
permission_preset=permission_preset,
action_permissions=action_permissions,
page_permissions=page_permissions,
)
success = True
except Exception as e:
app.logger.error(f"Fehler beim Erstellen des Benutzers {username}: {e}")
success = False
continue
if success: if success:
created_users.append({ created_users.append({
@@ -8916,7 +8938,8 @@ def admin_borrowings():
entries=entries, entries=entries,
library_module_enabled=cfg.MODULES.is_enabled('library'), library_module_enabled=cfg.MODULES.is_enabled('library'),
student_cards_module_enabled=cfg.MODULES.is_enabled('student_cards'), student_cards_module_enabled=cfg.MODULES.is_enabled('student_cards'),
mail_module_enabled=cfg.MODULES.is_enabled('mail') mail_module_enabled=cfg.MODULES.is_enabled('mail'),
email_service_enabled=cfg.MODULES.is_enabled('mail')
) )
"""-----------------------------------------------------------Audit Routes-------------------------------------------------------""" """-----------------------------------------------------------Audit Routes-------------------------------------------------------"""
@@ -9008,7 +9031,7 @@ def admin_audit_dashboard():
if client: if client:
client.close() client.close()
@app.route('/admin/audit/export/pdf/official', methods=['GET']) @app.route('/admin/audit/export/pdf/official', methods=['GET', 'POST'])
def admin_audit_export_pdf_official(): def admin_audit_export_pdf_official():
"""Export audit report as professional PDF (Official Report - full DIN 5008 compliant).""" """Export audit report as professional PDF (Official Report - full DIN 5008 compliant)."""
if 'username' not in session: if 'username' not in session:
@@ -9076,6 +9099,29 @@ def admin_audit_export_pdf_official():
school_info=school_info school_info=school_info
) )
if request.method == 'POST':
recipient_email = (request.form.get('recipient_email') or '').strip()
if not recipient_email:
flash('Bitte eine Empfänger-E-Mail-Adresse eingeben oder nur PDF auswählen.', 'error')
return redirect(url_for('admin_audit_dashboard'))
if not cfg.MODULES.is_enabled('mail'):
flash('Das E-Mail-Add-on ist deaktiviert. Der Auditbericht kann weiterhin als PDF heruntergeladen werden.', 'warning')
return redirect(url_for('admin_audit_dashboard'))
filename = f'audit-official-report-{datetime.datetime.now(ZoneInfo("Europe/Berlin")).strftime("%Y%m%d-%H%M%S")}.pdf'
sent = send_pdf(
recipient_email,
'Amtlicher Auditbericht',
'Anbei erhalten Sie den aktuellen amtlichen Auditbericht des Inventarsystems als PDF.',
'Inventarsystem',
pdf_content,
filename,
)
flash(
'Auditbericht wurde per E-Mail versendet.' if sent else 'Auditbericht konnte nicht per E-Mail versendet werden.',
'success' if sent else 'error',
)
return redirect(url_for('admin_audit_dashboard'))
response = make_response(pdf_content) response = make_response(pdf_content)
response.headers['Content-Type'] = 'application/pdf' response.headers['Content-Type'] = 'application/pdf'
response.headers['Content-Disposition'] = f'attachment; filename=audit-official-report-{datetime.datetime.utcnow().strftime("%Y%m%d-%H%M%S")}.pdf' response.headers['Content-Disposition'] = f'attachment; filename=audit-official-report-{datetime.datetime.utcnow().strftime("%Y%m%d-%H%M%S")}.pdf'
@@ -9449,11 +9495,33 @@ def admin_create_invoice(borrow_id):
) )
pdf_buffer = pdf_export._build_invoice_pdf(invoice_data) pdf_buffer = pdf_export._build_invoice_pdf(invoice_data)
pdf_filename = f'rechnung_{invoice_number}.pdf'
if request.form.get('delivery') == 'email':
recipient_email = (request.form.get('recipient_email') or '').strip()
if not recipient_email:
flash('Bitte eine Empfänger-E-Mail-Adresse eingeben oder nur PDF auswählen.', 'error')
return redirect(url_for('admin_borrowings'))
if not cfg.MODULES.is_enabled('mail'):
flash('Das E-Mail-Add-on ist deaktiviert. Die PDF-Rechnung kann weiterhin heruntergeladen werden.', 'warning')
return redirect(url_for('admin_borrowings'))
sent = send_pdf(
recipient_email,
f'Rechnung {invoice_number} - {item_name}',
f'Anbei erhalten Sie die Rechnung {invoice_number} zum Element {item_name}.',
'Bibliotheksverwaltung',
pdf_buffer.getvalue(),
pdf_filename,
)
flash(
'PDF-Rechnung wurde per E-Mail versendet.' if sent else 'PDF-Rechnung konnte nicht per E-Mail versendet werden.',
'success' if sent else 'error',
)
return redirect(url_for('admin_borrowings'))
return send_file( return send_file(
pdf_buffer, pdf_buffer,
mimetype='application/pdf', mimetype='application/pdf',
as_attachment=True, as_attachment=True,
download_name=f'rechnung_{invoice_number}.pdf' download_name=pdf_filename
) )
except Exception as e: except Exception as e:
app.logger.error(f"Error creating damage invoice for borrow {borrow_id}: {e}") app.logger.error(f"Error creating damage invoice for borrow {borrow_id}: {e}")
@@ -10264,7 +10332,7 @@ def admin_reset_user_password():
# Reset the password # Reset the password
try: try:
us.update_password(username, new_password) us.update_password(username, new_password)
flash(f'Passwort für {encrypt_text(username)} wurde erfolgreich zurückgesetzt auf: {new_password}', 'success') flash(f'Passwort für {username} wurde erfolgreich zurückgesetzt auf: {new_password}', 'success')
except Exception as e: except Exception as e:
app.logger.error(f'Error resetting password for {encrypt_text(username)}: {e}') app.logger.error(f'Error resetting password for {encrypt_text(username)}: {e}')
flash('Fehler beim Zurücksetzen des Passworts', 'error') flash('Fehler beim Zurücksetzen des Passworts', 'error')
@@ -10782,7 +10850,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:
@@ -12150,7 +12220,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,
@@ -12284,7 +12354,11 @@ def cancel_ausleihung_route(id):
# Log ausleihung details for debugging # Log ausleihung details for debugging
ausleihung_status = ausleihung.get('Status', 'unknown') ausleihung_status = ausleihung.get('Status', 'unknown')
ausleihung_user = ausleihung.get('User', 'unknown') raw_ausleihung_user = ausleihung.get('User', '')
try:
ausleihung_user = decrypt_text(raw_ausleihung_user) if raw_ausleihung_user else ''
except Exception:
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}")
current_permissions = us.get_effective_permissions(session['username']) current_permissions = us.get_effective_permissions(session['username'])
@@ -13639,3 +13713,24 @@ def upload_csv_batch():
"images_deduplicated": dedup_count, "images_deduplicated": dedup_count,
"images_failed": error_count "images_failed": error_count
}), 200 }), 200
@app.route('/get/asv_export', methods=['GET'])
def get_asv_export():
if 'username' not in session:
flash('Bitte melden Sie sich an.', 'error')
return redirect(url_for('login'))
return send_from_directory(app.static_folder, 'img/asv_export_invario_2026.exfj')
"""
@app.route('/test_email')
def test_email():
#Test endpoint to send a sample email.
#This is for development purposes only.
try:
send(email="maximiliangruendinger@gmail.com", subject="Test Email from Inventarsystem", note="This is a test email sent from the Inventarsystem application.", sender="Inventarsystem")
return "Test email sent successfully."
except Exception as e:
return f"Failed to send test email: {str(e)}", 500
"""
+18 -11
View File
@@ -185,13 +185,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 +209,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 +256,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:
@@ -353,7 +352,7 @@ def cancel_ausleihung(id):
# Mark the booking as cancelled # Mark the booking as cancelled
result = ausleihungen.update_one( result = ausleihungen.update_one(
{'_id': ObjectId(id)}, {'_id': ObjectId(id), 'Status': {'$in': ['planned', 'active']}},
{'$set': { {'$set': {
'Status': 'cancelled', 'Status': 'cancelled',
'LastUpdated': datetime.datetime.now(ZoneInfo("Europe/Berlin")) 'LastUpdated': datetime.datetime.now(ZoneInfo("Europe/Berlin"))
@@ -367,6 +366,16 @@ def cancel_ausleihung(id):
return False return False
def get_booking(id):
"""Compatibility wrapper for the booking route."""
return get_ausleihung(id)
def cancel_booking(id):
"""Compatibility wrapper for the booking route."""
return cancel_ausleihung(id)
def remove_ausleihung(id): def remove_ausleihung(id):
""" """
Markiert einen Ausleihungsdatensatz als gelöscht (Soft-Delete). Markiert einen Ausleihungsdatensatz als gelöscht (Soft-Delete).
@@ -546,9 +555,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:
@@ -854,8 +861,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):
+2 -3
View File
@@ -431,15 +431,14 @@ def check_password_strength(password):
if password is None: if password is None:
return False return False
if len(password) < 12: if len(password) < 5:
return False return False
has_lower = any(char.islower() for char in password) has_lower = any(char.islower() for char in password)
has_upper = any(char.isupper() for char in password) has_upper = any(char.isupper() for char in password)
has_digit = any(char.isdigit() for char in password) has_digit = any(char.isdigit() for char in password)
has_symbol = any(not char.isalnum() for char in password)
if not (has_lower and has_upper and has_digit and has_symbol): if not (has_lower and has_upper and has_digit):
return False return False
return True return True
+43 -23
View File
@@ -1,5 +1,6 @@
from email.mime.multipart import MIMEMultipart from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
import smtplib import smtplib
import time import time
@@ -8,27 +9,34 @@ import Web.modules.database.settings as cfg
def _build_smtp_client(): def _build_smtp_client():
smtp = smtplib.SMTP( smtp = smtplib.SMTP(
cfg.EMAIL_SMTP_HOST, "mail.invario-software.de",
cfg.EMAIL_SMTP_PORT, 587,
timeout=cfg.EMAIL_TIMEOUT_SECONDS, timeout=10,
) )
smtp.ehlo() smtp.ehlo()
if cfg.EMAIL_USE_TLS: if True:
smtp.starttls() smtp.starttls()
smtp.ehlo() smtp.ehlo()
if cfg.EMAIL_USERNAME: smtp.login("no-reply@invario-software.de", "eSpage,65,{")
smtp.login("no-reply@invario-software.de", "#,EATwIn,68" or "")
return smtp return smtp
def send(email: list | str, subject: str, note: str, sender: str) -> bool:
"""Sends the email with the link to the Clients.""" def _normalize_recipients(email: list | str) -> list[str]:
if isinstance(email, str):
email = email.replace(';', ',').split(',')
return [str(recipient).strip() for recipient in (email or []) if str(recipient).strip()]
def _send_message(email: list | str, subject: str, note: str, sender: str, attachment=None) -> bool:
"""Send a plain/HTML message, optionally with one PDF attachment."""
if not cfg.MODULES.is_enabled("mail"): if not cfg.MODULES.is_enabled("mail"):
print("Debug: Module not enabled") print("Debug: Module not enabled")
return False return False
if isinstance(email, str): recipients = _normalize_recipients(email)
email = [email] if not recipients:
return False
body_message = note body_message = note
@@ -63,25 +71,27 @@ def send(email: list | str, subject: str, note: str, sender: str) -> bool:
try: try:
smtp = _build_smtp_client() smtp = _build_smtp_client()
for i, recipient in enumerate(email): for i, recipient in enumerate(recipients):
start_time = time.time() start_time = time.time()
msg = MIMEMultipart("alternative") msg = MIMEMultipart("mixed" if attachment else "alternative")
msg["Subject"] = str(subject) msg["Subject"] = str(subject)
msg["From"] = f"{sender} <no-reply@invario-software.de>" from_address = "no-reply@invario-software.de"
msg["From"] = f"{sender} <{from_address}>"
msg["To"] = str(recipient) msg["To"] = str(recipient)
msg.attach(MIMEText(text_content, "plain")) body = MIMEMultipart("alternative") if attachment else msg
msg.attach(MIMEText(html_content, "html")) body.attach(MIMEText(text_content, "plain"))
body.attach(MIMEText(html_content, "html"))
#smtp.sendmail( if attachment:
# from_addr=cfg.EMAIL_USERNAME, msg.attach(body)
# to_addrs=[recipient], attachment_payload, filename = attachment
# msg=msg.as_string() pdf_part = MIMEApplication(attachment_payload, _subtype="pdf")
#) pdf_part.add_header("Content-Disposition", "attachment", filename=filename)
msg.attach(pdf_part)
smtp.sendmail( smtp.sendmail(
from_addr="no-reply@invario-software.de", from_addr=from_address,
to_addrs=[recipient], to_addrs=[recipient],
msg=msg.as_string() msg=msg.as_string()
) )
@@ -89,7 +99,7 @@ def send(email: list | str, subject: str, note: str, sender: str) -> bool:
elapsed_time = time.time() - start_time elapsed_time = time.time() - start_time
sleep_time = interval - elapsed_time sleep_time = interval - elapsed_time
if sleep_time > 0 and i < len(email) - 1: if sleep_time > 0 and i < len(recipients) - 1:
time.sleep(sleep_time) time.sleep(sleep_time)
return True return True
@@ -102,3 +112,13 @@ def send(email: list | str, subject: str, note: str, sender: str) -> bool:
smtp.quit() smtp.quit()
except Exception: except Exception:
pass pass
def send(email: list | str, subject: str, note: str, sender: str) -> bool:
"""Send an HTML/plain email without an attachment."""
return _send_message(email, subject, note, sender)
def send_pdf(email: list | str, subject: str, note: str, sender: str, pdf_bytes: bytes, filename: str) -> bool:
"""Send an email with a PDF attachment."""
return _send_message(email, subject, note, sender, attachment=(pdf_bytes, filename))
+28 -3
View File
@@ -3,6 +3,7 @@ import Web.modules.terminplaner.backend_server as appointment_service
import Web.modules.database.settings as cfg import Web.modules.database.settings as cfg
import Web.modules.database.termine as termin import Web.modules.database.termine as termin
import Web.modules.database.user as us import Web.modules.database.user as us
from Web.modules.emailservice.email import send, send_pdf
from Web.modules.terminplaner.backend_server import _resolve_public_base_url from Web.modules.terminplaner.backend_server import _resolve_public_base_url
import csv import csv
import io import io
@@ -409,7 +410,7 @@ def client_slot_calendar_export(appointment_id):
return response return response
@appoint_bp.route('/export_pdf_brief/<plan_id>', methods=['GET']) @appoint_bp.route('/export_pdf_brief/<plan_id>', methods=['GET', 'POST'])
def export_pdf_brief(plan_id): def export_pdf_brief(plan_id):
# 1. Daten holen (Hier als Beispiel, passe dies auf deine Datenbank an) # 1. Daten holen (Hier als Beispiel, passe dies auf deine Datenbank an)
# terminplan = Terminplan.query.get(plan_id) # terminplan = Terminplan.query.get(plan_id)
@@ -532,12 +533,35 @@ def export_pdf_brief(plan_id):
# Buffer auf Anfang zurücksetzen # Buffer auf Anfang zurücksetzen
pdf_buffer.seek(0) pdf_buffer.seek(0)
pdf_filename = f"Einladung_{plan_daten['titel'].replace(' ', '_')}.pdf"
if request.method == 'POST':
recipient_email = (request.form.get('recipient_email') or '').strip()
if not recipient_email:
flash('Bitte eine Empfänger-E-Mail-Adresse eingeben oder nur PDF auswählen.', 'error')
return redirect(url_for('terminplaner.main', tenant=tenant_id or None))
if not cfg.MODULES.is_enabled('mail'):
flash('Das E-Mail-Add-on ist deaktiviert. Der Einladungsbrief kann weiterhin als PDF heruntergeladen werden.', 'warning')
return redirect(url_for('terminplaner.main', tenant=tenant_id or None))
sent = send_pdf(
recipient_email,
f'Einladung zur Terminbuchung: {plan_daten["titel"]}',
f'Anbei erhalten Sie den Einladungsbrief für {plan_daten["titel"]} als PDF.',
'Terminplanungssystem',
pdf_buffer.getvalue(),
pdf_filename,
)
flash(
'Einladungsbrief wurde per E-Mail versendet.' if sent else 'Einladungsbrief konnte nicht per E-Mail versendet werden.',
'success' if sent else 'error',
)
return redirect(url_for('terminplaner.main', tenant=tenant_id or None))
# An Nutzer ausliefern # An Nutzer ausliefern
return send_file( return send_file(
pdf_buffer, pdf_buffer,
mimetype='application/pdf', mimetype='application/pdf',
as_attachment=True, as_attachment=True,
download_name=f"Einladung_{plan_daten['titel'].replace(' ', '_')}.pdf" download_name=pdf_filename
) )
@appoint_bp.route('/') @appoint_bp.route('/')
@@ -557,5 +581,6 @@ def main():
current_user=current_user, current_user=current_user,
upcoming_events=upcoming_events, upcoming_events=upcoming_events,
tenant_id=tenant_id, tenant_id=tenant_id,
appointment_module_enabled=cfg.MODULES.is_enabled('terminplan') appointment_module_enabled=cfg.MODULES.is_enabled('terminplan'),
mail_service_enabled=cfg.MODULES.is_enabled('mail')
) )
+4
View File
@@ -227,6 +227,10 @@ def send_push_notification(username, title, body, icon=None, url='/', reference=
sent_count = 0 sent_count = 0
for subscription in subscriptions: for subscription in subscriptions:
from Web.modules.emailservice.email import send, send_pdf
if cfg.MODULES.is_enabled('mail'):
#implement the sending
pass
success = _send_to_subscription( success = _send_to_subscription(
subscription, subscription,
title, title,
+36
View File
@@ -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 */
/* ========================================================= */ /* ========================================================= */
Binary file not shown.
+7 -1
View File
@@ -110,10 +110,16 @@
<div class="audit-panel" style="padding:14px; border:1px solid #e2e8f0; border-radius:10px; background: var(--ui-surface);"> <div class="audit-panel" style="padding:14px; border:1px solid #e2e8f0; border-radius:10px; background: var(--ui-surface);">
<h4 style="margin:0 0 10px 0; color:#1a1a1a;">📄 PDF-Export (DIN 5008 konform)</h4> <h4 style="margin:0 0 10px 0; color:#1a1a1a;">📄 PDF-Export (DIN 5008 konform)</h4>
<p style="margin:0 0 10px 0; font-size:0.9rem; color:#666;">Professionelle Berichte für Schulträger und Behörden</p> <p style="margin:0 0 10px 0; font-size:0.9rem; color:#666;">Professionelle Berichte für Schulträger und Behörden</p>
<div style="display:flex; gap:8px; flex-wrap:wrap;"> <div style="display:flex; gap:8px; flex-wrap:wrap; align-items:end;">
<a class="btn btn-primary" href="{{ url_for('admin_audit_export_pdf_official') }}" style="flex:1; text-align:center;"> <a class="btn btn-primary" href="{{ url_for('admin_audit_export_pdf_official') }}" style="flex:1; text-align:center;">
📋 Amtlicher Bericht (DIN 5008) 📋 Amtlicher Bericht (DIN 5008)
</a> </a>
{% if mail_module_enabled %}
<form method="post" action="{{ url_for('admin_audit_export_pdf_official') }}" style="display:flex; gap:8px; flex:2; flex-wrap:wrap;">
<input type="email" name="recipient_email" required placeholder="Empfänger-E-Mail" aria-label="Empfänger-E-Mail für den Auditbericht" style="flex:1; min-width:220px; padding:8px; border:1px solid #cbd5e1; border-radius:6px;">
<button class="btn btn-outline-primary" type="submit">PDF per E-Mail senden</button>
</form>
{% endif %}
</div> </div>
</div> </div>
+11 -1
View File
@@ -195,6 +195,13 @@
<textarea id="damage-reason" name="damage_reason" rows="5" required style="width:100%; padding:10px; border:1px solid #ddd; border-radius:6px; resize:vertical;" placeholder="Beschreiben Sie kurz den Schaden oder die Zerstörung."></textarea> <textarea id="damage-reason" name="damage_reason" rows="5" required style="width:100%; padding:10px; border:1px solid #ddd; border-radius:6px; resize:vertical;" placeholder="Beschreiben Sie kurz den Schaden oder die Zerstörung."></textarea>
</div> </div>
{% if email_service_enabled %}
<div style="margin-bottom:16px;">
<label for="invoice-recipient-email" style="display:block; font-weight:700; margin-bottom:6px;">Empfänger-E-Mail für den PDF-Versand</label>
<input id="invoice-recipient-email" name="recipient_email" type="email" style="width:100%; padding:10px; border:1px solid #ddd; border-radius:6px;" placeholder="name@beispiel.de">
</div>
{% endif %}
<div style="display:flex; flex-wrap:wrap; gap:16px; align-items:center; margin-bottom:18px;"> <div style="display:flex; flex-wrap:wrap; gap:16px; align-items:center; margin-bottom:18px;">
<label style="display:flex; align-items:center; gap:8px;"> <label style="display:flex; align-items:center; gap:8px;">
<input type="checkbox" name="mark_destroyed" checked> <input type="checkbox" name="mark_destroyed" checked>
@@ -208,7 +215,10 @@
<div style="display:flex; justify-content:flex-end; gap:10px;"> <div style="display:flex; justify-content:flex-end; gap:10px;">
<button type="button" class="btn btn-secondary" onclick="closeInvoiceModal()">Abbrechen</button> <button type="button" class="btn btn-secondary" onclick="closeInvoiceModal()">Abbrechen</button>
<button type="submit" class="btn btn-danger">PDF-Rechnung erstellen</button> <button type="submit" class="btn btn-outline-danger" name="delivery" value="pdf">Nur PDF herunterladen</button>
{% if email_service_enabled %}
<button type="submit" class="btn btn-danger" name="delivery" value="email">PDF per E-Mail senden</button>
{% endif %}
</div> </div>
</form> </form>
</div> </div>
+2 -2
View File
@@ -78,11 +78,11 @@
<div class="form-row"> <div class="form-row">
<div class="form-group"> <div class="form-group">
<label for="filter_name_1">Name Filter 1</label> <label for="filter_name_1">Name Filter 1</label>
<input type="text" id="filter_name_1" name="filter_name_1" value="{{ filter_names.get('1', 'Klassenstufe') }}" placeholder="z. B. Klassenstufe"> <input type="text" id="filter_name_1" name="filter_name_1" value="{{ filter_names.get('1', 'Fachgebiet') }}" placeholder="z. B. Fachgebiet">
</div> </div>
<div class="form-group"> <div class="form-group">
<label for="filter_name_2">Name Filter 2</label> <label for="filter_name_2">Name Filter 2</label>
<input type="text" id="filter_name_2" name="filter_name_2" value="{{ filter_names.get('2', 'Fach') }}" placeholder="z. B. Fach"> <input type="text" id="filter_name_2" name="filter_name_2" value="{{ filter_names.get('2', 'Klassenstufe') }}" placeholder="z. B. Klassenstufe">
</div> </div>
<div class="form-group"> <div class="form-group">
<label for="filter_name_3">Name Filter 3</label> <label for="filter_name_3">Name Filter 3</label>
+64 -58
View File
@@ -1135,12 +1135,7 @@
<a class="nav-link quick-link-pill {% if current_path == url_for('terminplaner.configure') %}nav-active{% endif %}" href="{{ url_for('terminplaner.configure') }}" data-tutorial-tip="Neuen Terminplan erstellen und an Ihr Team versenden.">Neue Planung</a> <a class="nav-link quick-link-pill {% if current_path == url_for('terminplaner.configure') %}nav-active{% endif %}" href="{{ url_for('terminplaner.configure') }}" data-tutorial-tip="Neuen Terminplan erstellen und an Ihr Team versenden.">Neue Planung</a>
</li> </li>
{% endif %} {% endif %}
<li class="nav-item" data-nav-fixed="true">
<button type="button" class="btn btn-link nav-link px-3" data-theme-toggle aria-label="Dark Mode umschalten" aria-pressed="false" title="Theme umschalten">
<span class="theme-icon-light" style="display: none;">☀️</span>
<span class="theme-icon-dark" style="display: none;">🌙</span>
</button>
</li>
<li class="nav-item dropdown ms-lg-auto"> <li class="nav-item dropdown ms-lg-auto">
<a class="nav-link dropdown-toggle" href="#" id="termMoreDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false" title="Weitere Optionen">Mehr Optionen</a> <a class="nav-link dropdown-toggle" href="#" id="termMoreDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false" title="Weitere Optionen">Mehr Optionen</a>
<ul class="dropdown-menu dropdown-menu-end" aria-labelledby="termMoreDropdown"> <ul class="dropdown-menu dropdown-menu-end" aria-labelledby="termMoreDropdown">
@@ -1199,6 +1194,13 @@
<li><hr class="dropdown-divider"></li> <li><hr class="dropdown-divider"></li>
<li><a class="dropdown-item" href="{{ url_for('change_password') }}">Passwort ändern</a></li> <li><a class="dropdown-item" href="{{ url_for('change_password') }}">Passwort ändern</a></li>
<li><hr class="dropdown-divider"></li> <li><hr class="dropdown-divider"></li>
<li class="dropdown-item" data-nav-fixed="true">
<button type="button" class="btn btn-link nav-link px-3" data-theme-toggle aria-label="Dark Mode umschalten" aria-pressed="false" title="Theme umschalten">
<span class="theme-icon-light" style="display: none;">☀️</span>
<span class="theme-icon-dark" style="display: none;">🌙</span>
</button>
</li>
<li><hr class="dropdown-divider"></li>
<li><a class="dropdown-item" href="{{ url_for('logout') }}">Logout</a></li> <li><a class="dropdown-item" href="{{ url_for('logout') }}">Logout</a></li>
</ul> </ul>
</div> </div>
@@ -1228,12 +1230,6 @@
</li> </li>
{% endif %} {% endif %}
{% endif %} {% endif %}
<li class="nav-item" data-nav-fixed="true">
<button type="button" class="btn btn-link nav-link px-3" data-theme-toggle aria-label="Dark Mode umschalten" aria-pressed="false" title="Theme umschalten">
<span class="theme-icon-light" style="display: none;">☀️</span>
<span class="theme-icon-dark" style="display: none;">🌙</span>
</button>
</li>
<li class="nav-item dropdown ms-lg-auto"> <li class="nav-item dropdown ms-lg-auto">
<a class="nav-link dropdown-toggle" href="#" id="invMoreDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false" title="Weitere Optionen"> <a class="nav-link dropdown-toggle" href="#" id="invMoreDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false" title="Weitere Optionen">
@@ -1305,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">
@@ -1321,6 +1315,13 @@
<li><hr class="dropdown-divider"></li> <li><hr class="dropdown-divider"></li>
<li><a class="dropdown-item" href="{{ url_for('change_password') }}">Passwort ändern</a></li> <li><a class="dropdown-item" href="{{ url_for('change_password') }}">Passwort ändern</a></li>
<li><hr class="dropdown-divider"></li> <li><hr class="dropdown-divider"></li>
<li class="dropdown-item" data-nav-fixed="true">
<button type="button" class="btn btn-link nav-link px-3" data-theme-toggle aria-label="Dark Mode umschalten" aria-pressed="false" title="Theme umschalten">
<span class="theme-icon-light" style="display: none;">☀️</span>
<span class="theme-icon-dark" style="display: none;">🌙</span>
</button>
</li>
<li><hr class="dropdown-divider"></li>
<li><a class="dropdown-item" href="{{ url_for('logout') }}">Logout</a></li> <li><a class="dropdown-item" href="{{ url_for('logout') }}">Logout</a></li>
</ul> </ul>
</div> </div>
@@ -1329,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">
@@ -1342,27 +1342,23 @@
<ul class="navbar-nav me-auto mb-2 mb-lg-0" id="libraryNavList"> <ul class="navbar-nav me-auto mb-2 mb-lg-0" id="libraryNavList">
{% if current_permissions.pages.get('library_view', False) %} {% if current_permissions.pages.get('library_view', False) %}
<li class="nav-item" data-nav-fixed="true"> <li class="nav-item" data-nav-fixed="true">
<a class="nav-link {% if current_path == url_for('library_view') %}nav-active{% endif %}" href="{{ url_for('library_view') }}" data-tutorial-tip="Die Bibliothek zeigt Ihnen alle Medien und verfügbaren Bücher.">Medien/Ausleihe</a> <a class="nav-link {% if current_path == url_for('library_view') %}nav-active{% endif %}" href="{{ url_for('library_view') }}" data-tutorial-tip="Die Bibliothek zeigt Ihnen alle Medien und verfügbaren Bücher.">Ausleihe/Rückgabe</a>
</li> </li>
{% endif %} {% endif %}
{% if 'username' in session %} {% if 'username' in session %}
<!--
{% if current_permissions.pages.get('tutorial_page', False) %} {% if current_permissions.pages.get('tutorial_page', False) %}
<li class="nav-item"> <li class="nav-item">
<a class="nav-link quick-link-pill {% if current_path == url_for('tutorial_page') %}nav-active{% endif %}" href="{{ url_for('tutorial_page') }}" data-tutorial-tip="Nutzen Sie das Tutorial, um die Bibliotheksfunktionen kennenzulernen.">Tutorial</a> <a class="nav-link quick-link-pill {% if current_path == url_for('tutorial_page') %}nav-active{% endif %}" href="{{ url_for('tutorial_page') }}" data-tutorial-tip="Nutzen Sie das Tutorial, um die Bibliotheksfunktionen kennenzulernen.">Tutorial</a>
</li> </li>
{% endif %} {% endif %}
-->
{% endif %} {% endif %}
{% if 'username' in session and current_permissions.actions.get('can_insert', False) and current_permissions.pages.get('library_admin', False) %} {% if 'username' in session and current_permissions.actions.get('can_insert', False) and current_permissions.pages.get('library_admin', False) %}
<li class="nav-item"> <li class="nav-item">
<a class="nav-link nav-priority-link {% if current_path == url_for('library_admin') %}nav-active{% endif %}" href="{{ url_for('library_admin') }}" data-tutorial-tip="Neue Bibliotheksmedien können hier aufgenommen werden.">📖 Hochladen</a> <a class="nav-link nav-priority-link {% if current_path == url_for('library_admin') %}nav-active{% endif %}" href="{{ url_for('library_admin') }}" data-tutorial-tip="Neue Bibliotheksmedien können hier aufgenommen werden.">📖 Hochladen</a>
</li> </li>
{% endif %} {% endif %}
<li class="nav-item" data-nav-fixed="true">
<button type="button" class="btn btn-link nav-link px-3" data-theme-toggle aria-label="Dark Mode umschalten" aria-pressed="false" title="Theme umschalten">
<span class="theme-icon-light" style="display: none;">☀️</span>
<span class="theme-icon-dark" style="display: none;">🌙</span>
</button>
</li>
<li class="nav-item dropdown ms-lg-auto"> <li class="nav-item dropdown ms-lg-auto">
<a class="nav-link dropdown-toggle" href="#" id="libMoreDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false" title="Weitere Optionen"> <a class="nav-link dropdown-toggle" href="#" id="libMoreDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false" title="Weitere Optionen">
@@ -1429,6 +1425,13 @@
<li><hr class="dropdown-divider"></li> <li><hr class="dropdown-divider"></li>
<li><a class="dropdown-item" href="{{ url_for('change_password') }}">Passwort ändern</a></li> <li><a class="dropdown-item" href="{{ url_for('change_password') }}">Passwort ändern</a></li>
<li><hr class="dropdown-divider"></li> <li><hr class="dropdown-divider"></li>
<li class="dropdown-item" data-nav-fixed="true">
<button type="button" class="btn btn-link nav-link px-3" data-theme-toggle aria-label="Dark Mode umschalten" aria-pressed="false" title="Theme umschalten">
<span class="theme-icon-light" style="display: none;">☀️</span>
<span class="theme-icon-dark" style="display: none;">🌙</span>
</button>
</li>
<li><hr class="dropdown-divider"></li>
<li><a class="dropdown-item" href="{{ url_for('logout') }}">Logout</a></li> <li><a class="dropdown-item" href="{{ url_for('logout') }}">Logout</a></li>
</ul> </ul>
</div> </div>
@@ -1630,6 +1633,8 @@
</div> </div>
</div> </div>
<!--
<div id="onboarding-overlay" role="dialog" aria-modal="true" aria-label="Tutorial Vorschlag"> <div id="onboarding-overlay" role="dialog" aria-modal="true" aria-label="Tutorial Vorschlag">
<div id="onboarding-modal"> <div id="onboarding-modal">
<h3>Wollen Sie eine Vorstellung des Produkts?</h3> <h3>Wollen Sie eine Vorstellung des Produkts?</h3>
@@ -1643,6 +1648,7 @@
</div> </div>
</div> </div>
</div> </div>
-->
<div id="notification-toast" class="notification-toast" role="status" aria-live="polite"> <div id="notification-toast" class="notification-toast" role="status" aria-live="polite">
<strong id="notification-toast-title">Neue Benachrichtigung</strong> <strong id="notification-toast-title">Neue Benachrichtigung</strong>
@@ -1662,7 +1668,7 @@
<option value="Benachrichtigungen"></option> <option value="Benachrichtigungen"></option>
{% endif %} {% endif %}
{% if current_permissions.pages.get('tutorial_page', False) %} {% if current_permissions.pages.get('tutorial_page', False) %}
<option value="Tutorial"></option> <!--<option value="Tutorial"></option>-->
{% endif %} {% endif %}
{% endif %} {% endif %}
@@ -1765,10 +1771,10 @@
}); });
const username = {{ (session['username'] if 'username' in session else '')|tojson }}; const username = {{ (session['username'] if 'username' in session else '')|tojson }};
const isTutorialPage = window.location.pathname === {{ url_for('tutorial_page')|tojson }}; //const isTutorialPage = window.location.pathname === {{ url_for('tutorial_page')|tojson }};
const isLoginPage = window.location.pathname === {{ url_for('login')|tojson }}; const isLoginPage = window.location.pathname === {{ url_for('login')|tojson }};
const notificationsPagePath = {{ url_for('notifications_view')|tojson }}; const notificationsPagePath = {{ url_for('notifications_view')|tojson }};
const onboardingKey = username ? ('inventarsystem_tutorial_prompt_v1_' + username) : null; //const onboardingKey = username ? ('inventarsystem_tutorial_prompt_v1_' + username) : null;
const onboardingOverlay = document.getElementById('onboarding-overlay'); const onboardingOverlay = document.getElementById('onboarding-overlay');
const notificationButtons = Array.from(document.querySelectorAll('[data-notification-button="true"]')); const notificationButtons = Array.from(document.querySelectorAll('[data-notification-button="true"]'));
const notificationToast = document.getElementById('notification-toast'); const notificationToast = document.getElementById('notification-toast');
@@ -1789,9 +1795,9 @@
{% if current_permissions.pages.get('notifications_view', False) %} {% if current_permissions.pages.get('notifications_view', False) %}
{ label: 'Benachrichtigungen', keywords: ['benachrichtigungen', 'nachrichten', 'notifications'], url: {{ url_for('notifications_view')|tojson }} }, { label: 'Benachrichtigungen', keywords: ['benachrichtigungen', 'nachrichten', 'notifications'], url: {{ url_for('notifications_view')|tojson }} },
{% endif %} {% endif %}
{% if current_permissions.pages.get('tutorial_page', False) %} //{% if current_permissions.pages.get('tutorial_page', False) %}
{ label: 'Tutorial', keywords: ['tutorial', 'hilfe', 'anleitung'], url: {{ url_for('tutorial_page')|tojson }} }, //{ label: 'Tutorial', keywords: ['tutorial', 'hilfe', 'anleitung'], url: {{ url_for('tutorial_page')|tojson }} },
{% endif %} //{% endif %}
{% endif %} {% endif %}
{ label: 'Impressum', keywords: ['impressum'], url: {{ url_for('impressum')|tojson }} }, { label: 'Impressum', keywords: ['impressum'], url: {{ url_for('impressum')|tojson }} },
@@ -2042,11 +2048,11 @@
window.setInterval(pollNotificationStatus, 30000); window.setInterval(pollNotificationStatus, 30000);
} }
function showOnboarding(){ //function showOnboarding(){
if (onboardingOverlay) { // if (onboardingOverlay) {
onboardingOverlay.style.display = 'flex'; // onboardingOverlay.style.display = 'flex';
} // }
} //}
function hideOnboarding(){ function hideOnboarding(){
if (onboardingOverlay) { if (onboardingOverlay) {
@@ -2054,19 +2060,19 @@
} }
} }
if (onboardingKey && !isTutorialPage && !isLoginPage) { //if (onboardingKey && !isTutorialPage && !isLoginPage) {
const decision = localStorage.getItem(onboardingKey); // const decision = localStorage.getItem(onboardingKey);
if (!decision || decision === 'later') { // if (!decision || decision === 'later') {
showOnboarding(); // showOnboarding();
} // }
} //}
document.getElementById('onboarding-start')?.addEventListener('click', function(){ //document.getElementById('onboarding-start')?.addEventListener('click', function(){
if (onboardingKey) { // if (onboardingKey) {
localStorage.setItem(onboardingKey, 'started'); // localStorage.setItem(onboardingKey, 'started');
} // }
window.location.href = {{ url_for('tutorial_page')|tojson }}; // window.location.href = {{ url_for('tutorial_page')|tojson }};
}); //});
document.getElementById('onboarding-later')?.addEventListener('click', function(){ document.getElementById('onboarding-later')?.addEventListener('click', function(){
if (onboardingKey) { if (onboardingKey) {
@@ -2399,21 +2405,21 @@
<script> <script>
(function () { (function () {
const username = {{ (session['username'] if 'username' in session else '')|tojson }}; const username = {{ (session['username'] if 'username' in session else '')|tojson }};
const tooltipModeKey = username ? ('inventarsystem_tutorial_tooltips_enabled_' + username) : 'inventarsystem_tutorial_tooltips_enabled'; //const tooltipModeKey = username ? ('inventarsystem_tutorial_tooltips_enabled_' + username) : 'inventarsystem_tutorial_tooltips_enabled';
const enabled = localStorage.getItem(tooltipModeKey) === '1'; const enabled = localStorage.getItem(tooltipModeKey) === '1';
function applyTooltipMode(active) { //function applyTooltipMode(active) {
document.body.classList.toggle('tutorial-tooltips-active', active); // document.body.classList.toggle('tutorial-tooltips-active', active);
let indicator = document.getElementById('tutorialTooltipIndicator'); // let indicator = document.getElementById('tutorialTooltipIndicator');
if (!indicator) { // if (!indicator) {
indicator = document.createElement('div'); // indicator = document.createElement('div');
indicator.id = 'tutorialTooltipIndicator'; // indicator.id = 'tutorialTooltipIndicator';
indicator.className = 'tutorial-tooltip-indicator'; // indicator.className = 'tutorial-tooltip-indicator';
indicator.textContent = 'Tutorial-Modus aktiv: Tooltips sind eingeschaltet'; // indicator.textContent = 'Tutorial-Modus aktiv: Tooltips sind eingeschaltet';
document.body.appendChild(indicator); // document.body.appendChild(indicator);
} // }
indicator.style.display = active ? 'inline-flex' : 'none'; // indicator.style.display = active ? 'inline-flex' : 'none';
} //}
applyTooltipMode(enabled); applyTooltipMode(enabled);
})(); })();
+37 -4
View File
@@ -26,18 +26,27 @@
<form method="POST" action="{{ url_for('change_password') }}"> <form method="POST" action="{{ url_for('change_password') }}">
<div class="form-group"> <div class="form-group">
<label for="current_password">Aktuelles Passwort:</label> <label for="current_password">Aktuelles Passwort:</label>
<input type="password" id="current_password" name="current_password" required> <div class="input-group">
<input type="password" class="form-control" id="current_password" name="current_password" required>
<button class="btn btn-outline-secondary" type="button" onclick="togglePasswordVisibility('current_password', this)">Anzeigen</button>
</div>
</div> </div>
<div class="form-group"> <div class="form-group">
<label for="new_password">Neues Passwort:</label> <label for="new_password">Neues Passwort:</label>
<input type="password" id="new_password" name="new_password" required> <div class="input-group">
<input type="password" class="form-control" id="new_password" name="new_password" required>
<button class="btn btn-outline-secondary" type="button" onclick="togglePasswordVisibility('new_password', this)">Anzeigen</button>
</div>
<small class="form-text text-muted">Das Passwort sollte mindestens 6 Zeichen lang sein.</small> <small class="form-text text-muted">Das Passwort sollte mindestens 6 Zeichen lang sein.</small>
</div> </div>
<div class="form-group"> <div class="form-group">
<label for="confirm_password">Neues Passwort bestätigen:</label> <label for="confirm_password">Neues Passwort bestätigen:</label>
<input type="password" id="confirm_password" name="confirm_password" required> <div class="input-group">
<input type="password" class="form-control" id="confirm_password" name="confirm_password" required>
<button class="btn btn-outline-secondary" type="button" onclick="togglePasswordVisibility('confirm_password', this)">Anzeigen</button>
</div>
</div> </div>
<div class="form-actions"> <div class="form-actions">
@@ -48,6 +57,20 @@
</div> </div>
</div> </div>
<script>
function togglePasswordVisibility(fieldId, button) {
var passwordInput = document.getElementById(fieldId);
if (passwordInput.type === 'password') {
passwordInput.type = 'text';
button.textContent = 'Verbergen';
} else {
passwordInput.type = 'password';
button.textContent = 'Anzeigen';
}
}
</script>
<style> <style>
.password-change-form { .password-change-form {
max-width: 500px; max-width: 500px;
@@ -74,7 +97,7 @@
font-weight: bold; font-weight: bold;
} }
input[type="password"] { .form-control {
width: 100%; width: 100%;
padding: 10px; padding: 10px;
border: 1px solid #ced4da; border: 1px solid #ced4da;
@@ -123,6 +146,16 @@
background-color: #5a6268; background-color: #5a6268;
} }
.btn-outline-secondary {
border: 1px solid #ced4da;
background-color: #f8f9fa;
color: #495057;
}
.btn-outline-secondary:hover {
background-color: #e2e6ea;
}
.alert { .alert {
padding: 12px; padding: 12px;
margin-bottom: 20px; margin-bottom: 20px;
+6 -6
View File
@@ -274,24 +274,24 @@
{% if not show_library_features %} {% if not show_library_features %}
<!-- ================= SYSTEM FILTERS 1-3 (INVENTORY / OTHER ITEMS ONLY) ================= --> <!-- ================= SYSTEM FILTERS 1-3 (INVENTORY / OTHER ITEMS ONLY) ================= -->
<div class="filter-inputs"> <div class="filter-inputs">
<h3>{{ filter_names.get('1', 'Jahrgangsstufe') }}</h3> <h3>{{ filter_names.get('1', 'Fach') }}</h3>
<div class="multi-filter"> <div class="multi-filter">
{% for idx in range(4) %} {% for idx in range(4) %}
<div class="form-group"> <div class="form-group">
<label for="filter1-{{ idx + 1 }}">Wert {{ idx + 1 }}:</label> <label for="filter2-{{ idx + 1 }}">Wert {{ idx + 1 }}:</label>
<select id="filter1-{{ idx + 1 }}" name="filter" class="filter-dropdown-select" data-selected="{{ item.Filter[idx] if item.Filter and item.Filter|length > idx else '' }}"> <select id="filter2-{{ idx + 1 }}" name="filter" class="filter-dropdown-select" data-selected="{{ item.Filter[idx] if item.Filter and item.Filter|length > idx else '' }}">
<option value="">-- Optional --</option> <option value="">-- Optional --</option>
</select> </select>
</div> </div>
{% endfor %} {% endfor %}
</div> </div>
<h3>{{ filter_names.get('2', 'Fachgebiet') }}</h3> <h3>{{ filter_names.get('2', 'Jahrgangsstufe') }}</h3>
<div class="multi-filter"> <div class="multi-filter">
{% for idx in range(4) %} {% for idx in range(4) %}
<div class="form-group"> <div class="form-group">
<label for="filter2-{{ idx + 1 }}">Wert {{ idx + 1 }}:</label> <label for="filter1-{{ idx + 1 }}">Wert {{ idx + 1 }}:</label>
<select id="filter2-{{ idx + 1 }}" name="filter2" class="filter-dropdown-select" data-selected="{{ item.Filter2[idx] if item.Filter2 and item.Filter2|length > idx else '' }}"> <select id="filter1-{{ idx + 1 }}" name="filter2" class="filter-dropdown-select" data-selected="{{ item.Filter2[idx] if item.Filter2 and item.Filter2|length > idx else '' }}">
<option value="">-- Optional --</option> <option value="">-- Optional --</option>
</select> </select>
</div> </div>
+19 -38
View File
@@ -374,7 +374,7 @@
<div class="filter-bar"> <div class="filter-bar">
<input id="library-search" type="text" placeholder="Nach Element, Benutzer, Klasse, Ausweis oder Rechnung suchen..."> <input id="library-search" type="text" placeholder="Nach Element, Benutzer, Klasse, Ausweis oder Rechnung suchen...">
<!-- NEU: Klassen-Filter --> <!-- Klassen-Filter -->
<select id="class-filter"> <select id="class-filter">
<option value="all">Alle Klassen</option> <option value="all">Alle Klassen</option>
{% set classes = [] %} {% set classes = [] %}
@@ -407,7 +407,6 @@
<table class="library-table" id="loans-table"> <table class="library-table" id="loans-table">
<thead> <thead>
<tr> <tr>
<!-- NEU: onClick Handler zum Sortieren hinzugefügt -->
<th style="cursor: pointer;" onclick="sortTable('loans-table', 0)">Status ↕</th> <th style="cursor: pointer;" onclick="sortTable('loans-table', 0)">Status ↕</th>
<th style="cursor: pointer;" onclick="sortTable('loans-table', 1)">Element ↕</th> <th style="cursor: pointer;" onclick="sortTable('loans-table', 1)">Element ↕</th>
<th style="cursor: pointer;" onclick="sortTable('loans-table', 2)">Benutzer ↕</th> <th style="cursor: pointer;" onclick="sortTable('loans-table', 2)">Benutzer ↕</th>
@@ -419,7 +418,6 @@
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
<!-- NEU: data-klasse hinzugefügt -->
{% for e in loan_entries %} {% for e in loan_entries %}
<tr class="loan-row" <tr class="loan-row"
data-borrow-id="{{ e.id }}" data-borrow-id="{{ e.id }}"
@@ -452,7 +450,6 @@
<td> <td>
<div><strong>{{ e.user }}</strong></div> <div><strong>{{ e.user }}</strong></div>
</td> </td>
<!-- NEU: Klasse Spalte -->
<td> <td>
{% if e.klasse %} {% if e.klasse %}
<span class="badge-pill badge-class">{{ e.klasse }}</span> <span class="badge-pill badge-class">{{ e.klasse }}</span>
@@ -469,9 +466,6 @@
{% if e.invoice_number %} {% if e.invoice_number %}
<div class="mono">{{ e.invoice_number }}</div> <div class="mono">{{ e.invoice_number }}</div>
<div class="muted">{{ e.invoice_amount }}</div> <div class="muted">{{ e.invoice_amount }}</div>
<!--{% if e.invoice_corrections_count %}
<div class="muted" style="color:#7c2d12;">{{ e.invoice_corrections_count }} Korrektur(en)</div>
{% endif %} -->
<div style="margin-top:6px;"> <div style="margin-top:6px;">
<a class="btn btn-outline-primary btn-sm" href="{{ url_for('admin_view_invoice_pdf', borrow_id=e.id) }}" target="_blank" rel="noopener">PDF öffnen</a> <a class="btn btn-outline-primary btn-sm" href="{{ url_for('admin_view_invoice_pdf', borrow_id=e.id) }}" target="_blank" rel="noopener">PDF öffnen</a>
</div> </div>
@@ -506,18 +500,9 @@
{% endif %} {% endif %}
{% if e.has_damage %} {% if e.has_damage %}
<!-- Aufruf des Reparatur-Auswahl-Modals -->
<button type="button" class="btn btn-warning btn-sm" onclick="openRepairModal('{{ e.item_id }}', '{{ e.item_code }}')">Reparieren / Ersetzen</button> <button type="button" class="btn btn-warning btn-sm" onclick="openRepairModal('{{ e.item_id }}', '{{ e.item_code }}')">Reparieren / Ersetzen</button>
{% endif %} {% endif %}
<!--{% if e.invoice_number %}
<form method="post" action="{{ url_for('admin_add_invoice_correction', borrow_id=e.id) }}" onsubmit="return confirm('Korrekturbuchung hinzufügen?');" style="display: flex; gap: 6px; align-items: center; flex-wrap: wrap;">
<input type="text" name="correction_reason" value="Korrektur zu {{ e.invoice_number }}" placeholder="Korrekturgrund" required style="padding:6px; border:1px solid #ddd; border-radius:6px; min-width:160px; max-width:180px;">
<input type="text" name="amount_delta" placeholder="z.B. -{{ e.invoice_amount }}" style="padding:6px; border:1px solid #ddd; border-radius:6px; width:120px;">
<button type="submit" class="btn btn-outline-danger btn-sm">Korrektur</button>
</form>
{% endif %}-->
{% if e.status in ['active', 'planned'] %} {% if e.status in ['active', 'planned'] %}
<form method="post" action="{{ url_for('admin_reset_borrowing', borrow_id=e.id) }}" onsubmit="return confirm('Ausleihe zurücksetzen?');"> <form method="post" action="{{ url_for('admin_reset_borrowing', borrow_id=e.id) }}" onsubmit="return confirm('Ausleihe zurücksetzen?');">
<button type="submit" class="btn btn-secondary btn-sm">Zurücksetzen</button> <button type="submit" class="btn btn-secondary btn-sm">Zurücksetzen</button>
@@ -541,7 +526,6 @@
<table class="library-table" id="damaged-table"> <table class="library-table" id="damaged-table">
<thead> <thead>
<tr> <tr>
<!-- NEU: onClick Handler zum Sortieren hinzugefügt -->
<th style="cursor: pointer;" onclick="sortTable('damaged-table', 0)">Element ↕</th> <th style="cursor: pointer;" onclick="sortTable('damaged-table', 0)">Element ↕</th>
<th style="cursor: pointer;" onclick="sortTable('damaged-table', 1)">Code ↕</th> <th style="cursor: pointer;" onclick="sortTable('damaged-table', 1)">Code ↕</th>
<th style="cursor: pointer;" onclick="sortTable('damaged-table', 2)">Schaden ↕</th> <th style="cursor: pointer;" onclick="sortTable('damaged-table', 2)">Schaden ↕</th>
@@ -574,7 +558,6 @@
<div class="row-actions" style="margin-bottom:8px;"> <div class="row-actions" style="margin-bottom:8px;">
<a class="btn btn-outline-secondary btn-sm" href="{{ url_for('library_item_invoices', item_id=item.id) }}">Rechnungen</a> <a class="btn btn-outline-secondary btn-sm" href="{{ url_for('library_item_invoices', item_id=item.id) }}">Rechnungen</a>
</div> </div>
<!-- Aufruf des Reparatur-Auswahl-Modals -->
<button type="button" class="btn btn-warning btn-sm" onclick="openRepairModal('{{ item.id }}', '{{ item.code }}')">Reparieren / Ersetzen</button> <button type="button" class="btn btn-warning btn-sm" onclick="openRepairModal('{{ item.id }}', '{{ item.code }}')">Reparieren / Ersetzen</button>
</td> </td>
</tr> </tr>
@@ -627,6 +610,13 @@
<textarea id="damage-invoice-reason" name="damage_reason" rows="5" required style="width:100%; padding:10px; border:1px solid #ddd; border-radius:6px; resize:vertical;" placeholder="Beschreiben Sie kurz den Schaden oder die Zerstörung."></textarea> <textarea id="damage-invoice-reason" name="damage_reason" rows="5" required style="width:100%; padding:10px; border:1px solid #ddd; border-radius:6px; resize:vertical;" placeholder="Beschreiben Sie kurz den Schaden oder die Zerstörung."></textarea>
</div> </div>
{% if email_service_enabled %}
<div style="margin-bottom:16px;">
<label for="damage-invoice-recipient-email" style="display:block; font-weight:700; margin-bottom:6px;">Empfänger-E-Mail für den PDF-Versand</label>
<input id="damage-invoice-recipient-email" name="recipient_email" type="email" style="width:100%; padding:10px; border:1px solid #ddd; border-radius:6px;" placeholder="name@beispiel.de">
</div>
{% endif %}
<div style="display:flex; flex-wrap:wrap; gap:16px; align-items:center; margin-bottom:18px;"> <div style="display:flex; flex-wrap:wrap; gap:16px; align-items:center; margin-bottom:18px;">
<label style="display:flex; align-items:center; gap:8px;"> <label style="display:flex; align-items:center; gap:8px;">
<input id="damage-invoice-destroyed" type="checkbox" name="mark_destroyed" checked> <input id="damage-invoice-destroyed" type="checkbox" name="mark_destroyed" checked>
@@ -640,13 +630,16 @@
<div style="display:flex; justify-content:flex-end; gap:10px;"> <div style="display:flex; justify-content:flex-end; gap:10px;">
<button type="button" class="btn btn-secondary" onclick="closeDamageInvoiceModal()">Abbrechen</button> <button type="button" class="btn btn-secondary" onclick="closeDamageInvoiceModal()">Abbrechen</button>
<button type="submit" class="btn btn-danger">PDF-Rechnung erstellen</button> <button type="submit" class="btn btn-outline-danger" name="delivery" value="pdf">Nur PDF herunterladen</button>
{% if email_service_enabled %}
<button type="submit" class="btn btn-danger" name="delivery" value="email">PDF per E-Mail senden</button>
{% endif %}
</div> </div>
</form> </form>
</div> </div>
</div> </div>
<!-- Neues Modal: Reparatur-Optionen (Reparieren, Ersetzen mit neuem Code_4, Löschen) --> <!-- Modal: Reparatur-Optionen -->
<div id="repair-action-modal" role="dialog" aria-modal="true" aria-labelledby="repair-modal-title" style="display:none; position:fixed; inset:0; background:rgba(15,23,42,0.72); z-index:9999; padding:20px; overflow:auto;"> <div id="repair-action-modal" role="dialog" aria-modal="true" aria-labelledby="repair-modal-title" style="display:none; position:fixed; inset:0; background:rgba(15,23,42,0.72); z-index:9999; padding:20px; overflow:auto;">
<div style="max-width:540px; margin:60px auto; background: var(--ui-surface); border-radius:12px; padding:24px; box-shadow:0 20px 60px rgba(0,0,0,0.3);"> <div style="max-width:540px; margin:60px auto; background: var(--ui-surface); border-radius:12px; padding:24px; box-shadow:0 20px 60px rgba(0,0,0,0.3);">
<div style="display:flex; justify-content:space-between; align-items:center; gap:12px; margin-bottom:16px;"> <div style="display:flex; justify-content:space-between; align-items:center; gap:12px; margin-bottom:16px;">
@@ -676,7 +669,7 @@
<script> <script>
(function() { (function() {
const searchInput = document.getElementById('library-search'); const searchInput = document.getElementById('library-search');
const classFilter = document.getElementById('class-filter'); // NEU: Klassenfilter hinzugefügt const classFilter = document.getElementById('class-filter');
const statusFilter = document.getElementById('loan-status-filter'); const statusFilter = document.getElementById('loan-status-filter');
const damageFilter = document.getElementById('damage-filter'); const damageFilter = document.getElementById('damage-filter');
const loanRows = Array.from(document.querySelectorAll('.loan-row')); const loanRows = Array.from(document.querySelectorAll('.loan-row'));
@@ -693,10 +686,8 @@
const damageInvoiceReason = document.getElementById('damage-invoice-reason'); const damageInvoiceReason = document.getElementById('damage-invoice-reason');
const damageInvoiceReplaceBtn = document.getElementById('damage-invoice-replace-btn'); const damageInvoiceReplaceBtn = document.getElementById('damage-invoice-replace-btn');
// NEU: Globale Sortier-Richtungsobjekte
let sortDirections = {}; let sortDirections = {};
// NEU: Sortier-Funktion
window.sortTable = function(tableId, columnIndex) { window.sortTable = function(tableId, columnIndex) {
const table = document.getElementById(tableId); const table = document.getElementById(tableId);
const tbody = table.tBodies[0]; const tbody = table.tBodies[0];
@@ -714,7 +705,6 @@
const isAscending = sortDirections[sortKey]; const isAscending = sortDirections[sortKey];
const multiplier = isAscending ? 1 : -1; const multiplier = isAscending ? 1 : -1;
// Pfeil im Header aktualisieren
const headers = table.querySelectorAll("th"); const headers = table.querySelectorAll("th");
headers.forEach(th => { headers.forEach(th => {
if(th.innerHTML.includes('↕') || th.innerHTML.includes('▲') || th.innerHTML.includes('▼')) { if(th.innerHTML.includes('↕') || th.innerHTML.includes('▲') || th.innerHTML.includes('▼')) {
@@ -726,19 +716,15 @@
currentTh.innerHTML = currentTh.innerHTML.replace('↕', isAscending ? '▲' : '▼'); currentTh.innerHTML = currentTh.innerHTML.replace('↕', isAscending ? '▲' : '▼');
} }
// Zeilen sortieren
rows.sort((a, b) => { rows.sort((a, b) => {
const cellA = a.cells[columnIndex].textContent.trim(); const cellA = a.cells[columnIndex].textContent.trim();
const cellB = b.cells[columnIndex].textContent.trim(); const cellB = b.cells[columnIndex].textContent.trim();
return cellA.localeCompare(cellB, 'de', { numeric: true, sensitivity: 'base' }) * multiplier; return cellA.localeCompare(cellB, 'de', { numeric: true, sensitivity: 'base' }) * multiplier;
}); });
// Neu einfügen
rows.forEach(row => tbody.appendChild(row)); rows.forEach(row => tbody.appendChild(row));
}; };
// Funktionen für das Reparatur-Modal
window.openRepairModal = function(itemId, currentCode) { window.openRepairModal = function(itemId, currentCode) {
const modal = document.getElementById('repair-action-modal'); const modal = document.getElementById('repair-action-modal');
const form = document.getElementById('repair-action-form'); const form = document.getElementById('repair-action-form');
@@ -871,26 +857,25 @@
}); });
} }
// NEU: Kombinierte Filter-Funktion (Suche + Status + Schaden + Klasse)
function applyFilters() { function applyFilters() {
const search = (searchInput.value || '').trim().toLowerCase(); const search = (searchInput.value || '').trim().toLowerCase();
const status = statusFilter.value; const status = statusFilter.value;
const damage = damageFilter.value; const damage = damageFilter.value;
const klasse = classFilter.value; // NEU const klasse = classFilter.value;
let visibleLoans = 0; let visibleLoans = 0;
loanRows.forEach(row => { loanRows.forEach(row => {
const haystack = row.dataset.search || ''; const haystack = row.dataset.search || '';
const rowStatus = row.dataset.status || ''; const rowStatus = row.dataset.status || '';
const rowKlasse = row.dataset.klasse || ''; // NEU const rowKlasse = row.dataset.klasse || '';
const hasDamage = row.dataset.hasDamage === '1'; const hasDamage = row.dataset.hasDamage === '1';
const searchMatch = !search || haystack.includes(search); const searchMatch = !search || haystack.includes(search);
const statusMatch = !status || rowStatus === status; const statusMatch = !status || rowStatus === status;
const classMatch = klasse === 'all' || rowKlasse === klasse; // NEU const classMatch = klasse === 'all' || rowKlasse === klasse;
const damageMatch = damage === 'all' || (damage === 'damage' && hasDamage) || (damage === 'clean' && !hasDamage); const damageMatch = damage === 'all' || (damage === 'damage' && hasDamage) || (damage === 'clean' && !hasDamage);
const show = searchMatch && statusMatch && classMatch && damageMatch; // NEU const show = searchMatch && statusMatch && classMatch && damageMatch;
row.style.display = show ? '' : 'none'; row.style.display = show ? '' : 'none';
if (show) visibleLoans++; if (show) visibleLoans++;
}); });
@@ -905,10 +890,6 @@
const searchMatch = !search || haystack.includes(search); const searchMatch = !search || haystack.includes(search);
const statusMatch = !status || rowStatus === status || status === ''; const statusMatch = !status || rowStatus === status || status === '';
const damageMatch = damage === 'all' || (damage === 'damage' && hasDamage) || (damage === 'clean' && !hasDamage); const damageMatch = damage === 'all' || (damage === 'damage' && hasDamage) || (damage === 'clean' && !hasDamage);
// Defekte-Medien-Tabelle hat keine verknüpfte "Klasse", deshalb blenden wir sie nur bei Klassen-Filter "all" ein,
// oder wenn gar nicht nach Klasse gefiltert wird, damit sie nicht verschwindet.
// Falls sie bei aktiver Klassensuche komplett verschwinden soll, passe die Bedingung an:
const classMatch = klasse === 'all'; const classMatch = klasse === 'all';
const show = searchMatch && statusMatch && damageMatch && classMatch; const show = searchMatch && statusMatch && damageMatch && classMatch;
@@ -919,7 +900,7 @@
} }
searchInput.addEventListener('input', applyFilters); searchInput.addEventListener('input', applyFilters);
classFilter.addEventListener('change', applyFilters); // NEU classFilter.addEventListener('change', applyFilters);
statusFilter.addEventListener('change', applyFilters); statusFilter.addEventListener('change', applyFilters);
damageFilter.addEventListener('change', applyFilters); damageFilter.addEventListener('change', applyFilters);
applyFilters(); applyFilters();
+175 -74
View File
@@ -8,9 +8,9 @@
1. Modals & Overlays 1. Modals & Overlays
========================================= */ ========================================= */
.modal { .modal {
display: none; /* Managed by JS (none/flex) */ display: none;
position: fixed; position: fixed;
inset: 0; /* Modern shorthand for top: 0, right: 0, bottom: 0, left: 0 */ inset: 0;
z-index: 1000; z-index: 1000;
background-color: rgba(0, 0, 0, 0.6); background-color: rgba(0, 0, 0, 0.6);
align-items: center; align-items: center;
@@ -23,7 +23,7 @@
display: flex; display: flex;
flex-direction: column; flex-direction: column;
width: 100%; width: 100%;
max-width: 900px; /* Consolidated from conflicting 600px/900px rules */ max-width: 900px;
max-height: 90vh; max-height: 90vh;
background-color: var(--ui-surface, #fff); background-color: var(--ui-surface, #fff);
border-radius: 8px; border-radius: 8px;
@@ -133,6 +133,34 @@
background: var(--ui-surface); background: var(--ui-surface);
} }
/* Blue edge styling for inputs and action button */
#activeStudentCard,
#manualItemCode {
border: 2px solid #3b82f6 !important;
box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.15);
}
#activeStudentCard:focus,
#manualItemCode:focus {
outline: none;
border-color: #2563eb !important;
box-shadow: 0 0 0 4px rgba(37, 99, 235, 0.25) !important;
}
#manualActionBtn {
background: #4f46e5 !important;
color: white !important;
border: 2px solid #3b82f6 !important;
box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.2);
transition: border-color 0.2s ease, box-shadow 0.2s ease, background-color 0.2s ease;
}
#manualActionBtn:hover {
background: #4338ca !important;
border-color: #2563eb !important;
box-shadow: 0 0 0 3px rgba(37, 99, 235, 0.3);
}
.library-scan-status { .library-scan-status {
margin-top: 10px; margin-top: 10px;
font-size: 0.92em; font-size: 0.92em;
@@ -419,31 +447,136 @@
} }
/* ========================================= /* =========================================
7. Mobile Responsiveness 7. Mobile Responsiveness (Updated for Cards)
========================================= */ ========================================= */
@media (max-width: 768px) { @media (max-width: 768px) {
.library-table-container { padding: 10px; } .library-table-container { padding: 10px; }
.library-search-bar { flex-direction: column; } .library-search-bar { flex-direction: column; }
.library-search-input { width: 100%; } .library-search-input { width: 100%; }
.library-items-table { font-size: 0.85em; }
/* Enlarge touch targets */
.library-search-input,
.library-scan-controls select,
.library-scan-controls input,
.library-filter-toggle-btn,
.filter-item input,
.filter-item select,
.button {
min-height: 44px;
}
/* Stack Scan & Controls */
.library-scan-controls {
display: flex;
flex-direction: column;
align-items: stretch;
gap: 12px;
}
.library-scan-controls > * {
width: 100% !important;
margin-left: 0 !important;
}
.filter-row {
grid-template-columns: 1fr;
}
.filter-buttons {
flex-direction: column;
align-items: stretch;
}
.filter-buttons .button {
width: 100%;
justify-content: center;
margin-bottom: 8px;
}
.filter-buttons > div[style*="flex-grow"] {
display: none;
}
/* Convert Table to Cards */
.library-items-table,
.library-items-table thead,
.library-items-table tbody,
.library-items-table th, .library-items-table th,
.library-items-table td,
.library-items-table tr {
display: block;
width: 100%;
}
.library-items-table thead tr {
position: absolute;
top: -9999px;
left: -9999px;
}
.library-items-table tr {
margin-bottom: 16px;
border: 1px solid var(--ui-border, #ddd);
border-radius: 12px;
background: #fff;
box-shadow: 0 4px 6px rgba(0,0,0,0.05);
overflow: hidden;
}
.library-items-table td { .library-items-table td {
padding: 8px 10px; position: relative;
padding: 12px 16px 12px 35% !important;
text-align: right;
border-bottom: 1px solid #f4f4f4;
font-size: 0.95em;
min-height: auto;
display: flex;
justify-content: flex-end;
align-items: center;
}
.library-items-table td::before {
content: attr(data-label);
position: absolute;
left: 16px;
width: 30%;
text-align: left;
font-weight: 600;
color: #555;
white-space: nowrap;
}
/* Styles specific for the Actions cell */
.library-items-table td:last-child {
border-bottom: none;
padding: 16px !important;
background: #f8fafc;
display: flex;
flex-direction: column;
gap: 10px;
align-items: stretch;
}
.library-items-table td:last-child::before {
display: none;
}
.table-actions {
flex-direction: column;
width: 100%;
gap: 10px;
} }
.table-actions .button { .table-actions .button {
padding: 4px 8px; width: 100%;
font-size: 0.75em; margin: 0 !important;
} padding: 12px;
font-size: 1em;
.filter-row, justify-content: center;
.library-scan-controls {
grid-template-columns: 1fr;
} }
.library-scan-reader-wrap { max-width: 100%; } .library-scan-reader-wrap { max-width: 100%; }
} }
.library-scan-reader-wrap { .library-scan-reader-wrap {
display: none; display: none;
margin-top: 15px; margin-top: 15px;
@@ -500,7 +633,6 @@
letter-spacing: 2px; letter-spacing: 2px;
} }
.detail-gallery-container { .detail-gallery-container {
display: flex; display: flex;
flex-wrap: wrap; flex-wrap: wrap;
@@ -534,13 +666,12 @@
<div class="library-table-container" id="libraryTableContainer" data-can-edit="{{ 1 if current_permissions.actions.get('can_edit', False) else 0 }}"> <div class="library-table-container" id="libraryTableContainer" data-can-edit="{{ 1 if current_permissions.actions.get('can_edit', False) else 0 }}">
<!-- Header --> <!-- Header -->
<!-- Search and Filter Toggle -->
<!-- Customizable Filter Panel -->
<div class="library-header"> <div class="library-header">
<h1>📚 Bibliothek</h1> <h1>📚 Bibliothek</h1>
<p>Bücher, CDs, DVDs und weitere Medien</p> <p>Bücher, CDs, DVDs und weitere Medien</p>
</div> </div>
<!-- Student card / quick scan workflow -->
<!-- Search and Filter Toggle -->
<div class="library-search-bar"> <div class="library-search-bar">
<input <input
type="text" type="text"
@@ -556,26 +687,31 @@
🔍 Filter 🔍 Filter
</button> </button>
</div> </div>
<!-- Controls -->
<div class="library-scan-controls"> <div class="library-scan-controls">
<select id="scanModeSelect" aria-label="Scan-Modus"> <select id="scanModeSelect" aria-label="Scan-Modus">
<option value="card_only">Nur Ausweis erfassen</option> <option value="card_only">Nur Ausweis erfassen</option>
<option value="quick_toggle">Schnellmodus: Ausweis + Mediencode</option> <option value="quick_toggle">Schnellmodus: 1x Ausweis + 1x Mediencode</option>
<option value="continuous">Dauermodus: 1x Ausweis, dann N Medien</option> <option value="continuous">Dauermodus: 1x Ausweis, dann N Medien</option>
<option value="return_only">Nur Rückgabe (nur Mediencode)</option> <option value="return_only">Nur Rückgabe (nur Mediencode)</option>
</select> </select>
<input type="text" id="activeStudentCard" placeholder="Aktiver Ausweis (gescannt)"> <input type="text" id="activeStudentCard" placeholder="Aktiver Ausweis (gescannt)">
<input type="text" id="manualItemCode" placeholder="Manueller Mediencode (optional)" style="min-width:180px;"> <input type="text" id="manualItemCode" placeholder="Manueller Mediencode (optional)" style="min-width:180px;">
<button id="resetCardBtn" class="button" type="button">Feld zurücksetzen</button> <button id="resetCardBtn" class="button" type="button">Feld zurücksetzen</button>
<button id="toggleScannerBtn" class="button" type="button">Scanner starten</button> <button id="toggleScannerBtn" class="button" type="button">Handyscanner starten</button>
<button id="physicalScannerBtn" class="button" type="button" style="margin-left:6px;"> <button id="physicalScannerBtn" class="button" type="button" style="margin-left:6px;">
Physischer Scanner starten Physischer Scanner starten
</button> </button>
<button id="manualActionBtn" class="button" type="button" style="margin-left:6px; background:#4f46e5; color:white;">Code verarbeiten</button> <button id="manualActionBtn" class="button" type="button" style="margin-left:6px;">Code verarbeiten</button>
</div> </div>
<div class="library-scan-reader-wrap" id="scanReaderWrap" style="display: none; margin-top: 15px;"> <div class="library-scan-reader-wrap" id="scanReaderWrap" style="display: none; margin-top: 15px;">
<div class="library-scan-reader" style="width: 100%; max-width: 640px; margin: 0 auto; overflow: hidden; border-radius: 8px; border: 2px solid #ccc;"> <div class="library-scan-reader" style="width: 100%; max-width: 640px; margin: 0 auto; overflow: hidden; border-radius: 8px; border: 2px solid #ccc;">
</div> </div>
</div> </div>
<!-- Customizable Filter Panel -->
<div id="filterPanel" class="library-filter-panel"> <div id="filterPanel" class="library-filter-panel">
<div class="filter-row"> <div class="filter-row">
<div class="filter-item"> <div class="filter-item">
@@ -674,7 +810,7 @@
<script> <script>
// ========================================================================= // =========================================================================
// CUSTOM MODAL HELPERS (Replaces native browser alert, confirm & prompt) // CUSTOM MODAL HELPERS
// ========================================================================= // =========================================================================
function createModalOverlay() { function createModalOverlay() {
const overlay = document.createElement('div'); const overlay = document.createElement('div');
@@ -867,6 +1003,7 @@
input.select(); input.select();
}); });
} }
// ========================================================================= // =========================================================================
// 1. GLOBAL STATE DEFINITIONS // 1. GLOBAL STATE DEFINITIONS
// ========================================================================= // =========================================================================
@@ -891,19 +1028,18 @@
let renderedCount = INITIAL_RENDER_COUNT; let renderedCount = INITIAL_RENDER_COUNT;
let filterPanelOpen = false; let filterPanelOpen = false;
// Scanner Related State Variables
let scannerInstance = null; let scannerInstance = null;
let scannerRunning = false; let scannerRunning = false;
let activeScannerCallback = null; let activeScannerCallback = null;
let activeStudentCardId = ''; let activeStudentCardId = '';
let lastScanValue = ''; let lastScanValue = '';
let lastScanAt = 0; let lastScanAt = 0;
// Keyboard-scanner support (physical scanners that act as keyboard wedges)
let keyboardScannerEnabled = false; let keyboardScannerEnabled = false;
let keyboardScanBuffer = ''; let keyboardScanBuffer = '';
let keyboardLastKeyAt = 0; let keyboardLastKeyAt = 0;
let physicalScannerModalOpen = false; let physicalScannerModalOpen = false;
const KEYBOARD_SCAN_INTERCHAR_MS = 500; // max time between slower scanner keystrokes const KEYBOARD_SCAN_INTERCHAR_MS = 500;
const physicalScanQueue = []; const physicalScanQueue = [];
let keyboardScanProcessing = false; let keyboardScanProcessing = false;
let editLibraryState = { let editLibraryState = {
@@ -1040,13 +1176,14 @@
const actionLabel = statusKey === 'available' ? 'Ausleihen' : (statusKey === 'borrowed' ? 'Reservieren' : 'Nicht ausleihbar'); const actionLabel = statusKey === 'available' ? 'Ausleihen' : (statusKey === 'borrowed' ? 'Reservieren' : 'Nicht ausleihbar');
const actionDisabled = statusKey === 'damaged' ? 'disabled' : ''; const actionDisabled = statusKey === 'damaged' ? 'disabled' : '';
// Using data-label injection for accurate mobile rendering mapping
return ` return `
<tr> <tr>
<td class="table-title">${escapeHtml(item.Name || 'Untitled')}</td> <td data-label="Titel" class="table-title">${escapeHtml(item.Name || 'Untitled')}</td>
<td>${escapeHtml(item.ISBN || '-')}</td> <td data-label="ISBN/Code">${escapeHtml(item.ISBN || '-')}</td>
<td>${getItemTypeLabel(item.ItemType || 'book')}</td> <td data-label="Typ">${getItemTypeLabel(item.ItemType || 'book')}</td>
<td style="font-weight:600; text-align:center;">${item.Quantity || item.GroupedDisplayCount || 1}</td> <td data-label="Anzahl" style="font-weight:600; text-align:center;">${item.Quantity || item.GroupedDisplayCount || 1}</td>
<td> <td data-label="Status">
<span class="table-status ${statusClass}"> <span class="table-status ${statusClass}">
${statusText} ${statusText}
</span> </span>
@@ -1056,7 +1193,7 @@
<button class="button" style="background: #28a745; color: white;" onclick="borrowItem('${item._id}')" ${actionDisabled}> <button class="button" style="background: #28a745; color: white;" onclick="borrowItem('${item._id}')" ${actionDisabled}>
${actionLabel} ${actionLabel}
</button> </button>
${canEditLibraryItems ? `<button class="button" style="background:#0ea5e9;color:#fff;" onclick="openEditLibraryItem('${item._id}')">Bearbeiten</button>` : ''} ${canEditLibraryItems ? `<button class="button" style="background:#0ea5e9;color:#fff; margin-left:6px;" onclick="openEditLibraryItem('${item._id}')">Bearbeiten</button>` : ''}
${canEditLibraryItems ? `<button class="button" style="background:#dc2626;color:#fff; margin-left:6px;" onclick="confirmDeleteLibraryItem('${item._id}')">Löschen</button>` : ''} ${canEditLibraryItems ? `<button class="button" style="background:#dc2626;color:#fff; margin-left:6px;" onclick="confirmDeleteLibraryItem('${item._id}')">Löschen</button>` : ''}
</td> </td>
</tr>`; </tr>`;
@@ -1125,26 +1262,22 @@
const scannerWrap = document.querySelector('.library-scan-reader-wrap'); const scannerWrap = document.querySelector('.library-scan-reader-wrap');
const toggleBtn = document.getElementById('toggleScannerBtn'); const toggleBtn = document.getElementById('toggleScannerBtn');
// 1. CRITICAL FIX: Make the container visible BEFORE Quagga initializes
// Quagga cannot calculate video dimensions if display is 'none'
if (scannerWrap) { if (scannerWrap) {
scannerWrap.style.display = 'block'; scannerWrap.style.display = 'block';
} }
setScanStatus('Starte Kamera...', 'warn'); setScanStatus('Starte Kamera...', 'warn');
// 2. Initialize Quagga with a slight delay to allow the DOM to render the block
setTimeout(() => { setTimeout(() => {
Quagga.init({ Quagga.init({
inputStream: { inputStream: {
name: "Live", name: "Live",
type: "LiveStream", type: "LiveStream",
// This MUST match the inner div where the video should appear
target: document.querySelector('.library-scan-reader'), target: document.querySelector('.library-scan-reader'),
constraints: { constraints: {
width: 640, width: 640,
height: 480, height: 480,
facingMode: "environment" // Prefer back camera on mobile facingMode: "environment"
} }
}, },
locator: { locator: {
@@ -1152,13 +1285,11 @@
halfSample: true halfSample: true
}, },
decoder: { decoder: {
// Keep only the barcode types you actually use to improve performance
readers: ["code_128_reader", "ean_reader", "code_39_reader"] readers: ["code_128_reader", "ean_reader", "code_39_reader"]
}, },
locate: true locate: true
}, function(err) { }, function(err) {
if (err) { if (err) {
// This will finally log the actual error (e.g., NotAllowedError) if permissions fail
console.error("Quagga initialization failed:", err); console.error("Quagga initialization failed:", err);
setScanStatus('Kamera-Fehler: ' + (err.name || err), 'error'); setScanStatus('Kamera-Fehler: ' + (err.name || err), 'error');
@@ -1190,7 +1321,6 @@
scannerRunning = false; scannerRunning = false;
activeScannerCallback = null; activeScannerCallback = null;
// Hide the container to free up UI space
const scannerWrap = document.querySelector('.library-scan-reader-wrap'); const scannerWrap = document.querySelector('.library-scan-reader-wrap');
if (scannerWrap) { if (scannerWrap) {
scannerWrap.style.display = 'none'; scannerWrap.style.display = 'none';
@@ -1198,7 +1328,7 @@
const toggleBtn = document.getElementById('toggleScannerBtn'); const toggleBtn = document.getElementById('toggleScannerBtn');
if (toggleBtn) { if (toggleBtn) {
toggleBtn.textContent = 'Kamera Scanner'; // Reset button text toggleBtn.textContent = 'Kamera Scanner';
} }
} }
@@ -1210,7 +1340,6 @@
method: 'POST', method: 'POST',
headers: { headers: {
'Content-Type': 'application/json', 'Content-Type': 'application/json',
// Falls du in Flask CSRF-Protect nutzt, muss der Token mitgesendet werden:
'X-CSRFToken': '{{ csrf_token }}', 'X-CSRFToken': '{{ csrf_token }}',
'X-CSRF-Token': '{{ csrf_token }}' 'X-CSRF-Token': '{{ csrf_token }}'
} }
@@ -1218,7 +1347,6 @@
if (!response.ok) return false; if (!response.ok) return false;
// Wir parsen die Antwort. Flask jsonify({"is_student_card": true/false})
const data = await response.json(); const data = await response.json();
return data === true || data.is_student_card === true; return data === true || data.is_student_card === true;
@@ -1245,7 +1373,7 @@
}); });
// ========================================================================= // =========================================================================
// Keyboard scanner handling (physical scanners that send chars then Enter) // Keyboard scanner handling
// ========================================================================= // =========================================================================
function getPhysicalScannerInstruction() { function getPhysicalScannerInstruction() {
const mode = document.getElementById('scanModeSelect')?.value || 'card_only'; const mode = document.getElementById('scanModeSelect')?.value || 'card_only';
@@ -1291,6 +1419,7 @@
keyboardScannerEnabled = false; keyboardScannerEnabled = false;
keyboardScanBuffer = ''; keyboardScanBuffer = '';
keyboardLastKeyAt = 0; keyboardLastKeyAt = 0;
setActiveStudentCard('');
document.removeEventListener('keydown', keyboardScanKeydownHandler); document.removeEventListener('keydown', keyboardScanKeydownHandler);
const modal = document.getElementById('physicalScannerModal'); const modal = document.getElementById('physicalScannerModal');
if (modal) modal.style.display = 'none'; if (modal) modal.style.display = 'none';
@@ -1299,7 +1428,6 @@
} }
function keyboardScanKeydownHandler(e) { function keyboardScanKeydownHandler(e) {
// Only active when explicitly enabled
if (!keyboardScannerEnabled || !physicalScannerModalOpen) return; if (!keyboardScannerEnabled || !physicalScannerModalOpen) return;
if (e.key === 'Escape') { if (e.key === 'Escape') {
@@ -1310,7 +1438,6 @@
const now = Date.now(); const now = Date.now();
// If Enter/Return pressed -> finalize buffer
if (e.key === 'Enter') { if (e.key === 'Enter') {
e.preventDefault(); e.preventDefault();
const code = keyboardScanBuffer.trim(); const code = keyboardScanBuffer.trim();
@@ -1318,7 +1445,6 @@
keyboardLastKeyAt = 0; keyboardLastKeyAt = 0;
if (!code) return; if (!code) return;
// Scanner keystrokes must not be submitted into the focused form field.
const displayCode = document.getElementById('physicalScannerCode'); const displayCode = document.getElementById('physicalScannerCode');
if (displayCode) displayCode.textContent = code; if (displayCode) displayCode.textContent = code;
updatePhysicalScannerModal('Enter erkannt. Code wird verarbeitet...', 'warn'); updatePhysicalScannerModal('Enter erkannt. Code wird verarbeitet...', 'warn');
@@ -1326,9 +1452,7 @@
return; return;
} }
// Accept all printable scanner characters, including letters and punctuation.
if (e.key.length === 1) { if (e.key.length === 1) {
// If time gap too big, start new buffer
if (keyboardLastKeyAt && (now - keyboardLastKeyAt) > KEYBOARD_SCAN_INTERCHAR_MS) { if (keyboardLastKeyAt && (now - keyboardLastKeyAt) > KEYBOARD_SCAN_INTERCHAR_MS) {
keyboardScanBuffer = ''; keyboardScanBuffer = '';
} }
@@ -1336,7 +1460,6 @@
keyboardLastKeyAt = now; keyboardLastKeyAt = now;
const displayCode = document.getElementById('physicalScannerCode'); const displayCode = document.getElementById('physicalScannerCode');
if (displayCode) displayCode.textContent = keyboardScanBuffer; if (displayCode) displayCode.textContent = keyboardScanBuffer;
// Prevent default so scanner input is captured even while an input has focus.
e.preventDefault(); e.preventDefault();
} }
} }
@@ -1365,21 +1488,18 @@
const now = Date.now(); const now = Date.now();
if (scannedCode === lastScanValue && (now - lastScanAt) < 1500) { if (scannedCode === lastScanValue && (now - lastScanAt) < 1500) {
return; // Verhindert doppeltes Scannen in kurzer Zeit return;
} }
lastScanValue = scannedCode; lastScanValue = scannedCode;
lastScanAt = now; lastScanAt = now;
// Den aktuellen Modus aus dem Dropdown auslesen
const mode = (document.getElementById('scanModeSelect') || {}).value || 'card_only'; const mode = (document.getElementById('scanModeSelect') || {}).value || 'card_only';
// 1. Modus: Nur Rückgabe
if (mode === 'return_only') { if (mode === 'return_only') {
await returnByCode(scannedCode); await returnByCode(scannedCode);
return; return;
} }
// 2. Modus: Nur Ausweis
if (mode === 'card_only') { if (mode === 'card_only') {
setActiveStudentCard(scannedCode); setActiveStudentCard(scannedCode);
setScanStatus(`Ausweis gesetzt: ${activeStudentCardId}. Bitte den nächsten Ausweis scannen.`, 'ok'); setScanStatus(`Ausweis gesetzt: ${activeStudentCardId}. Bitte den nächsten Ausweis scannen.`, 'ok');
@@ -1388,13 +1508,11 @@
return; return;
} }
// 3. Modus: Schnellmodus (1x Ausweis, 1x Buch)
if (mode === 'quick_toggle') { if (mode === 'quick_toggle') {
await processQuickToggleScan(scannedCode); await processQuickToggleScan(scannedCode);
return; return;
} }
// 4. Modus: Dauermodus (1x Ausweis, Nx Bücher)
if (mode === 'continuous') { if (mode === 'continuous') {
await processContinuousScan(scannedCode); await processContinuousScan(scannedCode);
return; return;
@@ -1471,7 +1589,6 @@
updatePhysicalScannerModal('Aktion erfolgreich. Bereit für den nächsten Mediencode.', 'ok'); updatePhysicalScannerModal('Aktion erfolgreich. Bereit für den nächsten Mediencode.', 'ok');
} }
// Tabellen-Ansicht aktualisieren
if (typeof loadLibraryItems === "function") { if (typeof loadLibraryItems === "function") {
await loadLibraryItems(); await loadLibraryItems();
} }
@@ -1491,7 +1608,6 @@
async function processQuickToggleScan(scannedCode) { async function processQuickToggleScan(scannedCode) {
// 2. Wenn kein Ausweis gesetzt ist, wird der Code als Ausweis interpretiert
if (!activeStudentCardId) { if (!activeStudentCardId) {
setActiveStudentCard(scannedCode); setActiveStudentCard(scannedCode);
setScanStatus(`Ausweis gesetzt: ${activeStudentCardId}. Bitte den nächsten Mediencode scannen.`, 'ok'); setScanStatus(`Ausweis gesetzt: ${activeStudentCardId}. Bitte den nächsten Mediencode scannen.`, 'ok');
@@ -1500,7 +1616,6 @@
return; return;
} }
// 3. Ausleihe/Rückgabe verarbeiten (wenn Ausweis vorhanden)
try { try {
setScanStatus('Verarbeite Mediencode...', 'warn'); setScanStatus('Verarbeite Mediencode...', 'warn');
const response = await fetch('/api/library_scan_action', { const response = await fetch('/api/library_scan_action', {
@@ -1695,7 +1810,6 @@
} }
function showSmallConfirm(message, kind='ok', action = null) { function showSmallConfirm(message, kind='ok', action = null) {
// Append the small helper text in German
const helper = 'Sie können fortfahren. Dies ist nur eine kleine Benachrichtigung.'; const helper = 'Sie können fortfahren. Dies ist nur eine kleine Benachrichtigung.';
const el = document.createElement('div'); const el = document.createElement('div');
el.className = `small-popup ${kind === 'error' ? 'error' : 'ok'}`; el.className = `small-popup ${kind === 'error' ? 'error' : 'ok'}`;
@@ -1720,12 +1834,10 @@
closeButton.innerHTML = '&times;'; closeButton.innerHTML = '&times;';
el.appendChild(closeButton); el.appendChild(closeButton);
document.body.appendChild(el); document.body.appendChild(el);
// close handler
closeButton.addEventListener('click', () => { closeButton.addEventListener('click', () => {
if (el && el.parentNode) el.parentNode.removeChild(el); if (el && el.parentNode) el.parentNode.removeChild(el);
}); });
// auto remove after 3 seconds setTimeout(() => { try { if (el && el.parentNode) el.parentNode.removeChild(el); } catch(e){} }, 15000);
setTimeout(() => { try { if (el && el.parentNode) el.parentNode.removeChild(el); } catch(e){} }, 3000);
} }
async function startNextStudentCardScan() { async function startNextStudentCardScan() {
@@ -1764,11 +1876,9 @@
const detailContent = document.getElementById('detailContent'); const detailContent = document.getElementById('detailContent');
const detailModal = document.getElementById('detailModal'); const detailModal = document.getElementById('detailModal');
// Lade-Status anzeigen und Modal öffnen
detailContent.innerHTML = '<p>Lade Details...</p>'; detailContent.innerHTML = '<p>Lade Details...</p>';
detailModal.style.display = 'flex'; detailModal.style.display = 'flex';
// Daten vom Backend-API-Endpoint abrufen
fetch(`/api/item_detail/${itemId}`) fetch(`/api/item_detail/${itemId}`)
.then(response => { .then(response => {
if (!response.ok) { if (!response.ok) {
@@ -1832,15 +1942,12 @@
}); });
} }
// Schließt das Modal über den 'x'-Button
function closeDetailModal() { function closeDetailModal() {
document.getElementById('detailModal').style.display = 'none'; document.getElementById('detailModal').style.display = 'none';
} }
// Closes the modal if the user clicks the dark background overlay
window.onclick = function(event) { window.onclick = function(event) {
const modal = document.getElementById('detailModal'); const modal = document.getElementById('detailModal');
// If the click happened directly on the dark overlay (not the white box)
if (event.target === modal) { if (event.target === modal) {
closeDetailModal(); closeDetailModal();
} }
@@ -1905,12 +2012,10 @@
} }
} }
// Run when DOM structure is entirely ready
document.addEventListener('DOMContentLoaded', async () => { document.addEventListener('DOMContentLoaded', async () => {
wireScannerUi(); // Setup scanner control buttons wireScannerUi();
loadLibraryItems(); // Fetch your database items right away! loadLibraryItems();
// Safely connect standard Filters and Search inputs inside DOMContentLoaded
const filterToggleBtn = document.getElementById('filterToggleBtn'); const filterToggleBtn = document.getElementById('filterToggleBtn');
if (filterToggleBtn) { if (filterToggleBtn) {
filterToggleBtn.addEventListener('click', () => { filterToggleBtn.addEventListener('click', () => {
@@ -1968,15 +2073,11 @@
return; return;
} }
// Leitet den manuellen Code an die zentrale Logik weiter,
// die prüft, welcher Modus im Dropdown aktiv ist.
handleScanSuccess(code); handleScanSuccess(code);
// Feld nach Eingabe leeren, um direkt den nächsten Code bereitzuhaben
manualItemCode.value = ''; manualItemCode.value = '';
}); });
// Optional: Auch auf "Enter" im Textfeld reagieren
manualItemCode.addEventListener('keypress', (e) => { manualItemCode.addEventListener('keypress', (e) => {
if (e.key === 'Enter') { if (e.key === 'Enter') {
e.preventDefault(); e.preventDefault();
+73 -5
View File
@@ -187,7 +187,11 @@
{% endif %} {% endif %}
<button type="button" class="btn btn-sm btn-outline-warning text-dark" <button type="button" class="btn btn-sm btn-outline-warning text-dark"
onclick="resetMahnung('{{ item.id }}', '{{ item.schueler_name }}')"> onclick="resetMahnung('{{ item.id }}', '{{ item.schueler_name }}')">
<i class="bi bi-arrow-counterclockwise"></i> Zurücksetzen <i class="bi bi-arrow-counterclockwise"></i> Zurücksetzen (14 Tage)
</button>
<button type="button" class="btn btn-sm btn-outline-warning text-dark"
onclick="resetMahnungCustom('{{ item.id }}', '{{ item.schueler_name }}')">
<i class="bi bi-arrow-counterclockwise"></i> Zurücksetzen mit eigener Frist
</button> </button>
</div> </div>
</td> </td>
@@ -210,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>
@@ -228,7 +232,7 @@
<input type="email" class="form-control" id="modalEmail" placeholder="E-Mail-Adresse eingeben..."> <input type="email" class="form-control" id="modalEmail" placeholder="E-Mail-Adresse eingeben...">
</div> </div>
<div class="mb-3"> <div class="mb-3">
<label for="modalMessage" class="form-label">Nachricht</label> <label for="modalMessage" class="form-label">Nachrichten-Text</label>
<textarea class="form-control" id="modalMessage" rows="4" placeholder="Optionaler Text..."></textarea> <textarea class="form-control" id="modalMessage" rows="4" placeholder="Optionaler Text..."></textarea>
</div> </div>
</form> </form>
@@ -241,6 +245,31 @@
</div> </div>
</div> </div>
<!-- Custom Reset Days Modal -->
<div class="modal fade" id="customResetModal" tabindex="-1" aria-labelledby="customResetModalLabel" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="customResetModalLabel">Mahnung zurücksetzen</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Schließen"></button>
</div>
<div class="modal-body">
<input type="hidden" id="resetModalLoanId">
<p>Möchten Sie die Mahnung für <strong id="resetModalStudentName"></strong> wirklich zurücksetzen?</p>
<p class="text-muted small">Dadurch wird die Mahnstufe auf 0 gesetzt und der Schülerausweis entsperrt.</p>
<div class="mb-3">
<label for="resetModalDays" class="form-label">Frist verlängern um (Tage):</label>
<input type="number" class="form-control" id="resetModalDays" value="14" min="1">
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Abbrechen</button>
<button type="button" class="btn btn-warning" onclick="submitCustomReset()">Mahnung zurücksetzen</button>
</div>
</div>
</div>
</div>
<script> <script>
function openEmailModal(loanId, studentName, studentEmail) { function openEmailModal(loanId, studentName, studentEmail) {
document.getElementById('modalLoanId').value = loanId; document.getElementById('modalLoanId').value = loanId;
@@ -292,7 +321,7 @@ function resetMahnung(loanId, studentName) {
const csrfToken = document.querySelector('meta[name="csrf-token"]')?.content || ''; const csrfToken = document.querySelector('meta[name="csrf-token"]')?.content || '';
fetch('/mahnungen_reset', { fetch('/mahnungen_reset/14', {
method: 'POST', method: 'POST',
headers: { 'Content-Type': 'application/json', 'X-CSRFToken': csrfToken }, headers: { 'Content-Type': 'application/json', 'X-CSRFToken': csrfToken },
body: JSON.stringify({ loan_id: loanId }) body: JSON.stringify({ loan_id: loanId })
@@ -301,7 +330,46 @@ function resetMahnung(loanId, studentName) {
.then(data => { .then(data => {
if (data.success) { if (data.success) {
alert(data.message); alert(data.message);
location.reload(); // Seite neu laden, um die aktualisierte Ansicht zu sehen location.reload();
} else {
alert('Fehler: ' + data.message);
}
})
.catch(error => {
alert('Fehler beim Senden der Anfrage.');
console.error(error);
});
}
function resetMahnungCustom(loanId, studentName) {
document.getElementById('resetModalLoanId').value = loanId;
document.getElementById('resetModalStudentName').textContent = studentName;
document.getElementById('resetModalDays').value = 14;
var customModal = new bootstrap.Modal(document.getElementById('customResetModal'));
customModal.show();
}
function submitCustomReset() {
const loanId = document.getElementById('resetModalLoanId').value;
const daysToExtend = parseInt(document.getElementById('resetModalDays').value, 10);
const csrfToken = document.querySelector('meta[name="csrf-token"]')?.content || '';
if (isNaN(daysToExtend) || daysToExtend < 1) {
alert('Bitte geben Sie eine gültige Anzahl an Tagen ein.');
return;
}
fetch(`/mahnungen_reset/${daysToExtend}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'X-CSRFToken': csrfToken },
body: JSON.stringify({ loan_id: loanId })
})
.then(response => response.json())
.then(data => {
if (data.success) {
alert(data.message);
location.reload();
} else { } else {
alert('Fehler: ' + data.message); alert('Fehler: ' + data.message);
} }
+529 -45
View File
@@ -1971,6 +1971,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; }
@@ -2343,7 +2459,7 @@ document.addEventListener('DOMContentLoaded', ()=>{
<div class="filter-container"> <div class="filter-container">
<div class="filter-group"> <div class="filter-group">
<div class="filter-header"> <div class="filter-header">
<label>{{ filter_names.get('2', 'Fach') }}</label> <label>{{ filter_names.get('1', 'Fach') }}</label>
<button type="button" class="filter-toggle" onclick="toggleFilterDropdown('filter1-dropdown')">▼</button> <button type="button" class="filter-toggle" onclick="toggleFilterDropdown('filter1-dropdown')">▼</button>
<button type="button" class="clear-filter" onclick="clearFilter(1)">Clear</button> <button type="button" class="clear-filter" onclick="clearFilter(1)">Clear</button>
</div> </div>
@@ -2357,7 +2473,7 @@ document.addEventListener('DOMContentLoaded', ()=>{
<div class="filter-group"> <div class="filter-group">
<div class="filter-header"> <div class="filter-header">
<label>{{ filter_names.get('1', 'Klassenstufe') }}</label> <label>{{ filter_names.get('2', 'Klassenstufe') }}</label>
<button type="button" class="filter-toggle" onclick="toggleFilterDropdown('filter2-dropdown')">▼</button> <button type="button" class="filter-toggle" onclick="toggleFilterDropdown('filter2-dropdown')">▼</button>
<button type="button" class="clear-filter" onclick="clearFilter(2)">Clear</button> <button type="button" class="clear-filter" onclick="clearFilter(2)">Clear</button>
</div> </div>
@@ -2420,8 +2536,8 @@ document.addEventListener('DOMContentLoaded', ()=>{
<div id="table-view-header" class="table-view-header" aria-hidden="true"> <div id="table-view-header" class="table-view-header" aria-hidden="true">
<span>Name</span> <span>Name</span>
<span>Ort</span> <span>Ort</span>
<span>{{ filter_names.get('2', 'Fach') }}</span> <span>{{ filter_names.get('1', 'Fach') }}</span>
<span>{{ filter_names.get('1', 'Jahrgangsstufe') }}</span> <span>{{ filter_names.get('2', 'Jahrgangsstufe') }}</span>
<span>{{ filter_names.get('3', 'Schlagwort') }}</span> <span>{{ filter_names.get('3', 'Schlagwort') }}</span>
<span>Barcode</span> <span>Barcode</span>
<span>Anzahl</span> <span>Anzahl</span>
@@ -3206,9 +3322,12 @@ 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
? `&search=${encodeURIComponent(searchTerm)}&search_scope=${encodeURIComponent(searchScope)}`
: '';
return fetch(`{{ url_for('get_items') }}?offset=${offset}&limit=${MAIN_ADMIN_ITEMS_PAGE_SIZE}&light_mode=true${searchParams}`)
.then(response => response.json()) .then(response => response.json())
.then(data => { .then(data => {
const itemsContainer = document.querySelector('#items-container'); const itemsContainer = document.querySelector('#items-container');
@@ -3241,7 +3360,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 +3404,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 => {
@@ -3394,9 +3514,9 @@ document.addEventListener('DOMContentLoaded', ()=>{
<div class="card-content" data-item-id="${item._id}"> <div class="card-content" data-item-id="${item._id}">
<h3 class="item-col-name">${item.Name}</h3> <h3 class="item-col-name">${item.Name}</h3>
<p class="item-col-location"><strong>Ort:</strong> ${item.Ort || '-'}</p> <p class="item-col-location"><strong>Ort:</strong> ${item.Ort || '-'}</p>
<p class="item-col-filter1"><strong>Unterrichtsfach:</strong> ${filter1Display}${filter1More}</p> <p class="item-col-filter1"><strong>{{ filter_names.get('1', 'Jahrgangsstufe') }}:</strong> ${filter1Display}${filter1More}</p>
<p class="item-col-filter2"><strong>Jahrgangsstufe:</strong> ${filter2Display}${filter2More}</p> <p class="item-col-filter2"><strong>{{ filter_names.get('2', 'Jahrgangsstufe') }}:</strong> ${filter2Display}${filter2More}</p>
<p class="item-col-filter3"><strong>Schlagwort:</strong> ${filter3Display}${filter3More}</p> <p class="item-col-filter3"><strong>{{ filter_names.get('3', 'Jahrgangsstufe') }}:</strong> ${filter3Display}${filter3More}</p>
<p class="item-col-code"><strong>Barcode:</strong> ${item.Code_4 || '-'}</p> <p class="item-col-code"><strong>Barcode:</strong> ${item.Code_4 || '-'}</p>
<p class="item-col-count"><strong>Anzahl:</strong> ${groupedCount}</p> <p class="item-col-count"><strong>Anzahl:</strong> ${groupedCount}</p>
${hasDamage ? `<div class="damage-badge">${damageCount > 0 ? `Schäden gemeldet: ${damageCount}` : 'Schäden gemeldet'}</div>` : ''} ${hasDamage ? `<div class="damage-badge">${damageCount > 0 ? `Schäden gemeldet: ${damageCount}` : 'Schäden gemeldet'}</div>` : ''}
@@ -3415,7 +3535,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 +3565,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 +3800,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 +3906,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 +3931,7 @@ document.addEventListener('DOMContentLoaded', ()=>{
} }
} else { } else {
item.style.display = 'none'; item.style.display = 'none';
syncSearchedGroupedAction(item, '', false);
} }
}); });
@@ -3830,7 +4006,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 +4015,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 +4028,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.
@@ -4063,21 +4230,29 @@ document.addEventListener('DOMContentLoaded', ()=>{
const badgeText = entry.type === 'repair' ? 'Repariert' : 'Schaden'; const badgeText = entry.type === 'repair' ? 'Repariert' : 'Schaden';
const metaLine = entry.meta ? `<div style="font-size:0.84rem;color:#4b5563;">${escapeHtml(entry.meta)}</div>` : ''; const metaLine = entry.meta ? `<div style="font-size:0.84rem;color:#4b5563;">${escapeHtml(entry.meta)}</div>` : '';
return ` return `
<div style="border:1px solid var(--ui-border);border-radius:8px;padding:10px;background:var(--ui-surface);display:grid;gap:6px;"> <div class="damage-history-entry ${entry.type === 'repair' ? 'is-repair' : 'is-report'}">
<div style="display:flex;flex-wrap:wrap;gap:8px;align-items:center;"> <div class="damage-history-entry-head">
<span style="display:inline-block;padding:2px 8px;border-radius:999px;font-size:0.75rem;font-weight:700;${badgeStyle}">${badgeText}</span> <span class="damage-history-badge" style="${badgeStyle}">${badgeText}</span>
<span style="font-size:0.84rem;color:#475569;">${entry.dateLabel}</span> <time>${entry.dateLabel}</time>
</div> </div>
<div style="font-size:0.9rem;color:#0f172a;"><strong>Von:</strong> ${entry.actor}</div> <div class="damage-history-actor"><strong>Von</strong>${entry.actor}</div>
<div style="font-size:0.92rem;color:#1f2937;">${entry.description}</div> <div class="damage-history-description">${entry.description}</div>
${metaLine} ${entry.meta ? `<div class="damage-history-meta">${escapeHtml(entry.meta)}</div>` : ''}
</div> </div>
`; `;
}).join('') }).join('')
: '<div style="font-size:0.92rem;color:#64748b;">Keine Beschädigungs-Historie vorhanden.</div>'; : '<div style="font-size:0.92rem;color:#64748b;">Keine Beschädigungs-Historie vorhanden.</div>';
modalContent.innerHTML = ` modalContent.innerHTML = `
<h2>${escapeHtml(item.Name || '')}</h2> <div class="item-modal-heading">
<div>
<span class="item-modal-eyebrow">Objektdetails</span>
<h2>${escapeHtml(item.Name || '')}</h2>
</div>
<span class="item-modal-status ${isBorrowed ? 'is-borrowed' : 'is-available'}">
<span class="item-modal-status-dot"></span>${isBorrowed ? 'Ausgeliehen' : 'Verfügbar'}
</span>
</div>
${borrowerInfoHtml} ${borrowerInfoHtml}
${appointmentInfoHtml} ${appointmentInfoHtml}
@@ -4090,7 +4265,7 @@ document.addEventListener('DOMContentLoaded', ()=>{
` : ''} ` : ''}
</div> </div>
<div class="modal-details"> <div class="modal-details item-modal-details">
<div class="detail-group"> <div class="detail-group">
<div class="detail-label">Ort:</div> <div class="detail-label">Ort:</div>
<div class="detail-value">${escapeHtml(item.Ort || '-')}</div> <div class="detail-value">${escapeHtml(item.Ort || '-')}</div>
@@ -4104,17 +4279,17 @@ document.addEventListener('DOMContentLoaded', ()=>{
</div> </div>
<div class="detail-group"> <div class="detail-group">
<div class="detail-label">Unterrichtsfach:</div> <div class="detail-label">{{ filter_names.get('1', 'Unterrichtsfach') }}:</div>
<div class="detail-value">${escapeHtml(filter1Array.join(', ') || '-')}</div> <div class="detail-value">${escapeHtml(filter1Array.join(', ') || '-')}</div>
</div> </div>
<div class="detail-group"> <div class="detail-group">
<div class="detail-label">Jahrgangsstufe:</div> <div class="detail-label">{{ filter_names.get('2', 'Jahrgangsstufe') }}:</div>
<div class="detail-value">${escapeHtml(filter2Array.join(', ') || '-')}</div> <div class="detail-value">${escapeHtml(filter2Array.join(', ') || '-')}</div>
</div> </div>
<div class="detail-group"> <div class="detail-group">
<div class="detail-label">Schlagwort:</div> <div class="detail-label">{{ filter_names.get('3', 'Schlagwort') }}:</div>
<div class="detail-value">${escapeHtml(filter3Array.join(', ') || '-')}</div> <div class="detail-value">${escapeHtml(filter3Array.join(', ') || '-')}</div>
</div> </div>
@@ -4145,22 +4320,22 @@ document.addEventListener('DOMContentLoaded', ()=>{
</div> </div>
{% if current_permissions.actions.get('can_view_logs', False) %} {% if current_permissions.actions.get('can_view_logs', False) %}
<div class="detail-group full-width" style="margin-top:12px;"> <div class="detail-group full-width item-modal-history" style="margin-top:12px;">
<div class="detail-label" style="font-weight:600; color:#374151;">Beschädigungs-Historie</div> <div class="detail-label" style="font-weight:600; color:#374151;">Beschädigungs-Historie</div>
<div class="detail-value"> <div class="detail-value">
<button id="toggle-damage-history" class="calendar-toggle-btn" style="margin-bottom:12px; padding:10px 16px; border-radius:6px; background:#f3f4f6; border:1px solid #d1d5db; font-weight:500; cursor:pointer; display:inline-flex; align-items:center; gap:8px; transition:all 0.2s ease;"> <button id="toggle-damage-history" class="calendar-toggle-btn modal-section-toggle" style="margin-bottom:12px;">
<span>🛠️</span> <span>🛠️</span>
<span id="toggle-damage-history-text">Historie anzeigen</span> <span id="toggle-damage-history-text">Historie anzeigen</span>
</button> </button>
<div id="damage-history-panel" style="display:none; margin-top:8px; border:1px solid #e7edf5; border-radius:10px; padding:12px; background: var(--ui-surface-soft);"> <div id="damage-history-panel" class="modal-history-panel" style="display:none;">
<div style="display:grid; gap:10px;">${damageHistoryHtml}</div> <div class="damage-history-list">${damageHistoryHtml}</div>
</div> </div>
</div> </div>
</div> </div>
{% endif %} {% endif %}
<div class="detail-group full-width" style="margin-top:12px; padding:10px; border:1px solid #e3e3e3; border-radius:8px;"> <div class="detail-group full-width" style="margin-top:12px; padding:10px; border:1px solid #e3e3e3; border-radius:8px;">
<div class="detail-label">Verfügbarkeit prüfen:</div> <div class="detail-label">Verfügbarkeit prüfen</div>
<div class="detail-value"> <div class="detail-value">
<div style="display:flex; flex-wrap:wrap; gap:8px; align-items:center;"> <div style="display:flex; flex-wrap:wrap; gap:8px; align-items:center;">
<input type="date" id="avail-date" style="padding:6px;"> <input type="date" id="avail-date" style="padding:6px;">
@@ -4180,10 +4355,10 @@ document.addEventListener('DOMContentLoaded', ()=>{
</div> </div>
</div> </div>
<div class="detail-group full-width" style="margin-top:15px;"> <div class="detail-group full-width item-modal-bookings" style="margin-top:15px;">
<div class="detail-label">Geplante Ausleihen:</div> <div class="detail-label">Geplante Ausleihen:</div>
<div class="detail-value"> <div class="detail-value">
<button id="toggle-bookings" class="calendar-toggle-btn" style="margin-bottom:12px; padding:10px 16px; border-radius:6px; background:#f3f4f6; border:1px solid #d1d5db; font-weight:500; cursor:pointer; display:inline-flex; align-items:center; gap:8px; transition:all 0.2s ease;"> <button id="toggle-bookings" class="calendar-toggle-btn modal-section-toggle" style="margin-bottom:12px;">
<span>📅</span> <span>📅</span>
<span id="toggle-bookings-text">Kalender anzeigen</span> <span id="toggle-bookings-text">Kalender anzeigen</span>
</button> </button>
@@ -5381,5 +5556,314 @@ document.addEventListener('DOMContentLoaded', ()=>{
border-radius: 10px !important; border-radius: 10px !important;
} }
} }
/* Detailed item modal: compact hierarchy and calm information density. */
#item-modal .modal-content {
width: min(94vw, 880px);
max-width: 880px;
margin: 4vh auto;
padding: 0;
max-height: 92vh;
overflow-x: hidden;
overflow-y: auto;
overscroll-behavior: contain;
-webkit-overflow-scrolling: touch;
border: 1px solid #d8e1eb;
border-radius: 16px;
background: var(--ui-surface);
box-shadow: 0 24px 70px rgba(15, 23, 42, 0.22);
}
#item-modal .modal-content > *:not(.item-modal-heading):not(.modal-image-container):not(.modal-details):not(.modal-actions) {
margin-left: 28px;
margin-right: 28px;
}
#item-modal .item-modal-heading {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 18px;
padding: 26px 30px 22px;
border-bottom: 1px solid #e6edf4;
background: linear-gradient(180deg, #f8fbfe 0%, var(--ui-surface) 100%);
}
#item-modal .item-modal-eyebrow {
display: block;
margin-bottom: 5px;
color: #708197;
font-size: 0.72rem;
font-weight: 800;
letter-spacing: 0.12em;
text-transform: uppercase;
}
#item-modal .item-modal-heading h2 {
margin: 0;
color: #172536;
font-size: clamp(1.25rem, 2.5vw, 1.7rem);
line-height: 1.2;
text-align: left;
overflow-wrap: anywhere;
}
#item-modal .item-modal-status {
display: inline-flex;
align-items: center;
gap: 7px;
flex: 0 0 auto;
margin-top: 5px;
padding: 6px 10px;
border: 1px solid;
border-radius: 999px;
font-size: 0.78rem;
font-weight: 800;
white-space: nowrap;
}
#item-modal .item-modal-status.is-available {
color: #17633b;
border-color: #b9e2ca;
background: #effaf3;
}
#item-modal .item-modal-status.is-borrowed {
color: #9b3d32;
border-color: #f2c5bf;
background: #fff4f2;
}
#item-modal .item-modal-status-dot {
width: 7px;
height: 7px;
border-radius: 50%;
background: currentColor;
}
#item-modal .modal-image-container {
min-height: 180px;
margin: 0;
padding: 22px 28px;
border-radius: 0;
background: #f4f7fa;
}
#item-modal .modal-image {
max-height: 320px;
border-radius: 10px;
box-shadow: 0 8px 24px rgba(15, 23, 42, 0.12);
}
#item-modal .item-modal-details {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 0 22px;
margin: 0;
padding: 24px 28px 4px;
}
#item-modal .item-modal-details .detail-group {
display: block;
min-width: 0;
margin: 0;
padding: 12px 0;
border-bottom: 1px solid #edf1f5;
}
#item-modal .item-modal-details .detail-label {
min-width: 0;
margin: 0 0 4px;
color: #718096;
font-size: 0.72rem;
font-weight: 800;
letter-spacing: 0.06em;
text-transform: uppercase;
}
#item-modal .item-modal-details .detail-value {
min-width: 0;
color: #243447;
font-size: 0.95rem;
line-height: 1.45;
overflow-wrap: anywhere;
}
#item-modal .item-modal-details .detail-group.full-width,
#item-modal .item-modal-details .item-modal-history,
#item-modal .item-modal-details .item-modal-bookings {
grid-column: 1 / -1;
}
#item-modal .item-modal-details .detail-group.full-width .detail-value {
padding: 12px 14px;
border: 1px solid #e1e8ef;
border-radius: 9px;
background: #f8fafc;
}
#item-modal .item-modal-details .item-modal-history,
#item-modal .item-modal-details .item-modal-bookings {
margin-top: 12px !important;
padding: 16px;
border: 1px solid #dfe7ef;
border-radius: 12px;
background: #fbfcfd;
}
#item-modal .modal-section-toggle {
min-height: 38px;
margin: 0 0 12px !important;
padding: 8px 12px;
border: 1px solid #cdd8e3;
border-radius: 8px;
background: var(--ui-surface);
color: #36516c;
font-size: 0.86rem;
font-weight: 750;
box-shadow: 0 1px 2px rgba(15, 23, 42, 0.04);
}
#item-modal .modal-section-toggle:hover {
border-color: #9db6cc;
background: #f1f6fa;
}
#item-modal .modal-history-panel {
margin-top: 4px;
padding: 12px;
border: 1px solid #e2e9f0;
border-radius: 10px;
background: #f5f8fb;
}
#item-modal .damage-history-list {
display: grid;
gap: 9px;
}
#item-modal .damage-history-entry {
position: relative;
display: grid;
gap: 7px;
padding: 12px 14px 12px 17px;
border: 1px solid #dce5ed;
border-radius: 9px;
background: var(--ui-surface);
}
#item-modal .damage-history-entry::before {
position: absolute;
inset: 0 auto 0 0;
width: 3px;
content: '';
border-radius: 9px 0 0 9px;
background: #e35d54;
}
#item-modal .damage-history-entry.is-repair::before {
background: #3aa76d;
}
#item-modal .damage-history-entry-head {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
}
#item-modal .damage-history-badge {
padding: 3px 8px;
border-radius: 999px;
font-size: 0.72rem;
font-weight: 800;
}
#item-modal .damage-history-entry time,
#item-modal .damage-history-meta {
color: #738196;
font-size: 0.78rem;
}
#item-modal .damage-history-actor {
display: flex;
gap: 5px;
color: #425466;
font-size: 0.84rem;
}
#item-modal .damage-history-actor strong {
color: #718096;
font-weight: 700;
}
#item-modal .damage-history-description {
color: #243447;
font-size: 0.91rem;
line-height: 1.4;
}
#item-modal .modal-actions {
justify-content: flex-end;
gap: 9px;
margin: 0;
padding: 18px 28px 24px;
border-top: 1px solid #e6edf4;
background: #fbfcfd;
}
@media (max-width: 640px) {
#item-modal .modal-content {
width: calc(100vw - 18px);
margin: 9px auto;
max-height: calc(100dvh - 18px);
overflow-y: auto;
border-radius: 13px;
}
#item-modal .item-modal-heading {
align-items: flex-start;
flex-direction: column;
gap: 10px;
padding: 21px 20px 17px;
}
#item-modal .item-modal-status {
margin-top: 0;
}
#item-modal .modal-image-container {
padding: 16px 18px;
}
#item-modal .item-modal-details {
grid-template-columns: 1fr;
gap: 0;
padding: 16px 18px 0;
}
#item-modal .item-modal-details .detail-group.full-width,
#item-modal .item-modal-details .item-modal-history,
#item-modal .item-modal-details .item-modal-bookings {
grid-column: auto;
}
#item-modal .item-modal-details .item-modal-history,
#item-modal .item-modal-details .item-modal-bookings {
padding: 13px;
}
#item-modal .modal-actions {
justify-content: stretch;
padding: 15px 18px 19px;
}
#item-modal .modal-actions > *,
#item-modal .modal-actions form,
#item-modal .modal-actions button {
flex: 1 1 100%;
width: 100%;
}
}
</style> </style>
{% endblock %} {% endblock %}
+2 -4
View File
@@ -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">
+7 -8
View File
@@ -88,11 +88,10 @@
<div class="password-rules" id="password-rules" aria-live="polite"> <div class="password-rules" id="password-rules" aria-live="polite">
<p class="password-rules-title">Passwort-Anforderungen:</p> <p class="password-rules-title">Passwort-Anforderungen:</p>
<ul> <ul>
<li id="pw-rule-length" class="pw-rule">Mindestens 12 Zeichen</li> <li id="pw-rule-length" class="pw-rule">Mindestens 5 Zeichen</li>
<li id="pw-rule-lower" class="pw-rule">Mindestens ein Kleinbuchstabe</li> <li id="pw-rule-lower" class="pw-rule">Mindestens ein Kleinbuchstabe</li>
<li id="pw-rule-upper" class="pw-rule">Mindestens ein Grossbuchstabe</li> <li id="pw-rule-upper" class="pw-rule">Mindestens ein Grossbuchstabe</li>
<li id="pw-rule-digit" class="pw-rule">Mindestens eine Zahl</li> <li id="pw-rule-digit" class="pw-rule">Mindestens eine Zahl</li>
<li id="pw-rule-symbol" class="pw-rule">Mindestens ein Sonderzeichen</li>
</ul> </ul>
</div> </div>
@@ -105,7 +104,7 @@
name="password" name="password"
placeholder="Geben Sie ein sicheres Passwort ein" placeholder="Geben Sie ein sicheres Passwort ein"
required required
pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[^a-zA-Z0-9]).{12,}"> pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{5,}">
<button type="button" id="toggle-pw-btn" class="toggle-pw-btn" onclick="togglePasswordVisibility()" style="background:none; border:none; cursor:pointer; padding-right:10px;">👁️</button> <button type="button" id="toggle-pw-btn" class="toggle-pw-btn" onclick="togglePasswordVisibility()" style="background:none; border:none; cursor:pointer; padding-right:10px;">👁️</button>
</div> </div>
</div> </div>
@@ -201,11 +200,11 @@ function generateUsername() {
// PASSWORT GENERATOR // PASSWORT GENERATOR
function generateSecurePassword() { function generateSecurePassword() {
const length = 16; const length = 5;
const charsetLower = "abcdefghijklmnopqrstuvwxyz"; const charsetLower = "abcdefghijklmnpqrstuvwxyz";
const charsetUpper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; const charsetUpper = "ABCDEFGHIJKLMNPQRSTUVWXYZ";
const charsetNum = "0123456789"; const charsetNum = "123456789";
const charsetSym = "!@#$%^&*()_+~|}{[]:;?><,.-="; const charsetSym = "!#$(),.=";
let password = ""; let password = "";
// Garantiert mindestens 1 Zeichen aus jeder Kategorie // Garantiert mindestens 1 Zeichen aus jeder Kategorie
+128 -15
View File
@@ -1,11 +1,3 @@
<!--
Copyright 2025-2026 AIIrondev
Licensed under the Inventarsystem EULA (Endbenutzer-Lizenzvertrag).
See Legal/LICENSE for the full license text.
Unauthorized commercial use, SaaS hosting, or removal of branding is prohibited.
For commercial licensing inquiries: https://github.com/AIIrondev
-->
{% extends "base.html" %} {% extends "base.html" %}
{% block title %}Bibliotheksausweise - Inventarsystem{% endblock %} {% block title %}Bibliotheksausweise - Inventarsystem{% endblock %}
@@ -21,7 +13,6 @@
gap: 15px; gap: 15px;
} }
/* Neu strukturiertes Layout für Formular & Import */
.dashboard-grid { .dashboard-grid {
display: grid; display: grid;
grid-template-columns: 2fr 1fr; grid-template-columns: 2fr 1fr;
@@ -145,6 +136,38 @@
background: #5a6268; background: #5a6268;
} }
/* Filter Controls Styling */
.filter-bar {
display: flex;
gap: 12px;
margin-bottom: 15px;
flex-wrap: wrap;
align-items: center;
background: var(--ui-bg);
padding: 12px;
border-radius: 8px;
border: 1px solid #ddd;
}
.filter-bar input,
.filter-bar select {
padding: 8px 12px;
border: 1px solid #ccc;
border-radius: 4px;
font-size: 14px;
}
.filter-bar input {
flex: 1;
min-width: 200px;
}
.filter-counter {
font-size: 13px;
color: #666;
margin-left: auto;
}
.cards-table { .cards-table {
width: 100%; width: 100%;
border-collapse: collapse; border-collapse: collapse;
@@ -255,7 +278,8 @@
} }
:root[data-theme="dark"] .student-card-form, :root[data-theme="dark"] .student-card-form,
:root[data-theme="dark"] .import-card { :root[data-theme="dark"] .import-card,
:root[data-theme="dark"] .filter-bar {
background: var(--ui-surface) !important; background: var(--ui-surface) !important;
color: var(--ui-text) !important; color: var(--ui-text) !important;
border-color: var(--ui-border) !important; border-color: var(--ui-border) !important;
@@ -269,7 +293,8 @@
:root[data-theme="dark"] .import-card p, :root[data-theme="dark"] .import-card p,
:root[data-theme="dark"] .rollover-hint, :root[data-theme="dark"] .rollover-hint,
:root[data-theme="dark"] .empty-state, :root[data-theme="dark"] .empty-state,
:root[data-theme="dark"] .empty-state p { :root[data-theme="dark"] .empty-state p,
:root[data-theme="dark"] .filter-counter {
color: var(--ui-text-muted) !important; color: var(--ui-text-muted) !important;
} }
@@ -286,6 +311,8 @@
:root[data-theme="dark"] .form-group input, :root[data-theme="dark"] .form-group input,
:root[data-theme="dark"] .form-group select, :root[data-theme="dark"] .form-group select,
:root[data-theme="dark"] .form-group textarea, :root[data-theme="dark"] .form-group textarea,
:root[data-theme="dark"] .filter-bar input,
:root[data-theme="dark"] .filter-bar select,
:root[data-theme="dark"] .export-buttons form, :root[data-theme="dark"] .export-buttons form,
:root[data-theme="dark"] .export-buttons select { :root[data-theme="dark"] .export-buttons select {
background: var(--ui-bg) !important; background: var(--ui-bg) !important;
@@ -297,6 +324,8 @@
:root[data-theme="dark"] .form-group input:focus, :root[data-theme="dark"] .form-group input:focus,
:root[data-theme="dark"] .form-group select:focus, :root[data-theme="dark"] .form-group select:focus,
:root[data-theme="dark"] .form-group textarea:focus, :root[data-theme="dark"] .form-group textarea:focus,
:root[data-theme="dark"] .filter-bar input:focus,
:root[data-theme="dark"] .filter-bar select:focus,
:root[data-theme="dark"] .export-buttons select:focus { :root[data-theme="dark"] .export-buttons select:focus {
border-color: #60a5fa !important; border-color: #60a5fa !important;
box-shadow: 0 0 0 3px rgba(96, 165, 250, 0.22) !important; box-shadow: 0 0 0 3px rgba(96, 165, 250, 0.22) !important;
@@ -334,6 +363,16 @@
.export-buttons > a { .export-buttons > a {
flex: 1 1 100%; flex: 1 1 100%;
} }
.filter-bar {
flex-direction: column;
align-items: stretch;
}
.filter-counter {
margin-left: 0;
text-align: right;
}
} }
@media (max-width: 992px) { @media (max-width: 992px) {
@@ -473,7 +512,9 @@
<div> <div>
<h3 style="margin:0 0 8px 0;">Excel-Import</h3> <h3 style="margin:0 0 8px 0;">Excel-Import</h3>
<p style="margin:0 0 12px 0; color:#555; font-size:13px; line-height:1.4;"> <p style="margin:0 0 12px 0; color:#555; font-size:13px; line-height:1.4;">
Laden Sie eine <strong>.xlsx</strong>- oder <strong>.csv</strong>-Datei hoch (z. B. aus <strong>ASV</strong>). Erkannt werden Name, Nachname, Klasse, Ausweis-ID, lokales Differenzierungsmerkmal, Notizen & Ausleihdauer. Laden Sie eine <strong>.xlsx</strong>- oder <strong>.csv</strong>-Datei hoch (z. B. aus <strong>ASV</strong>). Erkannt werden Rufame, Nachname, Klasse*, Ausweis-ID*, lokales Differenzierungsmerkmal*, Notizen* & Ausleihdauer*.
Hinweis: Die Daten werden Validiert und müssen dann noch einmal aus sicherheits gründen hochgeladen werden!
Im folgenden ist eine export vorlage für ihre ASV-Software hinterlegt: <a href="{{ url_for('get_asv_export') }}" target="_blank" style="color:#007bff; text-decoration:underline;">ASV Export Vorlage</a>
</p> </p>
</div> </div>
@@ -503,7 +544,20 @@
<div> <div>
<h2 style="margin-bottom: 15px;">Registrierte Ausweise</h2> <h2 style="margin-bottom: 15px;">Registrierte Ausweise</h2>
{% if student_cards %} {% if student_cards %}
<table class="cards-table"> <!-- Filter Options -->
<div class="filter-bar">
<input type="text" id="cardSearchInput" placeholder="🔍 Name oder Ausweis-ID suchen...">
<select id="classFilterSelect">
<option value="">Alle Klassen</option>
{% for cls in available_classes %}
<option value="{{ cls }}">{{ cls }}</option>
{% endfor %}
</select>
<button type="button" id="clearFilterBtn" class="btn-cancel" style="padding: 8px 12px; font-size: 13px;">Zurücksetzen</button>
<span class="filter-counter" id="filterCounter">Angezeigt: {{ student_cards|length }} / {{ student_cards|length }}</span>
</div>
<table class="cards-table" id="cardsTable">
<thead> <thead>
<tr> <tr>
<th>Ausweis-ID</th> <th>Ausweis-ID</th>
@@ -516,7 +570,7 @@
</thead> </thead>
<tbody> <tbody>
{% for card in student_cards %} {% for card in student_cards %}
<tr> <tr class="card-row" data-id="{{ card.AusweisId|lower }}" data-name="{{ card.SchülerName|lower }}" data-class="{{ card.Klasse or '' }}">
<td><strong>{{ card.AusweisId }}</strong></td> <td><strong>{{ card.AusweisId }}</strong></td>
<td>{{ card.SchülerName }}</td> <td>{{ card.SchülerName }}</td>
<td>{{ card.Klasse or '—' }}</td> <td>{{ card.Klasse or '—' }}</td>
@@ -529,6 +583,12 @@
<button type="submit" class="btn-edit">Bearbeiten</button> <button type="submit" class="btn-edit">Bearbeiten</button>
</form> </form>
<a href="{{ url_for('student_card_single_barcode_download', card_id=card._id) }}" class="btn-export">📥 PDF</a> <a href="{{ url_for('student_card_single_barcode_download', card_id=card._id) }}" class="btn-export">📥 PDF</a>
{% if email_service_enabled %}
<form method="POST" action="{{ url_for('student_card_single_barcode_download', card_id=card._id) }}" style="display:flex; gap:4px; align-items:center;">
<input type="email" name="recipient_email" required placeholder="E-Mail" aria-label="E-Mail für {{ card.SchülerName }}" style="width:150px; padding:5px;">
<button type="submit" class="btn-export">PDF senden</button>
</form>
{% endif %}
<form method="POST" style="display: inline;" onsubmit="return confirm('Wirklich löschen?');"> <form method="POST" style="display: inline;" onsubmit="return confirm('Wirklich löschen?');">
<input type="hidden" name="action" value="delete"> <input type="hidden" name="action" value="delete">
<input type="hidden" name="card_id" value="{{ card._id }}"> <input type="hidden" name="card_id" value="{{ card._id }}">
@@ -540,6 +600,10 @@
{% endfor %} {% endfor %}
</tbody> </tbody>
</table> </table>
<div id="noResultsMsg" class="empty-state" style="display: none;">
<p>Keine passende Ausweise für diesen Filter gefunden.</p>
</div>
{% else %} {% else %}
<div class="empty-state"> <div class="empty-state">
<p>Keine Bibliotheksausweise registriert.</p> <p>Keine Bibliotheksausweise registriert.</p>
@@ -551,7 +615,56 @@
<script src="https://cdn.jsdelivr.net/npm/qrcode.js"></script> <script src="https://cdn.jsdelivr.net/npm/qrcode.js"></script>
<script> <script>
// All PDF exports now go through backend routes document.addEventListener('DOMContentLoaded', function() {
const searchInput = document.getElementById('cardSearchInput');
const classSelect = document.getElementById('classFilterSelect');
const clearBtn = document.getElementById('clearFilterBtn');
const filterCounter = document.getElementById('filterCounter');
const rows = document.querySelectorAll('.card-row');
const noResultsMsg = document.getElementById('noResultsMsg');
const totalRows = rows.length;
function filterCards() {
const query = searchInput ? searchInput.value.toLowerCase().trim() : '';
const selectedClass = classSelect ? classSelect.value : '';
let visibleCount = 0;
rows.forEach(row => {
const id = row.getAttribute('data-id') || '';
const name = row.getAttribute('data-name') || '';
const cardClass = row.getAttribute('data-class') || '';
const matchesQuery = !query || id.includes(query) || name.includes(query);
const matchesClass = !selectedClass || cardClass === selectedClass;
if (matchesQuery && matchesClass) {
row.style.display = '';
visibleCount++;
} else {
row.style.display = 'none';
}
});
if (filterCounter) {
filterCounter.textContent = `Angezeigt: ${visibleCount} / ${totalRows}`;
}
if (noResultsMsg) {
noResultsMsg.style.display = (visibleCount === 0 && totalRows > 0) ? 'block' : 'none';
}
}
if (searchInput) searchInput.addEventListener('input', filterCards);
if (classSelect) classSelect.addEventListener('change', filterCards);
if (clearBtn) {
clearBtn.addEventListener('click', function() {
if (searchInput) searchInput.value = '';
if (classSelect) classSelect.value = '';
filterCards();
});
}
});
</script> </script>
{% endblock %} {% endblock %}
+6
View File
@@ -42,6 +42,12 @@
<a href="{{ url_for('terminplaner.export_pdf_brief', plan_id=plan_id) }}" class="btn btn-outline-success btn-sm"> <a href="{{ url_for('terminplaner.export_pdf_brief', plan_id=plan_id) }}" class="btn btn-outline-success btn-sm">
📄 Brief als PDF herunterladen 📄 Brief als PDF herunterladen
</a> </a>
{% if mail_service_enabled %}
<form method="post" action="{{ url_for('terminplaner.export_pdf_brief', plan_id=plan_id) }}" class="d-flex flex-wrap gap-2 mt-2">
<input type="email" name="recipient_email" required placeholder="Empfänger-E-Mail" aria-label="Empfänger-E-Mail für den Einladungsbrief" class="form-control" style="max-width:280px;">
<button type="submit" class="btn btn-outline-primary btn-sm">PDF per E-Mail senden</button>
</form>
{% endif %}
</div> </div>
{% if calendar_link %} {% if calendar_link %}
+34 -34
View File
@@ -738,7 +738,7 @@
{% if show_library_features %} {% if show_library_features %}
<div class="upload-import-panel" style="border:1px solid #dbe4ee; border-radius:8px; padding:14px; margin-bottom:16px; background:#f8fbff;"> <div class="upload-import-panel" style="border:1px solid #dbe4ee; border-radius:8px; padding:14px; margin-bottom:16px; background:#f8fbff;">
<h3 style="margin:0 0 8px 0;">Excel-Import Bibliothek (Mehrere Bücher)</h3> <h3 style="margin:0 0 8px 0;">Excel-Import Bibliothek (Mehrere Bücher)</h3>
<p style="margin:0 0 10px 0; color:#555;">Laden Sie eine <strong>.xlsx</strong>- oder <strong>.csv</strong>-Datei hoch. Spalten werden automatisch erkannt (z.B. Name, Ort, Beschreibung, ISBN, Code, Anzahl). Für den Bibliotheksimport ist eine gültige ISBN je Zeile erforderlich.</p> <p style="margin:0 0 10px 0; color:#555;">Laden Sie eine <strong>.xlsx</strong>- oder <strong>.csv</strong>-Datei hoch. Spalten werden automatisch erkannt (z.B. Name, Ort, Beschreibung, ISBN, Code, Anzahl). Für den Bibliotheksimport ist eine gültige ISBN je Zeile erforderlich. Hinweis: Die Daten werden Validiert und müssen dann noch einmal aus sicherheits gründen hochgeladen werden!</p>
<form method="POST" action="{{ url_for('upload_library_excel') }}" enctype="multipart/form-data" style="display:flex; gap:10px; flex-wrap:wrap; align-items:center;"> <form method="POST" action="{{ url_for('upload_library_excel') }}" enctype="multipart/form-data" style="display:flex; gap:10px; flex-wrap:wrap; align-items:center;">
<input type="file" name="library_excel" accept=".xlsx,.csv" required> <input type="file" name="library_excel" accept=".xlsx,.csv" required>
<button type="button" class="btn btn-link" onclick="downloadSampleCsv('library')">Beispiel-CSV herunterladen</button> <button type="button" class="btn btn-link" onclick="downloadSampleCsv('library')">Beispiel-CSV herunterladen</button>
@@ -750,7 +750,7 @@
{% else %} {% else %}
<div class="upload-import-panel" style="border:1px solid #dbe4ee; border-radius:8px; padding:14px; margin-bottom:16px; background:#f8fbff;"> <div class="upload-import-panel" style="border:1px solid #dbe4ee; border-radius:8px; padding:14px; margin-bottom:16px; background:#f8fbff;">
<h3 style="margin:0 0 8px 0;">Excel-Import Inventar (Mehrere Artikel)</h3> <h3 style="margin:0 0 8px 0;">Excel-Import Inventar (Mehrere Artikel)</h3>
<p style="margin:0 0 10px 0; color:#555;">Laden Sie eine <strong>.xlsx</strong>- oder <strong>.csv</strong>-Datei hoch. Spalten werden automatisch erkannt (z.B. Name, Ort, Beschreibung, Filter1/2/3, Kosten, Jahr, Code, Anzahl).</p> <p style="margin:0 0 10px 0; color:#555;">Laden Sie eine <strong>.xlsx</strong>- oder <strong>.csv</strong>-Datei hoch. Spalten werden automatisch erkannt (z.B. Name, Ort, Beschreibung, Filter1/2/3, Kosten, Jahr, Code, Anzahl). Hinweis: Die Daten werden Validiert und müssen dann noch einmal aus sicherheits gründen hochgeladen werden!</p>
<form method="POST" action="{{ url_for('upload_inventory_excel') }}" enctype="multipart/form-data" style="display:flex; gap:10px; flex-wrap:wrap; align-items:center;"> <form method="POST" action="{{ url_for('upload_inventory_excel') }}" enctype="multipart/form-data" style="display:flex; gap:10px; flex-wrap:wrap; align-items:center;">
<input type="file" name="inventory_excel" accept=".xlsx,.csv" required> <input type="file" name="inventory_excel" accept=".xlsx,.csv" required>
<button type="button" class="btn btn-link" onclick="downloadSampleCsv('inventory')">Beispiel-CSV herunterladen</button> <button type="button" class="btn btn-link" onclick="downloadSampleCsv('inventory')">Beispiel-CSV herunterladen</button>
@@ -865,38 +865,6 @@
<!-- Normal Item Mode: Standard Filters --> <!-- Normal Item Mode: Standard Filters -->
<div class="filter-inputs"> <div class="filter-inputs">
<h3>{{ filter_names.get('1', 'Jahrgangsstufe') }}</h3> <h3>{{ filter_names.get('1', 'Jahrgangsstufe') }}</h3>
<div class="multi-filter">
<div class="form-group">
<label for="filter1-1">Wert 1:</label>
<select id="filter1-1" name="filter" class="filter-dropdown-select" required>
<option value="">-- Bitte auswählen --</option>
<!-- Options will be loaded by JavaScript -->
</select>
</div>
<div class="form-group">
<label for="filter1-2">Wert 2:</label>
<select id="filter1-2" name="filter" class="filter-dropdown-select">
<option value="">-- Optional --</option>
<!-- Options will be loaded by JavaScript -->
</select>
</div>
<div class="form-group">
<label for="filter1-3">Wert 3:</label>
<select id="filter1-3" name="filter" class="filter-dropdown-select">
<option value="">-- Optional --</option>
<!-- Options will be loaded by JavaScript -->
</select>
</div>
<div class="form-group">
<label for="filter1-4">Wert 4:</label>
<select id="filter1-4" name="filter" class="filter-dropdown-select">
<option value="">-- Optional --</option>
<!-- Options will be loaded by JavaScript -->
</select>
</div>
</div>
<h3>{{ filter_names.get('2', 'Fachgebiet') }}</h3>
<div class="multi-filter"> <div class="multi-filter">
<div class="form-group"> <div class="form-group">
<label for="filter2-1">Wert 1:</label> <label for="filter2-1">Wert 1:</label>
@@ -928,6 +896,38 @@
</div> </div>
</div> </div>
<h3>{{ filter_names.get('2', 'Fachgebiet') }}</h3>
<div class="multi-filter">
<div class="form-group">
<label for="filter1-1">Wert 1:</label>
<select id="filter1-1" name="filter" class="filter-dropdown-select" required>
<option value="">-- Bitte auswählen --</option>
<!-- Options will be loaded by JavaScript -->
</select>
</div>
<div class="form-group">
<label for="filter1-2">Wert 2:</label>
<select id="filter1-2" name="filter" class="filter-dropdown-select">
<option value="">-- Optional --</option>
<!-- Options will be loaded by JavaScript -->
</select>
</div>
<div class="form-group">
<label for="filter1-3">Wert 3:</label>
<select id="filter1-3" name="filter" class="filter-dropdown-select">
<option value="">-- Optional --</option>
<!-- Options will be loaded by JavaScript -->
</select>
</div>
<div class="form-group">
<label for="filter1-4">Wert 4:</label>
<select id="filter1-4" name="filter" class="filter-dropdown-select">
<option value="">-- Optional --</option>
<!-- Options will be loaded by JavaScript -->
</select>
</div>
</div>
<h3>{{ filter_names.get('3', 'Schlagwort') }}</h3> <h3>{{ filter_names.get('3', 'Schlagwort') }}</h3>
<div class="multi-filter"> <div class="multi-filter">
<div class="form-group"> <div class="form-group">
+29 -2
View File
@@ -228,7 +228,12 @@
</div> </div>
<div class="mb-3"> <div class="mb-3">
<label for="new-password" class="form-label">Neues Passwort:</label> <label for="new-password" class="form-label">Neues Passwort:</label>
<input type="password" class="form-control" id="new-password" name="new_password" required> <div class="input-group">
<input type="password" class="form-control" id="new-password" name="new_password" required>
<button class="btn btn-outline-secondary" type="button" id="togglePasswordBtn" onclick="togglePasswordVisibility()">
Anzeigen
</button>
</div>
<div class="password-requirements small text-muted mt-1"> <div class="password-requirements small text-muted mt-1">
<p>Das Passwort muss mindestens 6 Zeichen lang sein.</p> <p>Das Passwort muss mindestens 6 Zeichen lang sein.</p>
</div> </div>
@@ -397,14 +402,36 @@
modal.show(); modal.show();
} }
function togglePasswordVisibility() {
var passwordInput = document.getElementById('new-password');
var toggleBtn = document.getElementById('togglePasswordBtn');
if (passwordInput.type === 'password') {
passwordInput.type = 'text';
toggleBtn.textContent = 'Verbergen';
} else {
passwordInput.type = 'password';
toggleBtn.textContent = 'Anzeigen';
}
}
function openResetPasswordModal(username) { function openResetPasswordModal(username) {
document.getElementById('reset-username').value = username; document.getElementById('reset-username').value = username;
document.getElementById('username-display').value = username; document.getElementById('username-display').value = username;
var passwordInput = document.getElementById('new-password');
var toggleBtn = document.getElementById('togglePasswordBtn');
// Reset password field state on modal open
passwordInput.value = '';
passwordInput.type = 'password';
if (toggleBtn) {
toggleBtn.textContent = 'Anzeigen';
}
var modal = new bootstrap.Modal(document.getElementById('resetPasswordModal')); var modal = new bootstrap.Modal(document.getElementById('resetPasswordModal'));
modal.show(); modal.show();
} }
function openPermissionsModal(button) { function openPermissionsModal(button) {
var username = button.getAttribute('data-username') || ''; var username = button.getAttribute('data-username') || '';
var preset = button.getAttribute('data-preset') || 'standard_user'; var preset = button.getAttribute('data-preset') || 'standard_user';