Compare commits
34 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 1b9bfe1b14 | |||
| 3cdd1552d9 | |||
| 80a206f524 | |||
| 3217da8b15 | |||
| 22bc7c9c3c | |||
| f156cc178a | |||
| 116261d334 | |||
| 042afc19e2 | |||
| 28d049b52a | |||
| 8e478aeba4 | |||
| 1b38d1f0c8 | |||
| e7e24b3fae | |||
| fc80857fbe | |||
| f763ad064d | |||
| bc94ffdc18 | |||
| 76e9670cee | |||
| 577c6c4bed | |||
| 3aa19b10d1 | |||
| ff742d018e | |||
| 6fa40f26b0 | |||
| 777fc81064 | |||
| cf5e38e319 | |||
| b76941d5fe | |||
| f46f2674b0 | |||
| 8ebbdcfd54 | |||
| 92b5235035 | |||
| 4bda2e044b | |||
| b83b6c0ba2 | |||
| ab718d6ac2 | |||
| 112d9b6aa0 | |||
| 5139a50a43 | |||
| 997c7b42d5 | |||
| 20e5d3bb9a | |||
| f62b22c2f7 |
@@ -15,15 +15,6 @@ on:
|
|||||||
- patch
|
- patch
|
||||||
- minor
|
- minor
|
||||||
- major
|
- major
|
||||||
- development
|
|
||||||
push_dev:
|
|
||||||
description: "If true, push the :dev image to GHCR for development releases"
|
|
||||||
required: false
|
|
||||||
default: "false"
|
|
||||||
type: choice
|
|
||||||
options:
|
|
||||||
- "true"
|
|
||||||
- "false"
|
|
||||||
|
|
||||||
permissions:
|
permissions:
|
||||||
contents: write
|
contents: write
|
||||||
@@ -48,13 +39,12 @@ jobs:
|
|||||||
EVENT_NAME: ${{ github.event_name }}
|
EVENT_NAME: ${{ github.event_name }}
|
||||||
REF_NAME: ${{ github.ref_name }}
|
REF_NAME: ${{ github.ref_name }}
|
||||||
BUMP_TYPE: ${{ github.event.inputs.bump || 'patch' }}
|
BUMP_TYPE: ${{ github.event.inputs.bump || 'patch' }}
|
||||||
PUSH_DEV: ${{ github.event.inputs.push_dev || 'false' }}
|
|
||||||
run: |
|
run: |
|
||||||
if [ "$EVENT_NAME" = "push" ] && [ -n "$REF_NAME" ]; then
|
if [ "$EVENT_NAME" = "push" ] && [ -n "$REF_NAME" ]; then
|
||||||
TAG="$REF_NAME"
|
TAG="$REF_NAME"
|
||||||
else
|
else
|
||||||
# Fetch latest release tag via GitHub API (fall back to v3.0.0)
|
# Fetch latest release tag via GitHub API (fall back to v0.8.31)
|
||||||
latest_tag="v3.0.0"
|
latest_tag="v0.8.31"
|
||||||
if meta_json=$(curl -fsSL -H "Authorization: Bearer $GH_TOKEN" -H "Accept: application/vnd.github+json" "https://api.github.com/repos/$REPO/releases/latest" 2>/dev/null); then
|
if meta_json=$(curl -fsSL -H "Authorization: Bearer $GH_TOKEN" -H "Accept: application/vnd.github+json" "https://api.github.com/repos/$REPO/releases/latest" 2>/dev/null); then
|
||||||
tag_name=$(printf "%s" "$meta_json" | sed -n 's/.*"tag_name"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' | head -n1)
|
tag_name=$(printf "%s" "$meta_json" | sed -n 's/.*"tag_name"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' | head -n1)
|
||||||
if [ -n "$tag_name" ]; then
|
if [ -n "$tag_name" ]; then
|
||||||
@@ -67,7 +57,7 @@ jobs:
|
|||||||
minor=${BASH_REMATCH[2]}
|
minor=${BASH_REMATCH[2]}
|
||||||
patch=${BASH_REMATCH[3]}
|
patch=${BASH_REMATCH[3]}
|
||||||
else
|
else
|
||||||
major=3; minor=0; patch=0
|
major=0; minor=8; patch=31
|
||||||
fi
|
fi
|
||||||
|
|
||||||
# Bump strategy: major / minor / patch
|
# Bump strategy: major / minor / patch
|
||||||
@@ -79,29 +69,27 @@ jobs:
|
|||||||
patch=$((patch + 1))
|
patch=$((patch + 1))
|
||||||
fi
|
fi
|
||||||
|
|
||||||
if [ "${BUMP_TYPE:-}" = "development" ]; then
|
# Zusammenbau des Tags für den manuellen Run
|
||||||
TAG="v${major}.${minor}.${patch}-dev"
|
|
||||||
else
|
|
||||||
TAG="v${major}.${minor}.${patch}"
|
TAG="v${major}.${minor}.${patch}"
|
||||||
fi
|
fi
|
||||||
fi
|
|
||||||
|
|
||||||
|
# Validierung des erzeugten oder übergebenen Tags
|
||||||
if ! echo "$TAG" | grep -Eq '^v[0-9]+\.[0-9]+\.[0-9]+(-dev(\.[0-9]+)?)?$'; then
|
if ! echo "$TAG" | grep -Eq '^v[0-9]+\.[0-9]+\.[0-9]+(-dev(\.[0-9]+)?)?$'; then
|
||||||
echo "Error: tag '$TAG' is not valid semver (vX.Y.Z or vX.Y.Z-dev)"
|
echo "Error: tag '$TAG' is not valid semver (vX.Y.Z)"
|
||||||
exit 1
|
exit 1
|
||||||
fi
|
fi
|
||||||
|
|
||||||
git fetch --tags --force
|
git fetch --tags --force
|
||||||
LATEST_TAG="$(git tag -l 'v*' | grep -E '^v[0-9]+\.[0-9]+\.[0-9]+$' | sort -V | tail -n1)"
|
LATEST_TAG="$(git tag -l 'v*' | grep -E '^v[0-9]+\.[0-9]+\.[0-9]+$' | sort -V | tail -n1)"
|
||||||
if [ -z "$LATEST_TAG" ]; then
|
if [ -z "$LATEST_TAG" ]; then
|
||||||
LATEST_TAG="v3.0.0"
|
LATEST_TAG="v0.8.31"
|
||||||
fi
|
fi
|
||||||
|
|
||||||
TAG_MAJOR="${TAG#v}"
|
TAG_MAJOR="${TAG#v}"
|
||||||
TAG_MAJOR="${TAG_MAJOR%%.*}"
|
TAG_MAJOR="${TAG_MAJOR%%.*}"
|
||||||
LATEST_MAJOR="$(echo "$LATEST_TAG" | grep -Eo '^v[0-9]+' | tr -d 'v')"
|
LATEST_MAJOR="$(echo "$LATEST_TAG" | grep -Eo '^v[0-9]+' | tr -d 'v')"
|
||||||
if [ -z "$LATEST_MAJOR" ]; then
|
if [ -z "$LATEST_MAJOR" ]; then
|
||||||
LATEST_MAJOR="3"
|
LATEST_MAJOR="0"
|
||||||
fi
|
fi
|
||||||
|
|
||||||
# If not explicitly bumping major, disallow changing major version
|
# If not explicitly bumping major, disallow changing major version
|
||||||
@@ -123,33 +111,6 @@ jobs:
|
|||||||
IMAGE="ghcr.io/aiirondev/legendary-octo-garbanzo:${TAG}"
|
IMAGE="ghcr.io/aiirondev/legendary-octo-garbanzo:${TAG}"
|
||||||
echo "tag=$TAG" >> "$GITHUB_OUTPUT"
|
echo "tag=$TAG" >> "$GITHUB_OUTPUT"
|
||||||
echo "image=$IMAGE" >> "$GITHUB_OUTPUT"
|
echo "image=$IMAGE" >> "$GITHUB_OUTPUT"
|
||||||
if [ "${BUMP_TYPE:-}" = "development" ]; then
|
|
||||||
echo "is_development=true" >> "$GITHUB_OUTPUT"
|
|
||||||
else
|
|
||||||
echo "is_development=false" >> "$GITHUB_OUTPUT"
|
|
||||||
fi
|
|
||||||
if [ "${BUMP_TYPE:-}" = "development" ] && [ "${PUSH_DEV:-}" = "true" ]; then
|
|
||||||
echo "push_dev=true" >> "$GITHUB_OUTPUT"
|
|
||||||
else
|
|
||||||
echo "push_dev=false" >> "$GITHUB_OUTPUT"
|
|
||||||
fi
|
|
||||||
|
|
||||||
- name: Update .release-version file
|
|
||||||
run: |
|
|
||||||
echo "${{ steps.meta.outputs.tag }}" > .release-version
|
|
||||||
cat .release-version
|
|
||||||
|
|
||||||
- name: Create and push tag for manual releases
|
|
||||||
if: github.event_name == 'workflow_dispatch'
|
|
||||||
run: |
|
|
||||||
TAG="${{ steps.meta.outputs.tag }}"
|
|
||||||
git config user.name "github-actions[bot]"
|
|
||||||
git config user.email "github-actions[bot]@users.noreply.github.com"
|
|
||||||
git add .release-version
|
|
||||||
git commit -m "chore: bump version to $TAG" || true
|
|
||||||
git tag "$TAG"
|
|
||||||
git push origin "$TAG"
|
|
||||||
git push origin HEAD:${{ github.ref_name }}
|
|
||||||
|
|
||||||
- name: Set up Docker Buildx
|
- name: Set up Docker Buildx
|
||||||
uses: docker/setup-buildx-action@v3
|
uses: docker/setup-buildx-action@v3
|
||||||
@@ -162,26 +123,16 @@ jobs:
|
|||||||
password: ${{ secrets.GITHUB_TOKEN }}
|
password: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
|
||||||
- name: Build and push release image
|
- name: Build and push release image
|
||||||
if: steps.meta.outputs.is_development != 'true'
|
|
||||||
uses: docker/build-push-action@v6
|
uses: docker/build-push-action@v6
|
||||||
with:
|
with:
|
||||||
context: .
|
context: .
|
||||||
file: ./Dockerfile
|
file: ./Dockerfile
|
||||||
push: true
|
push: true
|
||||||
|
load: true # Lädt das Image in den lokalen Docker-Daemon für den 'docker save' Schritt
|
||||||
tags: |
|
tags: |
|
||||||
${{ steps.meta.outputs.image }}
|
${{ steps.meta.outputs.image }}
|
||||||
ghcr.io/aiirondev/legendary-octo-garbanzo:latest
|
ghcr.io/aiirondev/legendary-octo-garbanzo:latest
|
||||||
|
|
||||||
- name: Build and push development image (:dev)
|
|
||||||
if: steps.meta.outputs.is_development == 'true' && steps.meta.outputs.push_dev == 'true'
|
|
||||||
uses: docker/build-push-action@v6
|
|
||||||
with:
|
|
||||||
context: .
|
|
||||||
file: ./Dockerfile
|
|
||||||
push: true
|
|
||||||
tags: |
|
|
||||||
ghcr.io/aiirondev/legendary-octo-garbanzo:dev
|
|
||||||
|
|
||||||
- name: Build local image tar for offline deploy
|
- name: Build local image tar for offline deploy
|
||||||
run: |
|
run: |
|
||||||
set -euo pipefail
|
set -euo pipefail
|
||||||
@@ -204,30 +155,17 @@ jobs:
|
|||||||
docker build -t "$IMG" .
|
docker build -t "$IMG" .
|
||||||
docker save "$IMG" | gzip > "inventarsystem-image-${TAG}.tar.gz"
|
docker save "$IMG" | gzip > "inventarsystem-image-${TAG}.tar.gz"
|
||||||
|
|
||||||
# development tar omitted: dev releases will be versioned (vX.Y.Z-dev) and handled by update.sh using the tag
|
|
||||||
|
|
||||||
- name: Commit .release-version for tag pushes
|
|
||||||
if: github.event_name == 'push'
|
|
||||||
run: |
|
|
||||||
git config user.name "github-actions[bot]"
|
|
||||||
git config user.email "github-actions[bot]@users.noreply.github.com"
|
|
||||||
if ! git diff --quiet .release-version; then
|
|
||||||
git add .release-version
|
|
||||||
git commit -m "chore: update version to ${{ steps.meta.outputs.tag }}"
|
|
||||||
git push origin HEAD:${{ github.ref_name }}
|
|
||||||
fi
|
|
||||||
|
|
||||||
- name: Create release-only docker bundle
|
- name: Create release-only docker bundle
|
||||||
run: |
|
run: |
|
||||||
mkdir -p release-bundle
|
mkdir -p release-bundle
|
||||||
cat > release-bundle/docker-compose.yml <<EOF
|
cat > release-bundle/docker-compose.yml <<EOF
|
||||||
services:
|
services:
|
||||||
app:
|
app:
|
||||||
image: ${INVENTAR_APP_IMAGE:-ghcr.io/aiirondev/legendary-octo-garbanzo:${{ steps.meta.outputs.tag }}}
|
image: \${INVENTAR_APP_IMAGE:-ghcr.io/aiirondev/legendary-octo-garbanzo:${{ steps.meta.outputs.tag }}}
|
||||||
container_name: inventarsystem-app
|
container_name: inventarsystem-app
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
ports:
|
ports:
|
||||||
- "${INVENTAR_HTTP_PORT:-10000}:8000"
|
- "\${INVENTAR_HTTP_PORT:-10000}:8000"
|
||||||
depends_on:
|
depends_on:
|
||||||
- mongodb
|
- mongodb
|
||||||
- redis
|
- redis
|
||||||
@@ -300,17 +238,6 @@ jobs:
|
|||||||
fi
|
fi
|
||||||
done
|
done
|
||||||
|
|
||||||
cat > release-bundle/DEVELOPMENT.md <<EOF
|
|
||||||
This is a development prerelease bundle for tag: ${{ steps.meta.outputs.tag }}
|
|
||||||
|
|
||||||
This prerelease is intentionally separate from normal releases and will not be used by default.
|
|
||||||
|
|
||||||
To install this prerelease on a target host run:
|
|
||||||
|
|
||||||
./update.sh ${{ steps.meta.outputs.tag }}
|
|
||||||
|
|
||||||
EOF
|
|
||||||
|
|
||||||
# Make any shipped scripts executable
|
# Make any shipped scripts executable
|
||||||
find release-bundle -maxdepth 1 -type f -name '*.sh' -exec chmod +x {} \; || true
|
find release-bundle -maxdepth 1 -type f -name '*.sh' -exec chmod +x {} \; || true
|
||||||
tar -czf inventarsystem-docker-bundle.tar.gz -C release-bundle .
|
tar -czf inventarsystem-docker-bundle.tar.gz -C release-bundle .
|
||||||
@@ -319,10 +246,8 @@ jobs:
|
|||||||
uses: softprops/action-gh-release@v2
|
uses: softprops/action-gh-release@v2
|
||||||
with:
|
with:
|
||||||
tag_name: ${{ steps.meta.outputs.tag }}
|
tag_name: ${{ steps.meta.outputs.tag }}
|
||||||
prerelease: ${{ steps.meta.outputs.is_development }}
|
|
||||||
files: |
|
files: |
|
||||||
inventarsystem-docker-bundle.tar.gz
|
inventarsystem-docker-bundle.tar.gz
|
||||||
inventarsystem-image-${{ steps.meta.outputs.tag }}.tar.gz
|
inventarsystem-image-${{ steps.meta.outputs.tag }}.tar.gz
|
||||||
inventarsystem-image-dev.tar.gz
|
|
||||||
fail_on_unmatched_files: false
|
fail_on_unmatched_files: false
|
||||||
generate_release_notes: true
|
generate_release_notes: true
|
||||||
+1
-1
@@ -1 +1 @@
|
|||||||
v0.8.26
|
v0.8.31.1
|
||||||
|
|||||||
+163
-101
@@ -4823,6 +4823,22 @@ def get_user_appointments():
|
|||||||
|
|
||||||
result = []
|
result = []
|
||||||
import re as _re
|
import re as _re
|
||||||
|
|
||||||
|
def _date_iter(start_value: str, end_value: str):
|
||||||
|
try:
|
||||||
|
start_date = datetime.datetime.strptime(start_value, '%Y-%m-%d').date()
|
||||||
|
end_date = datetime.datetime.strptime(end_value, '%Y-%m-%d').date()
|
||||||
|
except Exception:
|
||||||
|
return []
|
||||||
|
if end_date < start_date:
|
||||||
|
end_date = start_date
|
||||||
|
cursor = start_date
|
||||||
|
days = []
|
||||||
|
while cursor <= end_date:
|
||||||
|
days.append(cursor.strftime('%Y-%m-%d'))
|
||||||
|
cursor += datetime.timedelta(days=1)
|
||||||
|
return days
|
||||||
|
|
||||||
for appt in appointments:
|
for appt in appointments:
|
||||||
appt_id = str(appt.get('_id') or '')
|
appt_id = str(appt.get('_id') or '')
|
||||||
if not appt_id:
|
if not appt_id:
|
||||||
@@ -4831,64 +4847,36 @@ def get_user_appointments():
|
|||||||
date_start = str(appt.get('date_start') or '')
|
date_start = str(appt.get('date_start') or '')
|
||||||
date_end = str(appt.get('date_end') or date_start)
|
date_end = str(appt.get('date_end') or date_start)
|
||||||
time_span = appt.get('time_span', []) or []
|
time_span = appt.get('time_span', []) or []
|
||||||
|
title = appt.get('note') or f"Termin von {appt.get('user') or ''}"
|
||||||
|
days_in_range = _date_iter(date_start, date_end) or ([date_start] if date_start else [])
|
||||||
|
|
||||||
# Determine a sensible start and end datetime for the event.
|
span_entries = []
|
||||||
# Prefer a time from the time_span for the first day and a time for the last day when multi-day.
|
|
||||||
start_dt_str = date_start
|
|
||||||
end_dt_str = date_end
|
|
||||||
first_time = None
|
|
||||||
last_time = None
|
|
||||||
generic_first = None
|
|
||||||
generic_last = None
|
|
||||||
try:
|
|
||||||
# collect times from spans
|
|
||||||
for entry in time_span:
|
for entry in time_span:
|
||||||
s = str(entry or '').strip()
|
s = str(entry or '').strip()
|
||||||
if not s:
|
if not s:
|
||||||
continue
|
continue
|
||||||
m_date = _re.match(r"^(\d{4}-\d{2}-\d{2})\s+(\d{2}:\d{2})-(\d{2}:\d{2})$", s)
|
m_date = _re.match(r"^(\d{4}-\d{2}-\d{2})\s+(\d{2}:\d{2})-(\d{2}:\d{2})$", s)
|
||||||
if m_date:
|
if m_date:
|
||||||
d = m_date.group(1)
|
span_entries.append((m_date.group(1), m_date.group(2), m_date.group(3)))
|
||||||
if d == date_start and not first_time:
|
|
||||||
first_time = m_date.group(2)
|
|
||||||
if d == date_end:
|
|
||||||
last_time = m_date.group(3)
|
|
||||||
continue
|
continue
|
||||||
m = _re.match(r"^(\d{2}:\d{2})-(\d{2}:\d{2})$", s)
|
m = _re.match(r"^(\d{2}:\d{2})-(\d{2}:\d{2})$", s)
|
||||||
if m:
|
if m:
|
||||||
if generic_first is None:
|
for day in days_in_range:
|
||||||
generic_first = m.group(1)
|
span_entries.append((day, m.group(1), m.group(2)))
|
||||||
generic_last = m.group(2)
|
|
||||||
|
|
||||||
if not first_time and generic_first:
|
# If the stored span is already day-specific, use it as-is.
|
||||||
first_time = generic_first
|
# If it was generic, we duplicated it to each day in the range above.
|
||||||
if not last_time and generic_last:
|
if not span_entries and days_in_range:
|
||||||
last_time = generic_last
|
# Fallback: create a simple all-day marker for each date so the appointment is visible.
|
||||||
|
for day in days_in_range:
|
||||||
|
span_entries.append((day, '08:00', '16:45'))
|
||||||
|
|
||||||
if first_time:
|
for day, start_time, end_time in span_entries:
|
||||||
start_dt_str = f"{date_start}T{first_time}"
|
|
||||||
|
|
||||||
# If appointment spans multiple days and we have a last_time for the final day, use it
|
|
||||||
if date_end != date_start:
|
|
||||||
if last_time:
|
|
||||||
end_dt_str = f"{date_end}T{last_time}"
|
|
||||||
else:
|
|
||||||
# span until end of final day
|
|
||||||
end_dt_str = f"{date_end}T23:59:59"
|
|
||||||
else:
|
|
||||||
if last_time:
|
|
||||||
end_dt_str = f"{date_start}T{last_time}"
|
|
||||||
except Exception:
|
|
||||||
# fallback: use whole-day span
|
|
||||||
if date_end != date_start:
|
|
||||||
end_dt_str = f"{date_end}T23:59:59"
|
|
||||||
|
|
||||||
title = appt.get('note') or f"Termin von {appt.get('user') or ''}"
|
|
||||||
result.append({
|
result.append({
|
||||||
'id': appt_id,
|
'id': f"{appt_id}-{day}-{start_time}",
|
||||||
'title': title,
|
'title': title,
|
||||||
'start': start_dt_str,
|
'start': f"{day}T{start_time}",
|
||||||
'end': end_dt_str,
|
'end': f"{day}T{end_time}",
|
||||||
'status': 'planned',
|
'status': 'planned',
|
||||||
'itemId': appt_id,
|
'itemId': appt_id,
|
||||||
'userName': str(appt.get('user') or ''),
|
'userName': str(appt.get('user') or ''),
|
||||||
@@ -9388,35 +9376,14 @@ def search_word(word):
|
|||||||
except Exception as e:
|
except Exception as e:
|
||||||
return jsonify({"success": False, "response": str(e)})
|
return jsonify({"success": False, "response": str(e)})
|
||||||
|
|
||||||
@app.route('/fetch_book_info/<isbn>')
|
def _fetch_from_google_books(clean_isbn):
|
||||||
def fetch_book_info(isbn):
|
"""Source 1: Google Books API (Free, No Key required for basic use)"""
|
||||||
"""
|
|
||||||
API endpoint to fetch book information by ISBN using Google Books API
|
|
||||||
|
|
||||||
Args:
|
|
||||||
isbn (str): ISBN to look up
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
dict: Book information or error message
|
|
||||||
"""
|
|
||||||
if 'username' not in session or not us.check_admin(session['username']):
|
|
||||||
return jsonify({"error": "Not authorized"}), 403
|
|
||||||
|
|
||||||
if not cfg.MODULES.is_enabled('library'):
|
|
||||||
return jsonify({"error": "Bibliotheks-Modul ist deaktiviert."}), 403
|
|
||||||
|
|
||||||
try:
|
try:
|
||||||
clean_isbn = normalize_and_validate_isbn(isbn)
|
url = f"https://www.googleapis.com/books/v1/volumes?q=isbn:{clean_isbn}"
|
||||||
if not clean_isbn:
|
response = requests.get(url, timeout=5)
|
||||||
return jsonify({"error": "Ungültige ISBN. Bitte ISBN-10 oder ISBN-13 verwenden."}), 400
|
if response.status_code != 200:
|
||||||
|
return None
|
||||||
|
|
||||||
# First source: Google Books
|
|
||||||
response = requests.get(
|
|
||||||
f"https://www.googleapis.com/books/v1/volumes?q=isbn:{clean_isbn}",
|
|
||||||
timeout=10
|
|
||||||
)
|
|
||||||
|
|
||||||
if response.status_code == 200:
|
|
||||||
data = response.json()
|
data = response.json()
|
||||||
if data.get('totalItems', 0) > 0 and data.get('items'):
|
if data.get('totalItems', 0) > 0 and data.get('items'):
|
||||||
book_info = data['items'][0].get('volumeInfo', {})
|
book_info = data['items'][0].get('volumeInfo', {})
|
||||||
@@ -9434,51 +9401,146 @@ def fetch_book_info(isbn):
|
|||||||
if thumbnail:
|
if thumbnail:
|
||||||
thumbnail = thumbnail.replace('http:', 'https:')
|
thumbnail = thumbnail.replace('http:', 'https:')
|
||||||
|
|
||||||
return jsonify({
|
return {
|
||||||
"title": book_info.get('title', 'Unknown Title'),
|
"title": book_info.get('title', 'Unknown Title'),
|
||||||
"authors": ', '.join(book_info.get('authors', ['Unknown Author'])),
|
"authors": ', '.join(book_info.get('authors', ['Unknown Author'])),
|
||||||
"publisher": book_info.get('publisher', 'Unknown Publisher'),
|
"publisher": book_info.get('publisher', 'Unknown Publisher'),
|
||||||
"publishedDate": book_info.get('publishedDate', 'Unknown Date'),
|
"publishedDate": book_info.get('publishedDate', 'Unknown Date'),
|
||||||
"description": book_info.get('description', 'No description available'),
|
"description": book_info.get('description', 'Keine Beschreibung verfügbar'),
|
||||||
"pageCount": book_info.get('pageCount', 'Unknown'),
|
"pageCount": book_info.get('pageCount', 'Unknown'),
|
||||||
"price": price,
|
"price": price,
|
||||||
"thumbnail": thumbnail,
|
"thumbnail": thumbnail,
|
||||||
"isbn": clean_isbn,
|
|
||||||
"source": "google-books"
|
"source": "google-books"
|
||||||
})
|
}
|
||||||
|
except Exception as e:
|
||||||
|
print(f"Google Books error: {e}")
|
||||||
|
return None
|
||||||
|
|
||||||
# Fallback: OpenLibrary
|
|
||||||
ol_response = requests.get(
|
def _fetch_from_lobid_germany(clean_isbn):
|
||||||
f"https://openlibrary.org/isbn/{clean_isbn}.json",
|
"""
|
||||||
timeout=10
|
Source 2: Lobid.org (hbz Network)
|
||||||
)
|
The ultimate free, keyless fallback for German Schoolbooks and DACH literature.
|
||||||
if ol_response.status_code == 200:
|
"""
|
||||||
ol_data = ol_response.json()
|
|
||||||
author_names = []
|
|
||||||
for author_ref in ol_data.get('authors', []):
|
|
||||||
key = author_ref.get('key')
|
|
||||||
if not key:
|
|
||||||
continue
|
|
||||||
try:
|
try:
|
||||||
author_resp = requests.get(f"https://openlibrary.org{key}.json", timeout=8)
|
url = f"https://lobid.org/resources?q=isbn:{clean_isbn}&format=json"
|
||||||
if author_resp.status_code == 200:
|
response = requests.get(url, timeout=5)
|
||||||
author_names.append(author_resp.json().get('name'))
|
if response.status_code != 200:
|
||||||
except Exception:
|
return None
|
||||||
continue
|
|
||||||
|
|
||||||
return jsonify({
|
data = response.json()
|
||||||
"title": ol_data.get('title', 'Unknown Title'),
|
if 'member' in data and len(data['member']) > 0:
|
||||||
"authors": ', '.join([a for a in author_names if a]) if author_names else 'Unknown Author',
|
book = data['member'][0]
|
||||||
"publisher": ', '.join(ol_data.get('publishers', [])) if ol_data.get('publishers') else 'Unknown Publisher',
|
|
||||||
"publishedDate": ol_data.get('publish_date', 'Unknown Date'),
|
# Extract Authors (Lobid uses a nested contribution array)
|
||||||
"description": (ol_data.get('description', {}).get('value') if isinstance(ol_data.get('description'), dict) else ol_data.get('description')) or 'No description available',
|
authors = []
|
||||||
"pageCount": ol_data.get('number_of_pages', 'Unknown'),
|
for contrib in book.get('contribution', []):
|
||||||
|
if 'agent' in contrib and 'label' in contrib['agent']:
|
||||||
|
authors.append(contrib['agent']['label'])
|
||||||
|
|
||||||
|
# Extract Publishers
|
||||||
|
publishers = []
|
||||||
|
for pub in book.get('publication', []):
|
||||||
|
if 'publishedBy' in pub:
|
||||||
|
# sometimes publishedBy is a list, sometimes a string
|
||||||
|
pub_data = pub['publishedBy']
|
||||||
|
if isinstance(pub_data, list):
|
||||||
|
publishers.extend(pub_data)
|
||||||
|
else:
|
||||||
|
publishers.append(pub_data)
|
||||||
|
|
||||||
|
# Extract Date
|
||||||
|
pub_date = 'Unknown Date'
|
||||||
|
if book.get('publication'):
|
||||||
|
pub_date = book['publication'][0].get('startDate', 'Unknown Date')
|
||||||
|
|
||||||
|
# Extract Pages
|
||||||
|
pages = book.get('extent', ['Unknown'])[0] if 'extent' in book else 'Unknown'
|
||||||
|
|
||||||
|
return {
|
||||||
|
"title": book.get('title', 'Unknown Title'),
|
||||||
|
"authors": ', '.join(authors) if authors else 'Unknown Author',
|
||||||
|
"publisher": ', '.join(publishers) if publishers else 'Unknown Publisher',
|
||||||
|
"publishedDate": str(pub_date),
|
||||||
|
"description": 'Keine Beschreibung verfügbar (Schulbuch / Fachliteratur)',
|
||||||
|
"pageCount": pages,
|
||||||
|
"price": None,
|
||||||
|
"thumbnail": "", # Lobid rarely has covers, we will fallback to OpenLibrary cover below
|
||||||
|
"source": "lobid-germany"
|
||||||
|
}
|
||||||
|
except Exception as e:
|
||||||
|
print(f"Lobid error: {e}")
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def _fetch_from_open_library(clean_isbn):
|
||||||
|
"""Source 3: Open Library Search API (Free, No Key required)"""
|
||||||
|
try:
|
||||||
|
url = f"https://openlibrary.org/search.json?isbn={clean_isbn}"
|
||||||
|
response = requests.get(url, timeout=5)
|
||||||
|
if response.status_code != 200:
|
||||||
|
return None
|
||||||
|
|
||||||
|
data = response.json()
|
||||||
|
if data.get('numFound', 0) > 0 and data.get('docs'):
|
||||||
|
book_info = data['docs'][0]
|
||||||
|
|
||||||
|
return {
|
||||||
|
"title": book_info.get('title', 'Unknown Title'),
|
||||||
|
"authors": ', '.join(book_info.get('author_name', ['Unknown Author'])),
|
||||||
|
"publisher": ', '.join(book_info.get('publisher', ['Unknown Publisher'])),
|
||||||
|
"publishedDate": str(book_info.get('publish_date', ['Unknown Date'])[0]),
|
||||||
|
"description": 'Keine Beschreibung verfügbar',
|
||||||
|
"pageCount": book_info.get('number_of_pages_median', 'Unknown'),
|
||||||
"price": None,
|
"price": None,
|
||||||
"thumbnail": f"https://covers.openlibrary.org/b/isbn/{clean_isbn}-L.jpg",
|
"thumbnail": f"https://covers.openlibrary.org/b/isbn/{clean_isbn}-L.jpg",
|
||||||
"isbn": clean_isbn,
|
|
||||||
"source": "openlibrary"
|
"source": "openlibrary"
|
||||||
})
|
}
|
||||||
|
except Exception as e:
|
||||||
|
print(f"OpenLibrary Search error: {e}")
|
||||||
|
return None
|
||||||
|
|
||||||
|
@app.route('/fetch_book_info/<isbn>')
|
||||||
|
def fetch_book_info(isbn):
|
||||||
|
"""
|
||||||
|
API endpoint to fetch book information by ISBN using multiple open sources.
|
||||||
|
Optimized for global literature AND German educational books.
|
||||||
|
"""
|
||||||
|
# Authorization Checks
|
||||||
|
if 'username' not in session or not us.check_admin(session['username']):
|
||||||
|
return jsonify({"error": "Not authorized"}), 403
|
||||||
|
|
||||||
|
if not cfg.MODULES.is_enabled('library'):
|
||||||
|
return jsonify({"error": "Bibliotheks-Modul ist deaktiviert."}), 403
|
||||||
|
|
||||||
|
try:
|
||||||
|
# Validation
|
||||||
|
clean_isbn = normalize_and_validate_isbn(isbn)
|
||||||
|
if not clean_isbn:
|
||||||
|
return jsonify({"error": "Ungültige ISBN. Bitte ISBN-10 oder ISBN-13 verwenden."}), 400
|
||||||
|
|
||||||
|
# Define the Provider Chain (Order matters: General -> German/School -> Global Fallback)
|
||||||
|
providers = [
|
||||||
|
_fetch_from_google_books,
|
||||||
|
_fetch_from_lobid_germany,
|
||||||
|
_fetch_from_open_library
|
||||||
|
]
|
||||||
|
|
||||||
|
# Iterate through providers until a book is found
|
||||||
|
for provider in providers:
|
||||||
|
book_data = provider(clean_isbn)
|
||||||
|
|
||||||
|
if book_data:
|
||||||
|
# Add the ISBN back into the response payload
|
||||||
|
book_data["isbn"] = clean_isbn
|
||||||
|
|
||||||
|
# If a provider found the book but had no cover, assign a default OpenLibrary cover fallback
|
||||||
|
if not book_data.get("thumbnail"):
|
||||||
|
book_data["thumbnail"] = f"https://covers.openlibrary.org/b/isbn/{clean_isbn}-L.jpg"
|
||||||
|
|
||||||
|
return jsonify(book_data)
|
||||||
|
|
||||||
|
# If all providers fail
|
||||||
return jsonify({"error": f"Kein Buch zu dieser ISBN gefunden: {clean_isbn}"}), 404
|
return jsonify({"error": f"Kein Buch zu dieser ISBN gefunden: {clean_isbn}"}), 404
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
|
|||||||
@@ -1295,11 +1295,6 @@
|
|||||||
</li>
|
</li>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
{% if 'username' in session %}
|
{% if 'username' in session %}
|
||||||
{% if current_permissions.pages.get('my_borrowed_items', True) %}
|
|
||||||
<li class="nav-item">
|
|
||||||
<a class="nav-link quick-link-pill {% if current_path == url_for('my_borrowed_items') %}nav-active{% endif %}" href="{{ url_for('my_borrowed_items') }}" data-tutorial-tip="Hier sehen Sie Ihre bibliotheksbezogenen Ausleihen.">Meine Medien</a>
|
|
||||||
</li>
|
|
||||||
{% endif %}
|
|
||||||
{% if current_permissions.pages.get('tutorial_page', True) %}
|
{% if current_permissions.pages.get('tutorial_page', True) %}
|
||||||
<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>
|
||||||
|
|||||||
+60
-49
@@ -10,24 +10,6 @@
|
|||||||
<h1>📚 Bibliothek</h1>
|
<h1>📚 Bibliothek</h1>
|
||||||
<p class="subtitle">Bücher, CDs und weitere Medien</p>
|
<p class="subtitle">Bücher, CDs und weitere Medien</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="header-controls">
|
|
||||||
<!-- Favorites Toggle -->
|
|
||||||
<div class="view-switch">
|
|
||||||
<button id="favoriteToggle" class="toggle-btn" aria-label="Favoriten anzeigen/verbergen">
|
|
||||||
<span class="toggle-icon">⭐</span>
|
|
||||||
<span class="toggle-label">Favoriten</span>
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<!-- View Mode Toggle -->
|
|
||||||
<div class="view-switch">
|
|
||||||
<button id="viewModeToggle" class="toggle-btn" aria-label="Ansichtsmodus wechseln">
|
|
||||||
<span class="toggle-icon">ㄷ</span>
|
|
||||||
<span class="toggle-label">Tabelle</span>
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- Search & Filter Section -->
|
<!-- Search & Filter Section -->
|
||||||
@@ -205,8 +187,7 @@
|
|||||||
</form>
|
</form>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
<script src="https://cdn.jsdelivr.net/npm/@ericblade/quagga2/dist/quagga.js"></script>
|
||||||
<script src="https://cdn.jsdelivr.net/npm/html5-qrcode/minified/html5-qrcode.min.js"></script>
|
|
||||||
<script>
|
<script>
|
||||||
// View mode persistence
|
// View mode persistence
|
||||||
const LIBRARY_VIEW_MODE_KEY = 'inventarLibraryViewMode';
|
const LIBRARY_VIEW_MODE_KEY = 'inventarLibraryViewMode';
|
||||||
@@ -625,50 +606,80 @@ document.getElementById('clearFiltersBtn').addEventListener('click', function()
|
|||||||
closeAllFilters();
|
closeAllFilters();
|
||||||
});
|
});
|
||||||
|
|
||||||
// Favorites toggle
|
|
||||||
document.getElementById('favoriteToggle').addEventListener('click', function() {
|
|
||||||
this.classList.toggle('open');
|
|
||||||
// TODO: Implement favorites filtering
|
|
||||||
});
|
|
||||||
|
|
||||||
// Scanner toggle
|
// Scanner toggle
|
||||||
let scanner = null;
|
// Scanner state tracking
|
||||||
|
let isScanning = false;
|
||||||
|
|
||||||
document.getElementById('scannerBtn').addEventListener('click', function(e) {
|
document.getElementById('scannerBtn').addEventListener('click', function(e) {
|
||||||
e.stopPropagation();
|
e.stopPropagation();
|
||||||
const container = document.getElementById('qrContainer');
|
const container = document.getElementById('qrContainer');
|
||||||
const isOpen = container.style.display !== 'none';
|
const isOpen = container.style.display !== 'none';
|
||||||
|
const btn = this;
|
||||||
|
|
||||||
if (isOpen) {
|
if (isOpen) {
|
||||||
|
// Close the scanner
|
||||||
container.style.display = 'none';
|
container.style.display = 'none';
|
||||||
if (scanner) scanner.clear();
|
Quagga.stop();
|
||||||
this.classList.remove('open');
|
isScanning = false;
|
||||||
this.setAttribute('aria-expanded', 'false');
|
|
||||||
} else {
|
|
||||||
container.style.display = 'block';
|
|
||||||
this.classList.add('open');
|
|
||||||
this.setAttribute('aria-expanded', 'true');
|
|
||||||
|
|
||||||
if (!scanner) {
|
btn.classList.remove('open');
|
||||||
scanner = new Html5Qrcode('qr-reader');
|
btn.setAttribute('aria-expanded', 'false');
|
||||||
scanner.start(
|
} else {
|
||||||
{ facingMode: "environment" },
|
// Open the scanner
|
||||||
{ fps: 10, qrbox: 250 },
|
container.style.display = 'block';
|
||||||
onScanSuccess,
|
btn.classList.add('open');
|
||||||
onScanError
|
btn.setAttribute('aria-expanded', 'true');
|
||||||
);
|
|
||||||
|
Quagga.init({
|
||||||
|
inputStream: {
|
||||||
|
name: "Live",
|
||||||
|
type: "LiveStream",
|
||||||
|
// Targets the element where the video stream will inject
|
||||||
|
target: document.querySelector('#qr-reader'),
|
||||||
|
constraints: {
|
||||||
|
width: 640,
|
||||||
|
height: 480,
|
||||||
|
facingMode: "environment" // Forces back camera
|
||||||
|
},
|
||||||
|
},
|
||||||
|
decoder: {
|
||||||
|
// Optimized for 1D barcodes (e.g., student IDs, member cards)
|
||||||
|
readers: ["code_128_reader", "ean_reader", "code_39_reader", "upc_reader"]
|
||||||
}
|
}
|
||||||
|
}, function(err) {
|
||||||
|
if (err) {
|
||||||
|
console.error("Initialization error:", err);
|
||||||
|
alert("Kamera konnte nicht gestartet werden.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
Quagga.start();
|
||||||
|
isScanning = true;
|
||||||
|
});
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
function onScanSuccess(decodedText, decodedResult) {
|
// Single Quagga event listener for successful scans
|
||||||
const studentId = decodedText.trim();
|
Quagga.onDetected(function(data) {
|
||||||
|
const decodedText = data.codeResult.code;
|
||||||
|
const studentId = String(decodedText || '').trim();
|
||||||
|
|
||||||
|
// Stop scanning immediately to prevent multiple triggers
|
||||||
|
Quagga.stop();
|
||||||
|
isScanning = false;
|
||||||
|
|
||||||
|
// Reset UI states to closed
|
||||||
|
const container = document.getElementById('qrContainer');
|
||||||
|
const btn = document.getElementById('scannerBtn');
|
||||||
|
if (container) container.style.display = 'none';
|
||||||
|
if (btn) {
|
||||||
|
btn.classList.remove('open');
|
||||||
|
btn.setAttribute('aria-expanded', 'false');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Route the scanned data to your input
|
||||||
document.getElementById('studentIdInput').value = studentId;
|
document.getElementById('studentIdInput').value = studentId;
|
||||||
alert('Ausweis gescannt: ' + studentId);
|
alert('Ausweis gescannt: ' + studentId);
|
||||||
}
|
});
|
||||||
|
|
||||||
function onScanError(error) {
|
|
||||||
// Silently ignore scan errors
|
|
||||||
}
|
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<style>
|
<style>
|
||||||
|
|||||||
+313
-330
@@ -431,7 +431,7 @@
|
|||||||
type="text"
|
type="text"
|
||||||
id="librarySearch"
|
id="librarySearch"
|
||||||
class="library-search-input"
|
class="library-search-input"
|
||||||
placeholder="Nach Titel, Autor, ISBN suchen..."
|
placeholder="Nach Titel, ISBN suchen..."
|
||||||
>
|
>
|
||||||
<button
|
<button
|
||||||
id="filterToggleBtn"
|
id="filterToggleBtn"
|
||||||
@@ -458,16 +458,14 @@
|
|||||||
<div id="scanStatus" class="library-scan-status">
|
<div id="scanStatus" class="library-scan-status">
|
||||||
Hinweis: Im Schnellmodus zuerst den Schülerausweis scannen, danach den Buch-/Mediencode.
|
Hinweis: Im Schnellmodus zuerst den Schülerausweis scannen, danach den Buch-/Mediencode.
|
||||||
</div>
|
</div>
|
||||||
<div id="scanReaderWrap" class="library-scan-reader-wrap">
|
<div id="scanReaderWrap" class="library-scan-reader-wrap" style="display: none;">
|
||||||
<div id="libraryQrReader" class="library-scan-reader"></div>
|
<div id="libraryQrReader" class="library-scan-reader">
|
||||||
|
<div id="library-scanner-container"></div>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<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">
|
|
||||||
<label for="filterAuthor">Autor/Künstler:</label>
|
|
||||||
<input type="text" id="filterAuthor" placeholder="z.B. Goethe">
|
|
||||||
</div>
|
|
||||||
<div class="filter-item">
|
<div class="filter-item">
|
||||||
<label for="filterISBN">ISBN:</label>
|
<label for="filterISBN">ISBN:</label>
|
||||||
<input type="text" id="filterISBN" placeholder="z.B. 978-3...">
|
<input type="text" id="filterISBN" placeholder="z.B. 978-3...">
|
||||||
@@ -514,7 +512,6 @@
|
|||||||
<thead>
|
<thead>
|
||||||
<tr>
|
<tr>
|
||||||
<th style="width: 24%;">Titel</th>
|
<th style="width: 24%;">Titel</th>
|
||||||
<th style="width: 14%;">Autor/Künstler</th>
|
|
||||||
<th style="width: 12%;">ISBN/Code</th>
|
<th style="width: 12%;">ISBN/Code</th>
|
||||||
<th style="width: 8%;">Typ</th>
|
<th style="width: 8%;">Typ</th>
|
||||||
<th style="width: 8%;">Anzahl</th>
|
<th style="width: 8%;">Anzahl</th>
|
||||||
@@ -547,15 +544,17 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<script src="https://cdn.jsdelivr.net/npm/html5-qrcode/minified/html5-qrcode.min.js"></script>
|
<script src="https://cdn.jsdelivr.net/npm/@ericblade/quagga2/dist/quagga.js"></script>
|
||||||
|
<script src="https://cdn.jsdelivr.net/npm/@ericblade/quagga2/dist/quagga.js"></script>
|
||||||
<script>
|
<script>
|
||||||
// State
|
// =========================================================================
|
||||||
|
// 1. GLOBAL STATE DEFINITIONS
|
||||||
|
// =========================================================================
|
||||||
let libraryItems = [];
|
let libraryItems = [];
|
||||||
let filteredItems = [];
|
let filteredItems = [];
|
||||||
let visibleItems = [];
|
let visibleItems = [];
|
||||||
let currentSearchTerm = '';
|
let currentSearchTerm = '';
|
||||||
let activeFilters = {
|
let activeFilters = {
|
||||||
author: '',
|
|
||||||
isbn: '',
|
isbn: '',
|
||||||
type: '',
|
type: '',
|
||||||
status: ''
|
status: ''
|
||||||
@@ -571,13 +570,20 @@
|
|||||||
const RENDER_BATCH_COUNT = 120;
|
const RENDER_BATCH_COUNT = 120;
|
||||||
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 activeStudentCardId = '';
|
let activeStudentCardId = '';
|
||||||
let lastScanValue = '';
|
let lastScanValue = '';
|
||||||
let lastScanAt = 0;
|
let lastScanAt = 0;
|
||||||
|
|
||||||
const canEditLibraryItems = (document.getElementById('libraryTableContainer')?.dataset.canEdit === '1');
|
const canEditLibraryItems = (document.getElementById('libraryTableContainer')?.dataset.canEdit === '1');
|
||||||
|
|
||||||
|
// =========================================================================
|
||||||
|
// 2. DATA LOADING & FILTERING ENGINE
|
||||||
|
// =========================================================================
|
||||||
async function fetchLibraryPage(offset, limit) {
|
async function fetchLibraryPage(offset, limit) {
|
||||||
const response = await fetch(`/api/library_items?offset=${offset}&limit=${limit}`);
|
const response = await fetch(`/api/library_items?offset=${offset}&limit=${limit}`);
|
||||||
if (!response.ok) {
|
if (!response.ok) {
|
||||||
@@ -586,7 +592,6 @@
|
|||||||
return response.json();
|
return response.json();
|
||||||
}
|
}
|
||||||
|
|
||||||
// Load items progressively: first page immediately, rest in background
|
|
||||||
async function loadLibraryItems() {
|
async function loadLibraryItems() {
|
||||||
if (pagingState.loading) return;
|
if (pagingState.loading) return;
|
||||||
pagingState.loading = true;
|
pagingState.loading = true;
|
||||||
@@ -625,7 +630,6 @@
|
|||||||
pagingState.total = page.total || pagingState.total;
|
pagingState.total = page.total || pagingState.total;
|
||||||
pagingState.hasMore = Boolean(page.has_more);
|
pagingState.hasMore = Boolean(page.has_more);
|
||||||
|
|
||||||
// Keep the current view reactive while avoiding a full rerender burst.
|
|
||||||
applyFiltersAndSearch(false);
|
applyFiltersAndSearch(false);
|
||||||
|
|
||||||
if ('requestIdleCallback' in window) {
|
if ('requestIdleCallback' in window) {
|
||||||
@@ -641,18 +645,16 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
function filterItems(items) {
|
function filterItems(items) {
|
||||||
const author = activeFilters.author;
|
|
||||||
const isbn = activeFilters.isbn;
|
const isbn = activeFilters.isbn;
|
||||||
const type = activeFilters.type;
|
const type = activeFilters.type;
|
||||||
const status = activeFilters.status;
|
const status = activeFilters.status;
|
||||||
|
|
||||||
return items.filter(item => {
|
return items.filter(item => {
|
||||||
const authorMatch = !author || (item.Autor || item.Author || '').toLowerCase().includes(author);
|
|
||||||
const isbnMatch = !isbn || (item.ISBN || item.Code_4 || item.Code4 || '').toLowerCase().includes(isbn);
|
const isbnMatch = !isbn || (item.ISBN || item.Code_4 || item.Code4 || '').toLowerCase().includes(isbn);
|
||||||
const typeMatch = !type || (item.ItemType || 'book') === type;
|
const typeMatch = !type || (item.ItemType || 'book') === type;
|
||||||
const statusKey = item.LibraryDisplayStatus || (item.Verfuegbar === false ? 'borrowed' : 'available');
|
const statusKey = item.LibraryDisplayStatus || (item.Verfuegbar === false ? 'borrowed' : 'available');
|
||||||
const statusMatch = !status || statusKey === status;
|
const statusMatch = !status || statusKey === status;
|
||||||
return authorMatch && isbnMatch && typeMatch && statusMatch;
|
return isbnMatch && typeMatch && statusMatch;
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -660,7 +662,6 @@
|
|||||||
if (!currentSearchTerm) return items;
|
if (!currentSearchTerm) return items;
|
||||||
return items.filter(item =>
|
return items.filter(item =>
|
||||||
(item.Name || '').toLowerCase().includes(currentSearchTerm) ||
|
(item.Name || '').toLowerCase().includes(currentSearchTerm) ||
|
||||||
(item.Autor || item.Author || '').toLowerCase().includes(currentSearchTerm) ||
|
|
||||||
(item.ISBN || item.Code_4 || item.Code4 || '').toLowerCase().includes(currentSearchTerm)
|
(item.ISBN || item.Code_4 || item.Code4 || '').toLowerCase().includes(currentSearchTerm)
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -677,7 +678,6 @@
|
|||||||
renderItems();
|
renderItems();
|
||||||
}
|
}
|
||||||
|
|
||||||
// Display current view with incremental rendering
|
|
||||||
function renderItems() {
|
function renderItems() {
|
||||||
const tbody = document.getElementById('itemsTableBody');
|
const tbody = document.getElementById('itemsTableBody');
|
||||||
const emptyState = document.getElementById('emptyState');
|
const emptyState = document.getElementById('emptyState');
|
||||||
@@ -695,8 +695,7 @@
|
|||||||
emptyState.style.display = 'none';
|
emptyState.style.display = 'none';
|
||||||
const rowsToRender = visibleItems.slice(0, renderedCount);
|
const rowsToRender = visibleItems.slice(0, renderedCount);
|
||||||
|
|
||||||
tbody.innerHTML = rowsToRender.map(item => `
|
tbody.innerHTML = rowsToRender.map(item => {
|
||||||
${(() => {
|
|
||||||
const statusKey = item.LibraryDisplayStatus || (item.Verfuegbar === false ? 'borrowed' : 'available');
|
const statusKey = item.LibraryDisplayStatus || (item.Verfuegbar === false ? 'borrowed' : 'available');
|
||||||
const statusClass = statusKey === 'damaged' ? 'status-damaged' : (statusKey === 'borrowed' ? 'status-borrowed' : 'status-available');
|
const statusClass = statusKey === 'damaged' ? 'status-damaged' : (statusKey === 'borrowed' ? 'status-borrowed' : 'status-available');
|
||||||
const statusText = statusKey === 'damaged' ? 'Defekt/Zerstört' : (statusKey === 'borrowed' ? 'Ausgeliehen' : 'Verfügbar');
|
const statusText = statusKey === 'damaged' ? 'Defekt/Zerstört' : (statusKey === 'borrowed' ? 'Ausgeliehen' : 'Verfügbar');
|
||||||
@@ -705,7 +704,6 @@
|
|||||||
return `
|
return `
|
||||||
<tr>
|
<tr>
|
||||||
<td class="table-title">${escapeHtml(item.Name || 'Untitled')}</td>
|
<td class="table-title">${escapeHtml(item.Name || 'Untitled')}</td>
|
||||||
<td>${escapeHtml(item.Autor || item.Author || '-')}</td>
|
|
||||||
<td>${escapeHtml(item.ISBN || item.Code_4 || item.Code4 || '-')}</td>
|
<td>${escapeHtml(item.ISBN || item.Code_4 || item.Code4 || '-')}</td>
|
||||||
<td>${getItemTypeLabel(item.ItemType || 'book')}</td>
|
<td>${getItemTypeLabel(item.ItemType || 'book')}</td>
|
||||||
<td style="font-weight:600; text-align:center;">${item.Quantity || item.GroupedDisplayCount || 1}</td>
|
<td style="font-weight:600; text-align:center;">${item.Quantity || item.GroupedDisplayCount || 1}</td>
|
||||||
@@ -722,10 +720,8 @@
|
|||||||
${canEditLibraryItems ? `<button class="button" style="background:#0ea5e9;color:#fff;" onclick="openEditLibraryItem('${item._id}')">Bearbeiten</button>` : ''}
|
${canEditLibraryItems ? `<button class="button" style="background:#0ea5e9;color:#fff;" 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>`;
|
||||||
`;
|
}).join('');
|
||||||
})()}
|
|
||||||
`).join('');
|
|
||||||
|
|
||||||
const canLoadMoreRows = renderedCount < visibleItems.length;
|
const canLoadMoreRows = renderedCount < visibleItems.length;
|
||||||
if (canLoadMoreRows) {
|
if (canLoadMoreRows) {
|
||||||
@@ -740,13 +736,6 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Confirm and call library item delete endpoint
|
|
||||||
function confirmDeleteLibraryItem(itemId) {
|
|
||||||
if (!itemId) return;
|
|
||||||
if (!confirm('Dieses Bibliotheksmedium revisionssicher löschen? Diese Aktion deaktiviert alle zugehörigen Exemplare und archiviert Medien.')) return;
|
|
||||||
deleteLibraryItem(itemId);
|
|
||||||
}
|
|
||||||
|
|
||||||
async function deleteLibraryItem(itemId) {
|
async function deleteLibraryItem(itemId) {
|
||||||
if (!itemId) return;
|
if (!itemId) return;
|
||||||
document.body.style.cursor = 'wait';
|
document.body.style.cursor = 'wait';
|
||||||
@@ -770,7 +759,6 @@
|
|||||||
}
|
}
|
||||||
loadLibraryItems();
|
loadLibraryItems();
|
||||||
} else {
|
} else {
|
||||||
// Server redirected to HTML (flash messages). Reload to show state.
|
|
||||||
location.reload();
|
location.reload();
|
||||||
}
|
}
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
@@ -781,72 +769,183 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Filter toggle
|
function confirmDeleteLibraryItem(itemId) {
|
||||||
document.getElementById('filterToggleBtn').addEventListener('click', () => {
|
if (!itemId) return;
|
||||||
filterPanelOpen = !filterPanelOpen;
|
if (!confirm('Dieses Bibliotheksmedium revisionssicher löschen? Diese Aktion deaktiviert alle zugehörigen Exemplare und archiviert Medien.')) return;
|
||||||
const panel = document.getElementById('filterPanel');
|
deleteLibraryItem(itemId);
|
||||||
const btn = document.getElementById('filterToggleBtn');
|
|
||||||
panel.classList.toggle('open');
|
|
||||||
btn.classList.toggle('active');
|
|
||||||
});
|
|
||||||
|
|
||||||
// Apply filters
|
|
||||||
document.getElementById('applyFilterBtn').addEventListener('click', () => {
|
|
||||||
activeFilters.author = document.getElementById('filterAuthor').value.toLowerCase();
|
|
||||||
activeFilters.isbn = document.getElementById('filterISBN').value.toLowerCase();
|
|
||||||
activeFilters.type = document.getElementById('filterType').value;
|
|
||||||
activeFilters.status = document.getElementById('filterStatus').value;
|
|
||||||
applyFiltersAndSearch(true);
|
|
||||||
});
|
|
||||||
|
|
||||||
// Clear filters
|
|
||||||
document.getElementById('clearFilterBtn').addEventListener('click', () => {
|
|
||||||
document.getElementById('filterAuthor').value = '';
|
|
||||||
document.getElementById('filterISBN').value = '';
|
|
||||||
document.getElementById('filterType').value = '';
|
|
||||||
document.getElementById('filterStatus').value = '';
|
|
||||||
activeFilters = { author: '', isbn: '', type: '', status: '' };
|
|
||||||
applyFiltersAndSearch(true);
|
|
||||||
});
|
|
||||||
|
|
||||||
// Search input
|
|
||||||
document.getElementById('librarySearch').addEventListener('input', (e) => {
|
|
||||||
currentSearchTerm = (e.target.value || '').toLowerCase();
|
|
||||||
applyFiltersAndSearch(true);
|
|
||||||
});
|
|
||||||
|
|
||||||
document.getElementById('loadMoreBtn').addEventListener('click', () => {
|
|
||||||
renderedCount = Math.min(renderedCount + RENDER_BATCH_COUNT, visibleItems.length);
|
|
||||||
renderItems();
|
|
||||||
});
|
|
||||||
|
|
||||||
// Helper functions
|
|
||||||
function getItemTypeLabel(type) {
|
|
||||||
const labels = { 'book': 'Buch', 'cd': 'CD', 'dvd': 'DVD', 'other': 'Sonstige' };
|
|
||||||
return labels[type] || type;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function escapeHtml(text) {
|
// =========================================================================
|
||||||
const div = document.createElement('div');
|
// 3. CORE SCANNER ROUTING ENGINE (QUAGGA2)
|
||||||
div.textContent = text;
|
// =========================================================================
|
||||||
return div.innerHTML;
|
function startScanner(targetCallback) {
|
||||||
|
const readerWrap = document.getElementById('scanReaderWrap');
|
||||||
|
const toggleBtn = document.getElementById('toggleScannerBtn');
|
||||||
|
|
||||||
|
activeScannerCallback = targetCallback;
|
||||||
|
|
||||||
|
if (readerWrap) readerWrap.style.display = 'block';
|
||||||
|
setScanStatus('Initializing camera...', 'warn');
|
||||||
|
|
||||||
|
Quagga.init({
|
||||||
|
inputStream: {
|
||||||
|
name: "Live",
|
||||||
|
type: "LiveStream",
|
||||||
|
target: document.querySelector('#library-scanner-container'),
|
||||||
|
constraints: {
|
||||||
|
width: 640,
|
||||||
|
height: 480,
|
||||||
|
facingMode: "environment"
|
||||||
|
},
|
||||||
|
},
|
||||||
|
decoder: {
|
||||||
|
readers: [
|
||||||
|
"code_128_reader",
|
||||||
|
"ean_reader",
|
||||||
|
"code_39_reader",
|
||||||
|
"upc_reader",
|
||||||
|
"codabar_reader",
|
||||||
|
"i2of5_reader"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}, function(err) {
|
||||||
|
if (err) {
|
||||||
|
console.error('Scanner start failed:', err);
|
||||||
|
if (readerWrap) readerWrap.style.display = 'none';
|
||||||
|
const detail = (err && (err.message || err.name)) ? ` (${err.message || err.name})` : '';
|
||||||
|
setScanStatus(`Scanner konnte nicht gestartet werden${detail}`, 'error');
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
function showItemDetail(itemId) {
|
Quagga.start();
|
||||||
// Load and show detail modal
|
scannerRunning = true;
|
||||||
fetch(`/api/item_detail/${itemId}`)
|
|
||||||
.then(r => r.text())
|
if (!targetCallback && toggleBtn) {
|
||||||
.then(html => {
|
toggleBtn.textContent = 'Scanner stoppen';
|
||||||
document.getElementById('detailContent').innerHTML = html;
|
}
|
||||||
document.getElementById('detailModal').style.display = 'flex';
|
setScanStatus('Scanner aktiv. Jetzt Code scannen.', 'warn');
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function stopScanner() {
|
||||||
|
if (!scannerRunning) return;
|
||||||
|
|
||||||
|
const readerWrap = document.getElementById('scanReaderWrap');
|
||||||
|
const toggleBtn = document.getElementById('toggleScannerBtn');
|
||||||
|
|
||||||
|
Quagga.stop();
|
||||||
|
scannerRunning = false;
|
||||||
|
activeScannerCallback = null;
|
||||||
|
|
||||||
|
if (readerWrap) readerWrap.style.display = 'none';
|
||||||
|
if (toggleBtn) toggleBtn.textContent = 'Scanner starten';
|
||||||
|
setScanStatus('Scanner gestoppt.', 'warn');
|
||||||
|
}
|
||||||
|
|
||||||
|
Quagga.onDetected(function(data) {
|
||||||
|
if (!data || !data.codeResult || !data.codeResult.code) return;
|
||||||
|
|
||||||
|
const barcode = String(data.codeResult.code || '').trim();
|
||||||
|
console.log("Barcode detected:", barcode);
|
||||||
|
|
||||||
|
const currentCallback = activeScannerCallback;
|
||||||
|
stopScanner();
|
||||||
|
|
||||||
|
if (typeof currentCallback === "function") {
|
||||||
|
currentCallback(barcode);
|
||||||
|
} else {
|
||||||
|
handleScanSuccess(barcode);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
function handleScanSuccess(decodedText) {
|
||||||
|
const scannedCode = normalizeScannedCode(decodedText);
|
||||||
|
if (!scannedCode) return;
|
||||||
|
|
||||||
|
const now = Date.now();
|
||||||
|
if (scannedCode === lastScanValue && (now - lastScanAt) < 1500) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
lastScanValue = scannedCode;
|
||||||
|
lastScanAt = now;
|
||||||
|
|
||||||
|
const mode = (document.getElementById('scanModeSelect') || {}).value || 'card_only';
|
||||||
|
if (mode === 'card_only') {
|
||||||
|
setActiveStudentCard(scannedCode);
|
||||||
|
setScanStatus(`Ausweis gesetzt: ${activeStudentCardId}`, 'ok');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
processQuickToggleScan(scannedCode);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function processQuickToggleScan(scannedCode) {
|
||||||
|
if (!activeStudentCardId) {
|
||||||
|
setActiveStudentCard(scannedCode);
|
||||||
|
setScanStatus(`Ausweis gesetzt: ${activeStudentCardId}`, 'ok');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
setScanStatus('Verarbeite Mediencode...', 'warn');
|
||||||
|
const response = await fetch('/api/library_scan_action', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {'Content-Type': 'application/json'},
|
||||||
|
body: JSON.stringify({
|
||||||
|
student_card_id: activeStudentCardId,
|
||||||
|
item_code: scannedCode
|
||||||
})
|
})
|
||||||
.catch(err => console.error('Error loading detail:', err));
|
});
|
||||||
|
|
||||||
|
const result = await response.json();
|
||||||
|
if (!response.ok || !result.ok) {
|
||||||
|
setScanStatus(result.message || 'Scan-Aktion fehlgeschlagen.', 'error');
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
function closeDetailModal() {
|
if (result.action === 'borrowed') {
|
||||||
document.getElementById('detailModal').style.display = 'none';
|
setScanStatus(`Ausgeliehen: ${result.item_name}`, 'ok');
|
||||||
|
} else if (result.action === 'returned') {
|
||||||
|
setScanStatus(`Zurückgegeben: ${result.item_name}`, 'ok');
|
||||||
|
} else {
|
||||||
|
setScanStatus(result.message || 'Aktion durchgeführt.', 'ok');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
await loadLibraryItems();
|
||||||
|
} catch (err) {
|
||||||
|
console.error('Quick scan action failed:', err);
|
||||||
|
setScanStatus('Fehler beim Verarbeiten des Scans.', 'error');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function scanIntoEditCode() {
|
||||||
|
const scanReaderWrap = document.getElementById('scanReaderWrap');
|
||||||
|
const editCodeInput = document.getElementById('edit-code4');
|
||||||
|
const scanEditBtn = document.getElementById('scan-edit-code-btn');
|
||||||
|
if (!scanReaderWrap || !editCodeInput || !scanEditBtn) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (scannerRunning && scanReaderWrap.style.display !== 'none') {
|
||||||
|
stopScanner();
|
||||||
|
scanEditBtn.textContent = 'Barcode scannen';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
scanEditBtn.textContent = 'Scanner schließen';
|
||||||
|
|
||||||
|
startScanner(function(decodedText) {
|
||||||
|
editCodeInput.value = decodedText;
|
||||||
|
if(typeof validateCodeField === "function") {
|
||||||
|
validateCodeField(editCodeInput, document.getElementById('edit-item-id')?.value || null);
|
||||||
|
}
|
||||||
|
scanEditBtn.textContent = 'Barcode scannen';
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// =========================================================================
|
||||||
|
// 4. UI INTERACTIONS & UTILITIES
|
||||||
|
// =========================================================================
|
||||||
function borrowItem(itemId) {
|
function borrowItem(itemId) {
|
||||||
const selectedItem = (libraryItems || []).find(item => item._id === itemId);
|
const selectedItem = (libraryItems || []).find(item => item._id === itemId);
|
||||||
if (selectedItem && selectedItem.LibraryDisplayStatus === 'damaged') {
|
if (selectedItem && selectedItem.LibraryDisplayStatus === 'damaged') {
|
||||||
@@ -920,210 +1019,47 @@
|
|||||||
if (!el) return;
|
if (!el) return;
|
||||||
el.textContent = message;
|
el.textContent = message;
|
||||||
el.classList.remove('ok', 'warn', 'error');
|
el.classList.remove('ok', 'warn', 'error');
|
||||||
if (kind) {
|
if (kind) el.classList.add(kind);
|
||||||
el.classList.add(kind);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function setActiveStudentCard(cardId) {
|
function setActiveStudentCard(cardId) {
|
||||||
activeStudentCardId = (cardId || '').trim().toUpperCase();
|
activeStudentCardId = (cardId || '').trim().toUpperCase();
|
||||||
const input = document.getElementById('activeStudentCard');
|
const input = document.getElementById('activeStudentCard');
|
||||||
if (input) {
|
if (input) input.value = activeStudentCardId;
|
||||||
input.value = activeStudentCardId;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function normalizeScannedCode(code) {
|
function normalizeScannedCode(code) {
|
||||||
return (code || '').trim();
|
return (code || '').trim();
|
||||||
}
|
}
|
||||||
|
|
||||||
async function processQuickToggleScan(scannedCode) {
|
function getItemTypeLabel(type) {
|
||||||
if (!activeStudentCardId) {
|
const labels = { 'book': 'Buch', 'cd': 'CD', 'dvd': 'DVD', 'other': 'Sonstige' };
|
||||||
setActiveStudentCard(scannedCode);
|
return labels[type] || type;
|
||||||
setScanStatus(`Ausweis gesetzt: ${activeStudentCardId}`, 'ok');
|
|
||||||
return;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
function escapeHtml(text) {
|
||||||
setScanStatus('Verarbeite Mediencode...', 'warn');
|
const div = document.createElement('div');
|
||||||
const response = await fetch('/api/library_scan_action', {
|
div.textContent = text;
|
||||||
method: 'POST',
|
return div.innerHTML;
|
||||||
headers: {'Content-Type': 'application/json'},
|
}
|
||||||
body: JSON.stringify({
|
|
||||||
student_card_id: activeStudentCardId,
|
function showItemDetail(itemId) {
|
||||||
item_code: scannedCode
|
fetch(`/api/item_detail/${itemId}`)
|
||||||
|
.then(r => r.text())
|
||||||
|
.then(html => {
|
||||||
|
document.getElementById('detailContent').innerHTML = html;
|
||||||
|
document.getElementById('detailModal').style.display = 'flex';
|
||||||
})
|
})
|
||||||
});
|
.catch(err => console.error('Error loading detail:', err));
|
||||||
|
|
||||||
const result = await response.json();
|
|
||||||
if (!response.ok || !result.ok) {
|
|
||||||
setScanStatus(result.message || 'Scan-Aktion fehlgeschlagen.', 'error');
|
|
||||||
return;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (result.action === 'borrowed') {
|
function closeDetailModal() {
|
||||||
setScanStatus(`Ausgeliehen: ${result.item_name}`, 'ok');
|
document.getElementById('detailModal').style.display = 'none';
|
||||||
} else if (result.action === 'returned') {
|
|
||||||
setScanStatus(`Zurückgegeben: ${result.item_name}`, 'ok');
|
|
||||||
} else {
|
|
||||||
setScanStatus(result.message || 'Aktion durchgeführt.', 'ok');
|
|
||||||
}
|
|
||||||
|
|
||||||
await loadLibraryItems();
|
|
||||||
} catch (err) {
|
|
||||||
console.error('Quick scan action failed:', err);
|
|
||||||
setScanStatus('Fehler beim Verarbeiten des Scans.', 'error');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function handleScanSuccess(decodedText) {
|
|
||||||
const scannedCode = normalizeScannedCode(decodedText);
|
|
||||||
if (!scannedCode) return;
|
|
||||||
|
|
||||||
const now = Date.now();
|
|
||||||
if (scannedCode === lastScanValue && (now - lastScanAt) < 1500) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
lastScanValue = scannedCode;
|
|
||||||
lastScanAt = now;
|
|
||||||
|
|
||||||
const mode = (document.getElementById('scanModeSelect') || {}).value || 'card_only';
|
|
||||||
if (mode === 'card_only') {
|
|
||||||
setActiveStudentCard(scannedCode);
|
|
||||||
setScanStatus(`Ausweis gesetzt: ${activeStudentCardId}`, 'ok');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
processQuickToggleScan(scannedCode);
|
|
||||||
}
|
|
||||||
|
|
||||||
function handleScanError() {
|
|
||||||
// Intentionally silent to avoid UI spam while camera searches codes.
|
|
||||||
}
|
|
||||||
|
|
||||||
async function ensureScannerLibraryLoaded() {
|
|
||||||
if (typeof Html5QrcodeScanner !== 'undefined') {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
const sources = [
|
|
||||||
'https://cdn.jsdelivr.net/npm/html5-qrcode/minified/html5-qrcode.min.js'
|
|
||||||
];
|
|
||||||
|
|
||||||
for (const src of sources) {
|
|
||||||
try {
|
|
||||||
await new Promise((resolve, reject) => {
|
|
||||||
const existing = document.querySelector(`script[data-scanner-src="${src}"]`);
|
|
||||||
if (existing) {
|
|
||||||
const onLoad = () => resolve();
|
|
||||||
const onError = () => reject(new Error('Script load failed'));
|
|
||||||
existing.addEventListener('load', onLoad, { once: true });
|
|
||||||
existing.addEventListener('error', onError, { once: true });
|
|
||||||
setTimeout(() => {
|
|
||||||
existing.removeEventListener('load', onLoad);
|
|
||||||
existing.removeEventListener('error', onError);
|
|
||||||
if (typeof Html5QrcodeScanner !== 'undefined') {
|
|
||||||
resolve();
|
|
||||||
} else {
|
|
||||||
reject(new Error('Script not available'));
|
|
||||||
}
|
|
||||||
}, 1200);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const script = document.createElement('script');
|
|
||||||
script.src = src;
|
|
||||||
script.async = true;
|
|
||||||
script.defer = true;
|
|
||||||
script.dataset.scannerSrc = src;
|
|
||||||
script.onload = () => resolve();
|
|
||||||
script.onerror = () => reject(new Error('Script load failed'));
|
|
||||||
document.head.appendChild(script);
|
|
||||||
});
|
|
||||||
|
|
||||||
if (typeof Html5QrcodeScanner !== 'undefined') {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
} catch (err) {
|
|
||||||
console.warn('Scanner library load failed from', src, err);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
async function startScanner() {
|
|
||||||
if (scannerRunning) return;
|
|
||||||
|
|
||||||
const scannerLoaded = await ensureScannerLibraryLoaded();
|
|
||||||
if (!scannerLoaded) {
|
|
||||||
setScanStatus('Scanner-Bibliothek konnte nicht geladen werden.', 'error');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const readerWrap = document.getElementById('scanReaderWrap');
|
|
||||||
const toggleBtn = document.getElementById('toggleScannerBtn');
|
|
||||||
readerWrap.style.display = 'block';
|
|
||||||
|
|
||||||
try {
|
|
||||||
const formats = [];
|
|
||||||
if (typeof Html5QrcodeSupportedFormats !== 'undefined') {
|
|
||||||
formats.push(
|
|
||||||
Html5QrcodeSupportedFormats.QR_CODE,
|
|
||||||
Html5QrcodeSupportedFormats.EAN_13,
|
|
||||||
Html5QrcodeSupportedFormats.EAN_8,
|
|
||||||
Html5QrcodeSupportedFormats.CODE_128,
|
|
||||||
Html5QrcodeSupportedFormats.CODE_39,
|
|
||||||
Html5QrcodeSupportedFormats.UPC_A,
|
|
||||||
Html5QrcodeSupportedFormats.UPC_E,
|
|
||||||
Html5QrcodeSupportedFormats.ITF,
|
|
||||||
Html5QrcodeSupportedFormats.CODABAR
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
const scannerConfig = {
|
|
||||||
fps: 10,
|
|
||||||
rememberLastUsedCamera: true,
|
|
||||||
aspectRatio: 1.333334
|
|
||||||
};
|
|
||||||
if (formats.length > 0) {
|
|
||||||
scannerConfig.formatsToSupport = formats;
|
|
||||||
}
|
|
||||||
|
|
||||||
scannerInstance = scannerInstance || new Html5QrcodeScanner(
|
|
||||||
'libraryQrReader',
|
|
||||||
scannerConfig,
|
|
||||||
false
|
|
||||||
);
|
|
||||||
|
|
||||||
scannerInstance.render(handleScanSuccess, handleScanError);
|
|
||||||
scannerRunning = true;
|
|
||||||
toggleBtn.textContent = 'Scanner stoppen';
|
|
||||||
setScanStatus('Scanner aktiv. Jetzt Code scannen.', 'warn');
|
|
||||||
} catch (err) {
|
|
||||||
console.error('Scanner start failed:', err);
|
|
||||||
readerWrap.style.display = 'none';
|
|
||||||
const detail = (err && (err.message || err.name)) ? ` (${err.message || err.name})` : '';
|
|
||||||
setScanStatus(`Scanner konnte nicht gestartet werden${detail}`, 'error');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async function stopScanner() {
|
|
||||||
if (!scannerRunning || !scannerInstance) return;
|
|
||||||
const readerWrap = document.getElementById('scanReaderWrap');
|
|
||||||
const toggleBtn = document.getElementById('toggleScannerBtn');
|
|
||||||
try {
|
|
||||||
await scannerInstance.clear();
|
|
||||||
} catch (err) {
|
|
||||||
console.error('Scanner stop failed:', err);
|
|
||||||
}
|
|
||||||
scannerRunning = false;
|
|
||||||
scannerInstance = null;
|
|
||||||
readerWrap.style.display = 'none';
|
|
||||||
toggleBtn.textContent = 'Scanner starten';
|
|
||||||
setScanStatus('Scanner gestoppt.', 'warn');
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// =========================================================================
|
||||||
|
// 5. EVENT LISTENERS INITIALIZATION & ON-LOAD INITIALIZER
|
||||||
|
// =========================================================================
|
||||||
function wireScannerUi() {
|
function wireScannerUi() {
|
||||||
const toggleBtn = document.getElementById('toggleScannerBtn');
|
const toggleBtn = document.getElementById('toggleScannerBtn');
|
||||||
const resetBtn = document.getElementById('resetCardBtn');
|
const resetBtn = document.getElementById('resetCardBtn');
|
||||||
@@ -1134,7 +1070,7 @@
|
|||||||
if (scannerRunning) {
|
if (scannerRunning) {
|
||||||
await stopScanner();
|
await stopScanner();
|
||||||
} else {
|
} else {
|
||||||
await startScanner();
|
await startScanner(null);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -1151,84 +1087,135 @@
|
|||||||
if (modeSelect.value === 'quick_toggle' && !activeStudentCardId) {
|
if (modeSelect.value === 'quick_toggle' && !activeStudentCardId) {
|
||||||
setScanStatus('Schnellmodus: zuerst Schülerausweis scannen.', 'warn');
|
setScanStatus('Schnellmodus: zuerst Schülerausweis scannen.', 'warn');
|
||||||
} else if (modeSelect.value === 'card_only') {
|
} else if (modeSelect.value === 'card_only') {
|
||||||
setScanStatus('Modus aktiv: Nur Ausweis erfassen.', 'warn');
|
setScanStatus('Nur Ausweis-Modus aktiv.', 'warn');
|
||||||
} else {
|
|
||||||
setScanStatus('Schnellmodus aktiv: jetzt Mediencode scannen.', 'warn');
|
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function getLibraryItemById(itemId) {
|
// Run when DOM structure is entirely ready
|
||||||
return libraryItems.find(i => String(i._id) === String(itemId));
|
document.addEventListener('DOMContentLoaded', () => {
|
||||||
|
wireScannerUi(); // Setup scanner control buttons
|
||||||
|
loadLibraryItems(); // Fetch your database items right away!
|
||||||
|
|
||||||
|
// Safely connect standard Filters and Search inputs inside DOMContentLoaded
|
||||||
|
const filterToggleBtn = document.getElementById('filterToggleBtn');
|
||||||
|
if (filterToggleBtn) {
|
||||||
|
filterToggleBtn.addEventListener('click', () => {
|
||||||
|
filterPanelOpen = !filterPanelOpen;
|
||||||
|
document.getElementById('filterPanel').classList.toggle('open');
|
||||||
|
filterToggleBtn.classList.toggle('active');
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
function openEditLibraryItem(itemId) {
|
const applyFilterBtn = document.getElementById('applyFilterBtn');
|
||||||
const item = getLibraryItemById(itemId);
|
if (applyFilterBtn) {
|
||||||
if (!item) {
|
applyFilterBtn.addEventListener('click', () => {
|
||||||
alert('Element nicht gefunden.');
|
activeFilters.isbn = document.getElementById('filterISBN').value.toLowerCase();
|
||||||
return;
|
activeFilters.type = document.getElementById('filterType').value;
|
||||||
|
activeFilters.status = document.getElementById('filterStatus').value;
|
||||||
|
applyFiltersAndSearch(true);
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
const modal = document.getElementById('editLibraryModal');
|
const clearFilterBtn = document.getElementById('clearFilterBtn');
|
||||||
document.getElementById('editLibraryItemId').value = item._id || '';
|
if (clearFilterBtn) {
|
||||||
document.getElementById('editLibraryName').value = item.Name || '';
|
clearFilterBtn.addEventListener('click', () => {
|
||||||
document.getElementById('editLibraryAuthor').value = item.Autor || item.Author || '';
|
document.getElementById('filterISBN').value = '';
|
||||||
document.getElementById('editLibraryDescription').value = item.Beschreibung || '';
|
document.getElementById('filterType').value = '';
|
||||||
document.getElementById('editLibraryLocation').value = item.Ort || '';
|
document.getElementById('filterStatus').value = '';
|
||||||
document.getElementById('editLibraryIsbn').value = item.ISBN || '';
|
activeFilters = { isbn: '', type: '', status: '' };
|
||||||
document.getElementById('editLibraryCode4').value = item.Code_4 || '';
|
applyFiltersAndSearch(true);
|
||||||
document.getElementById('editLibraryType').value = (item.ItemType || 'book');
|
});
|
||||||
modal.style.display = 'flex';
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function closeEditLibraryModal() {
|
const librarySearch = document.getElementById('librarySearch');
|
||||||
const modal = document.getElementById('editLibraryModal');
|
if (librarySearch) {
|
||||||
modal.style.display = 'none';
|
librarySearch.addEventListener('input', (e) => {
|
||||||
|
currentSearchTerm = (e.target.value || '').toLowerCase();
|
||||||
|
applyFiltersAndSearch(true);
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
async function submitEditLibraryItem(event) {
|
const loadMoreBtn = document.getElementById('loadMoreBtn');
|
||||||
event.preventDefault();
|
if (loadMoreBtn) {
|
||||||
|
loadMoreBtn.addEventListener('click', () => {
|
||||||
|
renderedCount = Math.min(renderedCount + RENDER_BATCH_COUNT, visibleItems.length);
|
||||||
|
renderItems();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Edit Modal Form processing
|
||||||
|
const editForm = document.getElementById('editLibraryForm');
|
||||||
|
if (editForm) {
|
||||||
|
editForm.addEventListener('submit', async function(e) {
|
||||||
|
e.preventDefault();
|
||||||
|
|
||||||
const itemId = document.getElementById('editLibraryItemId').value;
|
const itemId = document.getElementById('editLibraryItemId').value;
|
||||||
const payload = {
|
|
||||||
|
const updatedData = {
|
||||||
name: document.getElementById('editLibraryName').value,
|
name: document.getElementById('editLibraryName').value,
|
||||||
autor: document.getElementById('editLibraryAuthor').value,
|
item_type: document.getElementById('editLibraryType').value,
|
||||||
beschreibung: document.getElementById('editLibraryDescription').value,
|
|
||||||
ort: document.getElementById('editLibraryLocation').value,
|
|
||||||
isbn: document.getElementById('editLibraryIsbn').value,
|
isbn: document.getElementById('editLibraryIsbn').value,
|
||||||
code_4: document.getElementById('editLibraryCode4').value,
|
code_4: document.getElementById('editLibraryCode4').value,
|
||||||
item_type: document.getElementById('editLibraryType').value
|
ort: document.getElementById('editLibraryLocation').value,
|
||||||
|
beschreibung: document.getElementById('editLibraryDescription').value
|
||||||
};
|
};
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const response = await fetch(`/api/library_item/${itemId}/update`, {
|
const response = await fetch(`/api/library_item/${itemId}/update`, {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: {'Content-Type': 'application/json'},
|
headers: {
|
||||||
body: JSON.stringify(payload)
|
'Content-Type': 'application/json',
|
||||||
|
'X-CSRFToken': '{{ csrf_token }}',
|
||||||
|
'X-CSRF-Token': '{{ csrf_token }}'
|
||||||
|
},
|
||||||
|
body: JSON.stringify(updatedData)
|
||||||
});
|
});
|
||||||
|
|
||||||
const result = await response.json();
|
const result = await response.json();
|
||||||
if (!response.ok || !result.ok) {
|
|
||||||
alert(result.message || 'Bearbeiten fehlgeschlagen.');
|
if (response.ok && result.ok) {
|
||||||
|
alert(result.message || 'Medium erfolgreich aktualisiert!');
|
||||||
|
closeEditLibraryModal();
|
||||||
|
|
||||||
|
pagingState.loading = false;
|
||||||
|
loadLibraryItems();
|
||||||
|
} else {
|
||||||
|
alert(result.message || 'Fehler beim Speichern der Änderungen.');
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Update failed:', error);
|
||||||
|
alert('Netzwerkfehler beim Aktualisieren des Mediums.');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Modal Control Functions (accessible globally from table buttons)
|
||||||
|
function openEditLibraryItem(itemId) {
|
||||||
|
const item = libraryItems.find(i => i._id === itemId);
|
||||||
|
|
||||||
|
if (!item) {
|
||||||
|
alert('Fehler: Das Medium konnte nicht gefunden werden.');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
closeEditLibraryModal();
|
|
||||||
await loadLibraryItems();
|
// Populate the form fields - Using correct German properties from MongoDB fields
|
||||||
setScanStatus('Bibliotheksmedium aktualisiert.', 'ok');
|
document.getElementById('editLibraryItemId').value = item._id || '';
|
||||||
} catch (err) {
|
document.getElementById('editLibraryName').value = item.Name || '';
|
||||||
console.error('Library edit failed:', err);
|
document.getElementById('editLibraryType').value = item.ItemType || 'book';
|
||||||
alert('Fehler beim Bearbeiten des Bibliotheksmediums.');
|
document.getElementById('editLibraryIsbn').value = item.ISBN || '';
|
||||||
}
|
document.getElementById('editLibraryCode4').value = item.Code_4 || item.Code4 || '';
|
||||||
|
document.getElementById('editLibraryLocation').value = item.Ort || '';
|
||||||
|
document.getElementById('editLibraryDescription').value = item.Beschreibung || '';
|
||||||
|
|
||||||
|
document.getElementById('editLibraryModal').style.display = 'block';
|
||||||
}
|
}
|
||||||
|
|
||||||
// Load on page init
|
function closeEditLibraryModal() {
|
||||||
document.addEventListener('DOMContentLoaded', () => {
|
document.getElementById('editLibraryModal').style.display = 'none';
|
||||||
loadLibraryItems();
|
|
||||||
wireScannerUi();
|
|
||||||
const editForm = document.getElementById('editLibraryForm');
|
|
||||||
if (editForm) {
|
|
||||||
editForm.addEventListener('submit', submitEditLibraryItem);
|
|
||||||
}
|
}
|
||||||
});
|
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<div id="editLibraryModal" class="modal" style="display:none;">
|
<div id="editLibraryModal" class="modal" style="display:none;">
|
||||||
@@ -1242,10 +1229,6 @@
|
|||||||
<label for="editLibraryName">Titel</label>
|
<label for="editLibraryName">Titel</label>
|
||||||
<input id="editLibraryName" required>
|
<input id="editLibraryName" required>
|
||||||
</div>
|
</div>
|
||||||
<div>
|
|
||||||
<label for="editLibraryAuthor">Autor/Künstler</label>
|
|
||||||
<input id="editLibraryAuthor">
|
|
||||||
</div>
|
|
||||||
<div>
|
<div>
|
||||||
<label for="editLibraryType">Medientyp</label>
|
<label for="editLibraryType">Medientyp</label>
|
||||||
<select id="editLibraryType">
|
<select id="editLibraryType">
|
||||||
|
|||||||
+94
-32
@@ -525,8 +525,7 @@
|
|||||||
|
|
||||||
window.isDebug = false; // Set to true only for development environment
|
window.isDebug = false; // Set to true only for development environment
|
||||||
</script>
|
</script>
|
||||||
|
<script src="https://cdn.jsdelivr.net/npm/@ericblade/quagga2/dist/quagga.js"></script>
|
||||||
<script src="https://unpkg.com/html5-qrcode@2.0.9/dist/html5-qrcode.min.js"></script>
|
|
||||||
<script>
|
<script>
|
||||||
// Global state
|
// Global state
|
||||||
const highlightItemId = (window.serverVars && window.serverVars.highlightItemId && window.serverVars.highlightItemId !== 'null')
|
const highlightItemId = (window.serverVars && window.serverVars.highlightItemId && window.serverVars.highlightItemId !== 'null')
|
||||||
@@ -535,51 +534,114 @@
|
|||||||
let codeSearchTerm = '';
|
let codeSearchTerm = '';
|
||||||
let descSearchIds = null; // Set of matching IDs or null when disabled
|
let descSearchIds = null; // Set of matching IDs or null when disabled
|
||||||
|
|
||||||
// QR scanner toggle setup
|
// Keep track of the scanner state globally/outer scope
|
||||||
document.addEventListener('DOMContentLoaded', function() {
|
let isScanning = false;
|
||||||
const scanButton = document.getElementById('scanButton');
|
let activeScannerCallback = null; // Tracks which function currently owns the scanner output
|
||||||
|
|
||||||
|
function startScanner(targetCallback) {
|
||||||
const qrReader = document.getElementById('qr-reader');
|
const qrReader = document.getElementById('qr-reader');
|
||||||
let html5QrcodeScanner = null;
|
const statusText = document.getElementById('status');
|
||||||
|
|
||||||
if (!scanButton || !qrReader) return;
|
// Store the custom action that should happen when a barcode is found
|
||||||
|
activeScannerCallback = targetCallback;
|
||||||
|
|
||||||
const setScannerUi = (isOpen) => {
|
// Show the container
|
||||||
scanButton.classList.toggle('is-active', isOpen);
|
if (qrReader) qrReader.style.display = 'block';
|
||||||
scanButton.setAttribute('aria-expanded', isOpen ? 'true' : 'false');
|
if (statusText) statusText.innerText = "Initializing camera...";
|
||||||
scanButton.textContent = isOpen ? 'Scanner schliessen' : 'Barcode scannen';
|
|
||||||
};
|
|
||||||
|
|
||||||
scanButton.addEventListener('click', function() {
|
Quagga.init({
|
||||||
if (qrReader.style.display !== 'block') {
|
inputStream: {
|
||||||
qrReader.style.display = 'block';
|
name: "Live",
|
||||||
|
type: "LiveStream",
|
||||||
|
// Make sure this targets your correct HTML container element
|
||||||
|
target: document.querySelector('#scanner-container'),
|
||||||
|
constraints: {
|
||||||
|
width: 640,
|
||||||
|
height: 480,
|
||||||
|
facingMode: "environment" // Force rear camera
|
||||||
|
},
|
||||||
|
},
|
||||||
|
decoder: {
|
||||||
|
// Your required formats mapped to Quagga2 reader strings
|
||||||
|
readers: ["code_128_reader", "ean_reader", "code_39_reader", "upc_reader"]
|
||||||
|
}
|
||||||
|
}, function(err) {
|
||||||
|
if (err) {
|
||||||
|
console.error("Initialization error:", err);
|
||||||
|
if (statusText) statusText.innerText = "Camera Error";
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
html5QrcodeScanner = new Html5QrcodeScanner(
|
Quagga.start();
|
||||||
'qr-reader', { fps: 10, qrbox: 250 }
|
isScanning = true;
|
||||||
);
|
|
||||||
|
|
||||||
html5QrcodeScanner.render((decodedText) => {
|
// If we are using the main search button, manage its UI state
|
||||||
html5QrcodeScanner.clear();
|
if (!targetCallback) {
|
||||||
qrReader.style.display = 'none';
|
setScannerUi(true);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (statusText) statusText.innerText = "Scanning...";
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function stopScanner() {
|
||||||
|
Quagga.stop();
|
||||||
|
isScanning = false;
|
||||||
|
activeScannerCallback = null; // Reset the callback routing
|
||||||
|
|
||||||
|
const qrReader = document.getElementById('qr-reader');
|
||||||
|
if (qrReader) qrReader.style.display = 'none';
|
||||||
|
|
||||||
|
setScannerUi(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
function setScannerUi(isOpen) {
|
||||||
|
const scanBtn = document.getElementById('scanButton');
|
||||||
|
if (!scanBtn) return;
|
||||||
|
|
||||||
|
scanBtn.classList.toggle('is-active', isOpen);
|
||||||
|
scanBtn.setAttribute('aria-expanded', isOpen ? 'true' : 'false');
|
||||||
|
scanBtn.textContent = isOpen ? 'Scanner schliessen' : 'Barcode scannen';
|
||||||
|
}
|
||||||
|
|
||||||
|
// Unified global reader callback
|
||||||
|
Quagga.onDetected(function(data) {
|
||||||
|
const barcode = String(data.codeResult.code || '').trim();
|
||||||
|
console.log("Barcode detected:", barcode);
|
||||||
|
|
||||||
|
// Keep a local reference to the active callback before shutting down the engine
|
||||||
|
const currentCallback = activeScannerCallback;
|
||||||
|
|
||||||
|
// Critical: Stop scanning immediately to prevent multiple triggers
|
||||||
|
stopScanner();
|
||||||
|
|
||||||
|
// Route data based on who opened the scanner
|
||||||
|
if (typeof currentCallback === "function") {
|
||||||
|
// Send data directly to the specific edit field's logic
|
||||||
|
currentCallback(barcode);
|
||||||
|
} else {
|
||||||
|
// Fallback Default: Main search box logic
|
||||||
|
const resultText = document.getElementById('barcode-result');
|
||||||
|
if (resultText) resultText.innerText = barcode;
|
||||||
|
|
||||||
// Put scanned code into the search box and trigger search
|
|
||||||
const searchInput = document.getElementById('code-search');
|
const searchInput = document.getElementById('code-search');
|
||||||
if (searchInput) {
|
if (searchInput) {
|
||||||
searchInput.value = decodedText;
|
searchInput.value = barcode;
|
||||||
|
if (typeof searchByCode === "function") {
|
||||||
searchByCode();
|
searchByCode();
|
||||||
}
|
}
|
||||||
|
}
|
||||||
setScannerUi(false);
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
setScannerUi(true);
|
// Event Listener for the main standalone search button
|
||||||
|
document.getElementById('scanButton')?.addEventListener('click', function() {
|
||||||
|
if (!isScanning) {
|
||||||
|
// Pass null so it defaults to filling the standard search box
|
||||||
|
startScanner(null);
|
||||||
} else {
|
} else {
|
||||||
if (html5QrcodeScanner) {
|
stopScanner();
|
||||||
html5QrcodeScanner.clear();
|
|
||||||
}
|
}
|
||||||
qrReader.style.display = 'none';
|
|
||||||
setScannerUi(false);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
});
|
});
|
||||||
|
|
||||||
// Return preferred primary and fallback image URLs based on extension
|
// Return preferred primary and fallback image URLs based on extension
|
||||||
|
|||||||
+111
-62
@@ -2435,7 +2435,10 @@ document.addEventListener('DOMContentLoaded', ()=>{
|
|||||||
</div>
|
</div>
|
||||||
<div class="qr-container">
|
<div class="qr-container">
|
||||||
<button id="scanButton" class="scan-button" aria-controls="qr-reader" aria-expanded="false">Barcode scannen</button>
|
<button id="scanButton" class="scan-button" aria-controls="qr-reader" aria-expanded="false">Barcode scannen</button>
|
||||||
<div id="qr-reader"></div>
|
<div id="qr-reader" style="display: none;">
|
||||||
|
<h3>Status: <span id="status">Bereit</span></h3>
|
||||||
|
<div id="scanner-container"></div>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div id="table-view-header" class="table-view-header" aria-hidden="true">
|
<div id="table-view-header" class="table-view-header" aria-hidden="true">
|
||||||
@@ -2729,7 +2732,7 @@ document.addEventListener('DOMContentLoaded', ()=>{
|
|||||||
|
|
||||||
window.isDebug = false; // Set to true only for development environment
|
window.isDebug = false; // Set to true only for development environment
|
||||||
</script>
|
</script>
|
||||||
<script src="https://unpkg.com/html5-qrcode@2.0.9/dist/html5-qrcode.min.js"></script>
|
<script src="https://cdn.jsdelivr.net/npm/@ericblade/quagga2/dist/quagga.js"></script>
|
||||||
<script>
|
<script>
|
||||||
// Function to check if a file is a video
|
// Function to check if a file is a video
|
||||||
function isVideoFile(filename) {
|
function isVideoFile(filename) {
|
||||||
@@ -2739,7 +2742,6 @@ document.addEventListener('DOMContentLoaded', ()=>{
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Initialize QR Code scanner and global variables
|
// Initialize QR Code scanner and global variables
|
||||||
let html5QrcodeScanner = null;
|
|
||||||
let codeSearchTerm = '';
|
let codeSearchTerm = '';
|
||||||
let descSearchIds = null; // Set of matching IDs or null when disabled
|
let descSearchIds = null; // Set of matching IDs or null when disabled
|
||||||
let currentUsername = '';
|
let currentUsername = '';
|
||||||
@@ -2769,50 +2771,113 @@ document.addEventListener('DOMContentLoaded', ()=>{
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
document.getElementById('scanButton').addEventListener('click', function() {
|
// Keep track of the scanner state globally/outer scope
|
||||||
const qrReader = document.getElementById('qr-reader');
|
let isScanning = false;
|
||||||
const scanBtn = document.getElementById('scanButton');
|
let activeScannerCallback = null; // Tracks which function currently owns the scanner output
|
||||||
|
|
||||||
const setScannerUi = (isOpen) => {
|
function startScanner(targetCallback) {
|
||||||
|
const qrReader = document.getElementById('qr-reader');
|
||||||
|
const statusText = document.getElementById('status');
|
||||||
|
|
||||||
|
// Store the custom action that should happen when a barcode is found
|
||||||
|
activeScannerCallback = targetCallback;
|
||||||
|
|
||||||
|
// Show the container
|
||||||
|
if (qrReader) qrReader.style.display = 'block';
|
||||||
|
if (statusText) statusText.innerText = "Initializing camera...";
|
||||||
|
|
||||||
|
Quagga.init({
|
||||||
|
inputStream: {
|
||||||
|
name: "Live",
|
||||||
|
type: "LiveStream",
|
||||||
|
// Make sure this targets your correct HTML container element
|
||||||
|
target: document.querySelector('#scanner-container'),
|
||||||
|
constraints: {
|
||||||
|
width: 640,
|
||||||
|
height: 480,
|
||||||
|
facingMode: "environment" // Force rear camera
|
||||||
|
},
|
||||||
|
},
|
||||||
|
decoder: {
|
||||||
|
// Your required formats mapped to Quagga2 reader strings
|
||||||
|
readers: ["code_128_reader", "ean_reader", "code_39_reader", "upc_reader"]
|
||||||
|
}
|
||||||
|
}, function(err) {
|
||||||
|
if (err) {
|
||||||
|
console.error("Initialization error:", err);
|
||||||
|
if (statusText) statusText.innerText = "Camera Error";
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
Quagga.start();
|
||||||
|
isScanning = true;
|
||||||
|
|
||||||
|
// If we are using the main search button, manage its UI state
|
||||||
|
if (!targetCallback) {
|
||||||
|
setScannerUi(true);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (statusText) statusText.innerText = "Scanning...";
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function stopScanner() {
|
||||||
|
Quagga.stop();
|
||||||
|
isScanning = false;
|
||||||
|
activeScannerCallback = null; // Reset the callback routing
|
||||||
|
|
||||||
|
const qrReader = document.getElementById('qr-reader');
|
||||||
|
if (qrReader) qrReader.style.display = 'none';
|
||||||
|
|
||||||
|
setScannerUi(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
function setScannerUi(isOpen) {
|
||||||
|
const scanBtn = document.getElementById('scanButton');
|
||||||
if (!scanBtn) return;
|
if (!scanBtn) return;
|
||||||
|
|
||||||
scanBtn.classList.toggle('is-active', isOpen);
|
scanBtn.classList.toggle('is-active', isOpen);
|
||||||
scanBtn.setAttribute('aria-expanded', isOpen ? 'true' : 'false');
|
scanBtn.setAttribute('aria-expanded', isOpen ? 'true' : 'false');
|
||||||
scanBtn.textContent = isOpen ? 'Scanner schliessen' : 'Barcode scannen';
|
scanBtn.textContent = isOpen ? 'Scanner schliessen' : 'Barcode scannen';
|
||||||
};
|
|
||||||
|
|
||||||
if (qrReader.style.display === 'none') {
|
|
||||||
qrReader.style.display = 'block';
|
|
||||||
|
|
||||||
html5QrcodeScanner = new Html5QrcodeScanner(
|
|
||||||
"qr-reader", {
|
|
||||||
fps: 10,
|
|
||||||
qrbox: 250,
|
|
||||||
rememberLastUsedCamera: true
|
|
||||||
}
|
}
|
||||||
);
|
|
||||||
|
|
||||||
html5QrcodeScanner.render((decodedText) => {
|
// Unified global reader callback
|
||||||
html5QrcodeScanner.clear();
|
Quagga.onDetected(function(data) {
|
||||||
qrReader.style.display = 'none';
|
const barcode = String(data.codeResult.code || '').trim();
|
||||||
|
console.log("Barcode detected:", barcode);
|
||||||
|
|
||||||
|
// Keep a local reference to the active callback before shutting down the engine
|
||||||
|
const currentCallback = activeScannerCallback;
|
||||||
|
|
||||||
|
// Critical: Stop scanning immediately to prevent multiple triggers
|
||||||
|
stopScanner();
|
||||||
|
|
||||||
|
// Route data based on who opened the scanner
|
||||||
|
if (typeof currentCallback === "function") {
|
||||||
|
// Send data directly to the specific edit field's logic
|
||||||
|
currentCallback(barcode);
|
||||||
|
} else {
|
||||||
|
// Fallback Default: Main search box logic
|
||||||
|
const resultText = document.getElementById('barcode-result');
|
||||||
|
if (resultText) resultText.innerText = barcode;
|
||||||
|
|
||||||
// Instead of navigating to the URL, put the scanned code in the search box
|
|
||||||
const searchInput = document.getElementById('code-search');
|
const searchInput = document.getElementById('code-search');
|
||||||
if (searchInput) {
|
if (searchInput) {
|
||||||
searchInput.value = decodedText;
|
searchInput.value = barcode;
|
||||||
// Trigger search automatically
|
if (typeof searchByCode === "function") {
|
||||||
searchByCode();
|
searchByCode();
|
||||||
}
|
}
|
||||||
|
}
|
||||||
setScannerUi(false);
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
setScannerUi(true);
|
// Event Listener for the main standalone search button
|
||||||
|
document.getElementById('scanButton')?.addEventListener('click', function() {
|
||||||
|
if (!isScanning) {
|
||||||
|
// Pass null so it defaults to filling the standard search box
|
||||||
|
startScanner(null);
|
||||||
} else {
|
} else {
|
||||||
if (html5QrcodeScanner) {
|
stopScanner();
|
||||||
html5QrcodeScanner.clear();
|
|
||||||
}
|
|
||||||
qrReader.style.display = 'none';
|
|
||||||
setScannerUi(false);
|
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -2824,26 +2889,18 @@ document.addEventListener('DOMContentLoaded', ()=>{
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (qrReader.style.display !== 'none') {
|
// Toggle close if it's already running
|
||||||
if (html5QrcodeScanner) {
|
if (isScanning && qrReader.style.display !== 'none') {
|
||||||
html5QrcodeScanner.clear();
|
stopScanner();
|
||||||
}
|
|
||||||
qrReader.style.display = 'none';
|
|
||||||
scanEditBtn.textContent = 'Barcode scannen';
|
scanEditBtn.textContent = 'Barcode scannen';
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
qrReader.style.display = 'block';
|
|
||||||
scanEditBtn.textContent = 'Scanner schließen';
|
scanEditBtn.textContent = 'Scanner schließen';
|
||||||
html5QrcodeScanner = new Html5QrcodeScanner('qr-reader', {
|
|
||||||
fps: 10,
|
// Start scanner with custom logic mapping to the Code input field
|
||||||
qrbox: 250,
|
startScanner(function(decodedText) {
|
||||||
rememberLastUsedCamera: true
|
editCodeInput.value = decodedText;
|
||||||
});
|
|
||||||
html5QrcodeScanner.render((decodedText) => {
|
|
||||||
html5QrcodeScanner.clear();
|
|
||||||
qrReader.style.display = 'none';
|
|
||||||
editCodeInput.value = String(decodedText || '').trim();
|
|
||||||
validateCodeField(editCodeInput, document.getElementById('edit-item-id')?.value || null);
|
validateCodeField(editCodeInput, document.getElementById('edit-item-id')?.value || null);
|
||||||
scanEditBtn.textContent = 'Barcode scannen';
|
scanEditBtn.textContent = 'Barcode scannen';
|
||||||
});
|
});
|
||||||
@@ -2857,26 +2914,18 @@ document.addEventListener('DOMContentLoaded', ()=>{
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (qrReader.style.display !== 'none') {
|
// Toggle close if it's already running
|
||||||
if (html5QrcodeScanner) {
|
if (isScanning && qrReader.style.display !== 'none') {
|
||||||
html5QrcodeScanner.clear();
|
stopScanner();
|
||||||
}
|
|
||||||
qrReader.style.display = 'none';
|
|
||||||
scanIsbnBtn.textContent = 'ISBN scannen';
|
scanIsbnBtn.textContent = 'ISBN scannen';
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
qrReader.style.display = 'block';
|
|
||||||
scanIsbnBtn.textContent = 'Scanner schließen';
|
scanIsbnBtn.textContent = 'Scanner schließen';
|
||||||
html5QrcodeScanner = new Html5QrcodeScanner('qr-reader', {
|
|
||||||
fps: 10,
|
// Start scanner with custom logic mapping to the ISBN input field
|
||||||
qrbox: 250,
|
startScanner(function(decodedText) {
|
||||||
rememberLastUsedCamera: true
|
editIsbnInput.value = decodedText;
|
||||||
});
|
|
||||||
html5QrcodeScanner.render((decodedText) => {
|
|
||||||
html5QrcodeScanner.clear();
|
|
||||||
qrReader.style.display = 'none';
|
|
||||||
editIsbnInput.value = String(decodedText || '').trim();
|
|
||||||
scanIsbnBtn.textContent = 'ISBN scannen';
|
scanIsbnBtn.textContent = 'ISBN scannen';
|
||||||
if (typeof fetchBookInfo === 'function') {
|
if (typeof fetchBookInfo === 'function') {
|
||||||
fetchBookInfo('edit');
|
fetchBookInfo('edit');
|
||||||
|
|||||||
@@ -288,22 +288,6 @@ document.addEventListener('DOMContentLoaded', function() {
|
|||||||
? processedEvents
|
? processedEvents
|
||||||
: processedEvents.filter(event => event.extendedProps.status !== 'completed');
|
: processedEvents.filter(event => event.extendedProps.status !== 'completed');
|
||||||
|
|
||||||
// If any event spans multiple days, switch to week view for better visibility
|
|
||||||
try {
|
|
||||||
const multiDay = processedEvents.some(ev => {
|
|
||||||
try {
|
|
||||||
const s = new Date(ev.start);
|
|
||||||
const e = new Date(ev.end);
|
|
||||||
return s && e && s.toDateString() !== e.toDateString();
|
|
||||||
} catch (e) { return false; }
|
|
||||||
});
|
|
||||||
if (multiDay && calendar && calendar.view && calendar.view.type === 'timeGridDay') {
|
|
||||||
calendar.changeView('timeGridWeek');
|
|
||||||
}
|
|
||||||
} catch (e) {
|
|
||||||
// ignore
|
|
||||||
}
|
|
||||||
|
|
||||||
// Provide events to calendar
|
// Provide events to calendar
|
||||||
successCallback(filteredEvents);
|
successCallback(filteredEvents);
|
||||||
})
|
})
|
||||||
@@ -330,22 +314,6 @@ document.addEventListener('DOMContentLoaded', function() {
|
|||||||
periodDiv.style.display = 'inline-block';
|
periodDiv.style.display = 'inline-block';
|
||||||
periodDiv.style.fontSize = '10px';
|
periodDiv.style.fontSize = '10px';
|
||||||
info.el.appendChild(periodDiv);
|
info.el.appendChild(periodDiv);
|
||||||
} else {
|
|
||||||
// Check if it is a multi-day event
|
|
||||||
const start = info.event.start;
|
|
||||||
const end = info.event.end;
|
|
||||||
if (start && end && start.toDateString() !== end.toDateString()) {
|
|
||||||
const periodDiv = document.createElement('div');
|
|
||||||
periodDiv.className = 'fc-event-period-marker';
|
|
||||||
periodDiv.textContent = 'Mehrtägig';
|
|
||||||
periodDiv.style.backgroundColor = 'rgba(255,255,255,0.3)';
|
|
||||||
periodDiv.style.borderRadius = '3px';
|
|
||||||
periodDiv.style.padding = '1px 3px';
|
|
||||||
periodDiv.style.marginTop = '2px';
|
|
||||||
periodDiv.style.display = 'inline-block';
|
|
||||||
periodDiv.style.fontSize = '10px';
|
|
||||||
info.el.appendChild(periodDiv);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Add borrowed indicator if relevant
|
// Add borrowed indicator if relevant
|
||||||
|
|||||||
+104
-238
@@ -970,8 +970,7 @@
|
|||||||
document.getElementById('csv-help-modal').style.display = 'none';
|
document.getElementById('csv-help-modal').style.display = 'none';
|
||||||
}
|
}
|
||||||
</script>
|
</script>
|
||||||
|
<script src="https://cdn.jsdelivr.net/npm/@ericblade/quagga2/dist/quagga.js"></script>
|
||||||
<script src="https://unpkg.com/html5-qrcode@2.0.9/dist/html5-qrcode.min.js"></script>
|
|
||||||
<script>
|
<script>
|
||||||
const libraryModuleEnabled = {{ 'true' if library_module_enabled else 'false' }};
|
const libraryModuleEnabled = {{ 'true' if library_module_enabled else 'false' }};
|
||||||
|
|
||||||
@@ -984,12 +983,12 @@
|
|||||||
|
|
||||||
// Global variable to store fetched book data
|
// Global variable to store fetched book data
|
||||||
let currentBookData = null;
|
let currentBookData = null;
|
||||||
let code4ScannerInstance = null;
|
|
||||||
let code4ScannerRunning = false;
|
// Quagga2 engine state management properties
|
||||||
|
let scannerRunning = false;
|
||||||
|
let activeScannerCallback = null; // Dynamically handles routing data to the active caller field
|
||||||
let code4LastScanned = '';
|
let code4LastScanned = '';
|
||||||
let code4LastScannedAt = 0;
|
let code4LastScannedAt = 0;
|
||||||
let isbnScannerInstance = null;
|
|
||||||
let isbnScannerRunning = false;
|
|
||||||
|
|
||||||
function setCode4ScanStatus(message, isError = false) {
|
function setCode4ScanStatus(message, isError = false) {
|
||||||
const statusEl = document.getElementById('code4-scan-status');
|
const statusEl = document.getElementById('code4-scan-status');
|
||||||
@@ -1042,56 +1041,109 @@
|
|||||||
statusEl.style.color = '#b00020';
|
statusEl.style.color = '#b00020';
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Centered Quagga2 Engine Initialization Pattern
|
||||||
|
function runEngineInitialization(targetSelector, activeCallback, completionMsg, errorStatusSetter) {
|
||||||
|
if (scannerRunning) {
|
||||||
|
Quagga.stop();
|
||||||
|
scannerRunning = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
activeScannerCallback = activeCallback;
|
||||||
|
|
||||||
|
Quagga.init({
|
||||||
|
inputStream: {
|
||||||
|
name: "Live",
|
||||||
|
type: "LiveStream",
|
||||||
|
target: document.querySelector(targetSelector),
|
||||||
|
constraints: {
|
||||||
|
width: 640,
|
||||||
|
height: 480,
|
||||||
|
facingMode: "environment" // Force rear camera lenses
|
||||||
|
},
|
||||||
|
},
|
||||||
|
decoder: {
|
||||||
|
readers: ["code_128_reader", "ean_reader", "code_39_reader", "upc_reader"]
|
||||||
|
}
|
||||||
|
}, function(err) {
|
||||||
|
if (err) {
|
||||||
|
console.error("Initialization error:", err);
|
||||||
|
errorStatusSetter("Kamera konnte nicht gestartet werden.", true);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
Quagga.start();
|
||||||
|
scannerRunning = true;
|
||||||
|
errorStatusSetter(completionMsg, false);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function killScannerHardware() {
|
||||||
|
if (!scannerRunning) return;
|
||||||
|
Quagga.stop();
|
||||||
|
scannerRunning = false;
|
||||||
|
activeScannerCallback = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Unified tracking capture listener
|
||||||
|
Quagga.onDetected(function(data) {
|
||||||
|
if (!data || !data.codeResult || !data.codeResult.code) return;
|
||||||
|
|
||||||
|
const rawBarcode = String(data.codeResult.code || '').trim();
|
||||||
|
const currentTargetCallback = activeScannerCallback;
|
||||||
|
|
||||||
|
if (typeof currentTargetCallback === "function") {
|
||||||
|
currentTargetCallback(rawBarcode);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
function startCode4Scanner() {
|
function startCode4Scanner() {
|
||||||
const scannerBox = document.getElementById('code4-scanner');
|
const scannerBox = document.getElementById('code4-scanner');
|
||||||
const scanButton = document.getElementById('scan-code4-btn');
|
const scanButton = document.getElementById('scan-code4-btn');
|
||||||
const codeField = document.getElementById('code_4');
|
const codeField = document.getElementById('code_4');
|
||||||
if (!scannerBox || !scanButton || !codeField) return;
|
if (!scannerBox || !scanButton || !codeField) return;
|
||||||
|
|
||||||
// Stop ISBN scanner if currently running to avoid camera conflicts.
|
// Automatically clean up running ISBN scanner to prevent track multi-binding
|
||||||
if (isbnScannerRunning && isbnScannerInstance) {
|
|
||||||
isbnScannerInstance.clear().catch(() => {});
|
|
||||||
const isbnScannerBox = document.getElementById('isbn-scanner');
|
const isbnScannerBox = document.getElementById('isbn-scanner');
|
||||||
const isbnScanButton = document.getElementById('scan-isbn-btn');
|
const isbnScanButton = document.getElementById('scan-isbn-btn');
|
||||||
|
if (isbnScannerBox && isbnScannerBox.style.display !== 'none') {
|
||||||
|
killScannerHardware();
|
||||||
if (isbnScannerBox) isbnScannerBox.style.display = 'none';
|
if (isbnScannerBox) isbnScannerBox.style.display = 'none';
|
||||||
if (isbnScanButton) isbnScanButton.textContent = 'ISBN scannen';
|
if (isbnScanButton) isbnScanButton.textContent = 'ISBN scannen';
|
||||||
isbnScannerRunning = false;
|
setIsbnScanStatus('Scanner gestoppt.');
|
||||||
}
|
}
|
||||||
|
|
||||||
if (code4ScannerRunning && code4ScannerInstance) {
|
if (scannerBox.style.display !== 'none') {
|
||||||
code4ScannerInstance.clear().catch(() => {});
|
killScannerHardware();
|
||||||
scannerBox.style.display = 'none';
|
scannerBox.style.display = 'none';
|
||||||
scanButton.textContent = 'Barcode scannen';
|
scanButton.textContent = 'Barcode scannen';
|
||||||
code4ScannerRunning = false;
|
|
||||||
setCode4ScanStatus('Scanner gestoppt.');
|
setCode4ScanStatus('Scanner gestoppt.');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
scannerBox.style.display = 'block';
|
scannerBox.style.display = 'block';
|
||||||
scanButton.textContent = 'Scanner stoppen';
|
scanButton.textContent = 'Scanner stoppen';
|
||||||
code4ScannerInstance = new Html5QrcodeScanner('code4-scanner', {
|
|
||||||
fps: 10,
|
|
||||||
qrbox: 250,
|
|
||||||
rememberLastUsedCamera: true
|
|
||||||
});
|
|
||||||
code4ScannerRunning = true;
|
|
||||||
setCode4ScanStatus('Scanner läuft. Der Scan wird im Basis-Codefeld übernommen.');
|
|
||||||
|
|
||||||
code4ScannerInstance.render((decodedText) => {
|
|
||||||
const scannedCode = String(decodedText || '').trim();
|
|
||||||
if (!scannedCode) return;
|
|
||||||
|
|
||||||
|
runEngineInitialization(
|
||||||
|
'#code4-scanner',
|
||||||
|
function(decodedText) {
|
||||||
const now = Date.now();
|
const now = Date.now();
|
||||||
if (scannedCode === code4LastScanned && (now - code4LastScannedAt) < 1500) {
|
if (decodedText === code4LastScanned && (now - code4LastScannedAt) < 1500) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
code4LastScanned = scannedCode;
|
code4LastScanned = decodedText;
|
||||||
code4LastScannedAt = now;
|
code4LastScannedAt = now;
|
||||||
|
|
||||||
codeField.value = scannedCode;
|
killScannerHardware();
|
||||||
|
scannerBox.style.display = 'none';
|
||||||
|
scanButton.textContent = 'Barcode scannen';
|
||||||
|
|
||||||
|
codeField.value = decodedText;
|
||||||
validateCodeField(codeField);
|
validateCodeField(codeField);
|
||||||
setCode4ScanStatus(`Code_4 gesetzt: ${scannedCode}`);
|
setCode4ScanStatus(`Code_4 gesetzt: ${decodedText}`);
|
||||||
}, () => {});
|
},
|
||||||
|
'Scanner läuft. Der Scan wird im Basis-Codefeld übernommen.',
|
||||||
|
setCode4ScanStatus
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function startIsbnScanner() {
|
function startIsbnScanner() {
|
||||||
@@ -1104,59 +1156,49 @@
|
|||||||
const isbnField = document.getElementById('isbn');
|
const isbnField = document.getElementById('isbn');
|
||||||
if (!scannerBox || !scanButton || !isbnField) return;
|
if (!scannerBox || !scanButton || !isbnField) return;
|
||||||
|
|
||||||
// Stop Code_4 scanner if currently running to avoid camera conflicts.
|
// Automatically clean up running Base Code_4 scanner to prevent track multi-binding
|
||||||
if (code4ScannerRunning && code4ScannerInstance) {
|
|
||||||
code4ScannerInstance.clear().catch(() => {});
|
|
||||||
const codeScannerBox = document.getElementById('code4-scanner');
|
const codeScannerBox = document.getElementById('code4-scanner');
|
||||||
const codeScanButton = document.getElementById('scan-code4-btn');
|
const codeScanButton = document.getElementById('scan-code4-btn');
|
||||||
|
if (codeScannerBox && codeScannerBox.style.display !== 'none') {
|
||||||
|
killScannerHardware();
|
||||||
if (codeScannerBox) codeScannerBox.style.display = 'none';
|
if (codeScannerBox) codeScannerBox.style.display = 'none';
|
||||||
if (codeScanButton) codeScanButton.textContent = 'Barcode scannen';
|
if (codeScanButton) codeScanButton.textContent = 'Barcode scannen';
|
||||||
code4ScannerRunning = false;
|
|
||||||
setCode4ScanStatus('Scanner gestoppt.');
|
setCode4ScanStatus('Scanner gestoppt.');
|
||||||
}
|
}
|
||||||
|
|
||||||
if (isbnScannerRunning && isbnScannerInstance) {
|
if (scannerBox.style.display !== 'none') {
|
||||||
isbnScannerInstance.clear().catch(() => {});
|
killScannerHardware();
|
||||||
scannerBox.style.display = 'none';
|
scannerBox.style.display = 'none';
|
||||||
scanButton.textContent = 'ISBN scannen';
|
scanButton.textContent = 'ISBN scannen';
|
||||||
isbnScannerRunning = false;
|
|
||||||
setIsbnScanStatus('Scanner gestoppt.');
|
setIsbnScanStatus('Scanner gestoppt.');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
scannerBox.style.display = 'block';
|
scannerBox.style.display = 'block';
|
||||||
scanButton.textContent = 'Scanner stoppen';
|
scanButton.textContent = 'Scanner stoppen';
|
||||||
isbnScannerInstance = new Html5QrcodeScanner('isbn-scanner', {
|
|
||||||
fps: 10,
|
|
||||||
qrbox: 250,
|
|
||||||
rememberLastUsedCamera: true
|
|
||||||
});
|
|
||||||
isbnScannerRunning = true;
|
|
||||||
setIsbnScanStatus('Scanner läuft. Bitte ISBN-Code erfassen.');
|
|
||||||
|
|
||||||
isbnScannerInstance.render((decodedText) => {
|
runEngineInitialization(
|
||||||
const scannedCode = String(decodedText || '').trim();
|
'#isbn-scanner',
|
||||||
if (!scannedCode) return;
|
function(decodedText) {
|
||||||
|
killScannerHardware();
|
||||||
|
scannerBox.style.display = 'none';
|
||||||
|
scanButton.textContent = 'ISBN scannen';
|
||||||
|
|
||||||
const normalizedIsbn = normalizeIsbnClient(scannedCode);
|
const normalizedIsbn = normalizeIsbnClient(decodedText);
|
||||||
isbnField.value = normalizedIsbn || scannedCode;
|
isbnField.value = normalizedIsbn || decodedText;
|
||||||
updateIsbnLiveValidation();
|
updateIsbnLiveValidation();
|
||||||
|
|
||||||
if (normalizedIsbn) {
|
if (normalizedIsbn) {
|
||||||
setIsbnScanStatus(`ISBN gesetzt: ${normalizedIsbn}`);
|
setIsbnScanStatus(`ISBN gesetzt: ${normalizedIsbn}`);
|
||||||
|
// Automatically load book metadata after a valid ISBN scan.
|
||||||
|
fetchBookInfo('upload');
|
||||||
} else {
|
} else {
|
||||||
setIsbnScanStatus('Kein gültiges ISBN-Format erkannt, der gescannte Wert bleibt aber im Feld.', true);
|
setIsbnScanStatus('Kein gültiges ISBN-Format erkannt, der gescannte Wert bleibt aber im Feld.', true);
|
||||||
}
|
}
|
||||||
|
},
|
||||||
isbnScannerInstance.clear().catch(() => {});
|
'Scanner läuft. Bitte ISBN-Code erfassen.',
|
||||||
scannerBox.style.display = 'none';
|
setIsbnScanStatus
|
||||||
scanButton.textContent = 'ISBN scannen';
|
);
|
||||||
isbnScannerRunning = false;
|
|
||||||
|
|
||||||
if (normalizedIsbn) {
|
|
||||||
// Automatically load book metadata after a valid ISBN scan.
|
|
||||||
fetchBookInfo('upload');
|
|
||||||
}
|
|
||||||
}, () => {});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Load predefined filter values for dropdowns
|
// Load predefined filter values for dropdowns
|
||||||
@@ -1558,6 +1600,7 @@
|
|||||||
}, 10000);
|
}, 10000);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Exported function for use within parent layout fields
|
||||||
function validateCodeField(input, excludeId = null) {
|
function validateCodeField(input, excludeId = null) {
|
||||||
const code = input.value.trim();
|
const code = input.value.trim();
|
||||||
|
|
||||||
@@ -1732,188 +1775,11 @@
|
|||||||
if (typeof duplicateData.images === 'string') {
|
if (typeof duplicateData.images === 'string') {
|
||||||
try {
|
try {
|
||||||
duplicateData.images = JSON.parse(duplicateData.images);
|
duplicateData.images = JSON.parse(duplicateData.images);
|
||||||
console.log("Parsed images from string:", duplicateData.images);
|
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.warn("Failed to parse images string, using as single item:", duplicateData.images);
|
console.error("Error parsing duplicate images array:", e);
|
||||||
duplicateData.images = [duplicateData.images];
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
console.log(`Final duplicateData.images (${Array.isArray(duplicateData.images) ? 'array' : typeof duplicateData.images}):`, duplicateData.images);
|
console.log("Parsed duplicate images successfully.");
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Then check for sessionStorage data (takes priority)
|
|
||||||
const sessionData = sessionStorage.getItem('duplicateItemData');
|
|
||||||
if (sessionData) {
|
|
||||||
try {
|
|
||||||
duplicateData = JSON.parse(sessionData);
|
|
||||||
sessionStorage.removeItem('duplicateItemData'); // Clean up
|
|
||||||
console.log("Session storage duplicate data:", duplicateData);
|
|
||||||
} catch (e) {
|
|
||||||
console.error('Error parsing session duplicate data:', e);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Function to prefill form with duplicate data
|
|
||||||
function prefillFormWithDuplicateData() {
|
|
||||||
if (!duplicateData) return;
|
|
||||||
|
|
||||||
// Fill basic fields
|
|
||||||
const nameField = document.getElementById('name');
|
|
||||||
if (nameField && duplicateData.name) nameField.value = duplicateData.name;
|
|
||||||
|
|
||||||
const descField = document.getElementById('beschreibung');
|
|
||||||
if (descField && duplicateData.description) descField.value = duplicateData.description;
|
|
||||||
|
|
||||||
const yearField = document.getElementById('anschaffungsjahr');
|
|
||||||
if (yearField && duplicateData.year) yearField.value = duplicateData.year;
|
|
||||||
|
|
||||||
const costField = document.getElementById('anschaffungskosten');
|
|
||||||
if (costField && duplicateData.cost) costField.value = duplicateData.cost;
|
|
||||||
|
|
||||||
// Fill location dropdown
|
|
||||||
const locationField = document.getElementById('ort');
|
|
||||||
if (locationField && duplicateData.location) {
|
|
||||||
// Wait for locations to load, then set value
|
|
||||||
setTimeout(() => {
|
|
||||||
locationField.value = duplicateData.location;
|
|
||||||
}, 100);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Fill filter arrays - handle up to 4 values per filter type
|
|
||||||
setTimeout(() => {
|
|
||||||
// Filter 1 (Unterrichtsfach)
|
|
||||||
if (duplicateData.filter1 && Array.isArray(duplicateData.filter1)) {
|
|
||||||
for (let j = 1; j <= Math.min(4, duplicateData.filter1.length); j++) {
|
|
||||||
const filterField = document.getElementById(`filter1-${j}`);
|
|
||||||
if (filterField && duplicateData.filter1[j-1]) {
|
|
||||||
filterField.value = duplicateData.filter1[j-1];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Filter 2 (Jahrgangsstufe)
|
|
||||||
if (duplicateData.filter2 && Array.isArray(duplicateData.filter2)) {
|
|
||||||
for (let j = 1; j <= Math.min(4, duplicateData.filter2.length); j++) {
|
|
||||||
const filterField = document.getElementById(`filter2-${j}`);
|
|
||||||
if (filterField && duplicateData.filter2[j-1]) {
|
|
||||||
filterField.value = duplicateData.filter2[j-1];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Filter 3 (Thema) - text inputs
|
|
||||||
if (duplicateData.filter3 && Array.isArray(duplicateData.filter3)) {
|
|
||||||
for (let j = 1; j <= Math.min(4, duplicateData.filter3.length); j++) {
|
|
||||||
const filterField = document.getElementById(`filter3-${j}`);
|
|
||||||
if (filterField && duplicateData.filter3[j-1]) {
|
|
||||||
filterField.value = duplicateData.filter3[j-1];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}, 200); // Wait for filter options to load
|
|
||||||
|
|
||||||
// Handle images - add hidden inputs for duplicate images
|
|
||||||
if (duplicateData.images && duplicateData.images.length > 0) {
|
|
||||||
console.log("Duplicate images data:", duplicateData.images);
|
|
||||||
const form = document.querySelector('form[action*="upload_item"]');
|
|
||||||
if (form) {
|
|
||||||
// Add hidden field to indicate duplication
|
|
||||||
const isDuplicatingField = document.createElement('input');
|
|
||||||
isDuplicatingField.type = 'hidden';
|
|
||||||
isDuplicatingField.name = 'is_duplicating';
|
|
||||||
isDuplicatingField.value = 'true';
|
|
||||||
form.appendChild(isDuplicatingField);
|
|
||||||
|
|
||||||
// Add each image as a duplicate image
|
|
||||||
const images = duplicateData.images || [];
|
|
||||||
console.log(`Adding ${images.length} images as hidden fields`);
|
|
||||||
|
|
||||||
if (Array.isArray(images)) {
|
|
||||||
images.forEach((imageName, index) => {
|
|
||||||
if (imageName) {
|
|
||||||
console.log(`Adding duplicate image ${index}: ${imageName}`);
|
|
||||||
const imageField = document.createElement('input');
|
|
||||||
imageField.type = 'hidden';
|
|
||||||
imageField.name = 'duplicate_images';
|
|
||||||
imageField.value = imageName;
|
|
||||||
form.appendChild(imageField);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
} else {
|
|
||||||
console.warn("Images is not an array:", images);
|
|
||||||
// Try to handle as single item if it's a string
|
|
||||||
if (typeof images === 'string' && images) {
|
|
||||||
console.log("Adding single image:", images);
|
|
||||||
const imageField = document.createElement('input');
|
|
||||||
imageField.type = 'hidden';
|
|
||||||
imageField.name = 'duplicate_images';
|
|
||||||
imageField.value = images;
|
|
||||||
form.appendChild(imageField);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Show image preview
|
|
||||||
showDuplicateImagePreview(duplicateData.images);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Function to show preview of duplicate images
|
|
||||||
function showDuplicateImagePreview(images) {
|
|
||||||
const previewContainer = document.getElementById('image-preview-container');
|
|
||||||
if (!previewContainer) return;
|
|
||||||
|
|
||||||
console.log("showDuplicateImagePreview called with:", images);
|
|
||||||
|
|
||||||
// Make sure images is treated as an array
|
|
||||||
if (!Array.isArray(images)) {
|
|
||||||
if (typeof images === 'string') {
|
|
||||||
// Try to parse if it's a JSON string
|
|
||||||
try {
|
|
||||||
images = JSON.parse(images);
|
|
||||||
} catch (e) {
|
|
||||||
// If parsing fails, wrap the single string in an array
|
|
||||||
images = [images];
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
console.error("Invalid images data:", images);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
previewContainer.innerHTML = '';
|
|
||||||
console.log(`Processing ${images.length} images for preview`);
|
|
||||||
|
|
||||||
images.forEach((imageName, index) => {
|
|
||||||
console.log(`Processing image ${index}:`, imageName);
|
|
||||||
const preview = document.createElement('div');
|
|
||||||
preview.className = 'image-preview-item';
|
|
||||||
preview.innerHTML = `
|
|
||||||
<img src="/uploads/${imageName}" alt="Duplicate Image ${index + 1}" class="duplicate-image-preview">
|
|
||||||
<div class="image-controls">
|
|
||||||
<span>Von Original übernommen</span>
|
|
||||||
<button type="button" onclick="removeDuplicateImage('${imageName}', this)" class="remove-duplicate-image-button">Entfernen</button>
|
|
||||||
</div>
|
|
||||||
`;
|
|
||||||
previewContainer.appendChild(preview);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
// Function to remove a duplicate image
|
|
||||||
function removeDuplicateImage(imageName, button) {
|
|
||||||
// Remove the hidden input
|
|
||||||
const hiddenInputs = document.querySelectorAll('input[name="duplicate_images"]');
|
|
||||||
hiddenInputs.forEach(input => {
|
|
||||||
if (input.value === imageName) {
|
|
||||||
input.remove();
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
// Remove the preview
|
|
||||||
const previewItem = button.closest('.image-preview-item');
|
|
||||||
if (previewItem) {
|
|
||||||
previewItem.remove();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
</script>
|
</script>
|
||||||
|
|||||||
@@ -1,54 +0,0 @@
|
|||||||
#!/usr/bin/env python3
|
|
||||||
"""
|
|
||||||
Small debug script to check tenant-aware lookup for an appointment id.
|
|
||||||
Usage: ./tools/debug_get_appointment.py <appointment_id> [tenant]
|
|
||||||
"""
|
|
||||||
import sys
|
|
||||||
from bson.objectid import ObjectId
|
|
||||||
from Web.modules.database.settings import MongoClient, MONGODB_HOST, MONGODB_PORT, MONGODB_DB
|
|
||||||
import Web.modules.database.termine as termine
|
|
||||||
|
|
||||||
|
|
||||||
def main():
|
|
||||||
if len(sys.argv) < 2:
|
|
||||||
print("Usage: debug_get_appointment.py <appointment_id> [tenant]")
|
|
||||||
sys.exit(2)
|
|
||||||
aid = sys.argv[1]
|
|
||||||
tenant = sys.argv[2] if len(sys.argv) > 2 else None
|
|
||||||
|
|
||||||
if tenant:
|
|
||||||
print(f"Looking up appointment {aid} for tenant {tenant}")
|
|
||||||
else:
|
|
||||||
print(f"Looking up appointment {aid} for default tenant")
|
|
||||||
|
|
||||||
try:
|
|
||||||
# Use the module helper directly
|
|
||||||
item = termine.get_item(aid)
|
|
||||||
if item:
|
|
||||||
print('Found with termini.get_item:')
|
|
||||||
print(item)
|
|
||||||
else:
|
|
||||||
print('termin.get_item returned None')
|
|
||||||
|
|
||||||
# Try explicit MongoClient + tenant DB resolution
|
|
||||||
client = MongoClient(MONGODB_HOST, MONGODB_PORT)
|
|
||||||
try:
|
|
||||||
from Web.tenant import TenantContext, get_tenant_db
|
|
||||||
if tenant:
|
|
||||||
ctx = TenantContext()
|
|
||||||
ctx.tenant_id = tenant
|
|
||||||
db = ctx.get_database(client)
|
|
||||||
else:
|
|
||||||
db = get_tenant_db(client) if 'get_tenant_db' in dir() else client[MONGODB_DB]
|
|
||||||
|
|
||||||
doc = db['appointments'].find_one({'_id': ObjectId(aid)})
|
|
||||||
print('Direct DB find_one returned:')
|
|
||||||
print(doc)
|
|
||||||
finally:
|
|
||||||
client.close()
|
|
||||||
except Exception as e:
|
|
||||||
print('Error during debug lookup:', e)
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
|
||||||
main()
|
|
||||||
Reference in New Issue
Block a user