Compare commits

...

7 Commits

Author SHA1 Message Date
Aiirondev_dev a11bce17c5 Fixy of the api_library_items()
Release Inventarsystem / release-docker (push) Has been cancelled
2026-08-11 00:31:57 +02:00
Aiirondev_dev 743e5b1c16 Reviewed the edeting function
Release Inventarsystem / release-docker (push) Successful in 2m18s
2026-08-10 23:40:02 +02:00
Aiirondev_dev 4e47ef0c88 Implement library item return by code API and enhance UI for manual returns
Release Inventarsystem / release-docker (push) Successful in 2m14s
2026-08-10 22:17:52 +02:00
Aiirondev_dev 0911b362fd Changes to match the designated endpoint of the user when uploading an Item to dont have the system Jump between the systems.
Release Inventarsystem / release-docker (push) Successful in 2m15s
2026-08-10 21:35:13 +02:00
Aiirondev_dev 71716f339a Add keyboard scanner support with toggle option in library table
Release Inventarsystem / release-docker (push) Successful in 2m16s
2026-08-10 21:23:33 +02:00
Aiirondev_dev 36ccee38cb Addition of the button as described in the Issue #17
Release Inventarsystem / release-docker (push) Successful in 2m17s
2026-08-10 17:41:18 +02:00
Aiirondev_dev 9255c87f57 Implement ISBN live validation and automatic lookup on input change
Release Inventarsystem / release-docker (push) Successful in 2m15s
2026-08-10 14:16:20 +02:00
5 changed files with 542 additions and 173 deletions
+154 -18
View File
@@ -225,12 +225,95 @@ def rollover_student_card_classes(dry_run=False, *, max_class=None, graduate_lab
if client:
client.close()
summary = {'examined': examined, 'updated': updated, 'failures': failures, 'dry_run': bool(dry_run)}
@app.route('/api/library_return_by_code', methods=['POST'])
def api_library_return_by_code():
"""
Return a library item by scanning its code only (no student card required).
This marks active ausleihungen for the item as completed and updates item status.
"""
if 'username' not in session:
return jsonify({'ok': False, 'message': 'Nicht angemeldet.'}), 401
if not cfg.MODULES.is_enabled('library'):
return jsonify({'ok': False, 'message': 'Bibliotheks-Modul ist deaktiviert.'}), 403
payload = request.get_json(silent=True) or {}
item_code_raw = str(payload.get('item_code') or payload.get('code') or '').strip()
if not item_code_raw:
return jsonify({'ok': False, 'message': 'Mediencode fehlt.'}), 400
normalized_isbn = normalize_and_validate_isbn(item_code_raw)
normalized_code = item_code_raw.upper()
client = None
try:
_append_audit_event_standalone('student_cards_rollover', summary)
except Exception:
app.logger.warning('Audit write failed for student_cards_rollover')
return summary
client = MongoClient(MONGODB_HOST, MONGODB_PORT)
db = client[MONGODB_DB]
items_col = db['items']
ausleihungen_col = db['ausleihungen']
query_or = [
{'Code_4': item_code_raw},
{'Code_4': normalized_code},
]
if normalized_isbn:
query_or.append({'ISBN': normalized_isbn})
item_doc = items_col.find_one({
'ItemType': {'$in': LIBRARY_ITEM_TYPES},
'$or': query_or
})
if not item_doc:
return jsonify({'ok': False, 'message': 'Kein Bibliotheksmedium für diesen Code gefunden.'}), 404
item_id = str(item_doc['_id'])
now = datetime.datetime.now()
# If item already available -> nothing to return
if item_doc.get('Verfuegbar', True):
return jsonify({'ok': False, 'message': 'Dieses Medium ist nicht als ausgeliehen markiert.'}), 409
# Mark active ausleihungen as completed
update_result = ausleihungen_col.update_many(
{'Item': item_id, 'Status': 'active'},
{'$set': {
'Status': 'completed',
'End': now,
'LastUpdated': now
}}
)
# Update item status to available
borrower_name = str(item_doc.get('User') or '').strip() or ''
it.update_item_status(item_id, True, borrower_name)
_append_audit_event_standalone(
event_type='ausleihung_returned_by_code',
payload={
'channel': 'library_return_code',
'item_id': item_id,
'item_name': item_doc.get('Name', ''),
'completed_records': update_result.modified_count,
'performed_by': session.get('username')
}
)
return jsonify({
'ok': True,
'action': 'returned',
'item_id': item_id,
'item_name': item_doc.get('Name', ''),
'completed_records': update_result.modified_count,
'message': f"{item_doc.get('Name', 'Medium')} wurde zurückgegeben."
}), 200
except Exception as e:
app.logger.error(f"Error in library return by code: {e}")
return jsonify({'ok': False, 'message': 'Fehler beim Verarbeiten der Rückgabe.'}), 500
finally:
if client:
client.close()
# Admin route to trigger rollover manually
@@ -3231,7 +3314,6 @@ def api_library_items():
query = {
'ItemType': {'$in': ['book', 'cd', 'dvd', 'schoolbook', 'schulbuch', 'Buch', 'Schulbuch']},
'IsGroupedSubItem': {'$ne': True},
'Deleted': {'$ne': True}
}
@@ -3249,7 +3331,12 @@ def api_library_items():
'User': 1,
'Ort': 1,
'Beschreibung': 1,
'Image': 1
'Image': 1,
'SeriesGroupId': 1,
'SeriesCount': 1,
'SeriesPosition': 1,
'IsGroupedSubItem': 1,
'ParentItemId': 1,
}
total_count = items_db.count_documents(query)
@@ -3277,6 +3364,10 @@ def api_library_items():
'Beschreibung': 1,
'Image': 1,
'ParentItemId': 1,
'SeriesGroupId': 1,
'SeriesCount': 1,
'SeriesPosition': 1,
'IsGroupedSubItem': 1,
}
child_items = list(items_db.find({
'ParentItemId': {'$in': parent_ids_list},
@@ -3390,6 +3481,48 @@ def api_library_items():
return jsonify({'error': 'An error occurred while fetching library items'}), 500
@app.route('/api/library_group/<series_group_id>')
def api_library_group(series_group_id):
"""Fetch all items belonging to one library series group."""
if 'username' not in session:
return jsonify({'items': []}), 401
try:
client = MongoClient(MONGODB_HOST, MONGODB_PORT)
db = client[MONGODB_DB]
items_col = db['items']
query = {
'SeriesGroupId': series_group_id,
'Deleted': {'$ne': True},
'ItemType': {'$in': ['book', 'cd', 'dvd', 'schoolbook', 'schulbuch', 'Buch', 'Schulbuch']},
}
projection = {
'Name': 1,
'ISBN': 1,
'Code_4': 1,
'Code4': 1,
'ItemType': 1,
'Ort': 1,
'Beschreibung': 1,
'SeriesGroupId': 1,
'SeriesCount': 1,
'SeriesPosition': 1,
'IsGroupedSubItem': 1,
'ParentItemId': 1,
}
items = list(items_col.find(query, projection).sort([('SeriesPosition', 1), ('Name', 1), ('_id', 1)]))
for item in items:
item['_id'] = str(item['_id'])
client.close()
return jsonify({'items': items, 'count': len(items), 'series_group_id': series_group_id})
except Exception as exc:
app.logger.error('Error loading library group %s: %s', series_group_id, exc)
return jsonify({'items': [], 'message': 'Gruppe konnte nicht geladen werden.'}), 500
@app.route('/api/library_scan_action', methods=['POST'])
def api_library_scan_action():
"""
@@ -6253,17 +6386,20 @@ def update_group():
# 1. Shared Fields (Group Logic)
# These apply to every item in the group
shared_update = {
'Name': data.get('name'),
'Ort': data.get('ort'),
'Beschreibung': data.get('beschreibung'),
'Anschaffungsjahr': data.get('ansch_jahr'),
'Anschaffungskosten': data.get('ansch_kost'),
'Reservierbar': data.get('reservierbar'),
'ISBN': data.get('isbn'),
'ItemType': data.get('item_type'),
'LastUpdated': datetime.datetime.now()
}
shared_update = {'LastUpdated': datetime.datetime.now()}
for source_key, target_key in (
('name', 'Name'),
('ort', 'Ort'),
('beschreibung', 'Beschreibung'),
('ansch_jahr', 'Anschaffungsjahr'),
('ansch_kost', 'Anschaffungskosten'),
('reservierbar', 'Reservierbar'),
('isbn', 'ISBN'),
('item_type', 'ItemType'),
):
value = data.get(source_key)
if value is not None:
shared_update[target_key] = value
# 2. Individual Updates (Specific Code Logic)
# Expected format: [{'id': '...', 'code_4': '...'}, ...]
+332 -141
View File
@@ -355,6 +355,28 @@
color: #6b7280;
}
/* Small confirmation popup (toast) */
.small-popup {
position: fixed;
bottom: 24px;
left: 50%;
transform: translateX(-50%);
background: rgba(17, 24, 39, 0.96);
color: #fff;
padding: 12px 16px;
border-radius: 8px;
box-shadow: 0 6px 24px rgba(2,6,23,0.6);
z-index: 2000;
display: flex;
gap: 10px;
align-items: center;
max-width: 90%;
font-size: 0.95em;
}
.small-popup.ok { background: rgba(16,185,129,0.95); color: #032; }
.small-popup.error { background: rgba(239,68,68,0.95); color: #210; }
.small-popup .close-x { margin-left: 8px; cursor: pointer; font-weight: 700; }
/* Modal styles */
.modal {
display: none;
@@ -503,8 +525,18 @@
<option value="quick_toggle">Schnellmodus: Ausweis + Mediencode</option>
</select>
<input type="text" id="activeStudentCard" placeholder="Aktiver Ausweis (gescannt)" readonly>
<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="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">
<span style="font-size:0.9em;">Physischer Scanner</span>
</label>
<label style="display:flex; align-items:center; gap:8px; margin-left:6px;">
<input type="checkbox" id="returnOnlyToggle">
<span style="font-size:0.9em;">Nur Rückgabe (nur Mediencode)</span>
</label>
<button id="manualReturnBtn" class="button" type="button" style="margin-left:6px; background:#10b981;color:white;">Rückgabe per Code</button>
</div>
<div id="scanStatus" class="library-scan-status">
Hinweis: Im Schnellmodus zuerst den Schülerausweis scannen, danach den Buch-/Mediencode.
@@ -632,6 +664,16 @@
let activeStudentCardId = '';
let lastScanValue = '';
let lastScanAt = 0;
// Keyboard-scanner support (physical scanners that act as keyboard wedges)
let keyboardScannerEnabled = false;
let keyboardScanBuffer = '';
let keyboardLastKeyAt = 0;
const KEYBOARD_SCAN_INTERCHAR_MS = 100; // max time between keystrokes to consider them one scan
let editLibraryState = {
itemId: '',
seriesGroupId: '',
groupMembers: []
};
const canEditLibraryItems = (document.getElementById('libraryTableContainer')?.dataset.canEdit === '1');
@@ -905,6 +947,13 @@
const currentCallback = activeScannerCallback;
stopScanner();
const returnOnly = (document.getElementById('returnOnlyToggle') || {}).checked;
if (returnOnly) {
// direct return flow
returnByCode(barcode);
return;
}
if (typeof currentCallback === "function") {
currentCallback(barcode);
} else {
@@ -912,6 +961,50 @@
}
});
// =========================================================================
// Keyboard scanner handling (physical scanners that send chars then Enter)
// =========================================================================
function keyboardScanKeydownHandler(e) {
// Only active when explicitly enabled
if (!keyboardScannerEnabled) return;
// Ignore if focus is in an input/textarea/contenteditable to avoid interfering with typing
const active = document.activeElement;
if (active && (active.tagName === 'INPUT' || active.tagName === 'TEXTAREA' || active.isContentEditable)) return;
const now = Date.now();
// If Enter/Return pressed -> finalize buffer
if (e.key === 'Enter') {
const code = keyboardScanBuffer.trim();
keyboardScanBuffer = '';
keyboardLastKeyAt = 0;
if (!code) return;
// If return-only mode is active, attempt direct return
const returnOnly = (document.getElementById('returnOnlyToggle') || {}).checked;
if (returnOnly) {
returnByCode(code);
return;
}
// Process exactly like a camera scan
handleScanSuccess(code);
return;
}
// Only accept common printable characters; ignore modifier keys
if (e.key.length === 1) {
// If time gap too big, start new buffer
if (keyboardLastKeyAt && (now - keyboardLastKeyAt) > KEYBOARD_SCAN_INTERCHAR_MS) {
keyboardScanBuffer = '';
}
keyboardScanBuffer += e.key;
keyboardLastKeyAt = now;
// Prevent default so scanner input doesn't accidentally move focus or trigger shortcuts
e.preventDefault();
}
}
function handleScanSuccess(decodedText) {
const scannedCode = normalizeScannedCode(decodedText);
if (!scannedCode) return;
@@ -935,11 +1028,46 @@
async function processQuickToggleScan(scannedCode) {
if (!activeStudentCardId) {
setActiveStudentCard(scannedCode);
setScanStatus(`Ausweis gesetzt: ${activeStudentCardId}`, 'ok');
return;
}
// If return-only mode is active, always attempt to return by code
const returnOnly = (document.getElementById('returnOnlyToggle') || {}).checked;
if (returnOnly) {
await returnByCode(scannedCode);
return;
}
if (!activeStudentCardId) {
setActiveStudentCard(scannedCode);
setScanStatus(`Ausweis gesetzt: ${activeStudentCardId}`, 'ok');
return;
}
async function returnByCode(code) {
if (!code) return;
setScanStatus('Verarbeite Rückgabe...', 'warn');
try {
const resp = await fetch('/api/library_return_by_code', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({ item_code: code })
});
const result = await resp.json();
if (!resp.ok || !result.ok) {
setScanStatus(result.message || 'Rückgabe fehlgeschlagen.', 'error');
showSmallConfirm(result.message || 'Rückgabe fehlgeschlagen.', 'error');
return false;
}
setScanStatus(result.message || `Zurückgegeben: ${result.item_name || ''}`, 'ok');
showSmallConfirm(result.message || `Zurückgegeben: ${result.item_name || ''}`, 'ok');
await loadLibraryItems();
return true;
} catch (err) {
console.error('Return by code failed:', err);
setScanStatus('Fehler bei Rückgabe.', 'error');
showSmallConfirm('Fehler bei Rückgabe.', 'error');
return false;
}
}
try {
setScanStatus('Verarbeite Mediencode...', 'warn');
const response = await fetch('/api/library_scan_action', {
@@ -959,10 +1087,13 @@
if (result.action === 'borrowed') {
setScanStatus(`Ausgeliehen: ${result.item_name}`, 'ok');
showSmallConfirm(`Ausgeliehen: ${result.item_name}`, 'ok');
} else if (result.action === 'returned') {
setScanStatus(`Zurückgegeben: ${result.item_name}`, 'ok');
showSmallConfirm(`Zurückgegeben: ${result.item_name}`, 'ok');
} else {
setScanStatus(result.message || 'Aktion durchgeführt.', 'ok');
showSmallConfirm(result.message || 'Aktion durchgeführt.', 'ok');
}
await loadLibraryItems();
@@ -1075,6 +1206,21 @@
el.classList.remove('ok', 'warn', 'error');
if (kind) el.classList.add(kind);
}
function showSmallConfirm(message, kind='ok') {
// Append the small helper text in German
const helper = 'Sie können fortfahren. Dies ist nur eine kleine Benachrichtigung.';
const el = document.createElement('div');
el.className = `small-popup ${kind === 'error' ? 'error' : 'ok'}`;
el.innerHTML = `<div>${escapeHtml(String(message || ''))}</div><div style="opacity:0.9; margin-left:8px; font-size:0.85em;">${helper}</div><div class="close-x">&times;</div>`;
document.body.appendChild(el);
// close handler
el.querySelector('.close-x').addEventListener('click', () => {
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){} }, 3000);
}
function setActiveStudentCard(cardId) {
activeStudentCardId = (cardId || '').trim().toUpperCase();
@@ -1145,6 +1291,7 @@
const toggleBtn = document.getElementById('toggleScannerBtn');
const resetBtn = document.getElementById('resetCardBtn');
const modeSelect = document.getElementById('scanModeSelect');
const keyboardToggle = document.getElementById('keyboardScannerToggle');
if (toggleBtn) {
toggleBtn.addEventListener('click', async () => {
@@ -1172,6 +1319,19 @@
}
});
}
if (keyboardToggle) {
keyboardToggle.addEventListener('change', () => {
keyboardScannerEnabled = !!keyboardToggle.checked;
if (keyboardScannerEnabled) {
document.addEventListener('keydown', keyboardScanKeydownHandler);
setScanStatus('Physischer Scanner aktiv (Schnellmodus empfohlen).', 'ok');
} else {
document.removeEventListener('keydown', keyboardScanKeydownHandler);
setScanStatus('Physischer Scanner deaktiviert.', 'warn');
}
});
}
}
// Run when DOM structure is entirely ready
@@ -1226,44 +1386,104 @@
});
}
// Edit Modal Form processing
const manualReturnBtn = document.getElementById('manualReturnBtn');
const manualItemCode = document.getElementById('manualItemCode');
if (manualReturnBtn && manualItemCode) {
manualReturnBtn.addEventListener('click', async () => {
const code = (manualItemCode.value || '').trim();
if (!code) {
alert('Bitte einen Mediencode eingeben.');
return;
}
await returnByCode(code);
});
}
const editForm = document.getElementById('editLibraryForm');
if (editForm) {
editForm.addEventListener('submit', async function(e) {
e.preventDefault();
e.preventDefault();
const itemId = document.getElementById('editLibraryItemId').value;
const currentItem = libraryItems.find(i => i._id === itemId);
if (!currentItem) return;
const updatedData = {
const sharedPayload = {
name: document.getElementById('editLibraryName').value,
item_type: document.getElementById('editLibraryType').value,
isbn: document.getElementById('editLibraryIsbn').value,
code_4: document.getElementById('editLibraryCode4').value,
ort: document.getElementById('editLibraryLocation').value,
beschreibung: document.getElementById('editLibraryDescription').value
beschreibung: document.getElementById('editLibraryDescription').value,
ansch_jahr: currentItem.Anschaffungsjahr || '',
ansch_kost: currentItem.Anschaffungskosten || '',
reservierbar: currentItem.Reservierbar !== false,
};
const codeInputs = Array.from(document.querySelectorAll('#editLibraryCodesContainer input[data-item-id]'));
const codeByItemId = new Map(codeInputs.map(input => [input.dataset.itemId, (input.value || '').trim()]));
const groupMembers = editLibraryState.groupMembers.length > 0 ? editLibraryState.groupMembers : [currentItem];
const isGroupedEdit = Boolean(currentItem.SeriesGroupId) && groupMembers.length > 1;
try {
const response = await fetch(`/api/library_item/${itemId}/update`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRFToken': '{{ csrf_token }}',
'X-CSRF-Token': '{{ csrf_token }}'
},
body: JSON.stringify(updatedData)
});
if (isGroupedEdit) {
const payload = {
series_group_id: currentItem.SeriesGroupId,
...sharedPayload,
items: groupMembers.map(member => ({
id: member._id,
code_4: codeByItemId.get(member._id) || ''
}))
};
const result = await response.json();
const response = await fetch('/update_group', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRFToken': '{{ csrf_token }}',
'X-CSRF-Token': '{{ csrf_token }}'
},
body: JSON.stringify(payload)
});
if (response.ok && result.ok) {
alert(result.message || 'Medium erfolgreich aktualisiert!');
closeEditLibraryModal();
pagingState.loading = false;
loadLibraryItems();
const result = await response.json();
if (response.ok && result.success) {
alert(result.message || 'Gruppe erfolgreich aktualisiert!');
closeEditLibraryModal();
pagingState.loading = false;
await loadLibraryItems();
} else {
alert(result.message || 'Fehler beim Speichern der Gruppenänderungen.');
}
} else {
alert(result.message || 'Fehler beim Speichern der Änderungen.');
const primaryCodeInput = codeInputs[0];
const payload = {
name: sharedPayload.name,
item_type: sharedPayload.item_type,
isbn: sharedPayload.isbn,
code_4: primaryCodeInput ? primaryCodeInput.value.trim() : (currentItem.Code_4 || currentItem.Code4 || '').trim(),
ort: sharedPayload.ort,
beschreibung: sharedPayload.beschreibung
};
const response = await fetch(`/api/library_item/${itemId}/update`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRFToken': '{{ csrf_token }}',
'X-CSRF-Token': '{{ csrf_token }}'
},
body: JSON.stringify(payload)
});
const result = await response.json();
if (response.ok && result.ok) {
alert(result.message || 'Medium erfolgreich aktualisiert!');
closeEditLibraryModal();
pagingState.loading = false;
await loadLibraryItems();
} else {
alert(result.message || 'Fehler beim Speichern der Änderungen.');
}
}
} catch (error) {
console.error('Update failed:', error);
@@ -1273,115 +1493,105 @@
}
});
window.openEditLibraryItem = function(itemId) {
async function fetchLibraryGroupMembers(seriesGroupId) {
if (!seriesGroupId) return [];
try {
const response = await fetch(`/api/library_group/${encodeURIComponent(seriesGroupId)}`);
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
const payload = await response.json();
return Array.isArray(payload.items) ? payload.items : [];
} catch (error) {
console.warn('Falling back to loaded library items for group editing:', error);
return (libraryItems || []).filter(item => item.SeriesGroupId === seriesGroupId);
}
}
function renderLibraryGroupCodeFields(groupMembers, currentItemId) {
const codesContainer = document.getElementById('editLibraryCodesContainer');
const groupWarning = document.getElementById('editLibraryGroupWarning');
const groupCount = document.getElementById('editLibraryGroupCount');
const groupHint = document.getElementById('editLibraryGroupHint');
if (!codesContainer) return;
const items = Array.isArray(groupMembers) ? groupMembers.slice() : [];
items.sort((a, b) => (a.SeriesPosition || 0) - (b.SeriesPosition || 0) || String(a.Name || '').localeCompare(String(b.Name || '')));
editLibraryState.groupMembers = items;
if (groupWarning) {
groupWarning.style.display = items.length > 1 ? 'block' : 'none';
}
if (groupCount) {
const totalCount = items.length || 1;
const declaredCount = items[0]?.SeriesCount || totalCount;
groupCount.textContent = `${totalCount} / ${declaredCount}`;
}
if (groupHint) {
groupHint.textContent = items.length > 1
? 'Jeder Code gehört zu einem eigenen Exemplar. Änderungen werden für alle Codes gespeichert.'
: 'Einzelnes Exemplar. Der Code wird direkt gespeichert.';
}
if (!items.length) {
codesContainer.innerHTML = '<div style="padding:10px 0; color:#6b7280;">Keine Codes geladen.</div>';
return;
}
codesContainer.innerHTML = items.map((member, index) => {
const codeValue = member.Code_4 || member.Code4 || '';
const labelParts = [];
if (member.SeriesPosition !== undefined && member.SeriesPosition !== null) {
labelParts.push(`Exemplar ${member.SeriesPosition}`);
} else {
labelParts.push(`Exemplar ${index + 1}`);
}
if (member._id === currentItemId) {
labelParts.push('aktuelles Medium');
}
return `
<div style="display:flex; flex-direction:column; gap:6px; margin-bottom:10px;">
<label for="editLibraryCode-${member._id}" style="font-weight:600; font-size:0.9em; color:var(--ui-text);">${escapeHtml(labelParts.join(' · '))}</label>
<input id="editLibraryCode-${member._id}" data-item-id="${escapeHtml(member._id)}" value="${escapeHtml(codeValue)}" placeholder="Mediencode" style="width:100%; padding:8px 10px; border:1px solid #d0d7e2; border-radius:6px;">
</div>
`;
}).join('');
}
window.openEditLibraryItem = async function(itemId) {
const item = libraryItems.find(i => i._id === itemId);
if (!item) return;
editLibraryState.itemId = item._id;
editLibraryState.seriesGroupId = item.SeriesGroupId || '';
editLibraryState.groupMembers = [];
// 1. Felder befüllen
document.getElementById('editLibraryItemId').value = item._id;
document.getElementById('editLibraryName').value = item.Name;
document.getElementById('editLibraryType').value = item.ItemType;
document.getElementById('editLibraryIsbn').value = item.ISBN || '';
document.getElementById('editLibraryCode4').value = item.Code_4 || '';
document.getElementById('editLibraryLocation').value = item.Ort;
document.getElementById('editLibraryDescription').value = item.Beschreibung;
// 2. Gruppen-Logik
const warningDiv = document.getElementById('editLibraryGroupWarning');
const codesContainer = document.getElementById('editLibraryAllCodes');
if (item.SeriesGroupId) {
// Filtern aus dem aktuell geladenen Array
let groupMembers = libraryItems.filter(i => i.SeriesGroupId === item.SeriesGroupId);
// SCHLÜSSEL: Wenn die Anzahl der gefundenen Elemente nicht mit SeriesCount übereinstimmt,
// haben wir die Gruppe noch nicht vollständig geladen.
if (groupMembers.length < (item.SeriesCount || 0)) {
console.warn("Gruppe noch nicht vollständig geladen. Anzeige ggf. unvollständig.");
// Optional: Zeige einen Ladehinweis im Modal
codesContainer.textContent = "Lade restliche Gruppenmitglieder...";
} else {
// Daten sind vollständig -> Anzeigen
const codeList = groupMembers
.sort((a, b) => (a.SeriesPosition || 0) - (b.SeriesPosition || 0))
.map(m => m.Code_4 || "---")
.join(', ');
codesContainer.textContent = codeList;
}
document.getElementById('editLibraryGroupCount').textContent = groupMembers.length + " / " + (item.SeriesCount || "?");
warningDiv.style.display = 'block';
} else {
warningDiv.style.display = 'none';
const codesContainer = document.getElementById('editLibraryCodesContainer');
if (codesContainer) {
codesContainer.innerHTML = '<div style="padding:10px 0; color:#6b7280;">Lade Codes...</div>';
}
const groupMembers = item.SeriesGroupId ? await fetchLibraryGroupMembers(item.SeriesGroupId) : [item];
renderLibraryGroupCodeFields(groupMembers.length > 0 ? groupMembers : [item], item._id);
document.getElementById('editLibraryModal').style.display = 'flex';
};
function closeEditLibraryModal() {
document.getElementById('editLibraryModal').style.display = 'none';
}
/**
* Event-Listener für das Formular (Initialisierung)
*/
document.addEventListener('DOMContentLoaded', function() {
const editForm = document.getElementById('editLibraryForm');
if (editForm) {
editForm.addEventListener('submit', async function(e) {
e.preventDefault();
const itemId = document.getElementById('editLibraryItemId').value;
const currentItem = libraryItems.find(i => i._id === itemId);
if (!currentItem) return;
// 1. Alle Mitglieder der Gruppe finden, um die Code-Liste aufzubauen
const groupMembers = libraryItems.filter(i => i.SeriesGroupId === currentItem.SeriesGroupId);
const individualUpdates = groupMembers.map(member => ({
id: member._id,
// Wenn dies das bearbeitete Item ist, nimm den neuen Code, sonst den alten
code_4: (member._id === itemId) ? document.getElementById('editLibraryCode4').value : member.Code_4
}));
// 2. Payload für das Backend bauen
const payload = {
series_group_id: currentItem.SeriesGroupId,
name: document.getElementById('editLibraryName').value,
ort: document.getElementById('editLibraryLocation').value,
beschreibung: document.getElementById('editLibraryDescription').value,
isbn: document.getElementById('editLibraryIsbn').value,
item_type: document.getElementById('editLibraryType').value,
items: individualUpdates
};
// 3. Request an die Gruppen-Update Route
try {
const response = await fetch('/update_group', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload)
});
const result = await response.json();
if (result.success) {
alert('Gruppe erfolgreich synchronisiert!');
closeEditLibraryModal();
await loadLibraryItems(); // Daten neu laden
// renderTable(); // Ggf. Tabelle neu rendern
} else {
await loadLibraryItems();
closeEditLibraryModal();
}
} catch (error) {
console.error('Update failed:', error);
alert('Netzwerkfehler.');
}
});
}
});
</script>
<div id="editLibraryModal" class="modal" style="display:none;">
@@ -1395,15 +1605,12 @@
<strong style="color: #0ea5e9;">Gruppen-Range (Total: <span id="editLibraryGroupCount"></span>)</strong>
</div>
<p style="margin: 5px 0; font-size: 12px; color: #555;">
Alle aufgeführten Codes gehören zu diesem Datensatz:
<p id="editLibraryGroupHint" style="margin: 5px 0; font-size: 12px; color: #555;">
Änderungen an Titel, Ort und Beschreibung werden auf alle Exemplare der Gruppe übertragen.
</p>
<!-- Hier werden die Codes per JS eingefügt -->
<div id="editLibraryAllCodes" style="display: flex; flex-wrap: wrap; gap: 5px; margin-top: 10px;"></div>
<div style="margin-top: 15px; font-size: 11px; background: #e0f2fe; padding: 8px; border-radius: 4px;">
<strong>Hinweis:</strong> Änderungen an Titel/Ort/Beschreibung werden auf <strong>alle</strong> Exemplare der Range übertragen.
<strong>Hinweis:</strong> Jeder Mediencode wird einzeln gespeichert, damit alle Exemplare der Gruppe korrekt bleiben.
</div>
</div>
@@ -1429,8 +1636,8 @@
<input id="editLibraryIsbn" placeholder="optional ISBN-10/13" style="width: 100%;">
</div>
<div>
<label for="editLibraryCode4">Code</label>
<input id="editLibraryCode4" placeholder="optional Mediencode" style="width: 100%;">
<label>Mediencodes</label>
<div id="editLibraryCodesContainer"></div>
</div>
<div class="full">
<label for="editLibraryLocation">Ort</label>
@@ -1448,20 +1655,4 @@
</form>
</div>
</div>
<div id="editLibraryGroupWarning" style="display:none; background-color: #fff; padding: 15px; border-radius: 6px; margin-bottom: 20px; border: 1px solid #0ea5e9;">
<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px; border-bottom: 1px solid #eee; padding-bottom: 10px;">
<strong style="color: #0ea5e9;">Gruppen-Range (Total: <span id="editLibraryGroupCount"></span>)</strong>
</div>
<p style="margin: 5px 0; font-size: 12px; color: #555;">
Alle Codes in dieser Gruppe:
</p>
<!-- Hier wird die Liste als Komma-Text eingefügt -->
<div id="editLibraryAllCodes" style="font-family: monospace; font-size: 14px; font-weight: bold; color: #333; margin-top: 5px;"></div>
<div style="margin-top: 15px; font-size: 11px; background: #e0f2fe; padding: 8px; border-radius: 4px;">
<strong>Hinweis:</strong> Änderungen an Titel/Ort/Beschreibung werden auf <strong>alle</strong> Exemplare der Range übertragen.
</div>
</div>
{% endblock %}
+2 -2
View File
@@ -19,7 +19,7 @@
<div class="col-md-4">
<div class="card mb-4">
<div class="card-header">
<h2 class="card-title h5 mb-0">{{ filter_names.get('1', 'Fach/Kategorie') }} (Filter 1)</h2>
<h2 class="card-title h5 mb-0">{{ filter_names.get('1', 'Jahrgang') }} (Filter 1)</h2>
</div>
<div class="card-body">
<form method="POST" action="{{ url_for('add_filter_value', filter_num=1) }}" class="mb-4">
@@ -67,7 +67,7 @@
<div class="col-md-4">
<div class="card mb-4">
<div class="card-header">
<h2 class="card-title h5 mb-0">{{ filter_names.get('2', 'System/Bereich') }} (Filter 2)</h2>
<h2 class="card-title h5 mb-0">{{ filter_names.get('2', 'Fach') }} (Filter 2)</h2>
</div>
<div class="card-body">
<form method="POST" action="{{ url_for('add_filter_value', filter_num=2) }}" class="mb-4">
+49 -3
View File
@@ -1067,6 +1067,24 @@
return false;
}
function handleIsbnLookupFromScanner() {
const isbnField = document.getElementById('isbn');
if (!isbnField) return false;
const normalizedIsbn = typeof normalizeIsbnClient === 'function' ? normalizeIsbnClient(isbnField.value) : isbnField.value.trim();
if (!normalizedIsbn) return false;
if (typeof updateIsbnLiveValidation === 'function') {
updateIsbnLiveValidation();
}
if (typeof fetchBookInfo === 'function') {
fetchBookInfo('upload');
}
return true;
}
document.addEventListener('DOMContentLoaded', function () {
document.querySelectorAll('form').forEach(function (form) {
form.addEventListener('keydown', function (event) {
@@ -1079,6 +1097,12 @@
if (['button', 'submit', 'reset', 'file', 'checkbox', 'radio', 'hidden'].includes(type)) return;
event.preventDefault();
if (target.id === 'isbn' || target.name === 'isbn') {
handleIsbnLookupFromScanner();
return;
}
focusNextFormField(target);
});
});
@@ -1445,10 +1469,32 @@
scanModeSelect.addEventListener('change', toggleScanMode);
}
// 4. ISBN Live-Validierung
// 4. ISBN Live-Validierung und automatische Abfrage nach Scan/Enter
const isbnInput = document.getElementById('isbn');
if (isbnInput && typeof updateIsbnLiveValidation === 'function') {
isbnInput.addEventListener('input', updateIsbnLiveValidation);
if (isbnInput) {
if (typeof updateIsbnLiveValidation === 'function') {
isbnInput.addEventListener('input', updateIsbnLiveValidation);
}
let isbnLookupTimer = null;
isbnInput.addEventListener('input', function () {
clearTimeout(isbnLookupTimer);
const normalizedIsbn = typeof normalizeIsbnClient === 'function' ? normalizeIsbnClient(isbnInput.value) : isbnInput.value.trim();
if (normalizedIsbn) {
isbnLookupTimer = setTimeout(function () {
handleIsbnLookupFromScanner();
}, 250);
}
});
isbnInput.addEventListener('change', function () {
if (typeof normalizeIsbnClient === 'function') {
const normalizedIsbn = normalizeIsbnClient(isbnInput.value);
if (normalizedIsbn) {
handleIsbnLookupFromScanner();
}
}
});
}
});
// Load predefined filter values for dropdowns
+5 -9
View File
@@ -17,15 +17,11 @@
<div class="user-management-container">
<h2>Benutzer</h2>
<form method="POST" action="{{ url_for('admin_anonymize_names') }}" class="mb-3">
<button
type="submit"
class="btn btn-outline-danger"
onclick="return confirm('Sollen alle gespeicherten Klarnamen dauerhaft in Synonym-Kuerzel umgewandelt werden?')"
>
Gespeicherte Namen anonymisieren
</button>
</form>
<div class="mb-3">
<a href="{{ url_for('register') }}" class="btn btn-success">
Neuen Benutzer registrieren
</a>
</div>
<div class="filter-bar mb-3">
<div class="row g-2 align-items-end">