Compare commits

...

18 Commits

Author SHA1 Message Date
Aiirondev_dev cd03bbd2e5 feat(inventory): add repair resolution workflow and invoice correction logic
Release Inventarsystem / release-docker (push) Successful in 2m14s
- Add repair resolution mechanism (`resolve_repaired_item`) allowing users to:
  * Just repair: Return item to normal state (`Verfuegbar: True`)
  * Replace: Update `Code_4` (inventory/barcode) and restore availability
  * Delete: Remove item and update series counts (`SeriesCount`) and parent/child references
- Support `Code_4` updates in `update_item` for specific physical items
- Implement invoice correction route (`admin_add_invoice_correction`) with audit logging
- Add modal UI in library admin view to handle repair actions and code replacements
2026-08-19 22:05:32 +02:00
Aiirondev_dev 78c215b234 slight database mixup fix
Release Inventarsystem / release-docker (push) Successful in 2m44s
2026-08-19 20:14:23 +02:00
Aiirondev_dev 9e77b4604d slight database mixup fix
Release Inventarsystem / release-docker (push) Successful in 2m14s
2026-08-19 19:57:13 +02:00
Aiirondev_dev c06473644a slight database mixup fix
Release Inventarsystem / release-docker (push) Successful in 2m14s
2026-08-19 18:55:30 +02:00
Aiirondev_dev 6c855ed9d9 slight database mixup fix
Release Inventarsystem / release-docker (push) Successful in 2m15s
2026-08-19 18:49:36 +02:00
Aiirondev_dev b09a6f7720 slight database mixup fix
Release Inventarsystem / release-docker (push) Successful in 3m25s
2026-08-19 18:42:01 +02:00
Aiirondev_dev 8c5185bd8c Spelling mistakes and renaming done.
Release Inventarsystem / release-docker (push) Successful in 2m16s
2026-08-18 21:52:45 +02:00
Aiirondev_dev 0b30f8463f Renamed from Ausleihen, to Alle Ausleihen. in base.html
Release Inventarsystem / release-docker (push) Successful in 2m14s
2026-08-18 21:43:00 +02:00
Aiirondev_dev 671a9e8e85 Renaming of the ResetCardBtn to Feld zurücksetzen in regards to user comprehension.
Release Inventarsystem / release-docker (push) Successful in 2m26s
2026-08-18 21:31:52 +02:00
Aiirondev_dev 3d9e5c470a Fix of an issue with the data being use for the button insert
Release Inventarsystem / release-docker (push) Successful in 2m16s
2026-08-18 21:12:47 +02:00
Aiirondev_dev e636242542 fix for the cost button in the damaged items cost
Release Inventarsystem / release-docker (push) Successful in 2m16s
2026-08-18 21:00:14 +02:00
Aiirondev_dev d61aeebb8f Implementation of a extra button to add the complete replacement for the Bibliotheks item
Release Inventarsystem / release-docker (push) Successful in 2m14s
2026-08-18 20:37:04 +02:00
Aiirondev_dev 375e9c46eb slight fix of an import dubbeling
Release Inventarsystem / release-docker (push) Successful in 2m14s
2026-08-18 20:33:17 +02:00
Aiirondev 8dc773d202 README.md aktualisiert
Release Inventarsystem / release-docker (push) Successful in 2m45s
2026-08-18 17:59:25 +00:00
Aiirondev_dev 1b2b462c52 changes to the _upload student to have the field encryptet
Release Inventarsystem / release-docker (push) Successful in 2m17s
2026-08-18 18:51:49 +02:00
Aiirondev_dev bd7ef61f5a Initial implementation of a studentcard abgleich.
Release Inventarsystem / release-docker (push) Successful in 2m15s
2026-08-18 18:10:44 +02:00
Aiirondev_dev df0f7d3066 Style changes to the student Cards admin
Release Inventarsystem / release-docker (push) Successful in 2m18s
2026-08-18 17:06:24 +02:00
Aiirondev_dev 2215fc76d8 Style changes to the student Cards admin
Release Inventarsystem / release-docker (push) Successful in 2m14s
2026-08-18 17:01:09 +02:00
6 changed files with 642 additions and 296 deletions
+1 -1
View File
@@ -1,6 +1,6 @@
# Inventarsystem
[![https://github.com/AIIrondev/legendary-octo-garbanzo](https://github.com/AIIrondev/legendary-octo-garbanzo/actions/workflows/release-docker.yml/badge.svg)](https://github.com/AIIrondev/legendary-octo-garbanzo/actions/workflows/release-docker.yml)
[![https://git.invario-software.eu/Invario/Inventarsystem](https://git.invario-software.eu/Invario/Inventarsystem/actions/workflows/release-docker.yml/badge.svg)](https://git.invario-software.eu/Invario/Inventarsystem/actions/workflows/release-docker.yml)
[![wakatime](https://wakatime.com/badge/user/30b8509f-5e17-4d16-b6b8-3ca0f3f936d3/project/8a380b7f-389f-4a7e-8877-0fe9e1a4c243.svg)](https://wakatime.com/badge/user/30b8509f-5e17-4d16-b6b8-3ca0f3f936d3/project/8a380b7f-389f-4a7e-8877-0fe9e1a4c243)
+325 -130
View File
@@ -2150,9 +2150,8 @@ def generate_ausweis_id_excel(existing_ids_set):
else:
print(f"Already found: {new_id}, trying another...")
def _upload_student_cards_excel():
"""Bulk import student cards from Excel with automatic name/class mapping."""
"""Bulk import student cards from Excel with automatic name/class mapping, rollover support, and encryption."""
if 'username' not in session:
flash('Nicht angemeldet.', 'error')
return redirect(url_for('login'))
@@ -2177,6 +2176,8 @@ def _upload_student_cards_excel():
flash('Nur .xlsx oder .csv Dateien werden unterstützt.', 'error')
return redirect(url_for('student_cards_admin'))
rollover_mode = request.form.get('rollover_mode') in ['true', '1', 'on']
try:
header_row, data_rows = _load_tabular_upload(excel_file)
except Exception as exc:
@@ -2191,12 +2192,14 @@ def _upload_student_cards_excel():
synonyms = {
'ausweis_id': ['ausweis_id', 'ausweisid', 'ausweis-id', 'karte', 'kartennummer', 'card_id', 'id'],
'ausweis_ident': ['lokales Differenzierungsmerkmal', 'lokales differenzierungsmerkmal', 'lokales_differenzierungsmerkmal', 'ausweis_ident', 'differenzierungsmerkmal'],
'first_name': ['vorname', 'first_name', 'firstname', 'rufname', 'Vorname'],
'last_name': ['nachname', 'last_name', 'lastname', 'Nachname'],
'class_name': ['klasse', 'class', 'class_name', 'jahrgang', 'jahrgangsstufe', 'stufe', 'gruppe', 'asv_klasse', 'Jahrgang', 'Klasse'],
'notes': ['notizen', 'notes', 'bemerkungen', 'bemerkung', 'hinweis', 'hinweise', 'Notizen', 'Bemerkung', 'Hinweis', 'Hinweise'],
'default_borrow_days': ['standard_ausleihdauer', 'ausleihdauer', 'borrow_days', 'tage', 'leihtage', 'max_borrow_days', 'Ausleihdauer'],
'ausweis_ident': ['lokales differenzierungsmerkmal', 'lokales_differenzierungsmerkmal', 'ausweis_ident',
'differenzierungsmerkmal'],
'first_name': ['vorname', 'first_name', 'firstname', 'rufname'],
'last_name': ['nachname', 'last_name', 'lastname'],
'class_name': ['klasse', 'class', 'class_name', 'jahrgang', 'jahrgangsstufe', 'stufe', 'gruppe', 'asv_klasse'],
'notes': ['notizen', 'notes', 'bemerkungen', 'bemerkung', 'hinweis', 'hinweise'],
'default_borrow_days': ['standard_ausleihdauer', 'ausleihdauer', 'borrow_days', 'tage', 'leihtage',
'max_borrow_days'],
}
def col_index(key):
@@ -2227,8 +2230,9 @@ def _upload_student_cards_excel():
client = MongoClient(cfg.MONGODB_HOST, cfg.MONGODB_PORT)
try:
db = client[cfg.MONGODB_DB]
student_cards_cursor = db['student_cards'].find({}, {'AusweisId': 1})
student_cards_col = db['student_cards']
student_cards_cursor = student_cards_col.find({}, {'AusweisId': 1})
existing_ids.update(
str(card.get('AusweisId', '')).strip().upper()
for card in student_cards_cursor
@@ -2250,34 +2254,27 @@ def _upload_student_cards_excel():
ausweis_id = sanitize_form_value(val('ausweis_id'))
ausweis_ident = sanitize_form_value(val('ausweis_ident'))
class_name = sanitize_form_value(val('class_name'))
class_name = sanitize_form_value(val('class_name')) or ""
notes = sanitize_form_value(val('notes'))
# Ausleihdauer extrahieren und standardmäßig auf 14 setzen
default_borrow_days = _excel_int(val('default_borrow_days'))
if not default_borrow_days:
default_borrow_days = 14
# Vor- und Nachname sicher auslesen und zusammensetzen
default_borrow_days = _excel_int(val('default_borrow_days')) or 14
first_name = sanitize_form_value(val('first_name')) or ""
last_name = sanitize_form_value(val('last_name')) or ""
student_name = f"{first_name} {last_name}".strip()
# Leere Zeilen überspringen
if not ausweis_id and not student_name and not class_name:
continue
row_errors = []
if not student_name:
row_errors.append('Vorname und Nachname fehlen')
# Logik für die Haupt-AusweisID
if not ausweis_id and student_name:
ausweis_id = generate_ausweis_id(existing_ids)
validation_warnings.append((row_number, f'Ausweis-ID wurde automatisch erzeugt: {ausweis_id}'))
existing_ids.add(ausweis_id.upper())
elif ausweis_id:
existing_ids.add(ausweis_id.upper())
elif ausweis_id and not rollover_mode:
ausweis_id = str(ausweis_id).strip().upper()
if ausweis_id in existing_ids:
row_errors.append(f'Ausweis-ID {ausweis_id} existiert bereits')
@@ -2300,29 +2297,92 @@ def _upload_student_cards_excel():
'notes': notes,
'default_borrow_days': default_borrow_days,
})
finally:
client.close()
if validation_errors:
details = '; '.join([f'Zeile {n}: {msg}' for n, msg in validation_errors[:15]])
flash(f'Validierung fehlgeschlagen ({len(validation_errors)} Zeilen). {details}', 'error')
return redirect(url_for('student_cards_admin'))
if validation_errors:
details = '; '.join([f'Zeile {n}: {msg}' for n, msg in validation_errors[:15]])
flash(f'Validierung fehlgeschlagen ({len(validation_errors)} Zeilen). {details}', 'error')
return redirect(url_for('student_cards_admin'))
if validation_only:
warning_text = ''
if validation_warnings:
warning_details = '; '.join([f'Zeile {n}: {msg}' for n, msg in validation_warnings[:10]])
warning_text = f' Hinweise: {warning_details}'
flash(f'Validierung erfolgreich: {len(planned_rows)} Ausweise würden importiert.{warning_text}', 'success')
return redirect(url_for('student_cards_admin'))
matched_db_doc_ids = set()
rows_to_create = []
matched_count = 0
client = MongoClient(cfg.MONGODB_HOST, cfg.MONGODB_PORT)
try:
db = client[cfg.MONGODB_DB]
student_cards = db['student_cards']
if rollover_mode:
raw_db_cards = list(student_cards_col.find())
decrypted_db_cards = []
for doc in raw_db_cards:
dec_name = decrypt_text(doc.get('SchülerName')) if doc.get('SchülerName') else ""
dec_class = decrypt_text(doc.get('Klasse')) if doc.get('Klasse') else ""
raw_ident = doc.get('ausweis_ident') or doc.get('AusweisIdent') or ""
dec_ident = raw_ident
if raw_ident and str(raw_ident).startswith("gAAAAA"):
try:
dec_ident = decrypt_text(raw_ident)
except Exception:
pass
decrypted_db_cards.append({
'_id': doc['_id'],
'AusweisId': str(doc.get('AusweisId', '')).strip().upper(),
'AusweisIdent': str(dec_ident or '').strip().upper(),
'SchülerName': str(dec_name or '').strip().lower(),
'Klasse': str(dec_class or '').strip().lower(),
})
for excel_row in planned_rows:
ex_ident = str(excel_row['ausweis_ident'] or '').strip().upper()
ex_name = str(excel_row['student_name'] or '').strip().lower()
ex_class = str(excel_row['class_name'] or '').strip().lower()
match_found = None
for db_card in decrypted_db_cards:
if db_card['_id'] in matched_db_doc_ids:
continue
ident_matches = ex_ident and (ex_ident == db_card['AusweisIdent'])
secondary_matches = (ex_name and ex_name == db_card['SchülerName']) and \
(ex_class and ex_class == db_card['Klasse'])
if ident_matches or secondary_matches:
match_found = db_card
break
if match_found:
matched_db_doc_ids.add(match_found['_id'])
matched_count += 1
else:
rows_to_create.append(excel_row)
db_ids_to_delete = [
doc['_id'] for doc in raw_db_cards
if doc['_id'] not in matched_db_doc_ids
]
else:
rows_to_create = planned_rows
db_ids_to_delete = []
if validation_only:
warning_text = f" Hinweise: {'; '.join([f'Zeile {n}: {msg}' for n, msg in validation_warnings[:10]])}" if validation_warnings else ""
if rollover_mode:
flash(
f'Validierung erfolgreich ({len(planned_rows)} Excel-Zeilen). '
f'Abgleich-Vorschau: {matched_count} unverändert, {len(rows_to_create)} neu, {len(db_ids_to_delete)} zum Löschen.{warning_text}',
'success'
)
else:
flash(f'Validierung erfolgreich: {len(planned_rows)} Ausweise würden importiert.{warning_text}',
'success')
return redirect(url_for('student_cards_admin'))
deleted_count = 0
if db_ids_to_delete:
res = student_cards_col.delete_many({'_id': {'$in': db_ids_to_delete}})
deleted_count = res.deleted_count
created_total = 0
for row in planned_rows:
for row in rows_to_create:
encrypted_payload = encrypt_document_fields(
{
'ausweis_ident': row['ausweis_ident'],
@@ -2332,29 +2392,33 @@ def _upload_student_cards_excel():
},
STUDENT_CARD_ENCRYPTED_FIELDS
)
student_cards.insert_one({
student_cards_col.insert_one({
'AusweisId': row['ausweis_id'],
'StandardAusleihdauer': int(row['default_borrow_days']),
'Erstellt': datetime.datetime.now(),
**encrypted_payload,
})
created_total += 1
except Exception as exc:
app.logger.error(f'Error importing student cards from Excel: {exc}')
flash(f'Fehler beim Import der Bibliotheksausweise', 'error')
flash('Fehler beim Import der Bibliotheksausweise.', 'error')
return redirect(url_for('student_cards_admin'))
finally:
client.close()
if validation_warnings:
warning_details = '; '.join([f'Zeile {n}: {msg}' for n, msg in validation_warnings[:10]])
flash(f'Excel-Import erfolgreich: {created_total} Ausweise importiert. Hinweise: {warning_details}', 'warning')
warning_details = f" Hinweise: {'; '.join([f'Zeile {n}: {msg}' for n, msg in validation_warnings[:10]])}" if validation_warnings else ""
if rollover_mode:
flash(
f'Schuljahres-Abgleich erfolgreich: {matched_count} Schüler beibehalten, '
f'{created_total} neu hinzugefügt, {deleted_count} alte Einträge gelöscht.{warning_details}',
'success'
)
else:
flash(f'Excel-Import erfolgreich: {created_total} Ausweise importiert.', 'success')
flash(f'Excel-Import erfolgreich: {created_total} Ausweise importiert.{warning_details}', 'success')
return redirect(url_for('student_cards_admin'))
def _upload_excel_items(scope='inventory'):
"""Bulk import inventory/library items from Excel with validation-first workflow."""
if 'username' not in session:
@@ -3262,9 +3326,6 @@ def library_loans_admin():
_ensure_audit_indexes_once()
# IMPORT HINZUGEFÜGT: Entschlüsselungs-Tool importieren
from modules.inventarsystem.data_protection import decrypt_text
def fmt_dt(dt):
try:
return dt.strftime('%d.%m.%Y %H:%M') if dt else ''
@@ -3321,6 +3382,7 @@ def library_loans_admin():
'item_code': item_doc.get('Code_4', ''),
'item_author': item_doc.get('Author', ''),
'item_isbn': item_doc.get('ISBN', ''),
'item_cost_raw': item_doc.get('Anschaffungskosten', ''),
'user': decrypted_user,
'status': record.get('Status', ''),
'start': fmt_dt(record.get('Start')),
@@ -6681,7 +6743,6 @@ def mark_damage_repaired(id):
if result.matched_count == 0:
return jsonify({'success': False, 'message': 'Objekt nicht gefunden.'}), 404
# Best-effort system log entry for repair action
try:
logs_collection = db['system_logs']
logs_collection.insert_one({
@@ -8778,132 +8839,145 @@ def admin_mark_invoice_paid(borrow_id):
client.close()
@app.route('/admin/borrowings/<borrow_id>/invoice/finalize', methods=['POST'])
def admin_finalize_invoice_and_repair(borrow_id):
"""Mark invoice as paid and item as repaired in one action."""
@app.route('/admin/borrowings/<borrow_id>/invoice/pay', methods=['POST'])
def admin_mark_invoice_paid(borrow_id):
"""Mark invoice as paid."""
if 'username' not in session:
flash('Ihnen ist es nicht gestattet auf dieser Internetanwendung, die eben besuchte Adrrese zu nutzen, versuchen sie es erneut nach dem sie sich mit einem berechtigten Nutzer angemeldet haben!', 'error')
flash('Ihnen ist es nicht gestattet, versuchen sie es erneut nach Anmeldung!', 'error')
return redirect(url_for('login'))
current_permissions = us.get_effective_permissions(session['username'])
if not current_permissions['pages'].get('admin_borrowings', False):
flash('Ihnen fehlen die nötigen Berechtigungen, um diese Aktion auszuführen.', 'error')
return redirect(url_for('home_admin'))
flash('Ihnen fehlen die nötigen Berechtigungen.', 'error')
return redirect(request.referrer or url_for('home_admin'))
client = None
try:
client = MongoClient(MONGODB_HOST, MONGODB_PORT)
db = client[MONGODB_DB]
ausleihungen = db['ausleihungen']
items_col = db['items']
borrow_doc = ausleihungen.find_one({'_id': ObjectId(borrow_id)})
if not borrow_doc:
flash('Ausleihung nicht gefunden.', 'error')
return redirect(url_for('admin_borrowings'))
return redirect(request.referrer or url_for('admin_borrowings'))
invoice_data = borrow_doc.get('InvoiceData') or {}
if not invoice_data:
flash('Für diese Ausleihung existiert keine Rechnung.', 'warning')
return redirect(url_for('admin_borrowings'))
item_doc = None
item_id = borrow_doc.get('Item')
if item_id:
try:
item_doc = items_col.find_one({'_id': ObjectId(item_id)})
except Exception:
item_doc = items_col.find_one({'_id': item_id})
return redirect(request.referrer or url_for('admin_borrowings'))
now = datetime.datetime.now()
update_fields = {'LastUpdated': now}
update_fields = {
'LastUpdated': now,
}
# Rechnung auf bezahlt setzen
if invoice_data.get('paid') is not True:
update_fields.update({
'InvoiceData.paid': True,
'InvoiceData.paid_at': now,
'InvoiceData.paid_by': session.get('username', ''),
})
# Ausleihe abschließen, falls noch aktiv
if borrow_doc.get('Status') == 'active':
update_fields['Status'] = 'completed'
update_fields['End'] = now
ausleihungen.update_one({'_id': borrow_doc['_id']}, {'$set': update_fields})
repaired = False
resolved_count = 0
if item_doc:
open_reports = item_doc.get('DamageReports', []) or []
resolved_count = len(open_reports)
item_update = {
'$set': {
'DamageReports': [],
'HasDamage': False,
'Verfuegbar': True,
'LastUpdated': now,
},
'$unset': {
'User': '',
'Condition': '',
},
}
if open_reports:
repair_entry = {
'repaired_by': session['username'],
'repaired_at': now,
'resolved_reports': open_reports,
}
item_update['$push'] = {'DamageRepairs': {'$each': [repair_entry], '$position': 0}}
item_result = items_col.update_one({'_id': item_doc['_id']}, item_update)
repaired = item_result.matched_count > 0
# Logging
try:
logs_collection = db['system_logs']
logs_collection.insert_one({
'type': 'damage_invoice_finalize',
db['system_logs'].insert_one({
'type': 'invoice_paid',
'timestamp': now.isoformat(),
'user': session.get('username'),
'borrow_id': borrow_id,
'item_id': str(item_doc.get('_id')) if item_doc else '',
'invoice_number': invoice_data.get('invoice_number', ''),
'amount': invoice_data.get('amount'),
'repaired': repaired,
'resolved_damage_reports': resolved_count,
'ip': request.remote_addr,
})
except Exception as log_err:
app.logger.warning(f"Damage invoice finalize log write failed for borrow {borrow_id}: {log_err}")
app.logger.warning(f"Log failed: {log_err}")
_append_audit_event_standalone(
event_type='invoice_finalized_and_repaired',
event_type='invoice_paid',
payload={
'borrow_id': borrow_id,
'item_id': str(item_doc.get('_id')) if item_doc else '',
'invoice_number': invoice_data.get('invoice_number', ''),
'amount': invoice_data.get('amount'),
'repaired': repaired,
'resolved_damage_reports': resolved_count,
}
)
if repaired:
flash('Rechnung als bezahlt markiert und Element als repariert abgeschlossen.', 'success')
else:
flash('Rechnung als bezahlt markiert. Element konnte nicht repariert werden (nicht gefunden).', 'warning')
return redirect(url_for('admin_borrowings'))
flash('Rechnung erfolgreich als bezahlt markiert.', 'success')
return redirect(request.referrer or url_for('library_loans_admin'))
except Exception as e:
app.logger.error(f"Error finalizing invoice/repair for borrow {borrow_id}: {e}")
flash('Fehler beim Kombinieren von bezahlt und repariert.', 'error')
return redirect(url_for('admin_borrowings'))
app.logger.error(f"Error marking invoice paid for borrow {borrow_id}: {e}")
flash('Fehler beim Markieren als bezahlt.', 'error')
return redirect(request.referrer or url_for('library_loans_admin'))
finally:
if client:
client.close()
@app.route('/admin/items/<item_id>/repair', methods=['POST'])
def mark_damage_repaired(item_id):
"""Mark item as repaired and make it available again."""
if 'username' not in session:
return redirect(url_for('login'))
client = None
try:
client = MongoClient(MONGODB_HOST, MONGODB_PORT)
db = client[MONGODB_DB]
items_col = db['items']
try:
obj_id = ObjectId(item_id)
except Exception:
obj_id = item_id
item_doc = items_col.find_one({'_id': obj_id})
if not item_doc:
flash('Element nicht gefunden.', 'error')
return redirect(request.referrer or url_for('library_loans_admin'))
now = datetime.datetime.now()
open_reports = item_doc.get('DamageReports', []) or []
item_update = {
'$set': {
'DamageReports': [],
'HasDamage': False,
'Verfuegbar': True,
'LastUpdated': now,
},
'$unset': {
'User': '',
'Condition': '',
},
}
# Historie der Reparaturen speichern
if open_reports:
repair_entry = {
'repaired_by': session['username'],
'repaired_at': now,
'resolved_reports': open_reports,
}
item_update['$push'] = {'DamageRepairs': {'$each': [repair_entry], '$position': 0}}
items_col.update_one({'_id': item_doc['_id']}, item_update)
flash('Element wurde erfolgreich als repariert markiert und ist wieder verfügbar.', 'success')
return redirect(request.referrer or url_for('library_loans_admin'))
except Exception as e:
app.logger.error(f"Error repairing item {item_id}: {e}")
flash('Fehler bei der Reparatur.', 'error')
return redirect(request.referrer or url_for('library_loans_admin'))
finally:
if client:
client.close()
@app.route('/admin/borrowings/<borrow_id>/invoice/pdf', methods=['GET'])
def admin_view_invoice_pdf(borrow_id):
"""View a previously created invoice PDF for a borrowing."""
@@ -8964,15 +9038,19 @@ def admin_view_invoice_pdf(borrow_id):
def admin_add_invoice_correction(borrow_id):
"""Append an invoice correction entry without mutating the original invoice body."""
if 'username' not in session:
flash('Ihnen ist es nicht gestattet auf dieser Internetanwendung, die eben besuchte Adrrese zu nutzen, versuchen sie es erneut nach dem sie sich mit einem berechtigten Nutzer angemeldet haben!', 'error')
flash('Bitte melden Sie sich an, um auf diese Seite zuzugreifen.', 'error')
return redirect(url_for('login'))
current_permissions = us.get_effective_permissions(session['username'])
if not current_permissions['pages'].get('admin_borrowings', False):
flash('Ihnen fehlen die nötigen Berechtigungen, um diese Aktion auszuführen.', 'error')
return redirect(url_for('home_admin'))
if not ObjectId.is_valid(borrow_id):
flash('Ungültige Ausleih-ID.', 'error')
return redirect(url_for('admin_borrowings'))
client = None
try:
client = MongoClient(MONGODB_HOST, MONGODB_PORT)
@@ -9002,6 +9080,7 @@ def admin_add_invoice_correction(borrow_id):
now = datetime.datetime.now()
correction_number = f"CORR-{now.strftime('%Y%m%d-%H%M%S')}-{str(borrow_doc.get('_id'))[-6:].upper()}"
correction_entry = {
'correction_number': correction_number,
'reason': correction_reason,
@@ -9033,6 +9112,7 @@ def admin_add_invoice_correction(borrow_id):
flash('Korrekturbuchung wurde revisionssicher ergänzt.', 'success')
return redirect(url_for('admin_borrowings'))
except Exception as e:
app.logger.error(f"Error creating invoice correction for borrow {borrow_id}: {e}")
flash('Fehler beim Anlegen der Korrekturbuchung.', 'error')
@@ -9042,17 +9122,121 @@ def admin_add_invoice_correction(borrow_id):
client.close()
def resolve_repaired_item(item_id, action, new_code_4="", current_user="admin"):
"""
Verarbeitet Items aus der Reparatur und aktualisiert die Serien-Counts
sowie Parent/Child-Abhängigkeiten beim Löschen korrekt.
"""
if not ObjectId.is_valid(item_id):
return False, "Ungültige Item-ID."
try:
with MongoClient(cfg.MONGODB_HOST, cfg.MONGODB_PORT) as client:
db = client[cfg.MONGODB_DB]
items = db['items']
item = items.find_one({'_id': ObjectId(item_id)})
if not item:
return False, "Item nicht in der Datenbank gefunden."
series_group_id = item.get('SeriesGroupId')
# --- OPTION 1: DELETE ---
if action == 'delete':
is_parent = not item.get('IsGroupedSubItem')
if is_parent and series_group_id:
sibling = items.find_one({
'SeriesGroupId': series_group_id,
'_id': {'$ne': ObjectId(item_id)},
'Deleted': {'$ne': True}
})
if sibling:
new_parent_id_str = str(sibling['_id'])
# 1. Mache das Geschwister-Item zum neuen Parent
items.update_one(
{'_id': sibling['_id']},
{'$set': {
'IsGroupedSubItem': False,
'ParentItemId': None
}}
)
# 2. Leite alle anderen verbleibenden Sub-Items auf den neuen Parent um
items.update_many(
{
'SeriesGroupId': series_group_id,
'_id': {'$nin': [ObjectId(item_id), sibling['_id']]}
},
{'$set': {'ParentItemId': new_parent_id_str}}
)
# Physisch aus der Datenbank löschen (Hard Delete)
items.delete_one({'_id': ObjectId(item_id)})
# ALTERNATIVE (Soft Delete have to see if it makes sense):
# now = datetime.datetime.now()
# items.update_one(
# {'_id': ObjectId(item_id)},
# {'$set': {'Deleted': True, 'DeletedAt': now, 'DeletedBy': current_user}}
# )
# SeriesCount bei ALLEN verbleibenden Items dieser Serie um 1 reduzieren
if series_group_id:
items.update_many(
{'SeriesGroupId': series_group_id},
{'$inc': {'SeriesCount': -1}}
)
return True, "Item wurde gelöscht und der Bestand aller Serien-Items angepasst."
# --- OPTION 2: REPLACE ---
elif action == 'replace':
items.update_one(
{'_id': ObjectId(item_id)},
{'$set': {
'Code_4': str(new_code_4).strip(),
'Verfuegbar': True,
'LastUpdated': datetime.datetime.now()
}}
)
return True, f"Item wurde ersetzt. Neuer Code 4 zugewiesen: {new_code_4}."
# --- OPTION 3: JUST REPAIR ---
elif action == 'repair':
items.update_one(
{'_id': ObjectId(item_id)},
{'$set': {
'Verfuegbar': True,
'LastUpdated': datetime.datetime.now()
}}
)
return True, "Item wurde repariert und ist wieder regulär verfügbar."
else:
return False, "Ungültige Aktion ausgewählt."
except Exception as e:
print(f"Error resolving repair for item {item_id}: {e}")
return False, "Ein Datenbankfehler ist aufgetreten."
@app.route('/admin/library/items/<item_id>/invoices', methods=['GET'])
def library_item_invoices(item_id):
"""Show all stored invoices for one specific library item."""
if 'username' not in session:
flash('Ihnen ist es nicht gestattet auf dieser Internetanwendung, die eben besuchte Adrrese zu nutzen, versuchen sie es erneut nach dem sie sich mit einem berechtigten Nutzer angemeldet haben!', 'error')
flash(
'Ihnen ist es nicht gestattet auf dieser Internetanwendung, die eben besuchte Adrrese zu nutzen, versuchen sie es erneut nach dem sie sich mit einem berechtigten Nutzer angemeldet haben!',
'error')
return redirect(url_for('login'))
if not cfg.MODULES.is_enabled('library'):
flash('Bibliotheks-Modul ist deaktiviert.', 'error')
return redirect(url_for('home_admin'))
current_permissions = us.get_effective_permissions(session['username'])
if not current_permissions['pages'].get('library_loans_admin', False):
flash('Ihnen fehlen die nötigen Berechtigungen, um diese Aktion auszuführen.', 'error')
return redirect(url_for('library_view'))
@@ -9073,9 +9257,12 @@ def library_item_invoices(item_id):
flash('Bibliotheksmedium nicht gefunden.', 'error')
return redirect(url_for('library_loans_admin'))
item_id_obj = item_doc.get('_id')
item_id_str = str(item_id_obj)
borrow_docs = list(ausleihungen.find(
{
'Item': str(item_doc.get('_id')),
'Item': {'$in': [item_id_str, item_id_obj]},
'InvoiceData': {'$exists': True, '$ne': {}}
},
{
@@ -9090,19 +9277,27 @@ def library_item_invoices(item_id):
entries = []
for borrow_doc in borrow_docs:
invoice_data = borrow_doc.get('InvoiceData') or {}
created_at = invoice_data.get('created_at')
created_at_display = created_at.strftime('%d.%m.%Y %H:%M') if isinstance(created_at, datetime.datetime) else (str(created_at) if created_at else '')
created_at_display = created_at.strftime('%d.%m.%Y %H:%M') if isinstance(created_at,
datetime.datetime) else (
str(created_at) if created_at else '')
paid_at = invoice_data.get('paid_at')
paid_at_display = paid_at.strftime('%d.%m.%Y %H:%M') if isinstance(paid_at, datetime.datetime) else (str(paid_at) if paid_at else '')
paid_at_display = paid_at.strftime('%d.%m.%Y %H:%M') if isinstance(paid_at, datetime.datetime) else (
str(paid_at) if paid_at else '')
entries.append({
'borrow_id': str(borrow_doc.get('_id')),
'borrow_status': borrow_doc.get('Status', ''),
'borrow_user': borrow_doc.get('User', ''),
'borrow_start': borrow_doc.get('Start').strftime('%d.%m.%Y %H:%M') if isinstance(borrow_doc.get('Start'), datetime.datetime) else '',
'borrow_end': borrow_doc.get('End').strftime('%d.%m.%Y %H:%M') if isinstance(borrow_doc.get('End'), datetime.datetime) else '',
'borrow_start': borrow_doc.get('Start').strftime('%d.%m.%Y %H:%M') if isinstance(
borrow_doc.get('Start'), datetime.datetime) else '',
'borrow_end': borrow_doc.get('End').strftime('%d.%m.%Y %H:%M') if isinstance(borrow_doc.get('End'),
datetime.datetime) else '',
'invoice_number': invoice_data.get('invoice_number', ''),
'invoice_amount': _format_money_value(invoice_data.get('amount')),
'invoice_amount': _format_money_value(invoice_data.get('amount')) if hasattr(invoice_data,
'get') else '0,00',
'invoice_reason': invoice_data.get('damage_reason', ''),
'invoice_created_at': created_at_display,
'invoice_created_by': invoice_data.get('created_by', ''),
@@ -9125,6 +9320,7 @@ def library_item_invoices(item_id):
student_cards_module_enabled=cfg.MODULES.is_enabled('student_cards'),
mail_module_enabled=cfg.MODULES.is_enabled('mail')
)
except Exception as e:
app.logger.error(f"Error loading invoice history for item {item_id}: {e}")
flash('Fehler beim Laden der Rechnungshistorie.', 'error')
@@ -9133,7 +9329,6 @@ def library_item_invoices(item_id):
if client:
client.close()
@app.route('/admin_reset_user_password', methods=['POST'])
def admin_reset_user_password():
"""
+3 -3
View File
@@ -1261,10 +1261,10 @@
<li><a class="dropdown-item" href="{{ url_for('admin_school_settings') }}">Schulstammdaten</a></li>
{% endif %}
{% if current_permissions.pages.get('admin_borrowings', False) %}
<li><a class="dropdown-item" href="{{ url_for('admin_borrowings') }}">Ausleihen</a></li>
<li><a class="dropdown-item" href="{{ url_for('admin_borrowings') }}">Alle Ausleihen</a></li>
{% endif %}
{% if current_permissions.pages.get('admin_damaged_items', False) %}
<li><a class="dropdown-item" href="{{ url_for('admin_damaged_items') }}">Defekte Items</a></li>
<li><a class="dropdown-item" href="{{ url_for('admin_damaged_items') }}">Alle defekten Items</a></li>
{% endif %}
{% if current_permissions.actions.get('can_view_logs', False) and current_permissions.pages.get('admin_audit_dashboard', False) %}
<li><a class="dropdown-item" href="{{ url_for('admin_audit_dashboard') }}">Audit Dashboard</a></li>
@@ -1372,7 +1372,7 @@
{% if 'username' in session and current_permissions.actions.get('can_manage_settings', False) %}
<li><h6 class="dropdown-header">Bibliotheks-Verwaltung</h6></li>
{% if current_permissions.pages.get('library_loans_admin', False) %}
<li><a class="dropdown-item" href="{{ url_for('library_loans_admin') }}">Ausleihen / Defekte Items</a></li>
<li><a class="dropdown-item" href="{{ url_for('library_loans_admin') }}">Alle Ausleihen/Alle Defekten Items</a></li>
{% endif %}
{% if student_cards_module_enabled %}
{% if current_permissions.actions.get('can_manage_users', False) %}
+134 -68
View File
@@ -154,6 +154,7 @@
display: flex;
flex-wrap: wrap;
gap: 8px;
align-items: center;
}
.row-actions form {
@@ -196,7 +197,7 @@
<div class="library-admin-hero">
<div>
<h1>Bibliotheks-Ausleihen</h1>
<p>Nur Bibliotheksmedien. Hier kannst du offene Ausleihen abschließen, Rechnungen bezahlen und defekte Medien direkt zurücksetzen.</p>
<p>Nur Bibliotheksmedien. Hier kannst du offene Ausleihen abschließen, Rechnungen bezahlen und defekte Medien verwalten.</p>
</div>
<div class="hero-actions">
<a class="btn btn-secondary" href="{{ url_for('library_view') }}">Bibliothek öffnen</a>
@@ -215,7 +216,7 @@
<div class="value">{{ damaged_items|length }}</div>
</div>
<div class="summary-card">
<span class="label">Direkt reparierbar</span>
<span class="label">Direkt bearbeitbar</span>
<div class="value">{{ damaged_items|length }}</div>
</div>
</div>
@@ -311,35 +312,29 @@
{% if e.status == 'active' %}
<button type="button" class="btn btn-outline-danger btn-sm" onclick="openDamageReportPrompt(this)">Schaden melden</button>
{% endif %}
{% if e.invoice_number and ((not e.invoice_paid) or e.has_damage) %}
<form method="post" action="{{ url_for('admin_finalize_invoice_and_repair', borrow_id=e.id) }}" onsubmit="return confirm('Rechnung als bezahlt und Element als repariert markieren?');">
<button type="submit" class="btn btn-success btn-sm">
{% if not e.invoice_paid and e.has_damage %}
Bezahlt + repariert
{% elif not e.invoice_paid %}
Als bezahlt markieren
{% else %}
Als repariert markieren
{% endif %}
</button>
</form>
{% elif e.has_damage %}
<form method="post" action="{{ url_for('mark_damage_repaired', id=e.item_id) }}" onsubmit="return confirm('Medium als repariert markieren?');">
<button type="submit" class="btn btn-success btn-sm">Als repariert markieren</button>
{% if e.invoice_number and not e.invoice_paid %}
<form method="post" action="{{ url_for('admin_mark_invoice_paid', borrow_id=e.id) }}" onsubmit="return confirm('Rechnung als bezahlt markieren?');">
<button type="submit" class="btn btn-success btn-sm">Als bezahlt markieren</button>
</form>
{% endif %}
{% 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>
{% 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?');">
<input type="text" name="correction_reason" placeholder="Korrekturgrund" required style="padding:6px; border:1px solid #ddd; border-radius:6px; min-width:140px;">
<input type="text" name="amount_delta" placeholder="Delta optional" style="padding:6px; border:1px solid #ddd; border-radius:6px; width:120px;">
<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'] %}
<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-warning btn-sm">Zurücksetzen</button>
<button type="submit" class="btn btn-secondary btn-sm">Zurücksetzen</button>
</form>
{% endif %}
</div>
@@ -392,9 +387,8 @@
<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>
</div>
<form method="post" action="{{ url_for('mark_damage_repaired', id=item.id) }}" onsubmit="return confirm('Dieses Medium als repariert und wieder verfügbar markieren?');">
<button type="submit" class="btn btn-success btn-sm">Als repariert markieren</button>
</form>
<!-- Aufruf des Reparatur-Auswahl-Modals -->
<button type="button" class="btn btn-warning btn-sm" onclick="openRepairModal('{{ item.id }}', '{{ item.code }}')">Reparieren / Ersetzen</button>
</td>
</tr>
{% endfor %}
@@ -407,14 +401,15 @@
</div>
</div>
<div id="damage-invoice-modal" style="display:none; position:fixed; inset:0; background:rgba(15,23,42,0.72); z-index:9999; padding:20px; overflow:auto;">
<!-- Modal: Rechnung für Schaden erstellen -->
<div id="damage-invoice-modal" role="dialog" aria-modal="true" aria-labelledby="modal-title" style="display:none; position:fixed; inset:0; background:rgba(15,23,42,0.72); z-index:9999; padding:20px; overflow:auto;">
<div style="max-width:760px; margin:40px auto; background: var(--ui-surface); border-radius:12px; padding:24px; box-shadow:0 20px 60px rgba(0,0,0,0.3);">
<div style="display:flex; justify-content:space-between; align-items:center; gap:12px; margin-bottom:18px;">
<div>
<h2 style="margin:0;">Rechnung erstellen</h2>
<h2 id="modal-title" style="margin:0;">Rechnung erstellen</h2>
<p style="margin:6px 0 0; color:#666;">Die Rechnung nutzt das bestehende Rechnungssystem und kann direkt nach der Schadensmeldung erstellt werden.</p>
</div>
<button type="button" class="btn btn-secondary" onclick="closeDamageInvoiceModal()">Schließen</button>
<button type="button" class="btn btn-secondary" onclick="closeDamageInvoiceModal()" aria-label="Modal schließen">Schließen</button>
</div>
<form id="damage-invoice-form" method="post" action="">
@@ -432,7 +427,10 @@
<input id="damage-invoice-code" type="text" readonly style="width:100%; padding:10px; border:1px solid #ddd; border-radius:6px; background: var(--ui-surface-soft);">
</div>
<div>
<label for="damage-invoice-amount" style="display:block; font-weight:700; margin-bottom:6px;">Preis</label>
<div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:6px;">
<label for="damage-invoice-amount" style="font-weight:700; margin:0;">Preis</label>
<button type="button" id="damage-invoice-replace-btn" class="btn btn-outline-secondary btn-sm" style="padding: 2px 8px; font-size: 0.75rem;">Komplett ersetzen</button>
</div>
<input id="damage-invoice-amount" name="invoice_amount" type="text" required style="width:100%; padding:10px; border:1px solid #ddd; border-radius:6px;" placeholder="z.B. 12,50">
</div>
</div>
@@ -461,6 +459,33 @@
</div>
</div>
<!-- Neues Modal: Reparatur-Optionen (Reparieren, Ersetzen mit neuem Code_4, Löschen) -->
<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="display:flex; justify-content:space-between; align-items:center; gap:12px; margin-bottom:16px;">
<h2 id="repair-modal-title" style="margin:0; font-size: 1.3rem;">Medium-Bearbeitung nach Reparatur</h2>
<button type="button" class="btn btn-secondary btn-sm" onclick="closeRepairModal()">Schließen</button>
</div>
<p style="color: #666; margin-bottom: 18px; font-size: 0.95rem;">Wähle aus, wie mit diesem beschädigten Medium weiter verfahren werden soll:</p>
<form id="repair-action-form" method="post" action="">
<input type="hidden" name="action" id="repair-action-input" value="repair">
<div style="margin-bottom: 16px; display: none;" id="new-code-container">
<label for="modal-new-code-4" style="display:block; font-weight:700; margin-bottom:6px;">Neuer Code 4 (Inventarnummer / Barcode)</label>
<input type="text" id="modal-new-code-4" name="new_code_4" placeholder="Neuen Code 4 eingeben..." style="width:100%; padding:10px; border:1px solid #ddd; border-radius:6px;">
</div>
<div style="display: flex; flex-direction: column; gap: 10px;">
<button type="button" class="btn btn-success" onclick="submitRepairAction('repair')">Nur Reparieren (Wieder verfügbar machen)</button>
<button type="button" class="btn btn-primary" onclick="toggleReplaceMode()">Ersetzen (Neuen Code 4 zuweisen)</button>
<button type="submit" id="submit-replace-btn" class="btn btn-primary" style="display:none;" onclick="document.getElementById('repair-action-input').value='replace'; return confirm('Medium wirklich mit neuem Code aktualisieren?');">Änderung speichern</button>
<button type="submit" class="btn btn-danger" onclick="document.getElementById('repair-action-input').value='delete'; return confirm('Achtung: Soll dieses Medium wirklich gelöscht und der Bestand aktualisiert werden?');">Löschen & Bestand anpassen</button>
</div>
</form>
</div>
</div>
<script>
(function() {
const searchInput = document.getElementById('library-search');
@@ -470,6 +495,7 @@
const damagedRows = Array.from(document.querySelectorAll('.damaged-row'));
const loansEmpty = document.getElementById('loans-empty');
const damagedEmpty = document.getElementById('damaged-empty');
const damageInvoiceModal = document.getElementById('damage-invoice-modal');
const damageInvoiceForm = document.getElementById('damage-invoice-form');
const damageInvoiceItem = document.getElementById('damage-invoice-item');
@@ -477,61 +503,94 @@
const damageInvoiceCode = document.getElementById('damage-invoice-code');
const damageInvoiceAmount = document.getElementById('damage-invoice-amount');
const damageInvoiceReason = document.getElementById('damage-invoice-reason');
const damageInvoiceReplaceBtn = document.getElementById('damage-invoice-replace-btn');
// Funktionen für das Reparatur-Modal
window.openRepairModal = function(itemId, currentCode) {
const modal = document.getElementById('repair-action-modal');
const form = document.getElementById('repair-action-form');
const codeContainer = document.getElementById('new-code-container');
const replaceBtn = document.getElementById('submit-replace-btn');
// Setze die Route im Formular (passe hier den Endpunkt an deine Backend-Route an, z.B. /admin/items/ID/resolve_repair)
form.action = `/admin/items/${itemId}/resolve_repair`;
document.getElementById('repair-action-input').value = 'repair';
document.getElementById('modal-new-code-4').value = currentCode || '';
codeContainer.style.display = 'none';
replaceBtn.style.display = 'none';
modal.style.display = 'block';
};
window.closeRepairModal = function() {
document.getElementById('repair-action-modal').style.display = 'none';
};
window.toggleReplaceMode = function() {
const codeContainer = document.getElementById('new-code-container');
const replaceBtn = document.getElementById('submit-replace-btn');
document.getElementById('repair-action-input').value = 'replace';
codeContainer.style.display = 'block';
replaceBtn.style.display = 'block';
document.getElementById('modal-new-code-4').focus();
};
window.submitRepairAction = function(actionType) {
const form = document.getElementById('repair-action-form');
document.getElementById('repair-action-input').value = actionType;
if (confirm('Medium als regulär repariert markieren?')) {
form.submit();
}
};
function openDamageReportPrompt(button) {
const row = button.closest('.loan-row');
if (!row) {
return;
}
if (!row) return;
const itemId = row.dataset.itemId || '';
const itemName = row.dataset.itemName || 'Bibliotheksmedium';
const noteInput = prompt('Schadensmeldung für dieses Bibliotheksmedium:\nNotiz zum Schaden (optional):', '');
if (noteInput === null) {
return;
}
if (noteInput === null) return;
const description = noteInput.trim() || 'Schaden erneut gemeldet';
const originalText = button.textContent;
button.disabled = true;
button.textContent = 'Speichere...';
fetch(`/report_damage/${itemId}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ description })
})
.then(response => response.json().then(data => ({ ok: response.ok, data })))
.then(({ ok, data }) => {
if (!ok || !data.success) {
.then(async response => {
const data = await response.json().catch(() => ({}));
if (!response.ok || !data.success) {
throw new Error(data.message || 'Fehler beim Speichern der Schadensmeldung.');
}
return data;
})
.then(data => {
if (confirm('Schaden gespeichert. Soll direkt eine Rechnung erstellt werden?')) {
openDamageInvoiceModal(row, description);
button.disabled = false;
button.textContent = originalText;
return;
}
window.location.reload();
})
.catch(error => {
alert(error.message || 'Fehler beim Speichern der Schadensmeldung.');
alert(error.message || 'Ein unbekannter Fehler ist aufgetreten.');
button.disabled = false;
button.textContent = originalText;
});
}
window.openDamageReportPrompt = openDamageReportPrompt;
function openDamageInvoiceModal(row, description) {
const modal = document.getElementById('damage-invoice-modal');
const form = document.getElementById('damage-invoice-form');
const inputItem = document.getElementById('damage-invoice-item');
const inputBorrower = document.getElementById('damage-invoice-borrower');
const inputCode = document.getElementById('damage-invoice-code');
const inputAmount = document.getElementById('damage-invoice-amount');
const inputReason = document.getElementById('damage-invoice-reason');
if (!modal || !form) {
console.error("Modal oder Formular nicht gefunden.");
return;
}
if (!damageInvoiceModal || !damageInvoiceForm) return;
const borrowId = row.dataset.borrowId || '';
const itemName = row.dataset.itemName || '';
@@ -539,27 +598,36 @@
const itemCode = row.dataset.itemCode || '';
const itemCost = row.dataset.itemCost || '';
form.action = "{{ url_for('admin_create_invoice', borrow_id='__BORROW_ID__') }}".replace('__BORROW_ID__', borrowId);
damageInvoiceForm.action = "{{ url_for('admin_create_invoice', borrow_id='__BORROW_ID__') }}".replace('__BORROW_ID__', borrowId);
inputItem.value = itemName;
inputBorrower.value = borrower;
inputCode.value = itemCode;
damageInvoiceItem.value = itemName;
damageInvoiceBorrower.value = borrower;
damageInvoiceCode.value = itemCode;
damageInvoiceAmount.value = '';
inputAmount.value = String(itemCost).replace(' EUR', '').trim();
if (damageInvoiceReplaceBtn) {
damageInvoiceReplaceBtn.dataset.acquisition_costs = String(itemCost).replace(' EUR', '').trim();
}
inputReason.value = description || `Schaden gemeldet für ${itemName}`;
modal.style.display = 'block';
inputAmount.focus();
damageInvoiceReason.value = description || `Schaden gemeldet für ${itemName}`;
damageInvoiceModal.style.display = 'block';
damageInvoiceAmount.focus();
}
function closeDamageInvoiceModal() {
const modal = document.getElementById('damage-invoice-modal');
if (modal) {
modal.style.display = 'none';
if (damageInvoiceModal) {
damageInvoiceModal.style.display = 'none';
}
}
if (damageInvoiceReplaceBtn) {
damageInvoiceReplaceBtn.addEventListener('click', function() {
if (this.dataset.acquisition_costs) {
damageInvoiceAmount.value = this.dataset.acquisition_costs;
}
});
}
window.openDamageInvoiceModal = openDamageInvoiceModal;
window.closeDamageInvoiceModal = closeDamageInvoiceModal;
@@ -571,8 +639,6 @@
});
}
window.closeDamageInvoiceModal = closeDamageInvoiceModal;
function applyFilters() {
const search = (searchInput.value || '').trim().toLowerCase();
const status = statusFilter.value;
@@ -613,4 +679,4 @@
applyFilters();
})();
</script>
{% endblock %}
{% endblock %}
+1 -1
View File
@@ -516,7 +516,7 @@
</select>
<input type="text" id="activeStudentCard" placeholder="Aktiver Ausweis (gescannt)">
<input type="text" id="manualItemCode" placeholder="Manueller Mediencode (optional)" style="min-width:180px;">
<button id="resetCardBtn" class="button" type="button">Ausweis löschen</button>
<button id="resetCardBtn" class="button" type="button">Feld zurücksetzen</button>
<button id="toggleScannerBtn" class="button" type="button">Scanner starten</button>
<label style="display:flex; align-items:center; gap:8px; margin-left:6px;">
<input type="checkbox" id="keyboardScannerToggle">
+178 -93
View File
@@ -18,14 +18,58 @@
align-items: center;
margin-bottom: 20px;
flex-wrap: wrap;
gap: 10px;
gap: 15px;
}
/* Neu strukturiertes Layout für Formular & Import */
.dashboard-grid {
display: grid;
grid-template-columns: 2fr 1fr;
gap: 20px;
margin-bottom: 30px;
}
.student-card-form {
background: var(--ui-bg);
padding: 20px;
border-radius: 8px;
margin-bottom: 30px;
}
.import-card {
border: 1px solid #dbe4ee;
border-radius: 8px;
padding: 20px;
background: #f8fbff;
display: flex;
flex-direction: column;
justify-content: space-between;
}
.rollover-box {
background: #fff3cd;
border: 1px solid #ffeeba;
border-radius: 6px;
padding: 10px 12px;
margin-top: 4px;
}
.rollover-label {
display: flex;
align-items: center;
gap: 8px;
cursor: pointer;
font-size: 13px;
color: #856404;
font-weight: 700;
margin: 0;
}
.rollover-hint {
display: block;
margin-top: 4px;
font-size: 11px;
color: #856404;
line-height: 1.3;
}
.form-row {
@@ -35,6 +79,10 @@
margin-bottom: 15px;
}
.form-row.full-width {
grid-template-columns: 1fr;
}
.form-group {
display: flex;
flex-direction: column;
@@ -47,7 +95,8 @@
}
.form-group input,
.form-group select {
.form-group select,
.form-group textarea {
padding: 10px;
border: 1px solid #ddd;
border-radius: 4px;
@@ -55,7 +104,8 @@
}
.form-group input:focus,
.form-group select:focus {
.form-group select:focus,
.form-group textarea:focus {
outline: none;
border-color: #007bff;
box-shadow: 0 0 5px rgba(0, 123, 255, 0.3);
@@ -65,14 +115,16 @@
display: flex;
gap: 10px;
justify-content: flex-end;
margin-top: 10px;
}
.form-actions button {
.form-actions button, .form-actions a {
padding: 10px 20px;
border: none;
border-radius: 4px;
cursor: pointer;
font-weight: 600;
text-decoration: none;
}
.btn-save {
@@ -126,15 +178,18 @@
.card-actions {
display: flex;
gap: 8px;
align-items: center;
}
.btn-edit, .btn-delete {
.btn-edit, .btn-delete, .btn-export {
padding: 6px 12px;
border: none;
border-radius: 4px;
cursor: pointer;
font-size: 13px;
font-weight: 600;
text-decoration: none;
display: inline-block;
}
.btn-edit {
@@ -164,9 +219,6 @@
font-weight: 600;
text-decoration: none;
display: inline-block;
}
.btn-print {
background: #17a2b8;
color: white;
}
@@ -188,6 +240,7 @@
display: flex;
gap: 10px;
flex-wrap: wrap;
align-items: center;
}
.empty-state {
@@ -201,6 +254,12 @@
margin: 10px 0;
}
@media (max-width: 992px) {
.dashboard-grid {
grid-template-columns: 1fr;
}
}
@media (max-width: 768px) {
.form-row {
grid-template-columns: 1fr;
@@ -222,14 +281,16 @@
.card-actions {
flex-direction: column;
align-items: stretch;
}
}
</style>
<div class="container">
<!-- Header mit Aktionen -->
<div class="student-card-header">
<div>
<h1>📚 Bibliotheksausweise (Bibliothek)</h1>
<h1 style="margin: 0;">📚 Bibliotheksausweise</h1>
</div>
<div class="export-buttons">
<form method="GET" action="{{ url_for('student_card_class_barcode_download') }}" style="display: inline-flex; gap: 5px; align-items: center; background: white; padding: 2px; border-radius: 4px; border: 1px solid #ddd;">
@@ -239,7 +300,7 @@
<option value="{{ cls }}">{{ cls }}</option>
{% endfor %}
</select>
<button type="submit" class="btn-print" style="background: #17a2b8; padding: 8px 12px; margin: 0;">📤 PDF</button>
<button type="submit" class="btn-print" style="padding: 8px 12px; margin: 0;">📤 PDF</button>
</form>
<a href="{{ url_for('student_card_barcode_download') }}" class="btn-print" style="background: #28a745;">📥 Alle Ausweise (PDF)</a>
@@ -247,93 +308,118 @@
</div>
</div>
<div style="border:1px solid #dbe4ee; border-radius:8px; padding:14px; margin-bottom:16px; background:#f8fbff;">
<h3 style="margin:0 0 8px 0;">Excel-Import Bibliotheksausweise</h3>
<p style="margin:0 0 10px 0; color:#555;">Laden Sie eine <strong>.xlsx</strong>- oder <strong>.csv</strong>-Datei hoch, zum Beispiel aus <strong>ASV (Amtliche Schuldaten)</strong>. Erkannt werden automatisch Spalten wie <strong>Name</strong>, <strong>Nachname</strong, <strong>Klasse</strong>, <strong>Ausweis-ID (optional)</strong>, <strong>lokales Differenzierungsmerkmal (optional aber empfohlen)</strong>, <strong>Notizen (optional)</strong> und <strong>Standard-Ausleihdauer (optional)</strong>.</p>
<form method="POST" action="{{ url_for('upload_student_cards_excel') }}" enctype="multipart/form-data" style="display:flex; gap:10px; flex-wrap:wrap; align-items:center;">
<input type="file" name="student_cards_excel" accept=".xlsx,.csv" required>
<button type="submit" class="btn btn-secondary" name="excel_action" value="validate">Nur validieren</button>
<button type="submit" class="btn btn-primary" name="excel_action" value="import">Ausweise importieren</button>
</form>
</div>
<!-- Hauptbereich Grid: Formular + Import -->
<div class="dashboard-grid">
<!-- Add/Edit Form -->
<div class="student-card-form">
<h2 style="margin-top:0;">{% if edit_mode %}Ausweis bearbeiten{% else %}Neuer Bibliotheksausweis{% endif %}</h2>
<!-- Add/Edit Form -->
<div class="student-card-form">
<h2>{% if edit_mode %}Ausweis bearbeiten{% else %}Neuer Bibliotheksausweis{% endif %}</h2>
<form method="POST" action="{{ url_for('student_cards_admin') }}">
{% if edit_mode %}
<input type="hidden" name="action" value="edit">
<input type="hidden" name="card_id" value="{{ form_data.get('card_id', '') }}">
{% else %}
<input type="hidden" name="action" value="add">
{% endif %}
<div class="form-row">
<div class="form-group">
<label for="ausweis_id">Ausweis-ID</label>
<input type="text" id="ausweis_id" name="ausweis_id"
value="{{ form_data.get('ausweis_id', '') }}"
placeholder="z.B. SIS2024001">
</div>
<div class="form-group">
<label for="ausweis_ident">Lokales Differenzierungsmerkmal</label>
<input type="text" id="ausweis_ident" name="ausweis_ident"
value="{{ form_data.get('ausweis_ident', '') }}"
placeholder="z.B. xw5oo123bbe">
</div>
<div class="form-group">
<label for="student_name">Schüler Name *</label>
<input type="text" id="student_name" name="student_name" required
value="{{ form_data.get('student_name', '') }}"
placeholder="z.B. Max Mustermann">
</div>
</div>
<div class="form-row">
<div class="form-group">
<label for="default_borrow_days">Standard Ausleihdauer (Tage) *</label>
<input type="number" id="default_borrow_days" name="default_borrow_days"
min="1" max="365" required
value="{{ form_data.get('default_borrow_days', config.get('default', 14)) }}">
</div>
<div class="form-group">
<label for="class_name">Klasse</label>
<input type="text" id="class_name" name="class_name" list="class_list"
value="{{ form_data.get('class_name', '') }}"
placeholder="z.B. 10A (Tippen oder Auswählen)">
<datalist id="class_list">
{% for cls in available_classes %}
<option value="{{ cls }}">
{% endfor %}
</datalist>
</div>
</div>
<div class="form-row">
<div class="form-group">
<label for="notes">Notizen</label>
<textarea id="notes" name="notes" rows="3"
placeholder="Optionale Notizen..."
style="padding: 10px; border: 1px solid #ddd; border-radius: 4px;">{{ form_data.get('notes', '') }}</textarea>
</div>
</div>
<div class="form-actions">
<form method="POST" action="{{ url_for('student_cards_admin') }}">
{% if edit_mode %}
<a href="{{ url_for('student_cards_admin') }}" class="btn-cancel">Abbrechen</a>
<input type="hidden" name="action" value="edit">
<input type="hidden" name="card_id" value="{{ form_data.get('card_id', '') }}">
{% else %}
<input type="hidden" name="action" value="add">
{% endif %}
<button type="submit" class="btn-save">
{% if edit_mode %}Speichern{% else %}Hinzufügen{% endif %}
</button>
<div class="form-row">
<div class="form-group">
<label for="student_name">Schüler Name *</label>
<input type="text" id="student_name" name="student_name" required
value="{{ form_data.get('student_name', '') }}"
placeholder="z.B. Max Mustermann">
</div>
<div class="form-group">
<label for="class_name">Klasse</label>
<input type="text" id="class_name" name="class_name" list="class_list"
value="{{ form_data.get('class_name', '') }}"
placeholder="z.B. 10A (Tippen oder Auswählen)">
<datalist id="class_list">
{% for cls in available_classes %}
<option value="{{ cls }}">
{% endfor %}
</datalist>
</div>
</div>
<div class="form-row">
<div class="form-group">
<label for="ausweis_id">Ausweis-ID</label>
<input type="text" id="ausweis_id" name="ausweis_id"
value="{{ form_data.get('ausweis_id', '') }}"
placeholder="z.B. SIS2024001">
</div>
<div class="form-group">
<label for="ausweis_ident">Lokales Differenzierungsmerkmal</label>
<input type="text" id="ausweis_ident" name="ausweis_ident"
value="{{ form_data.get('ausweis_ident', '') }}"
placeholder="z.B. xw5oo123bbe">
</div>
</div>
<div class="form-row">
<div class="form-group">
<label for="default_borrow_days">Standard Ausleihdauer (Tage) *</label>
<input type="number" id="default_borrow_days" name="default_borrow_days"
min="1" max="365" required
value="{{ form_data.get('default_borrow_days', config.get('default', 14)) }}">
</div>
</div>
<div class="form-row full-width">
<div class="form-group">
<label for="notes">Notizen</label>
<textarea id="notes" name="notes" rows="2"
placeholder="Optionale Notizen...">{{ form_data.get('notes', '') }}</textarea>
</div>
</div>
<div class="form-actions">
{% if edit_mode %}
<a href="{{ url_for('student_cards_admin') }}" class="btn-cancel">Abbrechen</a>
{% endif %}
<button type="submit" class="btn-save">
{% if edit_mode %}Speichern{% else %}Hinzufügen{% endif %}
</button>
</div>
</form>
</div>
<!-- Excel-Import mit Abgleich (Rollover-Modus) -->
<div class="import-card">
<div>
<h3 style="margin:0 0 8px 0;">Excel-Import</h3>
<p style="margin:0 0 12px 0; color:#555; font-size:13px; line-height:1.4;">
Laden Sie eine <strong>.xlsx</strong>- oder <strong>.csv</strong>-Datei hoch (z. B. aus <strong>ASV</strong>). Erkannt werden Name, Nachname, Klasse, Ausweis-ID, lokales Differenzierungsmerkmal, Notizen & Ausleihdauer.
</p>
</div>
</form>
<form method="POST" action="{{ url_for('upload_student_cards_excel') }}" enctype="multipart/form-data" style="display:flex; flex-direction:column; gap:12px;">
<input type="file" name="student_cards_excel" accept=".xlsx,.csv" required style="font-size:13px;">
<!-- Rollover / Abgleich Option -->
<div class="rollover-box">
<label class="rollover-label">
<input type="checkbox" name="rollover_mode" value="true">
<span>Rollover-Modus (Abgleich / Destruktiv)</span>
</label>
<span class="rollover-hint">
⚠️ <strong>Warnung:</strong> Nicht mehr vorhandene Ausweise/Schüler werden beim Import entfernt bzw. abgeglichen.
</span>
</div>
<div style="display:flex; gap:8px;">
<button type="submit" class="btn btn-secondary" name="excel_action" value="validate" style="flex:1;">Validieren</button>
<button type="submit" class="btn btn-primary" name="excel_action" value="import" style="flex:1;">Importieren</button>
</div>
</form>
</div>
</div>
<!-- Cards List -->
<div>
<h2>Registrierte Ausweise</h2>
<h2 style="margin-bottom: 15px;">Registrierte Ausweise</h2>
{% if student_cards %}
<table class="cards-table">
<thead>
@@ -360,7 +446,7 @@
<input type="hidden" name="edit" value="{{ card._id }}">
<button type="submit" class="btn-edit">Bearbeiten</button>
</form>
<a href="{{ url_for('student_card_single_barcode_download', card_id=card._id) }}" class="btn-export" style="text-decoration: none; display: inline-block;">📥 PDF</a>
<a href="{{ url_for('student_card_single_barcode_download', card_id=card._id) }}" class="btn-export">📥 PDF</a>
<form method="POST" style="display: inline;" onsubmit="return confirm('Wirklich löschen?');">
<input type="hidden" name="action" value="delete">
<input type="hidden" name="card_id" value="{{ card._id }}">
@@ -386,5 +472,4 @@
// All PDF exports now go through backend routes
</script>
{% endblock %}
{% endblock %}