Compare commits
54 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 5ba0944faf | |||
| 37f514af15 | |||
| 152a3ab135 | |||
| c2c5054814 | |||
| e058bd5f46 | |||
| d58958db39 | |||
| 9452743660 | |||
| 6a3865ef24 | |||
| 96d45710ac | |||
| dd3d8649a7 | |||
| 1af2a2be06 | |||
| 8e5e434116 | |||
| 2f9a93ee65 | |||
| 91467a1e76 | |||
| 3840348a2d | |||
| cdb7319c56 | |||
| 08bea97f0f | |||
| 9164cd030d | |||
| 9227392787 | |||
| 4917c22ae3 | |||
| a2f2dd5a9e | |||
| faf270ff93 | |||
| beeb562ac4 | |||
| 0199957545 | |||
| a518adb054 | |||
| 6a94d50d28 | |||
| c90cef6dcf | |||
| b5451a4ef0 | |||
| a4afef8283 | |||
| b2951eed6c | |||
| 9a37c047c1 | |||
| 7290fb4ed1 | |||
| ee9ef3df6f | |||
| 9f3799a77f | |||
| e9006f5a07 | |||
| a11bce17c5 | |||
| 743e5b1c16 | |||
| 4e47ef0c88 | |||
| 0911b362fd | |||
| 71716f339a | |||
| 36ccee38cb | |||
| 9255c87f57 | |||
| a6b246a92b | |||
| 25f52eeeb5 | |||
| c07d4e0bdd | |||
| 0cacfb0871 | |||
| d3bfaa4580 | |||
| 36531662d3 | |||
| 35b87a9a98 | |||
| 80262aca9b | |||
| 71a8823b35 | |||
| 10e7f3e70d | |||
| e8f0d4bdc5 | |||
| c77c52271c |
@@ -4,17 +4,20 @@ on:
|
|||||||
push:
|
push:
|
||||||
tags:
|
tags:
|
||||||
- "v*"
|
- "v*"
|
||||||
|
branches:
|
||||||
|
- main
|
||||||
workflow_dispatch:
|
workflow_dispatch:
|
||||||
inputs:
|
inputs:
|
||||||
bump:
|
release_type:
|
||||||
description: "Version bump type (major stays fixed from latest release)"
|
description: "Release type"
|
||||||
required: false
|
required: false
|
||||||
default: "patch"
|
default: "patch"
|
||||||
type: choice
|
type: choice
|
||||||
options:
|
options:
|
||||||
- patch
|
|
||||||
- minor
|
|
||||||
- major
|
- major
|
||||||
|
- minor
|
||||||
|
- patch
|
||||||
|
- dev
|
||||||
|
|
||||||
permissions:
|
permissions:
|
||||||
contents: write
|
contents: write
|
||||||
@@ -38,12 +41,70 @@ jobs:
|
|||||||
REPO: ${{ gitea.repository }}
|
REPO: ${{ gitea.repository }}
|
||||||
EVENT_NAME: ${{ gitea.event_name }}
|
EVENT_NAME: ${{ gitea.event_name }}
|
||||||
REF_NAME: ${{ gitea.ref_name }}
|
REF_NAME: ${{ gitea.ref_name }}
|
||||||
BUMP_TYPE: ${{ gitea.event.inputs.bump || 'patch' }}
|
RELEASE_TYPE: ${{ gitea.event.inputs.release_type || 'patch' }}
|
||||||
DOCKER_API_VERSION: '1.44'
|
DOCKER_API_VERSION: '1.44'
|
||||||
run: |
|
run: |
|
||||||
if [ "$EVENT_NAME" = "push" ] && [ -n "$REF_NAME" ]; then
|
latest_stable_tag() {
|
||||||
|
local releases_file="$1"
|
||||||
|
python3 -c "import json, sys; releases = json.load(open(sys.argv[1], encoding='utf-8')); print(next((release.get('tag_name', '').strip() for release in releases if not release.get('prerelease') and not release.get('draft')), ''))" "$releases_file"
|
||||||
|
}
|
||||||
|
|
||||||
|
next_dev_suffix() {
|
||||||
|
local releases_file="$1"
|
||||||
|
local base_tag="$2"
|
||||||
|
python3 -c "import json, re, sys; releases_path, base_tag = sys.argv[1], sys.argv[2].strip(); pattern = re.compile(r'^' + re.escape(base_tag) + r'-dev\\.(\\d+)$'); releases = json.load(open(releases_path, encoding='utf-8')); highest = max([int(match.group(1)) for release in releases for match in [pattern.match(release.get('tag_name', '').strip())] if match], default=0); print(highest + 1)" "$releases_file" "$base_tag"
|
||||||
|
}
|
||||||
|
|
||||||
|
make_dev_tag() {
|
||||||
|
local releases_file="$1"
|
||||||
|
local stable_tag="$2"
|
||||||
|
local major minor patch next_suffix
|
||||||
|
|
||||||
|
if [[ "$stable_tag" =~ ^v([0-9]+)\.([0-9]+)\.([0-9]+)$ ]]; then
|
||||||
|
major=${BASH_REMATCH[1]}
|
||||||
|
minor=${BASH_REMATCH[2]}
|
||||||
|
patch=${BASH_REMATCH[3]}
|
||||||
|
else
|
||||||
|
major=0
|
||||||
|
minor=8
|
||||||
|
patch=31
|
||||||
|
fi
|
||||||
|
|
||||||
|
patch=$((patch + 1))
|
||||||
|
next_suffix="$(next_dev_suffix "$releases_file" "v${major}.${minor}.${patch}")"
|
||||||
|
printf 'v%s.%s.%s-dev.%s' "$major" "$minor" "$patch" "$next_suffix"
|
||||||
|
}
|
||||||
|
|
||||||
|
releases_file="$(mktemp)"
|
||||||
|
trap 'rm -f "${releases_file:-}"' EXIT
|
||||||
|
|
||||||
|
if [ "$EVENT_NAME" = "push" ] && [ "$REF_NAME" = "main" ]; then
|
||||||
|
prerelease=true
|
||||||
|
if ! curl -fsSL -H "Authorization: Bearer $GH_TOKEN" -H "Accept: application/json" "https://git.invario-software.eu/api/v1/repos/$REPO/releases" -o "$releases_file"; then
|
||||||
|
echo "Error: could not fetch release list"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
latest_tag="$(latest_stable_tag "$releases_file")"
|
||||||
|
if [ -z "$latest_tag" ]; then
|
||||||
|
latest_tag="v0.8.31"
|
||||||
|
fi
|
||||||
|
TAG="$(make_dev_tag "$releases_file" "$latest_tag")"
|
||||||
|
elif [ "$EVENT_NAME" = "workflow_dispatch" ] && [ "$RELEASE_TYPE" = "dev" ]; then
|
||||||
|
prerelease=true
|
||||||
|
if ! curl -fsSL -H "Authorization: Bearer $GH_TOKEN" -H "Accept: application/json" "https://git.invario-software.eu/api/v1/repos/$REPO/releases" -o "$releases_file"; then
|
||||||
|
echo "Error: could not fetch release list"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
latest_tag="$(latest_stable_tag "$releases_file")"
|
||||||
|
if [ -z "$latest_tag" ]; then
|
||||||
|
latest_tag="v0.8.31"
|
||||||
|
fi
|
||||||
|
TAG="$(make_dev_tag "$releases_file" "$latest_tag")"
|
||||||
|
elif [ "$EVENT_NAME" = "push" ] && [ -n "$REF_NAME" ]; then
|
||||||
|
prerelease=false
|
||||||
TAG="$REF_NAME"
|
TAG="$REF_NAME"
|
||||||
else
|
else
|
||||||
|
prerelease=false
|
||||||
latest_tag="v0.8.31"
|
latest_tag="v0.8.31"
|
||||||
if meta_json=$(curl -fsSL -H "Authorization: Bearer $GH_TOKEN" -H "Accept: application/json" "https://git.invario-software.eu/api/v1/repos/$REPO/releases/latest" 2>/dev/null); then
|
if meta_json=$(curl -fsSL -H "Authorization: Bearer $GH_TOKEN" -H "Accept: application/json" "https://git.invario-software.eu/api/v1/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)
|
||||||
@@ -60,14 +121,14 @@ jobs:
|
|||||||
major=0; minor=8; patch=31
|
major=0; minor=8; patch=31
|
||||||
fi
|
fi
|
||||||
|
|
||||||
if [ "${BUMP_TYPE:-}" = "major" ]; then
|
if [ "${RELEASE_TYPE:-}" = "major" ]; then
|
||||||
major=$((major + 1)); minor=0; patch=0
|
major=$((major + 1)); minor=0; patch=0
|
||||||
elif [ "${BUMP_TYPE:-}" = "minor" ]; then
|
elif [ "${RELEASE_TYPE:-}" = "minor" ]; then
|
||||||
minor=$((minor + 1)); patch=0
|
minor=$((minor + 1)); patch=0
|
||||||
else
|
else
|
||||||
patch=$((patch + 1))
|
patch=$((patch + 1))
|
||||||
fi
|
fi
|
||||||
|
|
||||||
TAG="v${major}.${minor}.${patch}"
|
TAG="v${major}.${minor}.${patch}"
|
||||||
fi
|
fi
|
||||||
|
|
||||||
@@ -109,6 +170,7 @@ jobs:
|
|||||||
echo "tag=$TAG" >> "$GITHUB_OUTPUT"
|
echo "tag=$TAG" >> "$GITHUB_OUTPUT"
|
||||||
echo "image=$IMAGE" >> "$GITHUB_OUTPUT"
|
echo "image=$IMAGE" >> "$GITHUB_OUTPUT"
|
||||||
echo "lower_repo=$LOWER_REPO" >> "$GITHUB_OUTPUT"
|
echo "lower_repo=$LOWER_REPO" >> "$GITHUB_OUTPUT"
|
||||||
|
echo "prerelease=$prerelease" >> "$GITHUB_OUTPUT"
|
||||||
|
|
||||||
- name: Ensure Docker CLI is available and up to date
|
- name: Ensure Docker CLI is available and up to date
|
||||||
run: |
|
run: |
|
||||||
@@ -148,6 +210,7 @@ jobs:
|
|||||||
password: ${{ secrets.REGISTRY_TOKEN }}
|
password: ${{ secrets.REGISTRY_TOKEN }}
|
||||||
|
|
||||||
- name: Build and push release image
|
- name: Build and push release image
|
||||||
|
if: steps.meta.outputs.prerelease != 'true'
|
||||||
uses: docker/build-push-action@v6
|
uses: docker/build-push-action@v6
|
||||||
with:
|
with:
|
||||||
context: .
|
context: .
|
||||||
@@ -157,6 +220,16 @@ jobs:
|
|||||||
${{ steps.meta.outputs.image }}
|
${{ steps.meta.outputs.image }}
|
||||||
git.invario-software.eu/${{ steps.meta.outputs.lower_repo }}:latest
|
git.invario-software.eu/${{ steps.meta.outputs.lower_repo }}:latest
|
||||||
|
|
||||||
|
- name: Build and push prerelease image
|
||||||
|
if: steps.meta.outputs.prerelease == 'true'
|
||||||
|
uses: docker/build-push-action@v6
|
||||||
|
with:
|
||||||
|
context: .
|
||||||
|
file: ./Dockerfile
|
||||||
|
push: true
|
||||||
|
tags: |
|
||||||
|
${{ steps.meta.outputs.image }}
|
||||||
|
|
||||||
- name: Create release-only docker bundle
|
- name: Create release-only docker bundle
|
||||||
run: |
|
run: |
|
||||||
mkdir -p release-bundle
|
mkdir -p release-bundle
|
||||||
@@ -253,5 +326,6 @@ jobs:
|
|||||||
uses: https://gitea.com/actions/gitea-release-action@v1
|
uses: https://gitea.com/actions/gitea-release-action@v1
|
||||||
with:
|
with:
|
||||||
tag_name: ${{ steps.meta.outputs.tag }}
|
tag_name: ${{ steps.meta.outputs.tag }}
|
||||||
|
prerelease: ${{ steps.meta.outputs.prerelease }}
|
||||||
files: |
|
files: |
|
||||||
inventarsystem-docker-bundle.tar.gz
|
inventarsystem-docker-bundle.tar.gz
|
||||||
+569
-27
@@ -27,6 +27,10 @@ import os
|
|||||||
import sys
|
import sys
|
||||||
from bs4 import BeautifulSoup
|
from bs4 import BeautifulSoup
|
||||||
from gridfs import GridFS
|
from gridfs import GridFS
|
||||||
|
import string
|
||||||
|
from reportlab.lib.pagesizes import A4
|
||||||
|
from reportlab.pdfgen import canvas
|
||||||
|
from reportlab.lib import colors
|
||||||
|
|
||||||
# Ensure imports work regardless of whether gunicorn starts in /app or /app/Web.
|
# Ensure imports work regardless of whether gunicorn starts in /app or /app/Web.
|
||||||
_CURRENT_DIR = os.path.dirname(os.path.abspath(__file__))
|
_CURRENT_DIR = os.path.dirname(os.path.abspath(__file__))
|
||||||
@@ -46,7 +50,7 @@ import Web.modules.inventarsystem.pdf_export as pdf_export
|
|||||||
import Web.modules.inventarsystem.excel_export as excel_export
|
import Web.modules.inventarsystem.excel_export as excel_export
|
||||||
import datetime
|
import datetime
|
||||||
from apscheduler.schedulers.background import BackgroundScheduler
|
from apscheduler.schedulers.background import BackgroundScheduler
|
||||||
from bson.objectid import ObjectId
|
from bson.objectid import ObjectId, InvalidId
|
||||||
from urllib.parse import urlparse, urlunparse
|
from urllib.parse import urlparse, urlunparse
|
||||||
import requests
|
import requests
|
||||||
import csv
|
import csv
|
||||||
@@ -225,12 +229,95 @@ def rollover_student_card_classes(dry_run=False, *, max_class=None, graduate_lab
|
|||||||
if client:
|
if client:
|
||||||
client.close()
|
client.close()
|
||||||
|
|
||||||
summary = {'examined': examined, 'updated': updated, 'failures': failures, 'dry_run': bool(dry_run)}
|
|
||||||
|
@app.route('/api/library_return_by_code', methods=['POST'])
|
||||||
|
def api_library_return_by_code():
|
||||||
|
"""
|
||||||
|
Return a library item by scanning its code only (no student card required).
|
||||||
|
This marks active ausleihungen for the item as completed and updates item status.
|
||||||
|
"""
|
||||||
|
if 'username' not in session:
|
||||||
|
return jsonify({'ok': False, 'message': 'Nicht angemeldet.'}), 401
|
||||||
|
if not cfg.MODULES.is_enabled('library'):
|
||||||
|
return jsonify({'ok': False, 'message': 'Bibliotheks-Modul ist deaktiviert.'}), 403
|
||||||
|
|
||||||
|
payload = request.get_json(silent=True) or {}
|
||||||
|
item_code_raw = str(payload.get('item_code') or payload.get('code') or '').strip()
|
||||||
|
if not item_code_raw:
|
||||||
|
return jsonify({'ok': False, 'message': 'Mediencode fehlt.'}), 400
|
||||||
|
|
||||||
|
normalized_isbn = normalize_and_validate_isbn(item_code_raw)
|
||||||
|
normalized_code = item_code_raw.upper()
|
||||||
|
|
||||||
|
client = None
|
||||||
try:
|
try:
|
||||||
_append_audit_event_standalone('student_cards_rollover', summary)
|
client = MongoClient(MONGODB_HOST, MONGODB_PORT)
|
||||||
except Exception:
|
db = client[MONGODB_DB]
|
||||||
app.logger.warning('Audit write failed for student_cards_rollover')
|
items_col = db['items']
|
||||||
return summary
|
ausleihungen_col = db['ausleihungen']
|
||||||
|
|
||||||
|
query_or = [
|
||||||
|
{'Code_4': item_code_raw},
|
||||||
|
{'Code_4': normalized_code},
|
||||||
|
]
|
||||||
|
if normalized_isbn:
|
||||||
|
query_or.append({'ISBN': normalized_isbn})
|
||||||
|
|
||||||
|
item_doc = items_col.find_one({
|
||||||
|
'ItemType': {'$in': LIBRARY_ITEM_TYPES},
|
||||||
|
'$or': query_or
|
||||||
|
})
|
||||||
|
|
||||||
|
if not item_doc:
|
||||||
|
return jsonify({'ok': False, 'message': 'Kein Bibliotheksmedium für diesen Code gefunden.'}), 404
|
||||||
|
|
||||||
|
item_id = str(item_doc['_id'])
|
||||||
|
now = datetime.datetime.now()
|
||||||
|
|
||||||
|
# If item already available -> nothing to return
|
||||||
|
if item_doc.get('Verfuegbar', True):
|
||||||
|
return jsonify({'ok': False, 'message': 'Dieses Medium ist nicht als ausgeliehen markiert.'}), 409
|
||||||
|
|
||||||
|
# Mark active ausleihungen as completed
|
||||||
|
update_result = ausleihungen_col.update_many(
|
||||||
|
{'Item': item_id, 'Status': 'active'},
|
||||||
|
{'$set': {
|
||||||
|
'Status': 'completed',
|
||||||
|
'End': now,
|
||||||
|
'LastUpdated': now
|
||||||
|
}}
|
||||||
|
)
|
||||||
|
|
||||||
|
# Update item status to available
|
||||||
|
borrower_name = str(item_doc.get('User') or '').strip() or ''
|
||||||
|
it.update_item_status(item_id, True, borrower_name)
|
||||||
|
|
||||||
|
_append_audit_event_standalone(
|
||||||
|
event_type='ausleihung_returned_by_code',
|
||||||
|
payload={
|
||||||
|
'channel': 'library_return_code',
|
||||||
|
'item_id': item_id,
|
||||||
|
'item_name': item_doc.get('Name', ''),
|
||||||
|
'completed_records': update_result.modified_count,
|
||||||
|
'performed_by': session.get('username')
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
return jsonify({
|
||||||
|
'ok': True,
|
||||||
|
'action': 'returned',
|
||||||
|
'item_id': item_id,
|
||||||
|
'item_name': item_doc.get('Name', ''),
|
||||||
|
'completed_records': update_result.modified_count,
|
||||||
|
'message': f"{item_doc.get('Name', 'Medium')} wurde zurückgegeben."
|
||||||
|
}), 200
|
||||||
|
except Exception as e:
|
||||||
|
app.logger.error(f"Error in library return by code: {e}")
|
||||||
|
return jsonify({'ok': False, 'message': 'Fehler beim Verarbeiten der Rückgabe.'}), 500
|
||||||
|
finally:
|
||||||
|
if client:
|
||||||
|
client.close()
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
# Admin route to trigger rollover manually
|
# Admin route to trigger rollover manually
|
||||||
@@ -3230,7 +3317,7 @@ def api_library_items():
|
|||||||
ausleihungen_db = db['ausleihungen']
|
ausleihungen_db = db['ausleihungen']
|
||||||
|
|
||||||
query = {
|
query = {
|
||||||
'ItemType': {'$in': ['book', 'cd', 'dvd', 'schoolbook', 'schulbuch', 'Buch', 'Schulbuch']},
|
'ItemType': {'$in': ['book', 'cd', 'CD', 'DVD', 'dvd', 'schoolbook', 'schulbuch', 'Buch', 'Schulbuch']},
|
||||||
'IsGroupedSubItem': {'$ne': True},
|
'IsGroupedSubItem': {'$ne': True},
|
||||||
'Deleted': {'$ne': True}
|
'Deleted': {'$ne': True}
|
||||||
}
|
}
|
||||||
@@ -3249,7 +3336,12 @@ def api_library_items():
|
|||||||
'User': 1,
|
'User': 1,
|
||||||
'Ort': 1,
|
'Ort': 1,
|
||||||
'Beschreibung': 1,
|
'Beschreibung': 1,
|
||||||
'Image': 1
|
'Image': 1,
|
||||||
|
'SeriesGroupId': 1,
|
||||||
|
'SeriesCount': 1,
|
||||||
|
'SeriesPosition': 1,
|
||||||
|
'IsGroupedSubItem': 1,
|
||||||
|
'ParentItemId': 1,
|
||||||
}
|
}
|
||||||
|
|
||||||
total_count = items_db.count_documents(query)
|
total_count = items_db.count_documents(query)
|
||||||
@@ -3277,6 +3369,10 @@ def api_library_items():
|
|||||||
'Beschreibung': 1,
|
'Beschreibung': 1,
|
||||||
'Image': 1,
|
'Image': 1,
|
||||||
'ParentItemId': 1,
|
'ParentItemId': 1,
|
||||||
|
'SeriesGroupId': 1,
|
||||||
|
'SeriesCount': 1,
|
||||||
|
'SeriesPosition': 1,
|
||||||
|
'IsGroupedSubItem': 1,
|
||||||
}
|
}
|
||||||
child_items = list(items_db.find({
|
child_items = list(items_db.find({
|
||||||
'ParentItemId': {'$in': parent_ids_list},
|
'ParentItemId': {'$in': parent_ids_list},
|
||||||
@@ -3390,6 +3486,48 @@ def api_library_items():
|
|||||||
return jsonify({'error': 'An error occurred while fetching library items'}), 500
|
return jsonify({'error': 'An error occurred while fetching library items'}), 500
|
||||||
|
|
||||||
|
|
||||||
|
@app.route('/api/library_group/<series_group_id>')
|
||||||
|
def api_library_group(series_group_id):
|
||||||
|
"""Fetch all items belonging to one library series group."""
|
||||||
|
if 'username' not in session:
|
||||||
|
return jsonify({'items': []}), 401
|
||||||
|
|
||||||
|
try:
|
||||||
|
client = MongoClient(MONGODB_HOST, MONGODB_PORT)
|
||||||
|
db = client[MONGODB_DB]
|
||||||
|
items_col = db['items']
|
||||||
|
|
||||||
|
query = {
|
||||||
|
'SeriesGroupId': series_group_id,
|
||||||
|
'Deleted': {'$ne': True},
|
||||||
|
'ItemType': {'$in': ['book', 'cd', 'dvd', 'schoolbook', 'schulbuch', 'Buch', 'Schulbuch']},
|
||||||
|
}
|
||||||
|
projection = {
|
||||||
|
'Name': 1,
|
||||||
|
'ISBN': 1,
|
||||||
|
'Code_4': 1,
|
||||||
|
'Code4': 1,
|
||||||
|
'ItemType': 1,
|
||||||
|
'Ort': 1,
|
||||||
|
'Beschreibung': 1,
|
||||||
|
'SeriesGroupId': 1,
|
||||||
|
'SeriesCount': 1,
|
||||||
|
'SeriesPosition': 1,
|
||||||
|
'IsGroupedSubItem': 1,
|
||||||
|
'ParentItemId': 1,
|
||||||
|
}
|
||||||
|
|
||||||
|
items = list(items_col.find(query, projection).sort([('SeriesPosition', 1), ('Name', 1), ('_id', 1)]))
|
||||||
|
for item in items:
|
||||||
|
item['_id'] = str(item['_id'])
|
||||||
|
|
||||||
|
client.close()
|
||||||
|
return jsonify({'items': items, 'count': len(items), 'series_group_id': series_group_id})
|
||||||
|
except Exception as exc:
|
||||||
|
app.logger.error('Error loading library group %s: %s', series_group_id, exc)
|
||||||
|
return jsonify({'items': [], 'message': 'Gruppe konnte nicht geladen werden.'}), 500
|
||||||
|
|
||||||
|
|
||||||
@app.route('/api/library_scan_action', methods=['POST'])
|
@app.route('/api/library_scan_action', methods=['POST'])
|
||||||
def api_library_scan_action():
|
def api_library_scan_action():
|
||||||
"""
|
"""
|
||||||
@@ -3654,6 +3792,7 @@ def api_item_detail(item_id):
|
|||||||
<h2>{html.escape(str(item.get('Name', 'Untitled')))}</h2>
|
<h2>{html.escape(str(item.get('Name', 'Untitled')))}</h2>
|
||||||
<p><strong>ISBN:</strong> {html.escape(str(item.get('ISBN', item.get('Code4', '-'))))}</p>
|
<p><strong>ISBN:</strong> {html.escape(str(item.get('ISBN', item.get('Code4', '-'))))}</p>
|
||||||
<p><strong>Anzahl:</strong> {html.escape(str(item.get('SeriesCount', '-')))}</p>
|
<p><strong>Anzahl:</strong> {html.escape(str(item.get('SeriesCount', '-')))}</p>
|
||||||
|
<p><strong>Code:</strong> {html.escape(str(item.get('Code_4', '-')))}</p>
|
||||||
<p><strong>Ort:</strong> {html.escape(str(item.get('Ort', '-')))}</p>
|
<p><strong>Ort:</strong> {html.escape(str(item.get('Ort', '-')))}</p>
|
||||||
<p><strong>Typ:</strong> {html.escape(str(item.get('ItemType', '-')))}</p>
|
<p><strong>Typ:</strong> {html.escape(str(item.get('ItemType', '-')))}</p>
|
||||||
<p><strong>Kategorie:</strong> {html.escape(str(item.get('library_category', '-')))}</p>
|
<p><strong>Kategorie:</strong> {html.escape(str(item.get('library_category', '-')))}</p>
|
||||||
@@ -5177,17 +5316,13 @@ def upload_item():
|
|||||||
|
|
||||||
fs = get_gridfs()
|
fs = get_gridfs()
|
||||||
|
|
||||||
can_access_admin_home = _page_access_allowed(permissions, 'home_admin') and _action_access_allowed(permissions, 'can_manage_settings')
|
if cfg.MODULES.is_enabled('library') and sanitize_form_value(request.form.get('item_type_input', '')) != "other":
|
||||||
if can_access_admin_home:
|
success_redirect_endpoint = 'library'
|
||||||
success_redirect_endpoint = 'home_admin'
|
|
||||||
elif cfg.MODULES.is_enabled('library') and _page_access_allowed(permissions, 'home_library'):
|
|
||||||
success_redirect_endpoint = 'home_library'
|
|
||||||
else:
|
else:
|
||||||
success_redirect_endpoint = 'home_admin'
|
success_redirect_endpoint = 'home_admin'
|
||||||
|
|
||||||
# Detect if request is from mobile device
|
# Detect if request is from mobile device
|
||||||
is_mobile = 'Mobile' in request.headers.get('User-Agent', '')
|
is_mobile = 'Mobile' in request.headers.get('User-Agent', '')
|
||||||
is_ios = 'iPhone' in request.headers.get('User-Agent', '') or 'iPad' in request.headers.get('User-Agent', '')
|
|
||||||
|
|
||||||
# Log mobile request for debugging
|
# Log mobile request for debugging
|
||||||
if is_mobile:
|
if is_mobile:
|
||||||
@@ -5650,7 +5785,7 @@ def upload_item():
|
|||||||
app.logger.warning('Audit write failed for library_item_created')
|
app.logger.warning('Audit write failed for library_item_created')
|
||||||
|
|
||||||
flash(success_msg, 'success')
|
flash(success_msg, 'success')
|
||||||
return redirect(url_for(success_redirect_endpoint, highlight_item=str(item_id)))
|
return redirect(url_for(success_redirect_endpoint))
|
||||||
else:
|
else:
|
||||||
error_msg = 'Fehler beim Hinzufügen des Elements'
|
error_msg = 'Fehler beim Hinzufügen des Elements'
|
||||||
if is_mobile:
|
if is_mobile:
|
||||||
@@ -6235,6 +6370,214 @@ def edit_item(id):
|
|||||||
|
|
||||||
return redirect(url_for('home_admin'))
|
return redirect(url_for('home_admin'))
|
||||||
|
|
||||||
|
def is_library_item(item):
|
||||||
|
"""
|
||||||
|
Prüft, ob ein Artikel ein Bibliotheks-Item ist.
|
||||||
|
- 'other', None oder Leerstring -> Inventarsystem (False)
|
||||||
|
- Jeder andere Medientyp ('Buch', 'CD', etc.) -> Bibliothek (True)
|
||||||
|
"""
|
||||||
|
if not item:
|
||||||
|
return False
|
||||||
|
item_type = item.get('ItemType', 'other')
|
||||||
|
if not item_type:
|
||||||
|
return False
|
||||||
|
return item_type.strip().lower() != 'other'
|
||||||
|
|
||||||
|
|
||||||
|
@app.route('/item_edit/<id>', methods=['GET', 'POST'])
|
||||||
|
def item_edit(id):
|
||||||
|
if 'username' not in session:
|
||||||
|
if request.method == 'POST' and request.is_json:
|
||||||
|
return jsonify({'success': False, 'message': 'Nicht angemeldet.'}), 401
|
||||||
|
flash('Bitte melden Sie sich an.', 'error')
|
||||||
|
return redirect(url_for('login'))
|
||||||
|
|
||||||
|
current_permissions = us.get_effective_permissions(session['username'])
|
||||||
|
if not current_permissions['actions'].get('can_edit', False):
|
||||||
|
if request.method == 'POST' and request.is_json:
|
||||||
|
return jsonify({'success': False, 'message': 'Keine Berechtigung zum Bearbeiten.'}), 403
|
||||||
|
flash('Keine Berechtigung zum Bearbeiten.', 'error')
|
||||||
|
return redirect(url_for('home_admin'))
|
||||||
|
|
||||||
|
try:
|
||||||
|
obj_id = ObjectId(id)
|
||||||
|
except InvalidId:
|
||||||
|
flash('Ungültige Element-ID.', 'error')
|
||||||
|
return redirect(url_for('home_admin'))
|
||||||
|
|
||||||
|
current_item = it.get_item(obj_id)
|
||||||
|
if not current_item:
|
||||||
|
flash('Element in der Datenbank nicht gefunden.', 'error')
|
||||||
|
return redirect(url_for('home_admin'))
|
||||||
|
|
||||||
|
# Bibliothek-Status ermitteln
|
||||||
|
library_module_active = cfg.MODULES.is_enabled('library')
|
||||||
|
is_lib_item = it.is_library_item(current_item)
|
||||||
|
show_library_features = library_module_active and is_lib_item
|
||||||
|
|
||||||
|
# -------------------------------------------------------------------
|
||||||
|
# GET METHOD
|
||||||
|
# -------------------------------------------------------------------
|
||||||
|
if request.method == 'GET':
|
||||||
|
current_item['_id'] = str(current_item['_id'])
|
||||||
|
|
||||||
|
base_code = current_item.get('Code_4', '')
|
||||||
|
individual_codes = []
|
||||||
|
if current_item.get('SeriesGroupId'):
|
||||||
|
group_ids = it.get_group_item_ids(str(current_item['_id']))
|
||||||
|
if group_ids:
|
||||||
|
for gid in group_ids:
|
||||||
|
g_item = it.get_item(gid)
|
||||||
|
c4 = g_item.get('Code_4')
|
||||||
|
if c4 and c4 != base_code:
|
||||||
|
individual_codes.append(c4)
|
||||||
|
|
||||||
|
current_item['IndividualCodes'] = '\n'.join(individual_codes)
|
||||||
|
|
||||||
|
return render_template(
|
||||||
|
'edit_library.html',
|
||||||
|
username=session['username'],
|
||||||
|
item=current_item,
|
||||||
|
show_library_features=show_library_features,
|
||||||
|
library_module_enabled=library_module_active,
|
||||||
|
page_title=f"Bearbeiten: {current_item.get('Name', '')}"
|
||||||
|
)
|
||||||
|
|
||||||
|
# -------------------------------------------------------------------
|
||||||
|
# POST METHOD
|
||||||
|
# -------------------------------------------------------------------
|
||||||
|
redirect_target = request.referrer or url_for('home_admin')
|
||||||
|
|
||||||
|
name = sanitize_form_value(request.form.get('name'))
|
||||||
|
ort = sanitize_form_value(request.form.get('ort'))
|
||||||
|
beschreibung = sanitize_form_value(request.form.get('beschreibung'))
|
||||||
|
anschaffungs_jahr = sanitize_form_value(request.form.get('anschaffungsjahr'))
|
||||||
|
anschaffungs_kosten = sanitize_form_value(request.form.get('anschaffungskosten'))
|
||||||
|
reservierbar = 'reservierbar' in request.form
|
||||||
|
|
||||||
|
code_4 = sanitize_form_value(request.form.get('code_4'))
|
||||||
|
individual_codes_raw = request.form.get('individual_codes', '')
|
||||||
|
|
||||||
|
individual_codes = []
|
||||||
|
for c in individual_codes_raw.replace('\r', '').split('\n'):
|
||||||
|
clean_c = sanitize_form_value(c)
|
||||||
|
if clean_c and clean_c != code_4 and clean_c not in individual_codes:
|
||||||
|
individual_codes.append(clean_c)
|
||||||
|
|
||||||
|
all_codes_to_check = [code_4] + individual_codes
|
||||||
|
|
||||||
|
current_group_id = current_item.get('SeriesGroupId')
|
||||||
|
client = MongoClient(cfg.MONGODB_HOST, cfg.MONGODB_PORT)
|
||||||
|
db_instance = client[cfg.MONGODB_DB]
|
||||||
|
items_col = db_instance['items']
|
||||||
|
|
||||||
|
has_code_error = False
|
||||||
|
for code in all_codes_to_check:
|
||||||
|
if not code:
|
||||||
|
continue
|
||||||
|
existing = items_col.find_one({'Code_4': code, 'Deleted': {'$ne': True}})
|
||||||
|
if existing:
|
||||||
|
is_same_item = str(existing['_id']) == str(id)
|
||||||
|
is_in_same_group = current_group_id and existing.get('SeriesGroupId') == current_group_id
|
||||||
|
if not is_same_item and not is_in_same_group:
|
||||||
|
flash(f'Der Code "{code}" wird bereits von einem anderen Artikel verwendet.', 'error')
|
||||||
|
has_code_error = True
|
||||||
|
break
|
||||||
|
client.close()
|
||||||
|
|
||||||
|
if has_code_error:
|
||||||
|
return redirect(redirect_target)
|
||||||
|
|
||||||
|
if show_library_features:
|
||||||
|
# LIBRARY ITEM: Process ISBN/Medientyp/Category, preserve existing filters
|
||||||
|
isbn_raw = sanitize_form_value(request.form.get('isbn', ''))
|
||||||
|
item_isbn = normalize_and_validate_isbn(isbn_raw) if isbn_raw else ''
|
||||||
|
item_type = sanitize_form_value(request.form.get('item_type_input', current_item.get('ItemType', 'Buch')))
|
||||||
|
library_category = sanitize_form_value(request.form.get('library_category', ''))
|
||||||
|
images = current_item.get('Images', [])
|
||||||
|
|
||||||
|
filter1 = current_item.get('Filter', [])
|
||||||
|
filter2 = current_item.get('Filter2', [])
|
||||||
|
filter3 = current_item.get('Filter3', [])
|
||||||
|
else:
|
||||||
|
# NON-LIBRARY (INVENTORY) ITEM: Process Filter 1-3 from form
|
||||||
|
item_isbn = current_item.get('ISBN', '')
|
||||||
|
item_type = 'other'
|
||||||
|
library_category = current_item.get('library_category', '')
|
||||||
|
|
||||||
|
filter1 = expand_filter_selection(sanitize_form_value(request.form.getlist('filter')), 1)
|
||||||
|
filter2 = expand_filter_selection(sanitize_form_value(request.form.getlist('filter2')), 2)
|
||||||
|
filter3 = sanitize_form_value(request.form.getlist('filter3'))
|
||||||
|
|
||||||
|
images_to_keep = request.form.getlist('existing_images')
|
||||||
|
original_images = current_item.get('Images', [])
|
||||||
|
images = [img for img in original_images if img in images_to_keep]
|
||||||
|
|
||||||
|
new_files = request.files.getlist('images')
|
||||||
|
if new_files and new_files[0].filename != '':
|
||||||
|
fs = get_gridfs()
|
||||||
|
for file in new_files:
|
||||||
|
if file and file.filename:
|
||||||
|
is_allowed, error_msg = allowed_file(file.filename, file)
|
||||||
|
if not is_allowed:
|
||||||
|
flash(error_msg, 'error')
|
||||||
|
return redirect(redirect_target)
|
||||||
|
try:
|
||||||
|
secure_name = secure_filename(file.filename)
|
||||||
|
file.seek(0)
|
||||||
|
image_bytes = file.read()
|
||||||
|
if not image_bytes:
|
||||||
|
continue
|
||||||
|
optimized_io = io.BytesIO()
|
||||||
|
with Image.open(io.BytesIO(image_bytes)) as img:
|
||||||
|
if img.mode not in ('RGB', 'RGBA'):
|
||||||
|
img = img.convert('RGBA')
|
||||||
|
max_width = 800
|
||||||
|
if img.width > max_width:
|
||||||
|
ratio = max_width / img.width
|
||||||
|
img = img.resize((max_width, int(img.height * ratio)), Image.Resampling.LANCZOS)
|
||||||
|
img.save(optimized_io, format='WEBP', quality=85, optimize=True)
|
||||||
|
optimized_io.seek(0)
|
||||||
|
new_filename = f"{uuid.uuid4().hex}_{int(time.time())}.webp"
|
||||||
|
fs.put(
|
||||||
|
optimized_io,
|
||||||
|
filename=new_filename,
|
||||||
|
content_type='image/webp',
|
||||||
|
metadata={'original_filename': secure_name, 'item_id': str(id)}
|
||||||
|
)
|
||||||
|
images.append(new_filename)
|
||||||
|
except Exception as e:
|
||||||
|
app.logger.error(f"Image error for item {id}: {e}")
|
||||||
|
if ort and ort not in it.get_predefined_locations():
|
||||||
|
it.add_predefined_location(ort)
|
||||||
|
|
||||||
|
it.sync_group_codes(str(id), code_4, individual_codes)
|
||||||
|
|
||||||
|
success = it.update_item(
|
||||||
|
id=str(id),
|
||||||
|
name=name,
|
||||||
|
ort=ort,
|
||||||
|
beschreibung=beschreibung,
|
||||||
|
images=images,
|
||||||
|
verfuegbar=current_item.get('Verfuegbar', True),
|
||||||
|
filter1=filter1,
|
||||||
|
filter2=filter2,
|
||||||
|
filter3=filter3,
|
||||||
|
ansch_jahr=anschaffungs_jahr,
|
||||||
|
ansch_kost=anschaffungs_kosten,
|
||||||
|
code_4=code_4,
|
||||||
|
reservierbar=reservierbar,
|
||||||
|
isbn=item_isbn,
|
||||||
|
item_type=item_type,
|
||||||
|
library_category=library_category
|
||||||
|
)
|
||||||
|
|
||||||
|
if success:
|
||||||
|
flash('Artikel erfolgreich aktualisiert.', 'success')
|
||||||
|
else:
|
||||||
|
flash('Fehler beim Aktualisieren des Artikels.', 'error')
|
||||||
|
|
||||||
|
return redirect(redirect_target)
|
||||||
|
|
||||||
@app.route('/update_group', methods=['POST'])
|
@app.route('/update_group', methods=['POST'])
|
||||||
def update_group():
|
def update_group():
|
||||||
@@ -6257,17 +6600,20 @@ def update_group():
|
|||||||
|
|
||||||
# 1. Shared Fields (Group Logic)
|
# 1. Shared Fields (Group Logic)
|
||||||
# These apply to every item in the group
|
# These apply to every item in the group
|
||||||
shared_update = {
|
shared_update = {'LastUpdated': datetime.datetime.now()}
|
||||||
'Name': data.get('name'),
|
for source_key, target_key in (
|
||||||
'Ort': data.get('ort'),
|
('name', 'Name'),
|
||||||
'Beschreibung': data.get('beschreibung'),
|
('ort', 'Ort'),
|
||||||
'Anschaffungsjahr': data.get('ansch_jahr'),
|
('beschreibung', 'Beschreibung'),
|
||||||
'Anschaffungskosten': data.get('ansch_kost'),
|
('ansch_jahr', 'Anschaffungsjahr'),
|
||||||
'Reservierbar': data.get('reservierbar'),
|
('ansch_kost', 'Anschaffungskosten'),
|
||||||
'ISBN': data.get('isbn'),
|
('reservierbar', 'Reservierbar'),
|
||||||
'ItemType': data.get('item_type'),
|
('isbn', 'ISBN'),
|
||||||
'LastUpdated': datetime.datetime.now()
|
('item_type', 'ItemType'),
|
||||||
}
|
):
|
||||||
|
value = data.get(source_key)
|
||||||
|
if value is not None:
|
||||||
|
shared_update[target_key] = value
|
||||||
|
|
||||||
# 2. Individual Updates (Specific Code Logic)
|
# 2. Individual Updates (Specific Code Logic)
|
||||||
# Expected format: [{'id': '...', 'code_4': '...'}, ...]
|
# Expected format: [{'id': '...', 'code_4': '...'}, ...]
|
||||||
@@ -7519,6 +7865,202 @@ def register():
|
|||||||
permission_page_options=PERMISSION_PAGE_OPTIONS
|
permission_page_options=PERMISSION_PAGE_OPTIONS
|
||||||
)
|
)
|
||||||
|
|
||||||
|
def generate_compliant_password(length=16):
|
||||||
|
lowers = string.ascii_lowercase
|
||||||
|
uppers = string.ascii_uppercase
|
||||||
|
digits = string.digits
|
||||||
|
symbols = "!@#$%^&*()_+~|}{[]:;?><,.-="
|
||||||
|
|
||||||
|
# Ensure at least one character from each required category
|
||||||
|
pwd = [
|
||||||
|
secrets.choice(lowers),
|
||||||
|
secrets.choice(uppers),
|
||||||
|
secrets.choice(digits),
|
||||||
|
secrets.choice(symbols)
|
||||||
|
]
|
||||||
|
all_chars = lowers + uppers + digits + symbols
|
||||||
|
pwd += [secrets.choice(all_chars) for _ in range(length - 4)]
|
||||||
|
|
||||||
|
# Shuffle so guaranteed types aren't always at the start
|
||||||
|
secrets.SystemRandom().shuffle(pwd)
|
||||||
|
return "".join(pwd)
|
||||||
|
|
||||||
|
def generate_credentials_pdf(created_users):
|
||||||
|
"""
|
||||||
|
Creates a PDF in memory with 2 user credential cards per A4 page.
|
||||||
|
created_users: list of dicts [{'name': ..., 'last_name': ..., 'username': ..., 'password': ...}]
|
||||||
|
"""
|
||||||
|
buffer = io.BytesIO()
|
||||||
|
pdf = canvas.Canvas(buffer, pagesize=A4)
|
||||||
|
width, height = A4 # 595.27 x 841.89 points
|
||||||
|
card_height = height / 2.0 # Split page into 2 equal halves
|
||||||
|
|
||||||
|
for i, user in enumerate(created_users):
|
||||||
|
page_slot = i % 2 # 0 = Top half, 1 = Bottom half
|
||||||
|
|
||||||
|
# If starting a new page (except for the very first item)
|
||||||
|
if i > 0 and page_slot == 0:
|
||||||
|
pdf.showPage()
|
||||||
|
|
||||||
|
# Calculate Y offset for card position
|
||||||
|
y_offset = height - (page_slot + 1) * card_height
|
||||||
|
|
||||||
|
# Card Container Box
|
||||||
|
margin = 35
|
||||||
|
box_x = margin
|
||||||
|
box_y = y_offset + margin
|
||||||
|
box_w = width - (2 * margin)
|
||||||
|
box_h = card_height - (2 * margin)
|
||||||
|
|
||||||
|
# Outer Border
|
||||||
|
pdf.setStrokeColor(colors.HexColor('#CBD5E1'))
|
||||||
|
pdf.setLineWidth(1)
|
||||||
|
pdf.rect(box_x, box_y, box_w, box_h, fill=0)
|
||||||
|
|
||||||
|
# Header Banner inside Card
|
||||||
|
pdf.setFillColor(colors.HexColor('#1E293B'))
|
||||||
|
pdf.rect(box_x, box_y + box_h - 45, box_w, 45, fill=1, stroke=0)
|
||||||
|
|
||||||
|
# Header Title Text
|
||||||
|
pdf.setFillColor(colors.white)
|
||||||
|
pdf.setFont("Helvetica-Bold", 14)
|
||||||
|
pdf.drawString(box_x + 20, box_y + box_h - 28, "Zugangsdaten / Account Credentials")
|
||||||
|
|
||||||
|
# User Info Details
|
||||||
|
content_y = box_y + box_h - 80
|
||||||
|
|
||||||
|
# Name
|
||||||
|
pdf.setFillColor(colors.HexColor('#0F172A'))
|
||||||
|
pdf.setFont("Helvetica-Bold", 12)
|
||||||
|
pdf.drawString(box_x + 25, content_y, f"Name: {user['name']} {user['last_name']}")
|
||||||
|
|
||||||
|
# Username
|
||||||
|
content_y -= 35
|
||||||
|
pdf.setFont("Helvetica", 11)
|
||||||
|
pdf.setFillColor(colors.HexColor('#475569'))
|
||||||
|
pdf.drawString(box_x + 25, content_y, "Benutzername:")
|
||||||
|
pdf.setFont("Helvetica-Bold", 13)
|
||||||
|
pdf.setFillColor(colors.HexColor('#0F172A'))
|
||||||
|
pdf.drawString(box_x + 160, content_y, user['username'])
|
||||||
|
|
||||||
|
# Password
|
||||||
|
content_y -= 30
|
||||||
|
pdf.setFont("Helvetica", 11)
|
||||||
|
pdf.setFillColor(colors.HexColor('#475569'))
|
||||||
|
pdf.drawString(box_x + 25, content_y, "Passwort:")
|
||||||
|
pdf.setFont("Courier-Bold", 13)
|
||||||
|
pdf.setFillColor(colors.HexColor('#0F172A'))
|
||||||
|
pdf.drawString(box_x + 160, content_y, user['password'])
|
||||||
|
|
||||||
|
# Security Footer Note
|
||||||
|
content_y -= 45
|
||||||
|
pdf.setFont("Helvetica-Oblique", 9)
|
||||||
|
pdf.setFillColor(colors.HexColor('#64748B'))
|
||||||
|
pdf.drawString(box_x + 25, content_y, "Hinweis: Bitte ändern Sie Ihr Passwort nach der ersten Anmeldung.")
|
||||||
|
|
||||||
|
# Dashed Cut Line between top and bottom cards
|
||||||
|
if page_slot == 0 and i < len(created_users) - 1:
|
||||||
|
pdf.setDash(4, 4)
|
||||||
|
pdf.setStrokeColor(colors.HexColor('#94A3B8'))
|
||||||
|
pdf.line(0, card_height, width, card_height)
|
||||||
|
pdf.setDash() # Reset dash
|
||||||
|
|
||||||
|
pdf.save()
|
||||||
|
buffer.seek(0)
|
||||||
|
return buffer
|
||||||
|
|
||||||
|
|
||||||
|
@app.route('/register/csv', methods=['POST'])
|
||||||
|
def register_csv():
|
||||||
|
if 'username' not in session:
|
||||||
|
flash('Ihnen ist es nicht gestattet, diese Aktion auszuführen.', 'error')
|
||||||
|
return redirect(url_for('login'))
|
||||||
|
|
||||||
|
file = request.files.get('csv_file')
|
||||||
|
if not file or not file.filename.endswith('.csv'):
|
||||||
|
flash('Bitte laden Sie eine gültige CSV-Datei hoch.', 'error')
|
||||||
|
return redirect(url_for('register'))
|
||||||
|
|
||||||
|
permission_preset = (request.form.get('permission_preset') or 'standard_user').strip()
|
||||||
|
|
||||||
|
created_users = []
|
||||||
|
|
||||||
|
try:
|
||||||
|
# Read file stream handling UTF-8 and BOM (Excel exports)
|
||||||
|
file_stream = io.StringIO(file.stream.read().decode("utf-8-sig"), newline=None)
|
||||||
|
|
||||||
|
# Sniff delimiter (comma or semicolon)
|
||||||
|
sample = file_stream.read(2048)
|
||||||
|
file_stream.seek(0)
|
||||||
|
delimiter = ';' if ';' in sample else ','
|
||||||
|
|
||||||
|
reader = csv.reader(file_stream, delimiter=delimiter)
|
||||||
|
|
||||||
|
for row_num, row in enumerate(reader, start=1):
|
||||||
|
if not row or all(field.strip() == '' for field in row):
|
||||||
|
continue # Skip empty rows
|
||||||
|
|
||||||
|
# Clean entries
|
||||||
|
row = [field.strip() for field in row]
|
||||||
|
|
||||||
|
# Header row detection (Skip row if it looks like "Name, Nachname")
|
||||||
|
if row_num == 1 and ('name' in row[0].lower() or 'vorname' in row[0].lower()):
|
||||||
|
continue
|
||||||
|
|
||||||
|
if len(row) < 2:
|
||||||
|
continue
|
||||||
|
|
||||||
|
name = row[0]
|
||||||
|
last_name = row[1]
|
||||||
|
|
||||||
|
if not name or not last_name:
|
||||||
|
continue
|
||||||
|
|
||||||
|
# 1. Generate Username via backend logic
|
||||||
|
username = us.build_unique_username_from_name(name, last_name)
|
||||||
|
|
||||||
|
# 2. Generate Random Secure Password
|
||||||
|
password = generate_compliant_password(16)
|
||||||
|
|
||||||
|
# 3. Add User to DB
|
||||||
|
success = us.add_user(
|
||||||
|
username=username,
|
||||||
|
password=password,
|
||||||
|
name=name,
|
||||||
|
last_name=last_name,
|
||||||
|
is_student=False,
|
||||||
|
student_card_id=None,
|
||||||
|
max_borrow_days=None,
|
||||||
|
permission_preset=permission_preset,
|
||||||
|
)
|
||||||
|
|
||||||
|
if success:
|
||||||
|
created_users.append({
|
||||||
|
'name': name,
|
||||||
|
'last_name': last_name,
|
||||||
|
'username': username,
|
||||||
|
'password': password
|
||||||
|
})
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
flash(f'Fehler beim Verarbeiten der CSV-Datei: {str(e)}', 'error')
|
||||||
|
return redirect(url_for('register'))
|
||||||
|
|
||||||
|
if not created_users:
|
||||||
|
flash('Keine gültigen Benutzer in der CSV-Datei gefunden.', 'error')
|
||||||
|
return redirect(url_for('register'))
|
||||||
|
|
||||||
|
# Generate PDF
|
||||||
|
pdf_buffer = generate_credentials_pdf(created_users)
|
||||||
|
|
||||||
|
# Return downloadable PDF file
|
||||||
|
return send_file(
|
||||||
|
pdf_buffer,
|
||||||
|
as_attachment=True,
|
||||||
|
download_name='benutzer_zugangsdaten.pdf',
|
||||||
|
mimetype='application/pdf'
|
||||||
|
)
|
||||||
|
|
||||||
@app.route('/user_del', methods=['GET'])
|
@app.route('/user_del', methods=['GET'])
|
||||||
def user_del():
|
def user_del():
|
||||||
"""
|
"""
|
||||||
@@ -7564,7 +8106,7 @@ def user_del():
|
|||||||
last_name = ""
|
last_name = ""
|
||||||
fullname = None
|
fullname = None
|
||||||
users_list.append({
|
users_list.append({
|
||||||
'username': username,
|
'username': decrypt_text(username),
|
||||||
'admin': user.get('Admin', False),
|
'admin': user.get('Admin', False),
|
||||||
'fullname': fullname,
|
'fullname': fullname,
|
||||||
'name': name,
|
'name': name,
|
||||||
|
|||||||
+155
-10
@@ -20,12 +20,30 @@ Collection Structure:
|
|||||||
"""
|
"""
|
||||||
from bson.objectid import ObjectId
|
from bson.objectid import ObjectId
|
||||||
from bson.errors import InvalidId
|
from bson.errors import InvalidId
|
||||||
|
import uuid
|
||||||
import datetime
|
import datetime
|
||||||
import Web.modules.database.settings as cfg
|
import Web.modules.database.settings as cfg
|
||||||
from Web.modules.database.settings import MongoClient
|
from Web.modules.database.settings import MongoClient
|
||||||
import Web.modules.inventarsystem.data_protection as dp
|
import Web.modules.inventarsystem.data_protection as dp
|
||||||
|
|
||||||
|
|
||||||
|
def is_library_item(item):
|
||||||
|
"""
|
||||||
|
Ermittelt zuverlässig, ob ein Objekt zur Bibliothek gehört.
|
||||||
|
Gibt True zurück, wenn ItemType ein Medientyp ist (Buch, Schulbuch, CD, DVD etc.)
|
||||||
|
ODER wenn is_library explizit True ist.
|
||||||
|
"""
|
||||||
|
if not item:
|
||||||
|
return False
|
||||||
|
|
||||||
|
# 1. Prüfe zuerst den Medientyp (ItemType)
|
||||||
|
item_type = str(item.get('ItemType', '') or '').strip().lower()
|
||||||
|
if item_type and item_type not in ['other', 'general', 'none', 'null']:
|
||||||
|
return True
|
||||||
|
|
||||||
|
# 2. Falls ItemType 'other' ist, prüfe das is_library Flag
|
||||||
|
return bool(item.get('is_library', False))
|
||||||
|
|
||||||
def safe_decrypt_user(encrypted_user):
|
def safe_decrypt_user(encrypted_user):
|
||||||
"""
|
"""
|
||||||
Safely decrypt an encrypted username string.
|
Safely decrypt an encrypted username string.
|
||||||
@@ -250,7 +268,10 @@ def get_group_item_ids(id):
|
|||||||
|
|
||||||
|
|
||||||
def update_item(id, name, ort, beschreibung, images, verfuegbar, filter1, filter2, filter3,
|
def update_item(id, name, ort, beschreibung, images, verfuegbar, filter1, filter2, filter3,
|
||||||
ansch_jahr, ansch_kost, code_4, reservierbar, isbn=None, item_type='general'):
|
ansch_jahr, ansch_kost, code_4, reservierbar, isbn="", item_type='other', library_category=""):
|
||||||
|
"""
|
||||||
|
Aktualisiert ein Objekt in MongoDB und setzt is_library korrekt basierend auf dem Medientyp.
|
||||||
|
"""
|
||||||
try:
|
try:
|
||||||
client = MongoClient(cfg.MONGODB_HOST, cfg.MONGODB_PORT)
|
client = MongoClient(cfg.MONGODB_HOST, cfg.MONGODB_PORT)
|
||||||
db = client[cfg.MONGODB_DB]
|
db = client[cfg.MONGODB_DB]
|
||||||
@@ -258,29 +279,35 @@ def update_item(id, name, ort, beschreibung, images, verfuegbar, filter1, filter
|
|||||||
|
|
||||||
old_item = items.find_one({'_id': ObjectId(id)})
|
old_item = items.find_one({'_id': ObjectId(id)})
|
||||||
if not old_item:
|
if not old_item:
|
||||||
|
client.close()
|
||||||
return False
|
return False
|
||||||
|
|
||||||
series_group_id = old_item.get('SeriesGroupId')
|
series_group_id = old_item.get('SeriesGroupId')
|
||||||
|
|
||||||
|
# is_library automatisch anhand des neuen item_type bestimmen
|
||||||
|
is_lib = is_library_item({'ItemType': item_type})
|
||||||
|
|
||||||
shared_update = {
|
shared_update = {
|
||||||
'Name': name,
|
'Name': name,
|
||||||
'Ort': ort,
|
'Ort': ort,
|
||||||
'Beschreibung': beschreibung,
|
'Beschreibung': beschreibung,
|
||||||
'Images': images,
|
'Images': images if isinstance(images, list) else [],
|
||||||
'Filter': filter1,
|
'Filter': filter1 if isinstance(filter1, list) else [],
|
||||||
'Filter2': filter2,
|
'Filter2': filter2 if isinstance(filter2, list) else [],
|
||||||
'Filter3': filter3,
|
'Filter3': filter3 if isinstance(filter3, list) else [],
|
||||||
'Anschaffungsjahr': ansch_jahr,
|
'Anschaffungsjahr': ansch_jahr,
|
||||||
'Anschaffungskosten': ansch_kost,
|
'Anschaffungskosten': ansch_kost,
|
||||||
'Reservierbar': reservierbar,
|
'Reservierbar': bool(reservierbar),
|
||||||
'ISBN': isbn,
|
'ISBN': str(isbn) if isbn else '',
|
||||||
'ItemType': item_type,
|
'ItemType': item_type,
|
||||||
'Verfuegbar': verfuegbar,
|
'is_library': is_lib,
|
||||||
|
'library_category': library_category,
|
||||||
|
'Verfuegbar': bool(verfuegbar),
|
||||||
'LastUpdated': datetime.datetime.now()
|
'LastUpdated': datetime.datetime.now()
|
||||||
}
|
}
|
||||||
|
|
||||||
specific_update = shared_update.copy()
|
specific_update = shared_update.copy()
|
||||||
specific_update['Code_4'] = code_4
|
specific_update['Code_4'] = str(code_4) if code_4 else ''
|
||||||
|
|
||||||
items.update_one({'_id': ObjectId(id)}, {'$set': specific_update})
|
items.update_one({'_id': ObjectId(id)}, {'$set': specific_update})
|
||||||
|
|
||||||
@@ -1147,4 +1174,122 @@ def get_current_status(item_id, decrypt=True):
|
|||||||
return None
|
return None
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(f"Error retrieving current status for item {item_id}: {e}")
|
print(f"Error retrieving current status for item {item_id}: {e}")
|
||||||
return None
|
return None
|
||||||
|
|
||||||
|
def sync_group_codes(primary_obj_id, base_code, individual_codes_list):
|
||||||
|
"""
|
||||||
|
Synchronisiert die Barcodes einer Gruppe im korrekten Schema
|
||||||
|
(angelehnt an das 'Augenmodell groß'-Vorbild).
|
||||||
|
"""
|
||||||
|
if not base_code:
|
||||||
|
return False
|
||||||
|
|
||||||
|
# Alle Ziel-Codes zusammenführen (Basis-Code an erster Stelle)
|
||||||
|
all_target_codes = [base_code]
|
||||||
|
for c in individual_codes_list:
|
||||||
|
if c and c not in all_target_codes:
|
||||||
|
all_target_codes.append(c)
|
||||||
|
|
||||||
|
item_count = len(all_target_codes)
|
||||||
|
|
||||||
|
try:
|
||||||
|
client = MongoClient(cfg.MONGODB_HOST, cfg.MONGODB_PORT)
|
||||||
|
db = client[cfg.MONGODB_DB]
|
||||||
|
items = db['items']
|
||||||
|
|
||||||
|
primary_item = items.find_one({'_id': ObjectId(primary_obj_id)})
|
||||||
|
if not primary_item:
|
||||||
|
client.close()
|
||||||
|
return False
|
||||||
|
|
||||||
|
group_id = primary_item.get('SeriesGroupId')
|
||||||
|
|
||||||
|
# Wenn es mehr als 1 Item gibt und noch keine Gruppe existiert -> Neue GroupID erzeugen
|
||||||
|
if not group_id and item_count > 1:
|
||||||
|
group_id = str(uuid.uuid4())
|
||||||
|
|
||||||
|
# Wenn es nun eine Gruppe gibt (item_count > 1)
|
||||||
|
if item_count > 1:
|
||||||
|
# 1. Haupt-Item (Parent) aktualisieren
|
||||||
|
items.update_one(
|
||||||
|
{'_id': primary_item['_id']},
|
||||||
|
{'$set': {
|
||||||
|
'Code_4': base_code,
|
||||||
|
'SeriesGroupId': group_id,
|
||||||
|
'SeriesCount': item_count,
|
||||||
|
'SeriesPosition': 1,
|
||||||
|
'IsGroupedSubItem': False,
|
||||||
|
'ParentItemId': None
|
||||||
|
}}
|
||||||
|
)
|
||||||
|
|
||||||
|
# Bestehende Gruppenmitglieder laden
|
||||||
|
existing_items = list(items.find({'SeriesGroupId': group_id}))
|
||||||
|
existing_map = {it.get('Code_4'): it for it in existing_items if
|
||||||
|
it.get('Code_4') and str(it['_id']) != str(primary_item['_id'])}
|
||||||
|
|
||||||
|
# Alle verbleibenden Sub-Codes ab Position 2 abarbeiten
|
||||||
|
processed_sub_ids = []
|
||||||
|
for idx, code in enumerate(all_target_codes[1:], start=2):
|
||||||
|
if code in existing_map:
|
||||||
|
# Existiert bereits in der Gruppe -> Nur Position und Count aktualisieren
|
||||||
|
sub_item = existing_map[code]
|
||||||
|
processed_sub_ids.append(sub_item['_id'])
|
||||||
|
items.update_one(
|
||||||
|
{'_id': sub_item['_id']},
|
||||||
|
{'$set': {
|
||||||
|
'SeriesCount': item_count,
|
||||||
|
'SeriesPosition': idx,
|
||||||
|
'IsGroupedSubItem': True,
|
||||||
|
'ParentItemId': str(primary_item['_id'])
|
||||||
|
}}
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
# Neu hinzukommender Code -> Als Klon (Sub-Item) erstellen
|
||||||
|
new_sub = primary_item.copy()
|
||||||
|
if '_id' in new_sub:
|
||||||
|
del new_sub['_id']
|
||||||
|
|
||||||
|
new_sub.update({
|
||||||
|
'Code_4': code,
|
||||||
|
'SeriesGroupId': group_id,
|
||||||
|
'SeriesCount': item_count,
|
||||||
|
'SeriesPosition': idx,
|
||||||
|
'IsGroupedSubItem': True,
|
||||||
|
'ParentItemId': str(primary_item['_id']),
|
||||||
|
'LastUpdated': primary_item.get('LastUpdated')
|
||||||
|
})
|
||||||
|
inserted_res = items.insert_one(new_sub)
|
||||||
|
processed_sub_ids.append(inserted_res.inserted_id)
|
||||||
|
|
||||||
|
# Nicht mehr benötigte Sub-Items aus dieser Gruppe entfernen
|
||||||
|
for code, sub_item in existing_map.items():
|
||||||
|
if sub_item['_id'] not in processed_sub_ids:
|
||||||
|
items.delete_one({'_id': sub_item['_id']})
|
||||||
|
|
||||||
|
else:
|
||||||
|
# Fall: Nur 1 einziges Item (keine Gruppe / Gruppe aufgelöst)
|
||||||
|
# Eventuelle alte Sub-Items dieser Gruppe löschen
|
||||||
|
if group_id:
|
||||||
|
items.delete_many({
|
||||||
|
'SeriesGroupId': group_id,
|
||||||
|
'_id': {'$ne': primary_item['_id']}
|
||||||
|
})
|
||||||
|
|
||||||
|
items.update_one(
|
||||||
|
{'_id': primary_item['_id']},
|
||||||
|
{'$set': {
|
||||||
|
'Code_4': base_code,
|
||||||
|
'SeriesGroupId': None,
|
||||||
|
'SeriesCount': 1,
|
||||||
|
'SeriesPosition': 1,
|
||||||
|
'IsGroupedSubItem': False,
|
||||||
|
'ParentItemId': None
|
||||||
|
}}
|
||||||
|
)
|
||||||
|
|
||||||
|
client.close()
|
||||||
|
return True
|
||||||
|
except Exception as e:
|
||||||
|
print(f"Error syncing group codes: {e}")
|
||||||
|
return False
|
||||||
@@ -54,10 +54,34 @@ def _clean_name_fragment(value):
|
|||||||
return cleaned
|
return cleaned
|
||||||
|
|
||||||
|
|
||||||
def _get_tenant_db(client):
|
def _get_tenant_db(client, tenant_id=None):
|
||||||
"""Return the current tenant database for the request, or fall back to default."""
|
"""Return the current tenant database for the request, or fall back to default."""
|
||||||
try:
|
try:
|
||||||
from tenant import get_tenant_db
|
from tenant import get_tenant_db
|
||||||
|
if tenant_id is None:
|
||||||
|
return get_tenant_db(client)
|
||||||
|
|
||||||
|
tenant_id = str(tenant_id).strip()
|
||||||
|
if tenant_id:
|
||||||
|
try:
|
||||||
|
from tenant import get_tenant_config
|
||||||
|
|
||||||
|
config = get_tenant_config(tenant_id)
|
||||||
|
if isinstance(config, dict):
|
||||||
|
explicit_db = config.get('db') or config.get('db_name')
|
||||||
|
if explicit_db:
|
||||||
|
db_name = str(explicit_db).strip()
|
||||||
|
if db_name and not db_name.startswith('inventar_'):
|
||||||
|
db_name = f'inventar_{db_name}'
|
||||||
|
if db_name:
|
||||||
|
return client[db_name]
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
sanitized = ''.join(c for c in tenant_id.lower() if c.isalnum() or c == '_')
|
||||||
|
if sanitized:
|
||||||
|
return client[f'inventar_{sanitized}']
|
||||||
|
|
||||||
return get_tenant_db(client)
|
return get_tenant_db(client)
|
||||||
except Exception:
|
except Exception:
|
||||||
return client[cfg.MONGODB_DB]
|
return client[cfg.MONGODB_DB]
|
||||||
@@ -479,8 +503,45 @@ def check_nm_pwd(username, password):
|
|||||||
query = {'$or': [{'Username': username}, {'username': username}]}
|
query = {'$or': [{'Username': username}, {'username': username}]}
|
||||||
user_record_fallback = users.find_one(query)
|
user_record_fallback = users.find_one(query)
|
||||||
if user_record_fallback is None:
|
if user_record_fallback is None:
|
||||||
logger.warning("Kein Benutzer für %r in DB %r gefunden.", dp.encrypt_text(username), db_name)
|
if db_name != cfg.MONGODB_DB:
|
||||||
return None
|
default_users = client[cfg.MONGODB_DB]['users']
|
||||||
|
user_record_fallback = default_users.find_one(
|
||||||
|
{'$or': [
|
||||||
|
{'Username': dp.encrypt_text(username)},
|
||||||
|
{'username': dp.encrypt_text(username)},
|
||||||
|
{'Username': username},
|
||||||
|
{'username': username},
|
||||||
|
]}
|
||||||
|
)
|
||||||
|
if user_record_fallback is not None:
|
||||||
|
migrated_record = dict(user_record_fallback)
|
||||||
|
migrated_record.pop('_id', None)
|
||||||
|
users.replace_one(
|
||||||
|
{'$or': [
|
||||||
|
{'Username': migrated_record.get('Username')},
|
||||||
|
{'username': migrated_record.get('username')},
|
||||||
|
]},
|
||||||
|
migrated_record,
|
||||||
|
upsert=True,
|
||||||
|
)
|
||||||
|
logger.warning(
|
||||||
|
"Tenant user %r migrated from default DB %r to tenant DB %r.",
|
||||||
|
dp.encrypt_text(username),
|
||||||
|
cfg.MONGODB_DB,
|
||||||
|
db_name,
|
||||||
|
)
|
||||||
|
user_record = users.find_one(
|
||||||
|
{'$or': [
|
||||||
|
{'Username': migrated_record.get('Username')},
|
||||||
|
{'username': migrated_record.get('username')},
|
||||||
|
]}
|
||||||
|
) or migrated_record
|
||||||
|
else:
|
||||||
|
logger.warning("Kein Benutzer für %r in DB %r gefunden.", dp.encrypt_text(username), db_name)
|
||||||
|
return None
|
||||||
|
else:
|
||||||
|
logger.warning("Kein Benutzer für %r in DB %r gefunden.", dp.encrypt_text(username), db_name)
|
||||||
|
return None
|
||||||
else:
|
else:
|
||||||
user_record = user_record_fallback
|
user_record = user_record_fallback
|
||||||
|
|
||||||
@@ -506,6 +567,7 @@ def add_admin(
|
|||||||
permission_preset='full_access',
|
permission_preset='full_access',
|
||||||
action_permissions=None,
|
action_permissions=None,
|
||||||
page_permissions=None,
|
page_permissions=None,
|
||||||
|
tenant_id=None,
|
||||||
):
|
):
|
||||||
"""
|
"""
|
||||||
Add a new user to the database.
|
Add a new user to the database.
|
||||||
@@ -515,7 +577,7 @@ def add_admin(
|
|||||||
|
|
||||||
client = MongoClient(cfg.MONGODB_HOST, cfg.MONGODB_PORT)
|
client = MongoClient(cfg.MONGODB_HOST, cfg.MONGODB_PORT)
|
||||||
try:
|
try:
|
||||||
db = _get_tenant_db(client)
|
db = _get_tenant_db(client, tenant_id)
|
||||||
users = db['users']
|
users = db['users']
|
||||||
|
|
||||||
permission_defaults = build_default_permission_payload(permission_preset)
|
permission_defaults = build_default_permission_payload(permission_preset)
|
||||||
@@ -561,6 +623,7 @@ def add_user(
|
|||||||
permission_preset='standard_user',
|
permission_preset='standard_user',
|
||||||
action_permissions=None,
|
action_permissions=None,
|
||||||
page_permissions=None,
|
page_permissions=None,
|
||||||
|
tenant_id=None,
|
||||||
):
|
):
|
||||||
"""
|
"""
|
||||||
Add a new user to the database.
|
Add a new user to the database.
|
||||||
@@ -570,7 +633,7 @@ def add_user(
|
|||||||
|
|
||||||
client = MongoClient(cfg.MONGODB_HOST, cfg.MONGODB_PORT)
|
client = MongoClient(cfg.MONGODB_HOST, cfg.MONGODB_PORT)
|
||||||
try:
|
try:
|
||||||
db = _get_tenant_db(client)
|
db = _get_tenant_db(client, tenant_id)
|
||||||
users = db['users']
|
users = db['users']
|
||||||
|
|
||||||
permission_defaults = build_default_permission_payload(permission_preset)
|
permission_defaults = build_default_permission_payload(permission_preset)
|
||||||
@@ -587,7 +650,7 @@ def add_user(
|
|||||||
safe_last_name = last_name.strip() if last_name else ''
|
safe_last_name = last_name.strip() if last_name else ''
|
||||||
|
|
||||||
user_doc = {
|
user_doc = {
|
||||||
'Username': dp.encrypt_text(username),
|
'Username': username,
|
||||||
'Password': hashing(password),
|
'Password': hashing(password),
|
||||||
'Admin': (permission_preset == "full_access"),
|
'Admin': (permission_preset == "full_access"),
|
||||||
'active_ausleihung': None,
|
'active_ausleihung': None,
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@@ -1,288 +0,0 @@
|
|||||||
<!--
|
|
||||||
Copyright 2025-2026 AIIrondev
|
|
||||||
|
|
||||||
Licensed under the Inventarsystem EULA (Endbenutzer-Lizenzvertrag).
|
|
||||||
See Legal/LICENSE for the full license text.
|
|
||||||
Unauthorized commercial use, SaaS hosting, or removal of branding is prohibited.
|
|
||||||
For commercial licensing inquiries: https://github.com/AIIrondev
|
|
||||||
-->
|
|
||||||
<!-- Edit Item Functions -->
|
|
||||||
<script>
|
|
||||||
// Function to check if a file is a video
|
|
||||||
function isVideoFile(filename) {
|
|
||||||
const videoExtensions = ['.mp4', '.mov', '.avi', '.mkv', '.webm', '.flv', '.m4v', '.3gp'];
|
|
||||||
const extension = filename.toLowerCase().substring(filename.lastIndexOf('.'));
|
|
||||||
return videoExtensions.includes(extension);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Load location options for edit modal
|
|
||||||
function loadLocationOptions() {
|
|
||||||
fetch('/get_predefined_locations')
|
|
||||||
.then(response => response.json())
|
|
||||||
.then(data => {
|
|
||||||
const ortSelect = document.getElementById('edit-location');
|
|
||||||
if (ortSelect) {
|
|
||||||
// Clear existing options except the first one
|
|
||||||
while (ortSelect.children.length > 1) {
|
|
||||||
ortSelect.removeChild(ortSelect.lastChild);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Add new options - data.locations contains the array
|
|
||||||
data.locations.forEach(location => {
|
|
||||||
const option = document.createElement('option');
|
|
||||||
option.value = location;
|
|
||||||
option.textContent = location;
|
|
||||||
ortSelect.appendChild(option);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
})
|
|
||||||
.catch(error => {
|
|
||||||
console.error('Error loading location options:', error);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
// Edit modal functions
|
|
||||||
function openEditModal(itemId) {
|
|
||||||
if (typeof openEditModalFromServer === 'function') {
|
|
||||||
openEditModalFromServer(itemId);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Find the item data from allItems array
|
|
||||||
const item = allItems.find(i => i._id === itemId);
|
|
||||||
if (!item) {
|
|
||||||
console.error('Item not found:', itemId);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Populate the edit form with current item data
|
|
||||||
document.getElementById('edit-item-id').value = item._id;
|
|
||||||
document.getElementById('edit-name').value = item.Name || '';
|
|
||||||
document.getElementById('edit-description').value = item.Beschreibung || '';
|
|
||||||
document.getElementById('edit-code4').value = item.Code_4 || '';
|
|
||||||
document.getElementById('edit-year').value = item.Anschaffungsjahr || '';
|
|
||||||
document.getElementById('edit-cost').value = item.Anschaffungskosten || '';
|
|
||||||
|
|
||||||
// Set reservable status (default to true if undefined)
|
|
||||||
const reservierbarCheckbox = document.getElementById('edit-reservierbar');
|
|
||||||
if (reservierbarCheckbox) {
|
|
||||||
reservierbarCheckbox.checked = item.Reservierbar !== false;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Load location options
|
|
||||||
loadLocationOptions();
|
|
||||||
|
|
||||||
// Set the current location
|
|
||||||
setTimeout(() => {
|
|
||||||
const locationSelect = document.getElementById('edit-location');
|
|
||||||
if (locationSelect && item.Ort) {
|
|
||||||
locationSelect.value = item.Ort;
|
|
||||||
}
|
|
||||||
}, 100);
|
|
||||||
|
|
||||||
// Handle filter arrays - set current values
|
|
||||||
const filter1Array = Array.isArray(item.Filter) ? item.Filter : (item.Filter ? [item.Filter] : []);
|
|
||||||
const filter2Array = Array.isArray(item.Filter2) ? item.Filter2 : (item.Filter2 ? [item.Filter2] : []);
|
|
||||||
const filter3Array = Array.isArray(item.Filter3) ? item.Filter3 : (item.Filter3 ? [item.Filter3] : []);
|
|
||||||
|
|
||||||
// Set filter dropdowns (up to 4 each)
|
|
||||||
for (let i = 1; i <= 4; i++) {
|
|
||||||
// Filter 1
|
|
||||||
const filter1Select = document.getElementById(`edit-filter1-${i}`);
|
|
||||||
if (filter1Select) {
|
|
||||||
filter1Select.value = filter1Array[i-1] || '';
|
|
||||||
}
|
|
||||||
|
|
||||||
// Filter 2
|
|
||||||
const filter2Select = document.getElementById(`edit-filter2-${i}`);
|
|
||||||
if (filter2Select) {
|
|
||||||
filter2Select.value = filter2Array[i-1] || '';
|
|
||||||
}
|
|
||||||
|
|
||||||
// Filter 3
|
|
||||||
const filter3Select = document.getElementById(`edit-filter3-${i}`);
|
|
||||||
if (filter3Select) {
|
|
||||||
filter3Select.value = filter3Array[i-1] || '';
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Populate existing images
|
|
||||||
populateExistingImages(item.Images || []);
|
|
||||||
|
|
||||||
// Show the modal
|
|
||||||
document.getElementById('edit-modal').style.display = 'block';
|
|
||||||
}
|
|
||||||
|
|
||||||
function closeEditModal() {
|
|
||||||
document.getElementById('edit-modal').style.display = 'none';
|
|
||||||
}
|
|
||||||
|
|
||||||
// Function to add new location (for edit modal)
|
|
||||||
function addNewLocation(prefix) {
|
|
||||||
// Use different input IDs based on whether we're in edit mode
|
|
||||||
const inputId = prefix === 'edit' ? 'edit-new-location-input' : 'new-location-input';
|
|
||||||
const selectId = prefix === 'edit' ? 'edit-location' : 'ort';
|
|
||||||
|
|
||||||
const newLocationInput = document.getElementById(inputId);
|
|
||||||
const newLocation = newLocationInput.value.trim();
|
|
||||||
|
|
||||||
if (!newLocation) {
|
|
||||||
alert('Bitte geben Sie einen Ort ein.');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Add to dropdown
|
|
||||||
const ortSelect = document.getElementById(selectId);
|
|
||||||
const option = document.createElement('option');
|
|
||||||
option.value = newLocation;
|
|
||||||
option.textContent = newLocation;
|
|
||||||
ortSelect.appendChild(option);
|
|
||||||
ortSelect.value = newLocation;
|
|
||||||
|
|
||||||
// Hide the input field
|
|
||||||
document.getElementById(prefix + '-new-location-container').style.display = 'none';
|
|
||||||
newLocationInput.value = '';
|
|
||||||
|
|
||||||
// Save to server
|
|
||||||
fetch('/add_location_value', {
|
|
||||||
method: 'POST',
|
|
||||||
headers: {
|
|
||||||
'Content-Type': 'application/x-www-form-urlencoded',
|
|
||||||
},
|
|
||||||
body: 'value=' + encodeURIComponent(newLocation)
|
|
||||||
})
|
|
||||||
.then(response => response.json())
|
|
||||||
.then(data => {
|
|
||||||
if (!data.success) {
|
|
||||||
console.warn('Failed to save location to server:', data.error);
|
|
||||||
}
|
|
||||||
})
|
|
||||||
.catch(error => {
|
|
||||||
console.error('Error saving location:', error);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
// Function to cancel adding a new location
|
|
||||||
function cancelAddLocation(prefix) {
|
|
||||||
const containerId = prefix === 'edit' ? 'edit-new-location-container' : 'new-location-container';
|
|
||||||
const inputId = prefix === 'edit' ? 'edit-new-location-input' : 'new-location-input';
|
|
||||||
document.getElementById(containerId).style.display = 'none';
|
|
||||||
document.getElementById(inputId).value = '';
|
|
||||||
}
|
|
||||||
|
|
||||||
// Function to populate existing images in edit modal
|
|
||||||
function populateExistingImages(images) {
|
|
||||||
const previewContainer = document.getElementById('edit-image-preview-container');
|
|
||||||
if (!previewContainer) return;
|
|
||||||
|
|
||||||
previewContainer.innerHTML = '';
|
|
||||||
|
|
||||||
if (!images || images.length === 0) {
|
|
||||||
previewContainer.innerHTML = '<p>Keine Bilder vorhanden</p>';
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
images.forEach((imageName, index) => {
|
|
||||||
const preview = document.createElement('div');
|
|
||||||
preview.className = 'image-preview-item';
|
|
||||||
|
|
||||||
const isVideo = isVideoFile(imageName);
|
|
||||||
const mediaHtml = isVideo
|
|
||||||
? `<video src="/uploads/${imageName}" style="max-width: 150px; max-height: 150px; object-fit: cover;" controls preload="metadata"></video>`
|
|
||||||
: `<img src="/uploads/${imageName}" alt="Image ${index + 1}" style="max-width: 150px; max-height: 150px; object-fit: cover;">`;
|
|
||||||
|
|
||||||
preview.innerHTML = `
|
|
||||||
${mediaHtml}
|
|
||||||
<div class="image-controls">
|
|
||||||
<button type="button" onclick="removeExistingImage('${imageName}', this)" style="background: #dc3545; color: white; border: none; padding: 5px 10px; border-radius: 3px; cursor: pointer; margin-left: 10px;">Entfernen</button>
|
|
||||||
</div>
|
|
||||||
`;
|
|
||||||
previewContainer.appendChild(preview);
|
|
||||||
|
|
||||||
// Add hidden input for the image
|
|
||||||
const hiddenInput = document.createElement('input');
|
|
||||||
hiddenInput.type = 'hidden';
|
|
||||||
hiddenInput.name = 'existing_images';
|
|
||||||
hiddenInput.value = imageName;
|
|
||||||
previewContainer.appendChild(hiddenInput);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
// Function to remove an existing image
|
|
||||||
function removeExistingImage(imageName, button) {
|
|
||||||
try {
|
|
||||||
// First, determine context - are we in edit mode or main view?
|
|
||||||
const inEditMode = !!document.getElementById('edit-item-form');
|
|
||||||
|
|
||||||
// Always remove the preview element (works in both contexts)
|
|
||||||
const previewItem = button.closest('.image-preview-item');
|
|
||||||
if (previewItem) {
|
|
||||||
previewItem.remove();
|
|
||||||
}
|
|
||||||
|
|
||||||
// If we're in edit mode, handle form inputs
|
|
||||||
if (inEditMode) {
|
|
||||||
// Find and remove the corresponding hidden input in the edit form
|
|
||||||
const editForm = document.getElementById('edit-item-form');
|
|
||||||
|
|
||||||
if (editForm) {
|
|
||||||
// Remove from existing images
|
|
||||||
const existingInputs = editForm.querySelectorAll('input[name="existing_images"]');
|
|
||||||
existingInputs.forEach(input => {
|
|
||||||
if (input.value === imageName) {
|
|
||||||
input.remove();
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
// Add to removed images
|
|
||||||
const removedInput = document.createElement('input');
|
|
||||||
removedInput.type = 'hidden';
|
|
||||||
removedInput.name = 'removed_images';
|
|
||||||
removedInput.value = imageName;
|
|
||||||
editForm.appendChild(removedInput);
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
// In main view, we may need different logic
|
|
||||||
console.log(`Image ${imageName} removed from display in main view`);
|
|
||||||
// Add any main view specific handling here
|
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
console.error(`Error in removeExistingImage: ${error.message}`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Validate file types for image uploads
|
|
||||||
document.addEventListener('DOMContentLoaded', function() {
|
|
||||||
// Check if we're in the edit item context
|
|
||||||
if (!document.getElementById('edit-item-form')) {
|
|
||||||
console.log('Edit item form not found, skipping edit item functions initialization');
|
|
||||||
return; // Exit early if we're not in the edit item context
|
|
||||||
}
|
|
||||||
|
|
||||||
const imageInput = document.getElementById('edit-new-images');
|
|
||||||
const previewContainer = document.getElementById('edit-image-preview-container');
|
|
||||||
|
|
||||||
if (imageInput) {
|
|
||||||
imageInput.addEventListener('change', function(e) {
|
|
||||||
// Validate file types before preview
|
|
||||||
const allowedTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif',
|
|
||||||
'video/mp4', 'video/quicktime', 'video/x-msvideo', 'video/x-matroska',
|
|
||||||
'video/webm', 'video/x-flv', 'video/mp4', 'video/3gpp'];
|
|
||||||
const files = this.files;
|
|
||||||
let hasInvalidFile = false;
|
|
||||||
|
|
||||||
for (let i = 0; i < files.length; i++) {
|
|
||||||
if (!allowedTypes.includes(files[i].type)) {
|
|
||||||
hasInvalidFile = true;
|
|
||||||
// Clear the file input to prevent submission
|
|
||||||
this.value = '';
|
|
||||||
alert('Fehler: Datei "' + files[i].name + '" hat ein nicht unterstütztes Format. Erlaubte Formate: JPG, JPEG, PNG, GIF, MP4, MOV, AVI, MKV, WEBM, FLV, M4V, 3GP');
|
|
||||||
return; // Stop processing
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Continue with regular preview handling...
|
|
||||||
});
|
|
||||||
}
|
|
||||||
});
|
|
||||||
</script>
|
|
||||||
@@ -0,0 +1,509 @@
|
|||||||
|
<!--
|
||||||
|
Copyright 2025-2026 AIIrondev
|
||||||
|
Licensed under the Inventarsystem EULA.
|
||||||
|
-->
|
||||||
|
{% extends "base.html" %}
|
||||||
|
|
||||||
|
{% block title %}{{ page_title|default('Artikel bearbeiten') }} - Inventarsystem{% endblock %}
|
||||||
|
|
||||||
|
{% block content %}
|
||||||
|
<style>
|
||||||
|
.edit-container {
|
||||||
|
max-width: 800px;
|
||||||
|
margin: 0 auto;
|
||||||
|
padding: 20px;
|
||||||
|
background-color: var(--ui-surface);
|
||||||
|
border-radius: 8px;
|
||||||
|
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
|
||||||
|
}
|
||||||
|
|
||||||
|
.edit-form h1 {
|
||||||
|
color: var(--ui-text);
|
||||||
|
margin-bottom: 30px;
|
||||||
|
text-align: center;
|
||||||
|
font-size: 2em;
|
||||||
|
}
|
||||||
|
|
||||||
|
.form-group {
|
||||||
|
margin-bottom: 20px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.form-group label {
|
||||||
|
display: block;
|
||||||
|
margin-bottom: 5px;
|
||||||
|
font-weight: bold;
|
||||||
|
color: var(--ui-text);
|
||||||
|
}
|
||||||
|
|
||||||
|
.form-group input,
|
||||||
|
.form-group select,
|
||||||
|
.form-group textarea {
|
||||||
|
width: 100%;
|
||||||
|
padding: 10px;
|
||||||
|
border: 1px solid #ddd;
|
||||||
|
border-radius: 4px;
|
||||||
|
font-size: 16px;
|
||||||
|
box-sizing: border-box;
|
||||||
|
}
|
||||||
|
|
||||||
|
.form-group textarea {
|
||||||
|
height: 100px;
|
||||||
|
resize: vertical;
|
||||||
|
}
|
||||||
|
|
||||||
|
.filter-inputs {
|
||||||
|
background-color: var(--ui-surface-soft);
|
||||||
|
padding: 20px;
|
||||||
|
border-radius: 5px;
|
||||||
|
margin: 20px 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.filter-inputs h3 {
|
||||||
|
color: var(--ui-text);
|
||||||
|
margin-bottom: 15px;
|
||||||
|
font-size: 1.2em;
|
||||||
|
}
|
||||||
|
|
||||||
|
.multi-filter {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
|
||||||
|
gap: 15px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.filter-dropdown-select {
|
||||||
|
width: 100%;
|
||||||
|
padding: 8px;
|
||||||
|
border: 1px solid #ddd;
|
||||||
|
border-radius: 4px;
|
||||||
|
background-color: white;
|
||||||
|
}
|
||||||
|
|
||||||
|
.isbn-input-group {
|
||||||
|
display: flex;
|
||||||
|
gap: 10px;
|
||||||
|
align-items: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.isbn-input-group input {
|
||||||
|
flex: 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
.fetch-isbn-button {
|
||||||
|
background-color: #007bff;
|
||||||
|
color: white;
|
||||||
|
border: none;
|
||||||
|
padding: 8px 12px;
|
||||||
|
border-radius: 4px;
|
||||||
|
cursor: pointer;
|
||||||
|
white-space: nowrap;
|
||||||
|
transition: background-color 0.2s ease;
|
||||||
|
}
|
||||||
|
|
||||||
|
.fetch-isbn-button:hover {
|
||||||
|
background-color: #0056b3;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Scanner Elements */
|
||||||
|
#code4-scanner video, #code4-scanner canvas,
|
||||||
|
#isbn-scanner video, #isbn-scanner canvas {
|
||||||
|
width: 100%;
|
||||||
|
max-width: 640px;
|
||||||
|
height: auto;
|
||||||
|
border-radius: 5px;
|
||||||
|
box-shadow: 0 2px 8px rgba(0,0,0,0.1);
|
||||||
|
}
|
||||||
|
|
||||||
|
#code4-scanner canvas, #isbn-scanner canvas {
|
||||||
|
position: absolute;
|
||||||
|
top: 0;
|
||||||
|
left: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
#code4-scanner, #isbn-scanner {
|
||||||
|
position: relative;
|
||||||
|
overflow: hidden;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Image Management */
|
||||||
|
.existing-images-grid {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
gap: 15px;
|
||||||
|
margin-top: 10px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.existing-image-card {
|
||||||
|
border: 1px solid #ddd;
|
||||||
|
border-radius: 5px;
|
||||||
|
padding: 8px;
|
||||||
|
text-align: center;
|
||||||
|
background: #fff;
|
||||||
|
width: 120px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.existing-image-card img {
|
||||||
|
width: 100%;
|
||||||
|
height: 100px;
|
||||||
|
object-fit: cover;
|
||||||
|
border-radius: 4px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.existing-image-card label {
|
||||||
|
font-size: 0.8em;
|
||||||
|
margin-top: 5px;
|
||||||
|
cursor: pointer;
|
||||||
|
font-weight: normal;
|
||||||
|
}
|
||||||
|
|
||||||
|
.add-new-btn {
|
||||||
|
background-color: #007bff;
|
||||||
|
color: white;
|
||||||
|
border: none;
|
||||||
|
padding: 5px 10px;
|
||||||
|
border-radius: 3px;
|
||||||
|
cursor: pointer;
|
||||||
|
margin-top: 5px;
|
||||||
|
font-size: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.submit-button {
|
||||||
|
background-color: #28a745;
|
||||||
|
color: white;
|
||||||
|
border: none;
|
||||||
|
padding: 15px 30px;
|
||||||
|
border-radius: 5px;
|
||||||
|
font-size: 18px;
|
||||||
|
font-weight: bold;
|
||||||
|
cursor: pointer;
|
||||||
|
width: 100%;
|
||||||
|
margin-top: 20px;
|
||||||
|
transition: background-color 0.2s ease;
|
||||||
|
}
|
||||||
|
|
||||||
|
.submit-button:hover {
|
||||||
|
background-color: #218838;
|
||||||
|
}
|
||||||
|
|
||||||
|
.edit-new-location-container {
|
||||||
|
display: none;
|
||||||
|
margin-top: 10px;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
|
||||||
|
<div class="edit-container">
|
||||||
|
<div class="edit-form">
|
||||||
|
<h1>{{ page_title|default('Artikel bearbeiten') }}</h1>
|
||||||
|
<form method="POST" action="{{ url_for('item_edit', id=item._id) }}" enctype="multipart/form-data">
|
||||||
|
<input type="hidden" name="item_id" value="{{ item._id }}">
|
||||||
|
|
||||||
|
{% if show_library_features %}
|
||||||
|
<!-- ================= LIBRARY SPECIFIC FIELDS ================= -->
|
||||||
|
<div class="form-group">
|
||||||
|
<label for="isbn">ISBN / Barcode:</label>
|
||||||
|
<div class="isbn-input-group">
|
||||||
|
<input type="text" id="isbn" name="isbn" value="{{ item.ISBN|default('') }}" placeholder="ISBN oder Barcode eingeben...">
|
||||||
|
<button type="button" id="scan-isbn-btn" class="fetch-isbn-button">Barcode scannen</button>
|
||||||
|
<button type="button" class="fetch-isbn-button" onclick="fetchBookInfo('edit')">Informationen abrufen</button>
|
||||||
|
</div>
|
||||||
|
<div id="isbn-scanner" style="width:100%; max-width:520px; display:none; margin-top:10px;"></div>
|
||||||
|
<small id="isbn-scan-status" style="display:block; color:#666; margin-top:6px;"></small>
|
||||||
|
<div id="book-info-container"></div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="filter-inputs" style="margin-bottom: 20px;">
|
||||||
|
<h3>Medientyp</h3>
|
||||||
|
<div class="form-group">
|
||||||
|
<select name="item_type_input" id="item_type_input">
|
||||||
|
<option value="Buch" {% if item.ItemType == 'Buch' %}selected{% endif %}>Buch</option>
|
||||||
|
<option value="Schulbuch" {% if item.ItemType == 'Schulbuch' %}selected{% endif %}>Schulbuch</option>
|
||||||
|
<option value="CD" {% if item.ItemType == 'CD' %}selected{% endif %}>CD</option>
|
||||||
|
<option value="DVD" {% if item.ItemType == 'DVD' %}selected{% endif %}>DVD</option>
|
||||||
|
<option value="Sonstiges" {% if item.ItemType == 'Sonstiges' %}selected{% endif %}>Sonstiges</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
<h3>Bibliotheks-Kategorie:</h3>
|
||||||
|
<div class="form-group">
|
||||||
|
<input type="text" name="library_category" id="library_category" value="{{ item.library_category|default('') }}" placeholder="z.B. Belletristik, Sachbücher, etc.">
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{% endif %}
|
||||||
|
|
||||||
|
<!-- ================= COMMON CORE FIELDS ================= -->
|
||||||
|
<div class="form-group">
|
||||||
|
<label for="name">Name / Titel:</label>
|
||||||
|
<input type="text" id="name" name="name" value="{{ item.Name|default('') }}" required>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="form-group">
|
||||||
|
<label for="ort">Ort / Standort:</label>
|
||||||
|
<select id="ort" name="ort" data-selected="{{ item.Ort|default('') }}" required>
|
||||||
|
<option value="">-- Bitte Ort auswählen --</option>
|
||||||
|
{% if item.Ort %}
|
||||||
|
<option value="{{ item.Ort }}" selected>{{ item.Ort }}</option>
|
||||||
|
{% endif %}
|
||||||
|
</select>
|
||||||
|
<button type="button" class="add-new-btn" id="add-new-location-btn">Neuen Ort hinzufügen</button>
|
||||||
|
<div id="new-location-container" class="edit-new-location-container">
|
||||||
|
<input type="text" id="new-location-input" placeholder="Neuen Ort eingeben">
|
||||||
|
<button type="button" onclick="addNewLocation()">Hinzufügen</button>
|
||||||
|
<button type="button" onclick="cancelAddLocation()">Abbrechen</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="form-group">
|
||||||
|
<label for="beschreibung">Beschreibung:</label>
|
||||||
|
<textarea id="beschreibung" name="beschreibung" required>{{ item.Beschreibung|default('') }}</textarea>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="form-group" id="primary_code_group">
|
||||||
|
<label for="code_4">Basis-Code (Haupt-Barcode)</label>
|
||||||
|
<div style="display: flex; gap: 10px;">
|
||||||
|
<input type="text" id="code_4" name="code_4" class="form-control" value="{{ item.Code_4|default('') }}" required>
|
||||||
|
<button type="button" id="scan-code4-btn" class="fetch-isbn-button">Barcode scannen</button>
|
||||||
|
</div>
|
||||||
|
<div id="code4-scanner" style="display:none; margin-top: 10px;"></div>
|
||||||
|
<small id="code4-scan-status" class="form-text text-muted"></small>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="form-group" id="individual_codes_group">
|
||||||
|
<label for="individual_codes">Weitere Einzelcodes der Gruppe (je Zeile ein Code)</label>
|
||||||
|
<textarea id="individual_codes" name="individual_codes" rows="4" class="form-control" placeholder="z.B. ABC-001 ABC-002">{{ item.IndividualCodes|default('') }}</textarea>
|
||||||
|
<small style="display:block; color:#666; margin-top: 5px;">Der Basis-Code steht oben. Alle weiteren Gruppenmitglieder werden hier untereinander aufgeführt.</small>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{% if not show_library_features %}
|
||||||
|
<!-- ================= SYSTEM FILTERS 1-3 (INVENTORY / OTHER ITEMS ONLY) ================= -->
|
||||||
|
<div class="filter-inputs">
|
||||||
|
<h3>Unterrichtsfach (Filter 1):</h3>
|
||||||
|
<div class="multi-filter">
|
||||||
|
{% for idx in range(4) %}
|
||||||
|
<div class="form-group">
|
||||||
|
<label for="filter1-{{ idx + 1 }}">Wert {{ idx + 1 }}:</label>
|
||||||
|
<select id="filter1-{{ idx + 1 }}" name="filter" class="filter-dropdown-select" data-selected="{{ item.Filter[idx] if item.Filter and item.Filter|length > idx else '' }}">
|
||||||
|
<option value="">-- Optional --</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
{% endfor %}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<h3>Jahrgangsstufe (Filter 2):</h3>
|
||||||
|
<div class="multi-filter">
|
||||||
|
{% for idx in range(4) %}
|
||||||
|
<div class="form-group">
|
||||||
|
<label for="filter2-{{ idx + 1 }}">Wert {{ idx + 1 }}:</label>
|
||||||
|
<select id="filter2-{{ idx + 1 }}" name="filter2" class="filter-dropdown-select" data-selected="{{ item.Filter2[idx] if item.Filter2 and item.Filter2|length > idx else '' }}">
|
||||||
|
<option value="">-- Optional --</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
{% endfor %}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<h3>Schlagwort (Filter 3):</h3>
|
||||||
|
<div class="multi-filter">
|
||||||
|
{% for idx in range(4) %}
|
||||||
|
<div class="form-group">
|
||||||
|
<label for="filter3-{{ idx + 1 }}">Wert {{ idx + 1 }}:</label>
|
||||||
|
<input type="text" id="filter3-{{ idx + 1 }}" name="filter3" value="{{ item.Filter3[idx] if item.Filter3 and item.Filter3|length > idx else '' }}">
|
||||||
|
</div>
|
||||||
|
{% endfor %}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{% endif %}
|
||||||
|
|
||||||
|
<!-- ================= DATES & FINANCIALS ================= -->
|
||||||
|
<div class="form-group">
|
||||||
|
<label for="anschaffungsjahr">Anschaffungsjahr:</label>
|
||||||
|
<input type="date" id="anschaffungsjahr" name="anschaffungsjahr" value="{{ item.Anschaffungsjahr|default('') }}">
|
||||||
|
</div>
|
||||||
|
<div class="form-group">
|
||||||
|
<label for="anschaffungskosten">Anschaffungskosten (€):</label>
|
||||||
|
<input type="text" id="anschaffungskosten" name="anschaffungskosten" value="{{ item.Anschaffungskosten|default('') }}">
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{% if not show_library_features %}
|
||||||
|
<!-- ================= INVENTORY IMAGE MANAGEMENT ================= -->
|
||||||
|
<div class="form-group">
|
||||||
|
<label>Bestehende Bilder behalten:</label>
|
||||||
|
{% if item.Images and item.Images|length > 0 %}
|
||||||
|
<div class="existing-images-grid">
|
||||||
|
{% for img in item.Images %}
|
||||||
|
<div class="existing-image-card">
|
||||||
|
<img src="{{ url_for('uploaded_file', filename=img) }}" alt="Bild">
|
||||||
|
<label>
|
||||||
|
<input type="checkbox" name="existing_images" value="{{ img }}" checked>
|
||||||
|
Behalten
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
{% endfor %}
|
||||||
|
</div>
|
||||||
|
{% else %}
|
||||||
|
<p style="color:#777; font-size:0.9em;">Keine Bilder vorhanden.</p>
|
||||||
|
{% endif %}
|
||||||
|
|
||||||
|
<label for="images" style="margin-top:15px;">Neue Bilder/Videos hinzufügen:</label>
|
||||||
|
<input type="file" id="images" name="images" accept=".jpg, .jpeg, .png, .gif, .mp4, .mov, .avi, .mkv, .webm" multiple>
|
||||||
|
</div>
|
||||||
|
{% endif %}
|
||||||
|
|
||||||
|
<div class="form-group">
|
||||||
|
<label for="reservierbar" style="display:inline-block; width:auto; margin-right:10px;">Reservierbar:</label>
|
||||||
|
<input type="checkbox" id="reservierbar" name="reservierbar" style="width:auto;" {% if item.Reservierbar %}checked{% endif %}>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<button type="submit" class="submit-button">Änderungen speichern</button>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<script src="https://cdn.jsdelivr.net/npm/@ericblade/quagga2/dist/quagga.js"></script>
|
||||||
|
<script>
|
||||||
|
let scannerRunning = false;
|
||||||
|
let activeScannerCallback = null;
|
||||||
|
let code4LastScanned = '';
|
||||||
|
let code4LastScannedAt = 0;
|
||||||
|
|
||||||
|
function loadAndSelectFilterValues(filterNumber) {
|
||||||
|
fetch(`/get_predefined_filter_values/${filterNumber}`)
|
||||||
|
.then(res => res.json())
|
||||||
|
.then(data => {
|
||||||
|
for (let i = 1; i <= 4; i++) {
|
||||||
|
const select = document.getElementById(`filter${filterNumber}-${i}`);
|
||||||
|
if (!select) continue;
|
||||||
|
|
||||||
|
const selectedValue = select.getAttribute('data-selected') || '';
|
||||||
|
|
||||||
|
data.values.forEach(val => {
|
||||||
|
if (!val || String(val).trim() === '') return;
|
||||||
|
const opt = document.createElement('option');
|
||||||
|
opt.value = val;
|
||||||
|
opt.textContent = val;
|
||||||
|
select.appendChild(opt);
|
||||||
|
});
|
||||||
|
|
||||||
|
if (selectedValue && !Array.from(select.options).some(o => o.value === selectedValue)) {
|
||||||
|
const customOpt = document.createElement('option');
|
||||||
|
customOpt.value = selectedValue;
|
||||||
|
customOpt.textContent = selectedValue;
|
||||||
|
select.appendChild(customOpt);
|
||||||
|
}
|
||||||
|
|
||||||
|
select.value = selectedValue;
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.catch(err => console.error(`Error loading Filter ${filterNumber}:`, err));
|
||||||
|
}
|
||||||
|
|
||||||
|
function loadLocationOptions() {
|
||||||
|
fetch('/get_predefined_locations')
|
||||||
|
.then(res => res.json())
|
||||||
|
.then(data => {
|
||||||
|
const select = document.getElementById('ort');
|
||||||
|
if (!select) return;
|
||||||
|
const currentVal = select.getAttribute('data-selected') || select.value;
|
||||||
|
|
||||||
|
data.locations.forEach(loc => {
|
||||||
|
if (!Array.from(select.options).some(o => o.value === loc)) {
|
||||||
|
const opt = document.createElement('option');
|
||||||
|
opt.value = loc;
|
||||||
|
opt.textContent = loc;
|
||||||
|
select.appendChild(opt);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
select.value = currentVal;
|
||||||
|
})
|
||||||
|
.catch(err => console.error('Error loading locations:', err));
|
||||||
|
}
|
||||||
|
|
||||||
|
function addNewLocation() {
|
||||||
|
const input = document.getElementById('new-location-input');
|
||||||
|
const val = input.value.trim();
|
||||||
|
if (!val) return;
|
||||||
|
const select = document.getElementById('ort');
|
||||||
|
const opt = document.createElement('option');
|
||||||
|
opt.value = val;
|
||||||
|
opt.textContent = val;
|
||||||
|
opt.selected = true;
|
||||||
|
select.appendChild(opt);
|
||||||
|
document.getElementById('new-location-container').style.display = 'none';
|
||||||
|
input.value = '';
|
||||||
|
}
|
||||||
|
|
||||||
|
function cancelAddLocation() {
|
||||||
|
document.getElementById('new-location-container').style.display = 'none';
|
||||||
|
document.getElementById('new-location-input').value = '';
|
||||||
|
}
|
||||||
|
|
||||||
|
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" } },
|
||||||
|
decoder: { readers: ["code_128_reader", "ean_reader", "code_39_reader", "upc_reader"] }
|
||||||
|
}, function(err) {
|
||||||
|
if (err) { errorStatusSetter("Kamera-Fehler.", true); return; }
|
||||||
|
Quagga.start(); scannerRunning = true; errorStatusSetter(completionMsg, false);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function killScannerHardware() {
|
||||||
|
if (!scannerRunning) return;
|
||||||
|
Quagga.stop(); scannerRunning = false; activeScannerCallback = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
Quagga.onDetected(function(data) {
|
||||||
|
if (!data || !data.codeResult || !data.codeResult.code) return;
|
||||||
|
if (typeof activeScannerCallback === "function") activeScannerCallback(String(data.codeResult.code).trim());
|
||||||
|
});
|
||||||
|
|
||||||
|
function startCode4Scanner() {
|
||||||
|
const scannerBox = document.getElementById('code4-scanner');
|
||||||
|
const scanBtn = document.getElementById('scan-code4-btn');
|
||||||
|
const baseField = document.getElementById('code_4');
|
||||||
|
const indArea = document.getElementById('individual_codes');
|
||||||
|
|
||||||
|
if (scannerBox.style.display !== 'none') {
|
||||||
|
killScannerHardware(); scannerBox.style.display = 'none'; scanBtn.textContent = 'Barcode scannen'; return;
|
||||||
|
}
|
||||||
|
|
||||||
|
scannerBox.style.display = 'block'; scanBtn.textContent = 'Scanner stoppen';
|
||||||
|
runEngineInitialization('#code4-scanner', function(decodedText) {
|
||||||
|
const now = Date.now();
|
||||||
|
if (decodedText === code4LastScanned && (now - code4LastScannedAt) < 1500) return;
|
||||||
|
code4LastScanned = decodedText; code4LastScannedAt = now;
|
||||||
|
|
||||||
|
killScannerHardware(); scannerBox.style.display = 'none'; scanBtn.textContent = 'Barcode scannen';
|
||||||
|
|
||||||
|
if (!baseField.value.trim()) {
|
||||||
|
baseField.value = decodedText;
|
||||||
|
} else {
|
||||||
|
let codes = indArea.value.split('\n').map(c => c.trim()).filter(c => c);
|
||||||
|
if (!codes.includes(decodedText) && baseField.value.trim() !== decodedText) {
|
||||||
|
codes.push(decodedText);
|
||||||
|
indArea.value = codes.join('\n');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}, 'Scanner läuft...', msg => { document.getElementById('code4-scan-status').textContent = msg; });
|
||||||
|
}
|
||||||
|
|
||||||
|
document.addEventListener('DOMContentLoaded', function() {
|
||||||
|
loadLocationOptions();
|
||||||
|
|
||||||
|
// Load Filter options if elements exist on page
|
||||||
|
if (document.getElementById('filter1-1')) {
|
||||||
|
loadAndSelectFilterValues(1);
|
||||||
|
loadAndSelectFilterValues(2);
|
||||||
|
}
|
||||||
|
|
||||||
|
const scanCodeBtn = document.getElementById('scan-code4-btn');
|
||||||
|
if (scanCodeBtn) scanCodeBtn.addEventListener('click', startCode4Scanner);
|
||||||
|
|
||||||
|
const addLocBtn = document.getElementById('add-new-location-btn');
|
||||||
|
if (addLocBtn) addLocBtn.addEventListener('click', () => {
|
||||||
|
const c = document.getElementById('new-location-container');
|
||||||
|
c.style.display = c.style.display === 'none' ? 'block' : 'none';
|
||||||
|
});
|
||||||
|
});
|
||||||
|
</script>
|
||||||
|
{% endblock %}
|
||||||
+335
-230
@@ -355,6 +355,28 @@
|
|||||||
color: #6b7280;
|
color: #6b7280;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* Small confirmation popup (toast) */
|
||||||
|
.small-popup {
|
||||||
|
position: fixed;
|
||||||
|
bottom: 24px;
|
||||||
|
left: 50%;
|
||||||
|
transform: translateX(-50%);
|
||||||
|
background: rgba(17, 24, 39, 0.96);
|
||||||
|
color: #fff;
|
||||||
|
padding: 12px 16px;
|
||||||
|
border-radius: 8px;
|
||||||
|
box-shadow: 0 6px 24px rgba(2,6,23,0.6);
|
||||||
|
z-index: 2000;
|
||||||
|
display: flex;
|
||||||
|
gap: 10px;
|
||||||
|
align-items: center;
|
||||||
|
max-width: 90%;
|
||||||
|
font-size: 0.95em;
|
||||||
|
}
|
||||||
|
.small-popup.ok { background: rgba(16,185,129,0.95); color: #032; }
|
||||||
|
.small-popup.error { background: rgba(239,68,68,0.95); color: #210; }
|
||||||
|
.small-popup .close-x { margin-left: 8px; cursor: pointer; font-weight: 700; }
|
||||||
|
|
||||||
/* Modal styles */
|
/* Modal styles */
|
||||||
.modal {
|
.modal {
|
||||||
display: none;
|
display: none;
|
||||||
@@ -502,9 +524,19 @@
|
|||||||
<option value="card_only">Nur Ausweis erfassen</option>
|
<option value="card_only">Nur Ausweis erfassen</option>
|
||||||
<option value="quick_toggle">Schnellmodus: Ausweis + Mediencode</option>
|
<option value="quick_toggle">Schnellmodus: Ausweis + Mediencode</option>
|
||||||
</select>
|
</select>
|
||||||
<input type="text" id="activeStudentCard" placeholder="Aktiver Ausweis (gescannt)" readonly>
|
<input type="text" id="activeStudentCard" placeholder="Aktiver Ausweis (gescannt)" >
|
||||||
|
<input type="text" id="manualItemCode" placeholder="Manueller Mediencode (optional)" style="min-width:180px;">
|
||||||
<button id="resetCardBtn" class="button" type="button">Ausweis löschen</button>
|
<button id="resetCardBtn" class="button" type="button">Ausweis löschen</button>
|
||||||
<button id="toggleScannerBtn" class="button" type="button">Scanner starten</button>
|
<button id="toggleScannerBtn" class="button" type="button">Scanner starten</button>
|
||||||
|
<label style="display:flex; align-items:center; gap:8px; margin-left:6px;">
|
||||||
|
<input type="checkbox" id="keyboardScannerToggle">
|
||||||
|
<span style="font-size:0.9em;">Physischer Scanner</span>
|
||||||
|
</label>
|
||||||
|
<label style="display:flex; align-items:center; gap:8px; margin-left:6px;">
|
||||||
|
<input type="checkbox" id="returnOnlyToggle">
|
||||||
|
<span style="font-size:0.9em;">Nur Rückgabe (nur Mediencode)</span>
|
||||||
|
</label>
|
||||||
|
<button id="manualReturnBtn" class="button" type="button" style="margin-left:6px; background:#10b981;color:white;">Rückgabe per Code</button>
|
||||||
</div>
|
</div>
|
||||||
<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.
|
||||||
@@ -632,6 +664,16 @@
|
|||||||
let activeStudentCardId = '';
|
let activeStudentCardId = '';
|
||||||
let lastScanValue = '';
|
let lastScanValue = '';
|
||||||
let lastScanAt = 0;
|
let lastScanAt = 0;
|
||||||
|
// Keyboard-scanner support (physical scanners that act as keyboard wedges)
|
||||||
|
let keyboardScannerEnabled = false;
|
||||||
|
let keyboardScanBuffer = '';
|
||||||
|
let keyboardLastKeyAt = 0;
|
||||||
|
const KEYBOARD_SCAN_INTERCHAR_MS = 100; // max time between keystrokes to consider them one scan
|
||||||
|
let editLibraryState = {
|
||||||
|
itemId: '',
|
||||||
|
seriesGroupId: '',
|
||||||
|
groupMembers: []
|
||||||
|
};
|
||||||
|
|
||||||
const canEditLibraryItems = (document.getElementById('libraryTableContainer')?.dataset.canEdit === '1');
|
const canEditLibraryItems = (document.getElementById('libraryTableContainer')?.dataset.canEdit === '1');
|
||||||
|
|
||||||
@@ -758,7 +800,7 @@
|
|||||||
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.ISBN || item.Code_4 || item.Code4 || '-')}</td>
|
<td>${escapeHtml(item.ISBN || '-')}</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>
|
||||||
<td>
|
<td>
|
||||||
@@ -905,6 +947,13 @@
|
|||||||
const currentCallback = activeScannerCallback;
|
const currentCallback = activeScannerCallback;
|
||||||
stopScanner();
|
stopScanner();
|
||||||
|
|
||||||
|
const returnOnly = (document.getElementById('returnOnlyToggle') || {}).checked;
|
||||||
|
if (returnOnly) {
|
||||||
|
// direct return flow
|
||||||
|
returnByCode(barcode);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
if (typeof currentCallback === "function") {
|
if (typeof currentCallback === "function") {
|
||||||
currentCallback(barcode);
|
currentCallback(barcode);
|
||||||
} else {
|
} else {
|
||||||
@@ -912,6 +961,50 @@
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// =========================================================================
|
||||||
|
// Keyboard scanner handling (physical scanners that send chars then Enter)
|
||||||
|
// =========================================================================
|
||||||
|
function keyboardScanKeydownHandler(e) {
|
||||||
|
// Only active when explicitly enabled
|
||||||
|
if (!keyboardScannerEnabled) return;
|
||||||
|
|
||||||
|
// Ignore if focus is in an input/textarea/contenteditable to avoid interfering with typing
|
||||||
|
const active = document.activeElement;
|
||||||
|
if (active && (active.tagName === 'INPUT' || active.tagName === 'TEXTAREA' || active.isContentEditable)) return;
|
||||||
|
|
||||||
|
const now = Date.now();
|
||||||
|
|
||||||
|
// If Enter/Return pressed -> finalize buffer
|
||||||
|
if (e.key === 'Enter') {
|
||||||
|
const code = keyboardScanBuffer.trim();
|
||||||
|
keyboardScanBuffer = '';
|
||||||
|
keyboardLastKeyAt = 0;
|
||||||
|
if (!code) return;
|
||||||
|
// If return-only mode is active, attempt direct return
|
||||||
|
const returnOnly = (document.getElementById('returnOnlyToggle') || {}).checked;
|
||||||
|
if (returnOnly) {
|
||||||
|
returnByCode(code);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Process exactly like a camera scan
|
||||||
|
handleScanSuccess(code);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Only accept common printable characters; ignore modifier keys
|
||||||
|
if (e.key.length === 1) {
|
||||||
|
// If time gap too big, start new buffer
|
||||||
|
if (keyboardLastKeyAt && (now - keyboardLastKeyAt) > KEYBOARD_SCAN_INTERCHAR_MS) {
|
||||||
|
keyboardScanBuffer = '';
|
||||||
|
}
|
||||||
|
keyboardScanBuffer += e.key;
|
||||||
|
keyboardLastKeyAt = now;
|
||||||
|
// Prevent default so scanner input doesn't accidentally move focus or trigger shortcuts
|
||||||
|
e.preventDefault();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
function handleScanSuccess(decodedText) {
|
function handleScanSuccess(decodedText) {
|
||||||
const scannedCode = normalizeScannedCode(decodedText);
|
const scannedCode = normalizeScannedCode(decodedText);
|
||||||
if (!scannedCode) return;
|
if (!scannedCode) return;
|
||||||
@@ -934,12 +1027,21 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function processQuickToggleScan(scannedCode) {
|
async function processQuickToggleScan(scannedCode) {
|
||||||
|
// 1. Prüfen, ob "Nur Rückgabe"-Modus aktiv ist
|
||||||
|
const returnOnly = (document.getElementById('returnOnlyToggle') || {}).checked;
|
||||||
|
if (returnOnly) {
|
||||||
|
await returnByCode(scannedCode);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. Wenn kein Ausweis gesetzt ist, wird der Code als Ausweis interpretiert
|
||||||
if (!activeStudentCardId) {
|
if (!activeStudentCardId) {
|
||||||
setActiveStudentCard(scannedCode);
|
setActiveStudentCard(scannedCode);
|
||||||
setScanStatus(`Ausweis gesetzt: ${activeStudentCardId}`, 'ok');
|
setScanStatus(`Ausweis gesetzt: ${activeStudentCardId}`, 'ok');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 3. Ausleihe/Rückgabe verarbeiten (wenn Ausweis vorhanden)
|
||||||
try {
|
try {
|
||||||
setScanStatus('Verarbeite Mediencode...', 'warn');
|
setScanStatus('Verarbeite Mediencode...', 'warn');
|
||||||
const response = await fetch('/api/library_scan_action', {
|
const response = await fetch('/api/library_scan_action', {
|
||||||
@@ -950,21 +1052,24 @@
|
|||||||
item_code: scannedCode
|
item_code: scannedCode
|
||||||
})
|
})
|
||||||
});
|
});
|
||||||
|
|
||||||
const result = await response.json();
|
const result = await response.json();
|
||||||
if (!response.ok || !result.ok) {
|
if (!response.ok || !result.ok) {
|
||||||
setScanStatus(result.message || 'Scan-Aktion fehlgeschlagen.', 'error');
|
setScanStatus(result.message || 'Scan-Aktion fehlgeschlagen.', 'error');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (result.action === 'borrowed') {
|
if (result.action === 'borrowed') {
|
||||||
setScanStatus(`Ausgeliehen: ${result.item_name}`, 'ok');
|
setScanStatus(`Ausgeliehen: ${result.item_name}`, 'ok');
|
||||||
|
showSmallConfirm(`Ausgeliehen: ${result.item_name}`, 'ok');
|
||||||
} else if (result.action === 'returned') {
|
} else if (result.action === 'returned') {
|
||||||
setScanStatus(`Zurückgegeben: ${result.item_name}`, 'ok');
|
setScanStatus(`Zurückgegeben: ${result.item_name}`, 'ok');
|
||||||
|
showSmallConfirm(`Zurückgegeben: ${result.item_name}`, 'ok');
|
||||||
} else {
|
} else {
|
||||||
setScanStatus(result.message || 'Aktion durchgeführt.', 'ok');
|
setScanStatus(result.message || 'Aktion durchgeführt.', 'ok');
|
||||||
|
showSmallConfirm(result.message || 'Aktion durchgeführt.', 'ok');
|
||||||
}
|
}
|
||||||
|
|
||||||
await loadLibraryItems();
|
await loadLibraryItems();
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error('Quick scan action failed:', err);
|
console.error('Quick scan action failed:', err);
|
||||||
@@ -972,6 +1077,33 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function returnByCode(code) {
|
||||||
|
if (!code) return;
|
||||||
|
setScanStatus('Verarbeite Rückgabe...', 'warn');
|
||||||
|
try {
|
||||||
|
const resp = await fetch('/api/library_return_by_code', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {'Content-Type': 'application/json'},
|
||||||
|
body: JSON.stringify({ item_code: code })
|
||||||
|
});
|
||||||
|
const result = await resp.json();
|
||||||
|
if (!resp.ok || !result.ok) {
|
||||||
|
setScanStatus(result.message || 'Rückgabe fehlgeschlagen.', 'error');
|
||||||
|
showSmallConfirm(result.message || 'Rückgabe fehlgeschlagen.', 'error');
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
setScanStatus(result.message || `Zurückgegeben: ${result.item_name || ''}`, 'ok');
|
||||||
|
showSmallConfirm(result.message || `Zurückgegeben: ${result.item_name || ''}`, 'ok');
|
||||||
|
await loadLibraryItems();
|
||||||
|
return true;
|
||||||
|
} catch (err) {
|
||||||
|
console.error('Return by code failed:', err);
|
||||||
|
setScanStatus('Fehler bei Rückgabe.', 'error');
|
||||||
|
showSmallConfirm('Fehler bei Rückgabe.', 'error');
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
function scanIntoEditCode() {
|
function scanIntoEditCode() {
|
||||||
const scanReaderWrap = document.getElementById('scanReaderWrap');
|
const scanReaderWrap = document.getElementById('scanReaderWrap');
|
||||||
const editCodeInput = document.getElementById('edit-code4');
|
const editCodeInput = document.getElementById('edit-code4');
|
||||||
@@ -979,15 +1111,15 @@
|
|||||||
if (!scanReaderWrap || !editCodeInput || !scanEditBtn) {
|
if (!scanReaderWrap || !editCodeInput || !scanEditBtn) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (scannerRunning && scanReaderWrap.style.display !== 'none') {
|
if (scannerRunning && scanReaderWrap.style.display !== 'none') {
|
||||||
stopScanner();
|
stopScanner();
|
||||||
scanEditBtn.textContent = 'Barcode scannen';
|
scanEditBtn.textContent = 'Barcode scannen';
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
scanEditBtn.textContent = 'Scanner schließen';
|
scanEditBtn.textContent = 'Scanner schließen';
|
||||||
|
|
||||||
startScanner(function(decodedText) {
|
startScanner(function(decodedText) {
|
||||||
editCodeInput.value = decodedText;
|
editCodeInput.value = decodedText;
|
||||||
if(typeof validateCodeField === "function") {
|
if(typeof validateCodeField === "function") {
|
||||||
@@ -1006,16 +1138,16 @@
|
|||||||
alert('Dieses Medium ist als defekt/zerstört markiert und kann nicht ausgeliehen werden.');
|
alert('Dieses Medium ist als defekt/zerstört markiert und kann nicht ausgeliehen werden.');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const defaultCardId = activeStudentCardId || '';
|
const defaultCardId = activeStudentCardId || '';
|
||||||
const cardId = (window.prompt('Bitte Schülerausweis-ID eingeben:', defaultCardId) || '').trim().toUpperCase();
|
const cardId = (window.prompt('Bitte Schülerausweis-ID eingeben:', defaultCardId) || '').trim().toUpperCase();
|
||||||
if (!cardId) {
|
if (!cardId) {
|
||||||
alert('Ausleihe abgebrochen: Für Bibliotheksmedien ist eine gültige Schülerausweis-ID erforderlich.');
|
alert('Ausleihe abgebrochen: Für Bibliotheksmedien ist eine gültige Schülerausweis-ID erforderlich.');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
setActiveStudentCard(cardId);
|
setActiveStudentCard(cardId);
|
||||||
|
|
||||||
const durationInput = (window.prompt('Ausleihdauer in Tagen (optional):') || '').trim();
|
const durationInput = (window.prompt('Ausleihdauer in Tagen (optional):') || '').trim();
|
||||||
const maxAvailable = Math.max(1, parseInt(selectedItem?.AvailableGroupedCount || selectedItem?.Quantity || 1, 10) || 1);
|
const maxAvailable = Math.max(1, parseInt(selectedItem?.AvailableGroupedCount || selectedItem?.Quantity || 1, 10) || 1);
|
||||||
const countPrompt = (window.prompt(`Anzahl ausleihen? (Standard: 1, verfügbar: ${maxAvailable})`, '1') || '').trim();
|
const countPrompt = (window.prompt(`Anzahl ausleihen? (Standard: 1, verfügbar: ${maxAvailable})`, '1') || '').trim();
|
||||||
@@ -1027,29 +1159,29 @@
|
|||||||
alert(`Es sind nur ${maxAvailable} Exemplar(e) verfügbar.`);
|
alert(`Es sind nur ${maxAvailable} Exemplar(e) verfügbar.`);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const form = document.createElement('form');
|
const form = document.createElement('form');
|
||||||
form.method = 'POST';
|
form.method = 'POST';
|
||||||
form.action = `/ausleihen/${itemId}`;
|
form.action = `/ausleihen/${itemId}`;
|
||||||
|
|
||||||
const csrfField = document.createElement('input');
|
const csrfField = document.createElement('input');
|
||||||
csrfField.type = 'hidden';
|
csrfField.type = 'hidden';
|
||||||
csrfField.name = 'csrf_token';
|
csrfField.name = 'csrf_token';
|
||||||
csrfField.value = '{{ csrf_token }}';
|
csrfField.value = '{{ csrf_token }}';
|
||||||
form.appendChild(csrfField);
|
form.appendChild(csrfField);
|
||||||
|
|
||||||
const cardField = document.createElement('input');
|
const cardField = document.createElement('input');
|
||||||
cardField.type = 'hidden';
|
cardField.type = 'hidden';
|
||||||
cardField.name = 'borrower_card_id';
|
cardField.name = 'borrower_card_id';
|
||||||
cardField.value = cardId;
|
cardField.value = cardId;
|
||||||
form.appendChild(cardField);
|
form.appendChild(cardField);
|
||||||
|
|
||||||
const returnTargetField = document.createElement('input');
|
const returnTargetField = document.createElement('input');
|
||||||
returnTargetField.type = 'hidden';
|
returnTargetField.type = 'hidden';
|
||||||
returnTargetField.name = 'return_to';
|
returnTargetField.name = 'return_to';
|
||||||
returnTargetField.value = 'library';
|
returnTargetField.value = 'library';
|
||||||
form.appendChild(returnTargetField);
|
form.appendChild(returnTargetField);
|
||||||
|
|
||||||
if (durationInput) {
|
if (durationInput) {
|
||||||
const durationField = document.createElement('input');
|
const durationField = document.createElement('input');
|
||||||
durationField.type = 'hidden';
|
durationField.type = 'hidden';
|
||||||
@@ -1057,13 +1189,13 @@
|
|||||||
durationField.value = durationInput;
|
durationField.value = durationInput;
|
||||||
form.appendChild(durationField);
|
form.appendChild(durationField);
|
||||||
}
|
}
|
||||||
|
|
||||||
const countField = document.createElement('input');
|
const countField = document.createElement('input');
|
||||||
countField.type = 'hidden';
|
countField.type = 'hidden';
|
||||||
countField.name = 'exemplare_count';
|
countField.name = 'exemplare_count';
|
||||||
countField.value = String(borrowCount || 1);
|
countField.value = String(borrowCount || 1);
|
||||||
form.appendChild(countField);
|
form.appendChild(countField);
|
||||||
|
|
||||||
document.body.appendChild(form);
|
document.body.appendChild(form);
|
||||||
form.submit();
|
form.submit();
|
||||||
}
|
}
|
||||||
@@ -1075,13 +1207,28 @@
|
|||||||
el.classList.remove('ok', 'warn', 'error');
|
el.classList.remove('ok', 'warn', 'error');
|
||||||
if (kind) el.classList.add(kind);
|
if (kind) el.classList.add(kind);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function showSmallConfirm(message, kind='ok') {
|
||||||
|
// Append the small helper text in German
|
||||||
|
const helper = 'Sie können fortfahren. Dies ist nur eine kleine Benachrichtigung.';
|
||||||
|
const el = document.createElement('div');
|
||||||
|
el.className = `small-popup ${kind === 'error' ? 'error' : 'ok'}`;
|
||||||
|
el.innerHTML = `<div>${escapeHtml(String(message || ''))}</div><div style="opacity:0.9; margin-left:8px; font-size:0.85em;">${helper}</div><div class="close-x">×</div>`;
|
||||||
|
document.body.appendChild(el);
|
||||||
|
// close handler
|
||||||
|
el.querySelector('.close-x').addEventListener('click', () => {
|
||||||
|
if (el && el.parentNode) el.parentNode.removeChild(el);
|
||||||
|
});
|
||||||
|
// auto remove after 3 seconds
|
||||||
|
setTimeout(() => { try { if (el && el.parentNode) el.parentNode.removeChild(el); } catch(e){} }, 3000);
|
||||||
|
}
|
||||||
|
|
||||||
function setActiveStudentCard(cardId) {
|
function setActiveStudentCard(cardId) {
|
||||||
activeStudentCardId = (cardId || '').trim().toUpperCase();
|
activeStudentCardId = (cardId || '').trim().toUpperCase();
|
||||||
const input = document.getElementById('activeStudentCard');
|
const input = document.getElementById('activeStudentCard');
|
||||||
if (input) input.value = activeStudentCardId;
|
if (input) input.value = activeStudentCardId;
|
||||||
}
|
}
|
||||||
|
|
||||||
function normalizeScannedCode(code) {
|
function normalizeScannedCode(code) {
|
||||||
return (code || '').trim();
|
return (code || '').trim();
|
||||||
}
|
}
|
||||||
@@ -1145,7 +1292,8 @@
|
|||||||
const toggleBtn = document.getElementById('toggleScannerBtn');
|
const toggleBtn = document.getElementById('toggleScannerBtn');
|
||||||
const resetBtn = document.getElementById('resetCardBtn');
|
const resetBtn = document.getElementById('resetCardBtn');
|
||||||
const modeSelect = document.getElementById('scanModeSelect');
|
const modeSelect = document.getElementById('scanModeSelect');
|
||||||
|
const keyboardToggle = document.getElementById('keyboardScannerToggle');
|
||||||
|
|
||||||
if (toggleBtn) {
|
if (toggleBtn) {
|
||||||
toggleBtn.addEventListener('click', async () => {
|
toggleBtn.addEventListener('click', async () => {
|
||||||
if (scannerRunning) {
|
if (scannerRunning) {
|
||||||
@@ -1155,14 +1303,14 @@
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
if (resetBtn) {
|
if (resetBtn) {
|
||||||
resetBtn.addEventListener('click', () => {
|
resetBtn.addEventListener('click', () => {
|
||||||
setActiveStudentCard('');
|
setActiveStudentCard('');
|
||||||
setScanStatus('Ausweis zurückgesetzt. Bitte neu scannen.', 'warn');
|
setScanStatus('Ausweis zurückgesetzt. Bitte neu scannen.', 'warn');
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
if (modeSelect) {
|
if (modeSelect) {
|
||||||
modeSelect.addEventListener('change', () => {
|
modeSelect.addEventListener('change', () => {
|
||||||
if (modeSelect.value === 'quick_toggle' && !activeStudentCardId) {
|
if (modeSelect.value === 'quick_toggle' && !activeStudentCardId) {
|
||||||
@@ -1172,11 +1320,24 @@
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (keyboardToggle) {
|
||||||
|
keyboardToggle.addEventListener('change', () => {
|
||||||
|
keyboardScannerEnabled = !!keyboardToggle.checked;
|
||||||
|
if (keyboardScannerEnabled) {
|
||||||
|
document.addEventListener('keydown', keyboardScanKeydownHandler);
|
||||||
|
setScanStatus('Physischer Scanner aktiv (Schnellmodus empfohlen).', 'ok');
|
||||||
|
} else {
|
||||||
|
document.removeEventListener('keydown', keyboardScanKeydownHandler);
|
||||||
|
setScanStatus('Physischer Scanner deaktiviert.', 'warn');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Run when DOM structure is entirely ready
|
// Run when DOM structure is entirely ready
|
||||||
document.addEventListener('DOMContentLoaded', () => {
|
document.addEventListener('DOMContentLoaded', async () => {
|
||||||
wireScannerUi(); // Setup scanner control buttons
|
wireScannerUi(); // Setup scanner control buttons
|
||||||
loadLibraryItems(); // Fetch your database items right away!
|
loadLibraryItems(); // Fetch your database items right away!
|
||||||
|
|
||||||
// Safely connect standard Filters and Search inputs inside DOMContentLoaded
|
// Safely connect standard Filters and Search inputs inside DOMContentLoaded
|
||||||
@@ -1205,7 +1366,7 @@
|
|||||||
document.getElementById('filterISBN').value = '';
|
document.getElementById('filterISBN').value = '';
|
||||||
document.getElementById('filterType').value = '';
|
document.getElementById('filterType').value = '';
|
||||||
document.getElementById('filterStatus').value = '';
|
document.getElementById('filterStatus').value = '';
|
||||||
activeFilters = { isbn: '', type: '', status: '' };
|
activeFilters = {isbn: '', type: '', status: ''};
|
||||||
applyFiltersAndSearch(true);
|
applyFiltersAndSearch(true);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -1226,44 +1387,107 @@
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// Edit Modal Form processing
|
const manualReturnBtn = document.getElementById('manualReturnBtn');
|
||||||
|
const manualItemCode = document.getElementById('manualItemCode');
|
||||||
|
if (manualReturnBtn && manualItemCode) {
|
||||||
|
manualReturnBtn.addEventListener('click', async () => {
|
||||||
|
const code = (manualItemCode.value || '').trim();
|
||||||
|
if (!code) {
|
||||||
|
alert('Bitte einen Mediencode eingeben.');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
await returnByCode(code);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
const editForm = document.getElementById('editLibraryForm');
|
const editForm = document.getElementById('editLibraryForm');
|
||||||
if (editForm) {
|
if (editForm) {
|
||||||
editForm.addEventListener('submit', async function(e) {
|
editForm.addEventListener('submit', async function (e) {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
|
|
||||||
const itemId = document.getElementById('editLibraryItemId').value;
|
const itemId = document.getElementById('editLibraryItemId').value;
|
||||||
|
const currentItem = libraryItems.find(i => i._id === itemId);
|
||||||
|
if (!currentItem) return;
|
||||||
|
|
||||||
const updatedData = {
|
const codeInputs = Array.from(document.querySelectorAll('#editLibraryCodesContainer input[data-item-id]'));
|
||||||
|
|
||||||
|
// Daten aus dem Formular sammeln
|
||||||
|
const sharedPayload = {
|
||||||
name: document.getElementById('editLibraryName').value,
|
name: document.getElementById('editLibraryName').value,
|
||||||
item_type: document.getElementById('editLibraryType').value,
|
item_type: document.getElementById('editLibraryType').value,
|
||||||
isbn: document.getElementById('editLibraryIsbn').value,
|
isbn: document.getElementById('editLibraryIsbn').value,
|
||||||
code_4: document.getElementById('editLibraryCode4').value,
|
|
||||||
ort: document.getElementById('editLibraryLocation').value,
|
ort: document.getElementById('editLibraryLocation').value,
|
||||||
beschreibung: document.getElementById('editLibraryDescription').value
|
beschreibung: document.getElementById('editLibraryDescription').value,
|
||||||
|
ansch_jahr: currentItem.Anschaffungsjahr || '',
|
||||||
|
ansch_kost: currentItem.Anschaffungskosten || '',
|
||||||
|
reservierbar: currentItem.Reservierbar !== false,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const codeByItemId = new Map(codeInputs.map(input => [input.dataset.itemId, (input.value || '').trim()]));
|
||||||
|
const groupMembers = editLibraryState.groupMembers.length > 0 ? editLibraryState.groupMembers : [currentItem];
|
||||||
|
const isGroupedEdit = Boolean(currentItem.SeriesGroupId) && groupMembers.length > 1;
|
||||||
|
|
||||||
|
// API-Aufruf
|
||||||
try {
|
try {
|
||||||
const response = await fetch(`/api/library_item/${itemId}/update`, {
|
if (isGroupedEdit) {
|
||||||
method: 'POST',
|
const payload = {
|
||||||
headers: {
|
series_group_id: currentItem.SeriesGroupId,
|
||||||
'Content-Type': 'application/json',
|
...sharedPayload,
|
||||||
'X-CSRFToken': '{{ csrf_token }}',
|
items: groupMembers.map(member => ({
|
||||||
'X-CSRF-Token': '{{ csrf_token }}'
|
id: member._id,
|
||||||
},
|
code_4: codeByItemId.get(member._id) || ''
|
||||||
body: JSON.stringify(updatedData)
|
}))
|
||||||
});
|
};
|
||||||
|
|
||||||
const result = await response.json();
|
const response = await fetch('/update_group', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
'X-CSRFToken': '{{ csrf_token }}',
|
||||||
|
'X-CSRF-Token': '{{ csrf_token }}'
|
||||||
|
},
|
||||||
|
body: JSON.stringify(payload)
|
||||||
|
});
|
||||||
|
|
||||||
if (response.ok && result.ok) {
|
const result = await response.json();
|
||||||
alert(result.message || 'Medium erfolgreich aktualisiert!');
|
if (response.ok && result.success) {
|
||||||
closeEditLibraryModal();
|
alert(result.message || 'Gruppe erfolgreich aktualisiert!');
|
||||||
|
closeEditLibraryModal();
|
||||||
pagingState.loading = false;
|
pagingState.loading = false;
|
||||||
loadLibraryItems();
|
await loadLibraryItems();
|
||||||
|
} else {
|
||||||
|
alert(result.message || 'Fehler beim Speichern der Gruppenänderungen.');
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
alert(result.message || 'Fehler beim Speichern der Änderungen.');
|
const primaryCodeInput = codeInputs[0];
|
||||||
|
const payload = {
|
||||||
|
name: sharedPayload.name,
|
||||||
|
item_type: sharedPayload.item_type,
|
||||||
|
isbn: sharedPayload.isbn,
|
||||||
|
code_4: primaryCodeInput ? primaryCodeInput.value.trim() : (currentItem.Code_4 || currentItem.Code4 || '').trim(),
|
||||||
|
ort: sharedPayload.ort,
|
||||||
|
beschreibung: sharedPayload.beschreibung
|
||||||
|
};
|
||||||
|
|
||||||
|
const response = await fetch(`/api/library_item/${itemId}/update`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
'X-CSRFToken': '{{ csrf_token }}',
|
||||||
|
'X-CSRF-Token': '{{ csrf_token }}'
|
||||||
|
},
|
||||||
|
body: JSON.stringify(payload)
|
||||||
|
});
|
||||||
|
|
||||||
|
const result = await response.json();
|
||||||
|
if (response.ok && result.ok) {
|
||||||
|
alert(result.message || 'Medium erfolgreich aktualisiert!');
|
||||||
|
closeEditLibraryModal();
|
||||||
|
pagingState.loading = false;
|
||||||
|
await loadLibraryItems();
|
||||||
|
} else {
|
||||||
|
alert(result.message || 'Fehler beim Speichern der Änderungen.');
|
||||||
|
}
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Update failed:', error);
|
console.error('Update failed:', error);
|
||||||
@@ -1273,195 +1497,76 @@
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
window.openEditLibraryItem = function(itemId) {
|
async function fetchLibraryGroupMembers(seriesGroupId) {
|
||||||
const item = libraryItems.find(i => i._id === itemId);
|
if (!seriesGroupId) return [];
|
||||||
if (!item) return;
|
try {
|
||||||
|
const response = await fetch(`/api/library_group/${encodeURIComponent(seriesGroupId)}`);
|
||||||
// 1. Felder befüllen
|
if (!response.ok) {
|
||||||
document.getElementById('editLibraryItemId').value = item._id;
|
throw new Error(`HTTP ${response.status}`);
|
||||||
document.getElementById('editLibraryName').value = item.Name;
|
|
||||||
document.getElementById('editLibraryType').value = item.ItemType;
|
|
||||||
document.getElementById('editLibraryIsbn').value = item.ISBN || '';
|
|
||||||
document.getElementById('editLibraryCode4').value = item.Code_4 || '';
|
|
||||||
document.getElementById('editLibraryLocation').value = item.Ort;
|
|
||||||
document.getElementById('editLibraryDescription').value = item.Beschreibung;
|
|
||||||
|
|
||||||
// 2. Gruppen-Logik
|
|
||||||
const warningDiv = document.getElementById('editLibraryGroupWarning');
|
|
||||||
const codesContainer = document.getElementById('editLibraryAllCodes');
|
|
||||||
|
|
||||||
if (item.SeriesGroupId) {
|
|
||||||
// Filtern aus dem aktuell geladenen Array
|
|
||||||
let groupMembers = libraryItems.filter(i => i.SeriesGroupId === item.SeriesGroupId);
|
|
||||||
|
|
||||||
// SCHLÜSSEL: Wenn die Anzahl der gefundenen Elemente nicht mit SeriesCount übereinstimmt,
|
|
||||||
// haben wir die Gruppe noch nicht vollständig geladen.
|
|
||||||
if (groupMembers.length < (item.SeriesCount || 0)) {
|
|
||||||
console.warn("Gruppe noch nicht vollständig geladen. Anzeige ggf. unvollständig.");
|
|
||||||
// Optional: Zeige einen Ladehinweis im Modal
|
|
||||||
codesContainer.textContent = "Lade restliche Gruppenmitglieder...";
|
|
||||||
} else {
|
|
||||||
// Daten sind vollständig -> Anzeigen
|
|
||||||
const codeList = groupMembers
|
|
||||||
.sort((a, b) => (a.SeriesPosition || 0) - (b.SeriesPosition || 0))
|
|
||||||
.map(m => m.Code_4 || "---")
|
|
||||||
.join(', ');
|
|
||||||
|
|
||||||
codesContainer.textContent = codeList;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
document.getElementById('editLibraryGroupCount').textContent = groupMembers.length + " / " + (item.SeriesCount || "?");
|
const payload = await response.json();
|
||||||
warningDiv.style.display = 'block';
|
return Array.isArray(payload.items) ? payload.items : [];
|
||||||
} else {
|
} catch (error) {
|
||||||
warningDiv.style.display = 'none';
|
console.warn('Falling back to loaded library items for group editing:', error);
|
||||||
|
return (libraryItems || []).filter(item => item.SeriesGroupId === seriesGroupId);
|
||||||
}
|
}
|
||||||
|
|
||||||
document.getElementById('editLibraryModal').style.display = 'flex';
|
|
||||||
};
|
|
||||||
|
|
||||||
function closeEditLibraryModal() {
|
|
||||||
document.getElementById('editLibraryModal').style.display = 'none';
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
function renderLibraryGroupCodeFields(groupMembers, currentItemId) {
|
||||||
* Event-Listener für das Formular (Initialisierung)
|
const codesContainer = document.getElementById('editLibraryCodesContainer');
|
||||||
*/
|
const groupWarning = document.getElementById('editLibraryGroupWarning');
|
||||||
document.addEventListener('DOMContentLoaded', function() {
|
const groupCount = document.getElementById('editLibraryGroupCount');
|
||||||
const editForm = document.getElementById('editLibraryForm');
|
const groupHint = document.getElementById('editLibraryGroupHint');
|
||||||
if (editForm) {
|
|
||||||
editForm.addEventListener('submit', async function(e) {
|
|
||||||
e.preventDefault();
|
|
||||||
|
|
||||||
const itemId = document.getElementById('editLibraryItemId').value;
|
if (!codesContainer) return;
|
||||||
const currentItem = libraryItems.find(i => i._id === itemId);
|
|
||||||
|
|
||||||
if (!currentItem) return;
|
const items = Array.isArray(groupMembers) ? groupMembers.slice() : [];
|
||||||
|
items.sort((a, b) => (a.SeriesPosition || 0) - (b.SeriesPosition || 0) || String(a.Name || '').localeCompare(String(b.Name || '')));
|
||||||
|
|
||||||
// 1. Alle Mitglieder der Gruppe finden, um die Code-Liste aufzubauen
|
editLibraryState.groupMembers = items;
|
||||||
const groupMembers = libraryItems.filter(i => i.SeriesGroupId === currentItem.SeriesGroupId);
|
|
||||||
const individualUpdates = groupMembers.map(member => ({
|
|
||||||
id: member._id,
|
|
||||||
// Wenn dies das bearbeitete Item ist, nimm den neuen Code, sonst den alten
|
|
||||||
code_4: (member._id === itemId) ? document.getElementById('editLibraryCode4').value : member.Code_4
|
|
||||||
}));
|
|
||||||
|
|
||||||
// 2. Payload für das Backend bauen
|
|
||||||
const payload = {
|
|
||||||
series_group_id: currentItem.SeriesGroupId,
|
|
||||||
name: document.getElementById('editLibraryName').value,
|
|
||||||
ort: document.getElementById('editLibraryLocation').value,
|
|
||||||
beschreibung: document.getElementById('editLibraryDescription').value,
|
|
||||||
isbn: document.getElementById('editLibraryIsbn').value,
|
|
||||||
item_type: document.getElementById('editLibraryType').value,
|
|
||||||
items: individualUpdates
|
|
||||||
};
|
|
||||||
|
|
||||||
// 3. Request an die Gruppen-Update Route
|
|
||||||
try {
|
|
||||||
const response = await fetch('/update_group', {
|
|
||||||
method: 'POST',
|
|
||||||
headers: { 'Content-Type': 'application/json' },
|
|
||||||
body: JSON.stringify(payload)
|
|
||||||
});
|
|
||||||
|
|
||||||
const result = await response.json();
|
|
||||||
if (result.success) {
|
|
||||||
alert('Gruppe erfolgreich synchronisiert!');
|
|
||||||
closeEditLibraryModal();
|
|
||||||
await loadLibraryItems(); // Daten neu laden
|
|
||||||
// renderTable(); // Ggf. Tabelle neu rendern
|
|
||||||
} else {
|
|
||||||
await loadLibraryItems();
|
|
||||||
closeEditLibraryModal();
|
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Update failed:', error);
|
|
||||||
alert('Netzwerkfehler.');
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
|
if (groupWarning) {
|
||||||
|
groupWarning.style.display = items.length > 1 ? 'block' : 'none';
|
||||||
}
|
}
|
||||||
});
|
if (groupCount) {
|
||||||
|
const totalCount = items.length || 1;
|
||||||
|
const declaredCount = items[0]?.SeriesCount || totalCount;
|
||||||
|
groupCount.textContent = `${totalCount} / ${declaredCount}`;
|
||||||
|
}
|
||||||
|
if (groupHint) {
|
||||||
|
groupHint.textContent = items.length > 1
|
||||||
|
? 'Jeder Code gehört zu einem eigenen Exemplar. Änderungen werden für alle Codes gespeichert.'
|
||||||
|
: 'Einzelnes Exemplar. Der Code wird direkt gespeichert.';
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!items.length) {
|
||||||
|
codesContainer.innerHTML = '<div style="padding:10px 0; color:#6b7280;">Keine Codes geladen.</div>';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
codesContainer.innerHTML = items.map((member, index) => {
|
||||||
|
const codeValue = member.Code_4 || member.Code4 || '';
|
||||||
|
const labelParts = [];
|
||||||
|
if (member.SeriesPosition !== undefined && member.SeriesPosition !== null) {
|
||||||
|
labelParts.push(`Exemplar ${member.SeriesPosition}`);
|
||||||
|
} else {
|
||||||
|
labelParts.push(`Exemplar ${index + 1}`);
|
||||||
|
}
|
||||||
|
if (member._id === currentItemId) {
|
||||||
|
labelParts.push('aktuelles Medium');
|
||||||
|
}
|
||||||
|
return `
|
||||||
|
<div style="display:flex; flex-direction:column; gap:6px; margin-bottom:10px;">
|
||||||
|
<label for="editLibraryCode-${member._id}" style="font-weight:600; font-size:0.9em; color:var(--ui-text);">${escapeHtml(labelParts.join(' · '))}</label>
|
||||||
|
<input id="editLibraryCode-${member._id}" data-item-id="${escapeHtml(member._id)}" value="${escapeHtml(codeValue)}" placeholder="Mediencode" style="width:100%; padding:8px 10px; border:1px solid #d0d7e2; border-radius:6px;">
|
||||||
|
</div>
|
||||||
|
`;
|
||||||
|
}).join('');
|
||||||
|
}
|
||||||
|
|
||||||
|
function openEditLibraryItem(itemId) {
|
||||||
|
window.location.href = `/item_edit/${itemId}`;
|
||||||
|
}
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<div id="editLibraryModal" class="modal" style="display:none;">
|
|
||||||
<div class="modal-content" style="max-width: 760px; padding: 25px; border-radius: 8px;">
|
|
||||||
<span class="close" onclick="closeEditLibraryModal()" style="cursor: pointer; float: right; font-size: 24px;">×</span>
|
|
||||||
<h3 style="margin-top:0;">Bibliotheksmedium bearbeiten</h3>
|
|
||||||
|
|
||||||
<!-- Bereich für Gruppen-Informationen (Hier konsolidiert!) -->
|
|
||||||
<div id="editLibraryGroupWarning" style="display:none; background-color: #fff; padding: 15px; border-radius: 6px; margin-bottom: 20px; border: 1px solid #0ea5e9;">
|
|
||||||
<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px; border-bottom: 1px solid #eee; padding-bottom: 10px;">
|
|
||||||
<strong style="color: #0ea5e9;">Gruppen-Range (Total: <span id="editLibraryGroupCount"></span>)</strong>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<p style="margin: 5px 0; font-size: 12px; color: #555;">
|
|
||||||
Alle aufgeführten Codes gehören zu diesem Datensatz:
|
|
||||||
</p>
|
|
||||||
|
|
||||||
<!-- Hier werden die Codes per JS eingefügt -->
|
|
||||||
<div id="editLibraryAllCodes" style="display: flex; flex-wrap: wrap; gap: 5px; margin-top: 10px;"></div>
|
|
||||||
|
|
||||||
<div style="margin-top: 15px; font-size: 11px; background: #e0f2fe; padding: 8px; border-radius: 4px;">
|
|
||||||
<strong>Hinweis:</strong> Änderungen an Titel/Ort/Beschreibung werden auf <strong>alle</strong> Exemplare der Range übertragen.
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<form id="editLibraryForm">
|
|
||||||
<input type="hidden" id="editLibraryItemId">
|
|
||||||
<div class="edit-grid">
|
|
||||||
<div class="full">
|
|
||||||
<label for="editLibraryName">Titel</label>
|
|
||||||
<input id="editLibraryName" required style="width: 100%;">
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<label for="editLibraryType">Medientyp</label>
|
|
||||||
<select id="editLibraryType" style="width: 100%;">
|
|
||||||
<option value="Buch">Buch</option>
|
|
||||||
<option value="Schulbuch">Schulbuch</option>
|
|
||||||
<option value="cd">CD</option>
|
|
||||||
<option value="dvd">DVD</option>
|
|
||||||
<option value="other">Sonstige Medien</option>
|
|
||||||
</select>
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<label for="editLibraryIsbn">ISBN</label>
|
|
||||||
<input id="editLibraryIsbn" placeholder="optional ISBN-10/13" style="width: 100%;">
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<label for="editLibraryCode4">Code</label>
|
|
||||||
<input id="editLibraryCode4" placeholder="optional Mediencode" style="width: 100%;">
|
|
||||||
</div>
|
|
||||||
<div class="full">
|
|
||||||
<label for="editLibraryLocation">Ort</label>
|
|
||||||
<input id="editLibraryLocation" required style="width: 100%;">
|
|
||||||
</div>
|
|
||||||
<div class="full">
|
|
||||||
<label for="editLibraryDescription">Beschreibung</label>
|
|
||||||
<textarea id="editLibraryDescription" rows="4" required style="width: 100%;"></textarea>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div class="edit-actions" style="margin-top:20px;">
|
|
||||||
<button type="submit" class="button" style="background:#0ea5e9;color:#fff;">Speichern & Synchronisieren</button>
|
|
||||||
<button type="button" class="button" onclick="closeEditLibraryModal()">Abbrechen</button>
|
|
||||||
</div>
|
|
||||||
</form>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div id="editLibraryGroupWarning" style="display:none; background-color: #fff; padding: 15px; border-radius: 6px; margin-bottom: 20px; border: 1px solid #0ea5e9;">
|
|
||||||
<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px; border-bottom: 1px solid #eee; padding-bottom: 10px;">
|
|
||||||
<strong style="color: #0ea5e9;">Gruppen-Range (Total: <span id="editLibraryGroupCount"></span>)</strong>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<p style="margin: 5px 0; font-size: 12px; color: #555;">
|
|
||||||
Alle Codes in dieser Gruppe:
|
|
||||||
</p>
|
|
||||||
|
|
||||||
<!-- Hier wird die Liste als Komma-Text eingefügt -->
|
|
||||||
<div id="editLibraryAllCodes" style="font-family: monospace; font-size: 14px; font-weight: bold; color: #333; margin-top: 5px;"></div>
|
|
||||||
|
|
||||||
<div style="margin-top: 15px; font-size: 11px; background: #e0f2fe; padding: 8px; border-radius: 4px;">
|
|
||||||
<strong>Hinweis:</strong> Änderungen an Titel/Ort/Beschreibung werden auf <strong>alle</strong> Exemplare der Range übertragen.
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
+67
-497
@@ -1951,11 +1951,6 @@
|
|||||||
display: none;
|
display: none;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Edit new location container */
|
|
||||||
.edit-new-location-container {
|
|
||||||
display: none;
|
|
||||||
margin-top: 10px;
|
|
||||||
}
|
|
||||||
|
|
||||||
/* Modal dialog styling */
|
/* Modal dialog styling */
|
||||||
.modal-dialog-white {
|
.modal-dialog-white {
|
||||||
@@ -1969,11 +1964,6 @@
|
|||||||
margin-top: 10px;
|
margin-top: 10px;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Element text colors for better visibility */
|
|
||||||
.edit-button, .duplicate-button, .generate-qr-button {
|
|
||||||
color: var(--ui-title) !important;
|
|
||||||
}
|
|
||||||
|
|
||||||
/* Standardized button styles across the application */
|
/* Standardized button styles across the application */
|
||||||
.search-button, .scan-button, .filter-toggle, .clear-filter,
|
.search-button, .scan-button, .filter-toggle, .clear-filter,
|
||||||
.add-new-btn, .popup-close-button, .prev-image-button, .next-image-button,
|
.add-new-btn, .popup-close-button, .prev-image-button, .next-image-button,
|
||||||
@@ -2474,187 +2464,6 @@ document.addEventListener('DOMContentLoaded', ()=>{
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- Add the edit modal form -->
|
|
||||||
{% if current_permissions.actions.get('can_edit', False) %}
|
|
||||||
<div id="edit-modal" class="item-modal">
|
|
||||||
<div class="modal-content">
|
|
||||||
<span class="close-modal" onclick="closeEditModal()">×</span>
|
|
||||||
<h2>Objekt bearbeiten</h2>
|
|
||||||
<form id="edit-item-form" method="POST" enctype="multipart/form-data">
|
|
||||||
<input type="hidden" id="edit-item-id" name="id">
|
|
||||||
<div class="form-row">
|
|
||||||
<div class="form-group">
|
|
||||||
<label for="edit-name">Name:</label>
|
|
||||||
<input type="text" id="edit-name" name="name" required>
|
|
||||||
</div>
|
|
||||||
<div class="form-group">
|
|
||||||
<label for="edit-location">Ort:</label>
|
|
||||||
<select id="edit-location" name="ort" required>
|
|
||||||
<option value="">-- Bitte Ort auswählen --</option>
|
|
||||||
<!-- Options will be loaded by JavaScript -->
|
|
||||||
</select>
|
|
||||||
<button type="button" class="add-new-btn" id="edit-add-new-location-btn">
|
|
||||||
Neuen Ort hinzufügen
|
|
||||||
</button>
|
|
||||||
<div id="edit-new-location-container" class="edit-new-location-container">
|
|
||||||
<input type="text" id="edit-new-location-input" placeholder="Neuen Ort eingeben">
|
|
||||||
<button type="button" onclick="addNewLocation('edit')">Hinzufügen</button>
|
|
||||||
<button type="button" onclick="cancelAddLocation('edit')">Abbrechen</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div class="form-group">
|
|
||||||
<label for="edit-description">Beschreibung:</label>
|
|
||||||
<textarea id="edit-description" name="beschreibung" required></textarea>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<!-- Updated filter inputs for edit form with dropdowns -->
|
|
||||||
<div class="filter-inputs">
|
|
||||||
<h3>Unterrichtsfach:</h3>
|
|
||||||
<div class="multi-filter">
|
|
||||||
<div class="form-group">
|
|
||||||
<label for="edit-filter1-1">Wert 1:</label>
|
|
||||||
<select id="edit-filter1-1" name="filter" class="filter-dropdown-select">
|
|
||||||
<option value="">-- Bitte auswählen --</option>
|
|
||||||
<!-- Options will be loaded by JavaScript -->
|
|
||||||
</select>
|
|
||||||
</div>
|
|
||||||
<div class="form-group">
|
|
||||||
<label for="edit-filter1-2">Wert 2:</label>
|
|
||||||
<select id="edit-filter1-2" name="filter" class="filter-dropdown-select">
|
|
||||||
<option value="">-- Optional --</option>
|
|
||||||
<!-- Options will be loaded by JavaScript -->
|
|
||||||
</select>
|
|
||||||
</div>
|
|
||||||
<div class="form-group">
|
|
||||||
<label for="edit-filter1-3">Wert 3:</label>
|
|
||||||
<select id="edit-filter1-3" name="filter" class="filter-dropdown-select">
|
|
||||||
<option value="">-- Optional --</option>
|
|
||||||
<!-- Options will be loaded by JavaScript -->
|
|
||||||
</select>
|
|
||||||
</div>
|
|
||||||
<div class="form-group">
|
|
||||||
<label for="edit-filter1-4">Wert 4:</label>
|
|
||||||
<select id="edit-filter1-4" name="filter" class="filter-dropdown-select">
|
|
||||||
<option value="">-- Optional --</option>
|
|
||||||
<!-- Options will be loaded by JavaScript -->
|
|
||||||
</select>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<h3>Jahrgangsstufe:</h3>
|
|
||||||
<div class="multi-filter">
|
|
||||||
<div class="form-group">
|
|
||||||
<label for="edit-filter2-1">Wert 1:</label>
|
|
||||||
<select id="edit-filter2-1" name="filter2" class="filter-dropdown-select">
|
|
||||||
<option value="">-- Bitte auswählen --</option>
|
|
||||||
<!-- Options will be loaded by JavaScript -->
|
|
||||||
</select>
|
|
||||||
</div>
|
|
||||||
<div class="form-group">
|
|
||||||
<label for="edit-filter2-2">Wert 2:</label>
|
|
||||||
<select id="edit-filter2-2" name="filter2" class="filter-dropdown-select">
|
|
||||||
<option value="">-- Optional --</option>
|
|
||||||
<!-- Options will be loaded by JavaScript -->
|
|
||||||
</select>
|
|
||||||
</div>
|
|
||||||
<div class="form-group">
|
|
||||||
<label for="edit-filter2-3">Wert 3:</label>
|
|
||||||
<select id="edit-filter2-3" name="filter2" class="filter-dropdown-select">
|
|
||||||
<option value="">-- Optional --</option>
|
|
||||||
<!-- Options will be loaded by JavaScript -->
|
|
||||||
</select>
|
|
||||||
</div>
|
|
||||||
<div class="form-group">
|
|
||||||
<label for="edit-filter2-4">Wert 4:</label>
|
|
||||||
<select id="edit-filter2-4" name="filter2" class="filter-dropdown-select">
|
|
||||||
<option value="">-- Optional --</option>
|
|
||||||
<!-- Options will be loaded by JavaScript -->
|
|
||||||
</select>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<h3>Schlagwort:</h3>
|
|
||||||
<div class="multi-filter">
|
|
||||||
<div class="form-group">
|
|
||||||
<label for="edit-filter3-1">Wert 1:</label>
|
|
||||||
<input type="text" id="edit-filter3-1" name="filter3">
|
|
||||||
</div>
|
|
||||||
<div class="form-group">
|
|
||||||
<label for="edit-filter3-2">Wert 2:</label>
|
|
||||||
<input type="text" id="edit-filter3-2" name="filter3">
|
|
||||||
</div>
|
|
||||||
<div class="form-group">
|
|
||||||
<label for="edit-filter3-3">Wert 3:</label>
|
|
||||||
<input type="text" id="edit-filter3-3" name="filter3">
|
|
||||||
</div>
|
|
||||||
<div class="form-group">
|
|
||||||
<label for="edit-filter3-4">Wert 4:</label>
|
|
||||||
<input type="text" id="edit-filter3-4" name="filter3">
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="form-group">
|
|
||||||
<label for="edit-year">Anschaffungsjahr:</label>
|
|
||||||
<input type="date" id="edit-year" name="anschaffungsjahr">
|
|
||||||
</div>
|
|
||||||
<div class="form-group">
|
|
||||||
<label for="edit-cost">Anschaffungskosten (€):</label>
|
|
||||||
<input id="edit-cost" name="anschaffungskosten">
|
|
||||||
</div>
|
|
||||||
<div class="form-group">
|
|
||||||
<label for="edit-code4">Code:</label>
|
|
||||||
<div style="display:flex; gap:8px; align-items:center; flex-wrap:wrap;">
|
|
||||||
<input id="edit-code4" name="code_4">
|
|
||||||
<button type="button" class="fetch-isbn-button" id="scan-edit-code-btn">Barcode scannen</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="form-group">
|
|
||||||
<label for="edit-reservierbar" style="display:inline-block; width:auto; margin-right:10px;">Reservierbar:</label>
|
|
||||||
<input type="checkbox" id="edit-reservierbar" name="reservierbar" style="width:auto;">
|
|
||||||
<small style="display:block; color:#666;">Wenn deaktiviert, kann der Artikel nicht im Voraus reserviert werden.</small>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<!-- New section for managing images -->
|
|
||||||
<div class="form-group">
|
|
||||||
<label>Vorhandene Bilder:</label>
|
|
||||||
<div id="edit-existing-images" class="existing-images-container">
|
|
||||||
<!-- Existing images will be added here dynamically -->
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="form-group">
|
|
||||||
<label for="edit-new-images">
|
|
||||||
<span>Neue Bilder/Videos hinzufügen:</span>
|
|
||||||
<span>(Bilder/Videos werden vom Original übernommen)</span>
|
|
||||||
</label>
|
|
||||||
<input type="file" id="edit-new-images" name="new_images" accept=".jpg, .jpeg, .png, .gif, .mp4, .mov, .avi, .mkv, .webm, .flv, .m4v, .3gp" multiple>
|
|
||||||
<div class="allowed-formats">Erlaubte Formate: JPG, JPEG, PNG, GIF, MP4, MOV, AVI, MKV, WEBM, FLV, M4V, 3GP</div>
|
|
||||||
<!-- Add image preview container -->
|
|
||||||
<div class="image-preview-container" id="edit-image-preview-container"></div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="form-group">
|
|
||||||
<label for="edit-isbn">ISBN:</label>
|
|
||||||
<div class="isbn-input-group">
|
|
||||||
<input type="text" id="edit-isbn" name="isbn" placeholder="ISBN eingeben...">
|
|
||||||
<button type="button" class="fetch-isbn-button" id="scan-edit-isbn-btn">ISBN scannen</button>
|
|
||||||
<button type="button" class="fetch-isbn-button" onclick="fetchBookInfo('edit')">Buchinformationen abrufen</button>
|
|
||||||
</div>
|
|
||||||
<div id="edit-book-info-container" class="book-info-container"></div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="form-actions">
|
|
||||||
<button type="submit" class="save-button">Speichern</button>
|
|
||||||
<button type="button" class="cancel-button" onclick="closeEditModal()">Abbrechen</button>
|
|
||||||
</div>
|
|
||||||
</form>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
{% endif %}
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- Schedule Appointment Modal -->
|
<!-- Schedule Appointment Modal -->
|
||||||
@@ -2889,58 +2698,6 @@ document.addEventListener('DOMContentLoaded', ()=>{
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
function scanIntoEditCode() {
|
|
||||||
const qrReader = document.getElementById('qr-reader');
|
|
||||||
const editCodeInput = document.getElementById('edit-code4');
|
|
||||||
const scanEditBtn = document.getElementById('scan-edit-code-btn');
|
|
||||||
if (!qrReader || !editCodeInput || !scanEditBtn) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Toggle close if it's already running
|
|
||||||
if (isScanning && qrReader.style.display !== 'none') {
|
|
||||||
stopScanner();
|
|
||||||
scanEditBtn.textContent = 'Barcode scannen';
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
scanEditBtn.textContent = 'Scanner schließen';
|
|
||||||
|
|
||||||
// Start scanner with custom logic mapping to the Code input field
|
|
||||||
startScanner(function(decodedText) {
|
|
||||||
editCodeInput.value = decodedText;
|
|
||||||
validateCodeField(editCodeInput, document.getElementById('edit-item-id')?.value || null);
|
|
||||||
scanEditBtn.textContent = 'Barcode scannen';
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
function scanIntoEditIsbn() {
|
|
||||||
const qrReader = document.getElementById('qr-reader');
|
|
||||||
const editIsbnInput = document.getElementById('edit-isbn');
|
|
||||||
const scanIsbnBtn = document.getElementById('scan-edit-isbn-btn');
|
|
||||||
if (!qrReader || !editIsbnInput || !scanIsbnBtn) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Toggle close if it's already running
|
|
||||||
if (isScanning && qrReader.style.display !== 'none') {
|
|
||||||
stopScanner();
|
|
||||||
scanIsbnBtn.textContent = 'ISBN scannen';
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
scanIsbnBtn.textContent = 'Scanner schließen';
|
|
||||||
|
|
||||||
// Start scanner with custom logic mapping to the ISBN input field
|
|
||||||
startScanner(function(decodedText) {
|
|
||||||
editIsbnInput.value = decodedText;
|
|
||||||
scanIsbnBtn.textContent = 'ISBN scannen';
|
|
||||||
if (typeof fetchBookInfo === 'function') {
|
|
||||||
fetchBookInfo('edit');
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
function rebuildFilter3Options() {
|
function rebuildFilter3Options() {
|
||||||
if (!allItems) return;
|
if (!allItems) return;
|
||||||
|
|
||||||
@@ -3324,21 +3081,11 @@ document.addEventListener('DOMContentLoaded', ()=>{
|
|||||||
loadPredefinedFilterValues(1);
|
loadPredefinedFilterValues(1);
|
||||||
loadPredefinedFilterValues(2);
|
loadPredefinedFilterValues(2);
|
||||||
loadPredefinedFilterValues(3);
|
loadPredefinedFilterValues(3);
|
||||||
|
|
||||||
// Set up edit form submission
|
|
||||||
setupEditFormSubmission();
|
|
||||||
|
|
||||||
// Set up schedule form submission
|
// Set up schedule form submission
|
||||||
setupScheduleFormSubmission();
|
setupScheduleFormSubmission();
|
||||||
|
|
||||||
// Set up add new location buttons
|
|
||||||
const editAddLocationBtn = document.getElementById('edit-add-new-location-btn');
|
|
||||||
if (editAddLocationBtn) {
|
|
||||||
editAddLocationBtn.addEventListener('click', function() {
|
|
||||||
const container = document.getElementById('edit-new-location-container');
|
|
||||||
container.style.display = container.style.display === 'none' ? 'block' : 'none';
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
// Find and attach event listener to all logout links
|
// Find and attach event listener to all logout links
|
||||||
const logoutLinks = document.querySelectorAll('a[href*="logout"]');
|
const logoutLinks = document.querySelectorAll('a[href*="logout"]');
|
||||||
@@ -3391,35 +3138,11 @@ document.addEventListener('DOMContentLoaded', ()=>{
|
|||||||
// Close modals when clicking outside
|
// Close modals when clicking outside
|
||||||
window.onclick = function(event) {
|
window.onclick = function(event) {
|
||||||
const itemModal = document.getElementById('item-modal');
|
const itemModal = document.getElementById('item-modal');
|
||||||
const editModal = document.getElementById('edit-modal');
|
|
||||||
|
|
||||||
if (event.target === itemModal) {
|
if (event.target === itemModal) {
|
||||||
itemModal.style.display = 'none';
|
itemModal.style.display = 'none';
|
||||||
}
|
}
|
||||||
if (event.target === editModal) {
|
|
||||||
editModal.style.display = 'none';
|
|
||||||
}
|
|
||||||
};
|
};
|
||||||
|
|
||||||
// Set up code validation for edit form
|
|
||||||
const editCodeField = document.getElementById('edit-code4');
|
|
||||||
if (editCodeField) {
|
|
||||||
editCodeField.addEventListener('blur', function() {
|
|
||||||
const itemIdField = document.getElementById('edit-item-id');
|
|
||||||
const excludeId = itemIdField ? itemIdField.value : null;
|
|
||||||
validateCodeField(this, excludeId);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
const scanEditCodeBtn = document.getElementById('scan-edit-code-btn');
|
|
||||||
if (scanEditCodeBtn) {
|
|
||||||
scanEditCodeBtn.addEventListener('click', scanIntoEditCode);
|
|
||||||
}
|
|
||||||
|
|
||||||
const scanEditIsbnBtn = document.getElementById('scan-edit-isbn-btn');
|
|
||||||
if (scanEditIsbnBtn) {
|
|
||||||
scanEditIsbnBtn.addEventListener('click', scanIntoEditIsbn);
|
|
||||||
}
|
|
||||||
});
|
});
|
||||||
|
|
||||||
// Function to load items from server
|
// Function to load items from server
|
||||||
@@ -4171,162 +3894,6 @@ document.addEventListener('DOMContentLoaded', ()=>{
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
function openEditModalForSelectedUnit(defaultItemId, selectId) {
|
|
||||||
let targetItemId = defaultItemId;
|
|
||||||
|
|
||||||
try {
|
|
||||||
const selectedUnit = selectId ? document.getElementById(selectId) : null;
|
|
||||||
if (selectedUnit && selectedUnit.value) {
|
|
||||||
targetItemId = selectedUnit.value;
|
|
||||||
}
|
|
||||||
} catch (e) {
|
|
||||||
// Keep default item id as fallback.
|
|
||||||
}
|
|
||||||
|
|
||||||
openEditModalFromServer(targetItemId);
|
|
||||||
}
|
|
||||||
|
|
||||||
function closeEditModal() {
|
|
||||||
const editModal = document.getElementById('edit-modal');
|
|
||||||
if (editModal) {
|
|
||||||
editModal.style.display = 'none';
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function openEditModalFromServer(itemId) {
|
|
||||||
const editModal = document.getElementById('edit-modal');
|
|
||||||
if (!editModal) {
|
|
||||||
console.error('Edit modal nicht gefunden');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
console.log('DEBUG: openEditModal called with itemId:', itemId);
|
|
||||||
|
|
||||||
// Fetch the item data from the backend
|
|
||||||
fetch(`/get_item/${itemId}`)
|
|
||||||
.then(response => {
|
|
||||||
console.log('DEBUG: Response status:', response.status);
|
|
||||||
if (!response.ok) throw new Error(`HTTP ${response.status}`);
|
|
||||||
return response.json();
|
|
||||||
})
|
|
||||||
.then(data => {
|
|
||||||
console.log('DEBUG: Fetched data:', data);
|
|
||||||
// Backend returns the item directly or wrapped in error/success
|
|
||||||
const item = data.error ? null : (data.item || data);
|
|
||||||
|
|
||||||
console.log('DEBUG: Parsed item:', item);
|
|
||||||
|
|
||||||
if (!item || !item._id) {
|
|
||||||
console.error('DEBUG: Item not found or invalid');
|
|
||||||
alert('Item nicht gefunden');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Fill in the form fields with the item data
|
|
||||||
document.getElementById('edit-item-id').value = item._id || '';
|
|
||||||
document.getElementById('edit-name').value = item.Name || '';
|
|
||||||
document.getElementById('edit-location').value = item.Ort || '';
|
|
||||||
document.getElementById('edit-description').value = item.Beschreibung || '';
|
|
||||||
document.getElementById('edit-year').value = item.Anschaffungsjahr || '';
|
|
||||||
document.getElementById('edit-cost').value = item.Anschaffungskosten || '';
|
|
||||||
document.getElementById('edit-code4').value = item.Code_4 || '';
|
|
||||||
document.getElementById('edit-isbn').value = item.ISBN || '';
|
|
||||||
document.getElementById('edit-reservierbar').checked = item.Reservierbar !== false;
|
|
||||||
|
|
||||||
// Fill in filter 1 (Unterrichtsfach)
|
|
||||||
const filter1Array = Array.isArray(item.Filter) ? item.Filter : (item.Filter ? [item.Filter] : []);
|
|
||||||
document.getElementById('edit-filter1-1').value = filter1Array[0] || '';
|
|
||||||
document.getElementById('edit-filter1-2').value = filter1Array[1] || '';
|
|
||||||
document.getElementById('edit-filter1-3').value = filter1Array[2] || '';
|
|
||||||
document.getElementById('edit-filter1-4').value = filter1Array[3] || '';
|
|
||||||
|
|
||||||
// Fill in filter 2 (Jahrgangsstufe)
|
|
||||||
const filter2Array = Array.isArray(item.Filter2) ? item.Filter2 : (item.Filter2 ? [item.Filter2] : []);
|
|
||||||
document.getElementById('edit-filter2-1').value = filter2Array[0] || '';
|
|
||||||
document.getElementById('edit-filter2-2').value = filter2Array[1] || '';
|
|
||||||
document.getElementById('edit-filter2-3').value = filter2Array[2] || '';
|
|
||||||
document.getElementById('edit-filter2-4').value = filter2Array[3] || '';
|
|
||||||
|
|
||||||
// Fill in filter 3 (Schlagwort)
|
|
||||||
const filter3Array = Array.isArray(item.Filter3) ? item.Filter3 : (item.Filter3 ? [item.Filter3] : []);
|
|
||||||
document.getElementById('edit-filter3-1').value = filter3Array[0] || '';
|
|
||||||
document.getElementById('edit-filter3-2').value = filter3Array[1] || '';
|
|
||||||
document.getElementById('edit-filter3-3').value = filter3Array[2] || '';
|
|
||||||
document.getElementById('edit-filter3-4').value = filter3Array[3] || '';
|
|
||||||
|
|
||||||
// Display existing images
|
|
||||||
const existingImagesContainer = document.getElementById('edit-existing-images');
|
|
||||||
const editForm = document.getElementById('edit-item-form');
|
|
||||||
existingImagesContainer.innerHTML = '';
|
|
||||||
if (editForm) {
|
|
||||||
editForm.querySelectorAll('input[name="existing_images"], input[name="removed_images"]').forEach(input => input.remove());
|
|
||||||
}
|
|
||||||
if (item.Images && Array.isArray(item.Images)) {
|
|
||||||
item.Images.forEach((image, index) => {
|
|
||||||
const isVideo = isVideoFile(image);
|
|
||||||
const imageDiv = document.createElement('div');
|
|
||||||
imageDiv.className = 'existing-image-item';
|
|
||||||
imageDiv.style.marginBottom = '10px';
|
|
||||||
|
|
||||||
const thumbnailInfo = item.ThumbnailInfo && item.ThumbnailInfo[index];
|
|
||||||
const imageSrc = thumbnailInfo && thumbnailInfo.has_preview ?
|
|
||||||
thumbnailInfo.preview_url :
|
|
||||||
(image.startsWith('/uploads/') || image.startsWith('http') ?
|
|
||||||
image :
|
|
||||||
`{{ url_for('uploaded_file', filename='') }}${image}`);
|
|
||||||
|
|
||||||
const row = document.createElement('div');
|
|
||||||
row.style.display = 'flex';
|
|
||||||
row.style.gap = '8px';
|
|
||||||
row.style.alignItems = 'center';
|
|
||||||
|
|
||||||
if (isVideo) {
|
|
||||||
const video = document.createElement('video');
|
|
||||||
video.src = imageSrc;
|
|
||||||
video.style.maxWidth = '100px';
|
|
||||||
video.style.maxHeight = '100px';
|
|
||||||
video.style.objectFit = 'contain';
|
|
||||||
video.controls = true;
|
|
||||||
row.appendChild(video);
|
|
||||||
} else {
|
|
||||||
const img = document.createElement('img');
|
|
||||||
img.src = imageSrc;
|
|
||||||
img.style.maxWidth = '100px';
|
|
||||||
img.style.maxHeight = '100px';
|
|
||||||
img.style.objectFit = 'contain';
|
|
||||||
img.alt = `Existierendes Bild ${index + 1}`;
|
|
||||||
row.appendChild(img);
|
|
||||||
}
|
|
||||||
|
|
||||||
const deleteButton = document.createElement('button');
|
|
||||||
deleteButton.type = 'button';
|
|
||||||
deleteButton.className = 'delete-image-button';
|
|
||||||
deleteButton.textContent = 'Löschen';
|
|
||||||
deleteButton.addEventListener('click', () => removeExistingImage(image, deleteButton));
|
|
||||||
row.appendChild(deleteButton);
|
|
||||||
|
|
||||||
imageDiv.appendChild(row);
|
|
||||||
existingImagesContainer.appendChild(imageDiv);
|
|
||||||
|
|
||||||
if (editForm) {
|
|
||||||
const hiddenInput = document.createElement('input');
|
|
||||||
hiddenInput.type = 'hidden';
|
|
||||||
hiddenInput.name = 'existing_images';
|
|
||||||
hiddenInput.value = image;
|
|
||||||
editForm.appendChild(hiddenInput);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
// Display the modal
|
|
||||||
editModal.style.display = 'block';
|
|
||||||
})
|
|
||||||
.catch(error => {
|
|
||||||
console.error('Fehler beim Laden des Items:', error);
|
|
||||||
alert('Fehler beim Laden des Items');
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
function escapeHtml(value) {
|
function escapeHtml(value) {
|
||||||
return String(value ?? '').replace(/[&<>'"]/g, (char) => {
|
return String(value ?? '').replace(/[&<>'"]/g, (char) => {
|
||||||
const map = {
|
const map = {
|
||||||
@@ -4686,7 +4253,9 @@ document.addEventListener('DOMContentLoaded', ()=>{
|
|||||||
<button type="button" class="details-button" onclick="document.getElementById('item-modal').style.display='none';">Schließen</button>
|
<button type="button" class="details-button" onclick="document.getElementById('item-modal').style.display='none';">Schließen</button>
|
||||||
</div>
|
</div>
|
||||||
`;
|
`;
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
modal.style.display = 'block';
|
modal.style.display = 'block';
|
||||||
|
|
||||||
const closeButton = modal.querySelector('.close-modal');
|
const closeButton = modal.querySelector('.close-modal');
|
||||||
@@ -4923,6 +4492,13 @@ document.addEventListener('DOMContentLoaded', ()=>{
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function openEditModalForSelectedUnit(itemId, selectId) {
|
||||||
|
const select = document.getElementById(selectId);
|
||||||
|
const targetId = (select && select.value) ? select.value : itemId;
|
||||||
|
// Leitet auf die Bearbeiten-Seite weiter und übergibt die aktuelle URL für den Redirect nach dem Speichern
|
||||||
|
window.location.href = `/item_edit/${targetId}`;
|
||||||
|
}
|
||||||
|
|
||||||
function changeModalImage(direction) {
|
function changeModalImage(direction) {
|
||||||
const currentIndex = window.currentModalImageIndex;
|
const currentIndex = window.currentModalImageIndex;
|
||||||
const total = window.totalModalImages;
|
const total = window.totalModalImages;
|
||||||
@@ -5349,8 +4925,6 @@ document.addEventListener('DOMContentLoaded', ()=>{
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// Load location options for edit modal
|
|
||||||
// Edit-related functions moved to edit_item_functions.html
|
|
||||||
|
|
||||||
// Schedule modal functions
|
// Schedule modal functions
|
||||||
function openScheduleModal(itemId) {
|
function openScheduleModal(itemId) {
|
||||||
@@ -5470,50 +5044,6 @@ document.addEventListener('DOMContentLoaded', ()=>{
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Setup edit form submission
|
|
||||||
function setupEditFormSubmission() {
|
|
||||||
const editForm = document.getElementById('edit-item-form');
|
|
||||||
if (editForm) {
|
|
||||||
editForm.addEventListener('submit', function(e) {
|
|
||||||
e.preventDefault();
|
|
||||||
|
|
||||||
const itemId = document.getElementById('edit-item-id').value;
|
|
||||||
const formData = new FormData(this);
|
|
||||||
|
|
||||||
fetch(`/edit_item/${itemId}`, {
|
|
||||||
method: 'POST',
|
|
||||||
body: formData
|
|
||||||
})
|
|
||||||
.then(response => {
|
|
||||||
if (response.ok) {
|
|
||||||
closeEditModal();
|
|
||||||
// Reload items to show updated information
|
|
||||||
loadItems();
|
|
||||||
// Show success message
|
|
||||||
const successMsg = document.createElement('div');
|
|
||||||
successMsg.className = 'alert alert-success';
|
|
||||||
successMsg.textContent = 'Item wurde erfolgreich aktualisiert!';
|
|
||||||
successMsg.style.position = 'fixed';
|
|
||||||
successMsg.style.top = '20px';
|
|
||||||
successMsg.style.right = '20px';
|
|
||||||
successMsg.style.zIndex = '9999';
|
|
||||||
document.body.appendChild(successMsg);
|
|
||||||
setTimeout(() => {
|
|
||||||
if (successMsg.parentNode) {
|
|
||||||
successMsg.parentNode.removeChild(successMsg);
|
|
||||||
}
|
|
||||||
}, 3000);
|
|
||||||
} else {
|
|
||||||
alert('Fehler beim Aktualisieren des Items');
|
|
||||||
}
|
|
||||||
})
|
|
||||||
.catch(error => {
|
|
||||||
console.error('Error updating item:', error);
|
|
||||||
alert('Fehler beim Aktualisieren des Items');
|
|
||||||
});
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Duplication function
|
// Duplication function
|
||||||
function duplicateItem(itemId) {
|
function duplicateItem(itemId) {
|
||||||
@@ -5632,10 +5162,62 @@ document.addEventListener('DOMContentLoaded', ()=>{
|
|||||||
futureAppointments.sort((a, b) => new Date(a.date) - new Date(b.date));
|
futureAppointments.sort((a, b) => new Date(a.date) - new Date(b.date));
|
||||||
return futureAppointments[0];
|
return futureAppointments[0];
|
||||||
}
|
}
|
||||||
</script>
|
|
||||||
|
|
||||||
<!-- Include edit item functions -->
|
// Load location options
|
||||||
{% include "edit_item_functions.html" %}
|
function loadLocationOptions() {
|
||||||
|
fetch('/get_predefined_locations')
|
||||||
|
.then(response => response.json())
|
||||||
|
.then(data => {
|
||||||
|
const ortSelect = document.getElementById('ort');
|
||||||
|
if (ortSelect) {
|
||||||
|
// Clear existing options except the first one
|
||||||
|
while (ortSelect.children.length > 1) {
|
||||||
|
ortSelect.removeChild(ortSelect.lastChild);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Add new options - data.locations contains the array
|
||||||
|
data.locations.forEach(location => {
|
||||||
|
const option = document.createElement('option');
|
||||||
|
option.value = location;
|
||||||
|
option.textContent = location;
|
||||||
|
ortSelect.appendChild(option);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.catch(error => {
|
||||||
|
console.error('Error loading location options:', error);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Function to add new location
|
||||||
|
function addNewLocation() {
|
||||||
|
const newLocationInput = document.getElementById('new-location-input');
|
||||||
|
const newLocation = newLocationInput.value.trim();
|
||||||
|
|
||||||
|
if (!newLocation) {
|
||||||
|
alert('Bitte geben Sie einen Ort ein.');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Add to dropdown
|
||||||
|
const ortSelect = document.getElementById('ort');
|
||||||
|
const option = document.createElement('option');
|
||||||
|
option.value = newLocation;
|
||||||
|
option.textContent = newLocation;
|
||||||
|
option.selected = true;
|
||||||
|
ortSelect.appendChild(option);
|
||||||
|
|
||||||
|
// Hide the input container
|
||||||
|
document.getElementById('new-location-container').style.display = 'none';
|
||||||
|
newLocationInput.value = '';
|
||||||
|
}
|
||||||
|
|
||||||
|
// Function to cancel adding new location
|
||||||
|
function cancelAddLocation() {
|
||||||
|
document.getElementById('new-location-container').style.display = 'none';
|
||||||
|
document.getElementById('new-location-input').value = '';
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
<!-- Include reset item functions -->
|
<!-- Include reset item functions -->
|
||||||
{% include "reset_item_functions.html" %}
|
{% include "reset_item_functions.html" %}
|
||||||
@@ -5864,16 +5446,4 @@ document.addEventListener('DOMContentLoaded', ()=>{
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
</style>
|
</style>
|
||||||
|
|
||||||
{% if open_item %}
|
|
||||||
<script>
|
|
||||||
document.addEventListener("DOMContentLoaded", function() {
|
|
||||||
if (typeof openEditModalFromServer === 'function') {
|
|
||||||
setTimeout(function() {
|
|
||||||
openEditModalFromServer('{{ open_item }}');
|
|
||||||
}, 500);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
</script>
|
|
||||||
{% endif %}
|
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
|
|||||||
@@ -19,7 +19,7 @@
|
|||||||
<div class="col-md-4">
|
<div class="col-md-4">
|
||||||
<div class="card mb-4">
|
<div class="card mb-4">
|
||||||
<div class="card-header">
|
<div class="card-header">
|
||||||
<h2 class="card-title h5 mb-0">{{ filter_names.get('1', 'Fach/Kategorie') }} (Filter 1)</h2>
|
<h2 class="card-title h5 mb-0">{{ filter_names.get('1', 'Jahrgang') }} (Filter 1)</h2>
|
||||||
</div>
|
</div>
|
||||||
<div class="card-body">
|
<div class="card-body">
|
||||||
<form method="POST" action="{{ url_for('add_filter_value', filter_num=1) }}" class="mb-4">
|
<form method="POST" action="{{ url_for('add_filter_value', filter_num=1) }}" class="mb-4">
|
||||||
@@ -67,7 +67,7 @@
|
|||||||
<div class="col-md-4">
|
<div class="col-md-4">
|
||||||
<div class="card mb-4">
|
<div class="card mb-4">
|
||||||
<div class="card-header">
|
<div class="card-header">
|
||||||
<h2 class="card-title h5 mb-0">{{ filter_names.get('2', 'System/Bereich') }} (Filter 2)</h2>
|
<h2 class="card-title h5 mb-0">{{ filter_names.get('2', 'Fach') }} (Filter 2)</h2>
|
||||||
</div>
|
</div>
|
||||||
<div class="card-body">
|
<div class="card-body">
|
||||||
<form method="POST" action="{{ url_for('add_filter_value', filter_num=2) }}" class="mb-4">
|
<form method="POST" action="{{ url_for('add_filter_value', filter_num=2) }}" class="mb-4">
|
||||||
@@ -110,54 +110,6 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- Filter 3 -->
|
|
||||||
<div class="col-md-4">
|
|
||||||
<div class="card mb-4">
|
|
||||||
<div class="card-header">
|
|
||||||
<h2 class="card-title h5 mb-0">{{ filter_names.get('3', 'Typ/Art') }} (Filter 3)</h2>
|
|
||||||
</div>
|
|
||||||
<div class="card-body">
|
|
||||||
<form method="POST" action="{{ url_for('add_filter_value', filter_num=3) }}" class="mb-4">
|
|
||||||
<div class="input-group">
|
|
||||||
<input type="text" name="value" class="form-control" placeholder="Neuer Wert..." required>
|
|
||||||
<button type="submit" class="btn btn-primary">Hinzufügen</button>
|
|
||||||
</div>
|
|
||||||
</form>
|
|
||||||
|
|
||||||
<h5 class="mb-3">Vorhandene Werte</h5>
|
|
||||||
{% if filter3_values %}
|
|
||||||
<div class="list-group">
|
|
||||||
{% for value in filter3_values %}
|
|
||||||
<div class="list-group-item">
|
|
||||||
<div class="d-flex justify-content-between align-items-center mb-2">
|
|
||||||
<span>{{ value }}</span>
|
|
||||||
<div>
|
|
||||||
<button type="button" class="btn btn-sm btn-secondary me-1" onclick="toggleEdit('edit-3-{{ loop.index }}')">Bearbeiten</button>
|
|
||||||
<form method="POST" action="{{ url_for('remove_filter_value', filter_num=3, value=value) }}" class="d-inline">
|
|
||||||
<button type="submit" class="btn btn-sm btn-danger"
|
|
||||||
onclick="return confirm('Sind Sie sicher, dass Sie den Wert \"' + '{{ value }}'.replace(/'/g, '\\\'') + '\" löschen möchten?');">
|
|
||||||
Entfernen
|
|
||||||
</button>
|
|
||||||
</form>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<form id="edit-3-{{ loop.index }}" method="POST" action="{{ url_for('edit_filter_value', filter_num=3, old_value=value) }}" style="display: none;" class="mt-2">
|
|
||||||
<div class="input-group input-group-sm">
|
|
||||||
<input type="text" name="new_value" class="form-control" value="{{ value }}" required>
|
|
||||||
<button type="submit" class="btn btn-primary" onclick="return confirm('Tipp: Das Ändern des Namens aktualisiert auch alle Einträge in der Datenbank, die diesen Filter verwenden. Fortfahren?');">Speichern</button>
|
|
||||||
<button type="button" class="btn btn-secondary" onclick="toggleEdit('edit-3-{{ loop.index }}')">Abbrechen</button>
|
|
||||||
</div>
|
|
||||||
</form>
|
|
||||||
</div>
|
|
||||||
{% endfor %}
|
|
||||||
</div>
|
|
||||||
{% else %}
|
|
||||||
<div class="alert alert-info">Keine Werte definiert.</div>
|
|
||||||
{% endif %}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="alert alert-warning">
|
<div class="alert alert-warning">
|
||||||
|
|||||||
+207
-166
@@ -6,7 +6,7 @@
|
|||||||
<div class="container">
|
<div class="container">
|
||||||
<div class="header-section">
|
<div class="header-section">
|
||||||
<h1>Neuen Benutzer registrieren</h1>
|
<h1>Neuen Benutzer registrieren</h1>
|
||||||
<p class="subtitle">Erstellen Sie ein neues Benutzerkonto und legen Sie Zugriffsrechte fest</p>
|
<p class="subtitle">Erstellen Sie ein neues Benutzerkonto oder importieren Sie mehrere Benutzer per CSV</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="flash-container">
|
<div class="flash-container">
|
||||||
@@ -23,7 +23,43 @@
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="content">
|
<div class="content">
|
||||||
|
<!-- 1. CSV BULK IMPORT CARD -->
|
||||||
|
<div class="form-card" style="margin-bottom: 2rem; border-top: 4px solid #059669;">
|
||||||
|
<div class="card-header" style="margin-bottom: 1rem;">
|
||||||
|
<h2>Massenregistrierung via CSV</h2>
|
||||||
|
<p class="subtitle" style="color: #4b5563;">
|
||||||
|
Laden Sie eine CSV-Datei hoch (Format: <code>Vorname, Nachname</code>).
|
||||||
|
Benutzernamen und sichere Passwörter werden serverseitig generiert. Nach dem Upload erhalten Sie direkt ein PDF mit Zugangsdaten (2 pro Seite zum Ausschneiden).
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<form method="POST" action="{{ url_for('register_csv') }}" enctype="multipart/form-data">
|
||||||
|
<div class="form-group">
|
||||||
|
<label for="permission-preset-csv">Berechtigungs-Preset für alle CSV-Benutzer</label>
|
||||||
|
<select id="permission-preset-csv" name="permission_preset" class="form-select" style="margin-bottom: 1rem;">
|
||||||
|
{% for preset_key, preset in permission_presets.items() %}
|
||||||
|
<option value="{{ preset_key }}">{{ preset.label }}</option>
|
||||||
|
{% endfor %}
|
||||||
|
</select>
|
||||||
|
|
||||||
|
<label for="csv_file">CSV-Datei auswählen</label>
|
||||||
|
<div class="input-container">
|
||||||
|
<span class="input-icon">📄</span>
|
||||||
|
<input type="file" id="csv_file" name="csv_file" accept=".csv" required style="padding: 10px;">
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="form-group form-actions" style="margin-top: 1.5rem;">
|
||||||
|
<button type="submit" class="action-button" style="background-color: #059669; color: white;">
|
||||||
|
📥 CSV Importieren & Zugangsdaten-PDF Herunterladen
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- 2. SINGLE USER REGISTRATION CARD -->
|
||||||
<div class="form-card">
|
<div class="form-card">
|
||||||
|
<h2>Einzelnen Benutzer registrieren</h2>
|
||||||
<form method="POST" action="{{ url_for('register') }}">
|
<form method="POST" action="{{ url_for('register') }}">
|
||||||
|
|
||||||
<div class="form-group">
|
<div class="form-group">
|
||||||
@@ -32,11 +68,13 @@
|
|||||||
<span class="input-icon">👤</span>
|
<span class="input-icon">👤</span>
|
||||||
<input type="text" id="name" name="name" placeholder="Geben Sie den Vornamen ein" required onchange="generateUsername()" oninput="generateUsername()">
|
<input type="text" id="name" name="name" placeholder="Geben Sie den Vornamen ein" required onchange="generateUsername()" oninput="generateUsername()">
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<label for="last-name">Nachname</label>
|
<label for="last-name">Nachname</label>
|
||||||
<div class="input-container">
|
<div class="input-container">
|
||||||
<span class="input-icon">👤</span>
|
<span class="input-icon">👤</span>
|
||||||
<input type="text" id="last-name" name="last-name" placeholder="Geben Sie den Nachnamen ein" required onchange="generateUsername()" oninput="generateUsername()">
|
<input type="text" id="last-name" name="last-name" placeholder="Geben Sie den Nachnamen ein" required onchange="generateUsername()" oninput="generateUsername()">
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<label for="username">Benutzername <span style="color: #9ca3af;">(Vorschau - wird serverseitig finalisiert)</span></label>
|
<label for="username">Benutzername <span style="color: #9ca3af;">(Vorschau - wird serverseitig finalisiert)</span></label>
|
||||||
<div class="input-container">
|
<div class="input-container">
|
||||||
<span class="input-icon">👤</span>
|
<span class="input-icon">👤</span>
|
||||||
@@ -44,7 +82,7 @@
|
|||||||
</div>
|
</div>
|
||||||
<p class="anonymize-hint">Klarnamen werden nur zur Erzeugung des Benutzernamens als Kürzel (z.B. SimFri) verwendet; bei Kollision wird automatisch ein Buchstabe mehr genommen.</p>
|
<p class="anonymize-hint">Klarnamen werden nur zur Erzeugung des Benutzernamens als Kürzel (z.B. SimFri) verwendet; bei Kollision wird automatisch ein Buchstabe mehr genommen.</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="form-group">
|
<div class="form-group">
|
||||||
<label for="password">Passwort</label>
|
<label for="password">Passwort</label>
|
||||||
<div class="password-rules" id="password-rules" aria-live="polite">
|
<div class="password-rules" id="password-rules" aria-live="polite">
|
||||||
@@ -57,20 +95,21 @@
|
|||||||
<li id="pw-rule-symbol" class="pw-rule">Mindestens ein Sonderzeichen</li>
|
<li id="pw-rule-symbol" class="pw-rule">Mindestens ein Sonderzeichen</li>
|
||||||
</ul>
|
</ul>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="input-wrapper">
|
<div class="input-wrapper">
|
||||||
<div class="input-container">
|
<div class="input-container">
|
||||||
<span class="input-icon">🔒</span>
|
<span class="input-icon">🔒</span>
|
||||||
<!-- HTML5 Pattern blockiert unsichere Passwörter vor dem Absenden -->
|
<input
|
||||||
<input
|
type="password"
|
||||||
id="password"
|
id="password"
|
||||||
name="password"
|
name="password"
|
||||||
placeholder="Geben Sie ein sicheres Passwort ein"
|
placeholder="Geben Sie ein sicheres Passwort ein"
|
||||||
required
|
required
|
||||||
pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[^a-zA-Z0-9]).{12,}">
|
pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[^a-zA-Z0-9]).{12,}">
|
||||||
|
<button type="button" id="toggle-pw-btn" class="toggle-pw-btn" onclick="togglePasswordVisibility()" style="background:none; border:none; cursor:pointer; padding-right:10px;">👁️</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="pw-actions">
|
<div class="pw-actions" style="margin-top: 8px;">
|
||||||
<button type="button" class="btn-secondary" onclick="generateSecurePassword()">Passwort generieren</button>
|
<button type="button" class="btn-secondary" onclick="generateSecurePassword()">Passwort generieren</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -120,6 +159,163 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
// Hilfsfunktion: Umlaute auflösen und Sonderzeichen entfernen
|
||||||
|
function cleanNameForUsername(text) {
|
||||||
|
if (!text) return '';
|
||||||
|
let cleaned = text.trim().toLowerCase()
|
||||||
|
.replace(/ä/g, 'ae')
|
||||||
|
.replace(/ö/g, 'oe')
|
||||||
|
.replace(/ü/g, 'ue')
|
||||||
|
.replace(/ß/g, 'ss')
|
||||||
|
.replace(/[^a-z]/g, '');
|
||||||
|
return cleaned;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Hilfsfunktion: Erster Buchstabe groß
|
||||||
|
function formatPart(str, len) {
|
||||||
|
if (!str) return '';
|
||||||
|
const part = str.slice(0, len);
|
||||||
|
return part.charAt(0).toUpperCase() + part.slice(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Generiert die Vorschau des Benutzernamens (z.B. SimFri)
|
||||||
|
function generateUsername() {
|
||||||
|
const firstName = cleanNameForUsername(document.getElementById('name').value);
|
||||||
|
const lastName = cleanNameForUsername(document.getElementById('last-name').value);
|
||||||
|
let username = '';
|
||||||
|
|
||||||
|
if (firstName && lastName) {
|
||||||
|
username = formatPart(firstName, 3) + formatPart(lastName, 3);
|
||||||
|
} else if (firstName) {
|
||||||
|
username = formatPart(firstName, 6);
|
||||||
|
} else if (lastName) {
|
||||||
|
username = formatPart(lastName, 6);
|
||||||
|
}
|
||||||
|
|
||||||
|
const usernameField = document.getElementById('username');
|
||||||
|
if (usernameField) {
|
||||||
|
usernameField.value = username || '';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// PASSWORT GENERATOR
|
||||||
|
function generateSecurePassword() {
|
||||||
|
const length = 16;
|
||||||
|
const charsetLower = "abcdefghijklmnopqrstuvwxyz";
|
||||||
|
const charsetUpper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
|
||||||
|
const charsetNum = "0123456789";
|
||||||
|
const charsetSym = "!@#$%^&*()_+~|}{[]:;?><,.-=";
|
||||||
|
|
||||||
|
let password = "";
|
||||||
|
// Garantiert mindestens 1 Zeichen aus jeder Kategorie
|
||||||
|
password += charsetLower[Math.floor(Math.random() * charsetLower.length)];
|
||||||
|
password += charsetUpper[Math.floor(Math.random() * charsetUpper.length)];
|
||||||
|
password += charsetNum[Math.floor(Math.random() * charsetNum.length)];
|
||||||
|
password += charsetSym[Math.floor(Math.random() * charsetSym.length)];
|
||||||
|
|
||||||
|
const allChars = charsetLower + charsetUpper + charsetNum + charsetSym;
|
||||||
|
// Restliche Zeichen auffüllen
|
||||||
|
for (let i = 4; i < length; i++) {
|
||||||
|
password += allChars[Math.floor(Math.random() * allChars.length)];
|
||||||
|
}
|
||||||
|
|
||||||
|
// Passwort durchmischen
|
||||||
|
password = password.split('').sort(() => 0.5 - Math.random()).join('');
|
||||||
|
|
||||||
|
const pwField = document.getElementById('password');
|
||||||
|
pwField.value = password;
|
||||||
|
|
||||||
|
// Automatisch sichtbar machen
|
||||||
|
pwField.type = 'text';
|
||||||
|
const toggleBtn = document.getElementById('toggle-pw-btn');
|
||||||
|
if (toggleBtn) toggleBtn.textContent = '🙈';
|
||||||
|
|
||||||
|
updatePasswordRules();
|
||||||
|
}
|
||||||
|
|
||||||
|
// PASSWORT SICHTBARKEIT UMSCHALTEN
|
||||||
|
function togglePasswordVisibility() {
|
||||||
|
const pwField = document.getElementById('password');
|
||||||
|
const toggleBtn = document.getElementById('toggle-pw-btn');
|
||||||
|
if (pwField.type === "password") {
|
||||||
|
pwField.type = "text";
|
||||||
|
if (toggleBtn) toggleBtn.textContent = '🙈';
|
||||||
|
} else {
|
||||||
|
pwField.type = "password";
|
||||||
|
if (toggleBtn) toggleBtn.textContent = '👁️';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Globale Funktion für Passwort-Update
|
||||||
|
function updatePasswordRules() {
|
||||||
|
const passwordInput = document.getElementById('password');
|
||||||
|
if (!passwordInput) return;
|
||||||
|
|
||||||
|
const value = String(passwordInput.value || '');
|
||||||
|
|
||||||
|
const setRuleState = (id, ok) => {
|
||||||
|
const node = document.getElementById(id);
|
||||||
|
if (node) node.classList.toggle('ok', !!ok);
|
||||||
|
};
|
||||||
|
|
||||||
|
setRuleState('pw-rule-length', value.length >= 12);
|
||||||
|
setRuleState('pw-rule-lower', /[a-z]/.test(value));
|
||||||
|
setRuleState('pw-rule-upper', /[A-Z]/.test(value));
|
||||||
|
setRuleState('pw-rule-digit', /[0-9]/.test(value));
|
||||||
|
setRuleState('pw-rule-symbol', /[^A-Za-z0-9]/.test(value));
|
||||||
|
}
|
||||||
|
|
||||||
|
document.addEventListener('DOMContentLoaded', function () {
|
||||||
|
const permissionPresets = {{ permission_presets | tojson }};
|
||||||
|
const presetSelect = document.getElementById('permission-preset');
|
||||||
|
const useCustomPermissions = document.getElementById('use-custom-permissions');
|
||||||
|
const customPermissions = document.getElementById('custom-permissions');
|
||||||
|
|
||||||
|
function applyPresetToPermissionForm(presetKey) {
|
||||||
|
const preset = permissionPresets[presetKey] || {};
|
||||||
|
const actionDefaults = preset.actions || {};
|
||||||
|
const pageDefaults = preset.pages || {};
|
||||||
|
|
||||||
|
document.querySelectorAll('.permission-action-checkbox').forEach(function (checkbox) {
|
||||||
|
const key = checkbox.name.replace('action_', '');
|
||||||
|
checkbox.checked = !!actionDefaults[key];
|
||||||
|
});
|
||||||
|
|
||||||
|
document.querySelectorAll('.permission-page-checkbox').forEach(function (checkbox) {
|
||||||
|
const key = checkbox.name.replace('page_', '');
|
||||||
|
checkbox.checked = !!pageDefaults[key];
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function toggleCustomPermissions() {
|
||||||
|
if (!useCustomPermissions || !customPermissions) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
customPermissions.style.display = useCustomPermissions.checked ? 'block' : 'none';
|
||||||
|
}
|
||||||
|
|
||||||
|
if (presetSelect) {
|
||||||
|
presetSelect.addEventListener('change', function () {
|
||||||
|
applyPresetToPermissionForm(this.value);
|
||||||
|
});
|
||||||
|
applyPresetToPermissionForm(presetSelect.value);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (useCustomPermissions) {
|
||||||
|
useCustomPermissions.addEventListener('change', toggleCustomPermissions);
|
||||||
|
toggleCustomPermissions();
|
||||||
|
}
|
||||||
|
|
||||||
|
const passwordInput = document.getElementById('password');
|
||||||
|
if (passwordInput) {
|
||||||
|
passwordInput.addEventListener('input', updatePasswordRules);
|
||||||
|
passwordInput.addEventListener('blur', updatePasswordRules);
|
||||||
|
updatePasswordRules();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
</script>
|
||||||
|
|
||||||
<style>
|
<style>
|
||||||
:root {
|
:root {
|
||||||
--primary-color: #3498db;
|
--primary-color: #3498db;
|
||||||
@@ -310,11 +506,11 @@ input::placeholder {
|
|||||||
padding: 0 1rem;
|
padding: 0 1rem;
|
||||||
margin: 1rem auto;
|
margin: 1rem auto;
|
||||||
}
|
}
|
||||||
|
|
||||||
.content {
|
.content {
|
||||||
padding: 1.5rem;
|
padding: 1.5rem;
|
||||||
}
|
}
|
||||||
|
|
||||||
.header-section h1 {
|
.header-section h1 {
|
||||||
font-size: 2rem;
|
font-size: 2rem;
|
||||||
}
|
}
|
||||||
@@ -437,159 +633,4 @@ input::placeholder {
|
|||||||
}
|
}
|
||||||
</style>
|
</style>
|
||||||
|
|
||||||
<script>
|
|
||||||
// Hilfsfunktion: Umlaute auflösen und Sonderzeichen entfernen
|
|
||||||
function cleanNameForUsername(text) {
|
|
||||||
if (!text) return '';
|
|
||||||
let cleaned = text.trim().toLowerCase()
|
|
||||||
.replace(/ä/g, 'ae')
|
|
||||||
.replace(/ö/g, 'oe')
|
|
||||||
.replace(/ü/g, 'ue')
|
|
||||||
.replace(/ß/g, 'ss')
|
|
||||||
.replace(/[^a-z]/g, '');
|
|
||||||
return cleaned;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Hilfsfunktion: Erster Buchstabe groß
|
|
||||||
function formatPart(str, len) {
|
|
||||||
if (!str) return '';
|
|
||||||
const part = str.slice(0, len);
|
|
||||||
return part.charAt(0).toUpperCase() + part.slice(1);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Generiert die Vorschau des Benutzernamens (z.B. SimFri)
|
|
||||||
function generateUsername() {
|
|
||||||
const firstName = cleanNameForUsername(document.getElementById('name').value);
|
|
||||||
const lastName = cleanNameForUsername(document.getElementById('last-name').value);
|
|
||||||
let username = '';
|
|
||||||
|
|
||||||
if (firstName && lastName) {
|
|
||||||
username = formatPart(firstName, 3) + formatPart(lastName, 3);
|
|
||||||
} else if (firstName) {
|
|
||||||
username = formatPart(firstName, 6);
|
|
||||||
} else if (lastName) {
|
|
||||||
username = formatPart(lastName, 6);
|
|
||||||
}
|
|
||||||
|
|
||||||
const usernameField = document.getElementById('username');
|
|
||||||
if (usernameField) {
|
|
||||||
usernameField.value = username || '';
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// PASSWORT GENERATOR
|
|
||||||
function generateSecurePassword() {
|
|
||||||
const length = 16;
|
|
||||||
const charsetLower = "abcdefghijklmnopqrstuvwxyz";
|
|
||||||
const charsetUpper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
|
|
||||||
const charsetNum = "0123456789";
|
|
||||||
const charsetSym = "!@#$%^&*()_+~|}{[]:;?><,.-=";
|
|
||||||
|
|
||||||
let password = "";
|
|
||||||
// Garantiert mindestens 1 Zeichen aus jeder Kategorie
|
|
||||||
password += charsetLower[Math.floor(Math.random() * charsetLower.length)];
|
|
||||||
password += charsetUpper[Math.floor(Math.random() * charsetUpper.length)];
|
|
||||||
password += charsetNum[Math.floor(Math.random() * charsetNum.length)];
|
|
||||||
password += charsetSym[Math.floor(Math.random() * charsetSym.length)];
|
|
||||||
|
|
||||||
const allChars = charsetLower + charsetUpper + charsetNum + charsetSym;
|
|
||||||
// Restliche Zeichen auffüllen
|
|
||||||
for (let i = 4; i < length; i++) {
|
|
||||||
password += allChars[Math.floor(Math.random() * allChars.length)];
|
|
||||||
}
|
|
||||||
|
|
||||||
// Passwort durchmischen
|
|
||||||
password = password.split('').sort(() => 0.5 - Math.random()).join('');
|
|
||||||
|
|
||||||
const pwField = document.getElementById('password');
|
|
||||||
pwField.value = password;
|
|
||||||
|
|
||||||
// Automatisch sichtbar machen, damit der User es kopieren kann
|
|
||||||
pwField.type = 'text';
|
|
||||||
document.getElementById('toggle-pw-btn').textContent = '🙈';
|
|
||||||
|
|
||||||
updatePasswordRules();
|
|
||||||
}
|
|
||||||
|
|
||||||
// PASSWORT SICHTBARKEIT UMSCHALTEN
|
|
||||||
function togglePasswordVisibility() {
|
|
||||||
const pwField = document.getElementById('password');
|
|
||||||
const toggleBtn = document.getElementById('toggle-pw-btn');
|
|
||||||
if (pwField.type === "password") {
|
|
||||||
pwField.type = "text";
|
|
||||||
toggleBtn.textContent = '🙈';
|
|
||||||
} else {
|
|
||||||
pwField.type = "password";
|
|
||||||
toggleBtn.textContent = '👁️';
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Globale Funktion für Passwort-Update
|
|
||||||
function updatePasswordRules() {
|
|
||||||
const passwordInput = document.getElementById('password');
|
|
||||||
if (!passwordInput) return;
|
|
||||||
|
|
||||||
const value = String(passwordInput.value || '');
|
|
||||||
|
|
||||||
const setRuleState = (id, ok) => {
|
|
||||||
const node = document.getElementById(id);
|
|
||||||
if (node) node.classList.toggle('ok', !!ok);
|
|
||||||
};
|
|
||||||
|
|
||||||
setRuleState('pw-rule-length', value.length >= 12);
|
|
||||||
setRuleState('pw-rule-lower', /[a-z]/.test(value));
|
|
||||||
setRuleState('pw-rule-upper', /[A-Z]/.test(value));
|
|
||||||
setRuleState('pw-rule-digit', /[0-9]/.test(value));
|
|
||||||
setRuleState('pw-rule-symbol', /[^A-Za-z0-9]/.test(value));
|
|
||||||
}
|
|
||||||
|
|
||||||
document.addEventListener('DOMContentLoaded', function () {
|
|
||||||
const permissionPresets = {{ permission_presets | tojson }};
|
|
||||||
const presetSelect = document.getElementById('permission-preset');
|
|
||||||
const useCustomPermissions = document.getElementById('use-custom-permissions');
|
|
||||||
const customPermissions = document.getElementById('custom-permissions');
|
|
||||||
|
|
||||||
function applyPresetToPermissionForm(presetKey) {
|
|
||||||
const preset = permissionPresets[presetKey] || {};
|
|
||||||
const actionDefaults = preset.actions || {};
|
|
||||||
const pageDefaults = preset.pages || {};
|
|
||||||
|
|
||||||
document.querySelectorAll('.permission-action-checkbox').forEach(function (checkbox) {
|
|
||||||
const key = checkbox.name.replace('action_', '');
|
|
||||||
checkbox.checked = !!actionDefaults[key];
|
|
||||||
});
|
|
||||||
|
|
||||||
document.querySelectorAll('.permission-page-checkbox').forEach(function (checkbox) {
|
|
||||||
const key = checkbox.name.replace('page_', '');
|
|
||||||
checkbox.checked = !!pageDefaults[key];
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
function toggleCustomPermissions() {
|
|
||||||
if (!useCustomPermissions || !customPermissions) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
customPermissions.style.display = useCustomPermissions.checked ? 'block' : 'none';
|
|
||||||
}
|
|
||||||
|
|
||||||
if (presetSelect) {
|
|
||||||
presetSelect.addEventListener('change', function () {
|
|
||||||
applyPresetToPermissionForm(this.value);
|
|
||||||
});
|
|
||||||
applyPresetToPermissionForm(presetSelect.value);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (useCustomPermissions) {
|
|
||||||
useCustomPermissions.addEventListener('change', toggleCustomPermissions);
|
|
||||||
toggleCustomPermissions();
|
|
||||||
}
|
|
||||||
|
|
||||||
const passwordInput = document.getElementById('password');
|
|
||||||
if (passwordInput) {
|
|
||||||
passwordInput.addEventListener('input', updatePasswordRules);
|
|
||||||
passwordInput.addEventListener('blur', updatePasswordRules);
|
|
||||||
updatePasswordRules();
|
|
||||||
}
|
|
||||||
});
|
|
||||||
</script>
|
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
@@ -229,7 +229,7 @@
|
|||||||
<div class="container">
|
<div class="container">
|
||||||
<div class="student-card-header">
|
<div class="student-card-header">
|
||||||
<div>
|
<div>
|
||||||
<h1>📚 Bibliotheksausweise (Bibliotek)</h1>
|
<h1>📚 Bibliotheksausweise (Bibliothek)</h1>
|
||||||
</div>
|
</div>
|
||||||
<div class="export-buttons">
|
<div class="export-buttons">
|
||||||
<a href="{{ url_for('student_card_barcode_download') }}" class="btn-print" style="background: #28a745;">📥 Alle Ausweise (PDF)</a>
|
<a href="{{ url_for('student_card_barcode_download') }}" class="btn-print" style="background: #28a745;">📥 Alle Ausweise (PDF)</a>
|
||||||
|
|||||||
@@ -280,7 +280,7 @@
|
|||||||
<button type="button" data-target-step="0">1. Startseite</button>
|
<button type="button" data-target-step="0">1. Startseite</button>
|
||||||
<button type="button" data-target-step="1">2. {{ 'Artikel erfassen' if is_admin else 'Artikel finden' }}</button>
|
<button type="button" data-target-step="1">2. {{ 'Artikel erfassen' if is_admin else 'Artikel finden' }}</button>
|
||||||
{% if library_module_enabled %}
|
{% if library_module_enabled %}
|
||||||
<button type="button" data-target-step="2">3. Bibliotek</button>
|
<button type="button" data-target-step="2">3. Bibliothek</button>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
<button type="button" data-target-step="{{ '3' if library_module_enabled else '2' }}">4. Alltag</button>
|
<button type="button" data-target-step="{{ '3' if library_module_enabled else '2' }}">4. Alltag</button>
|
||||||
</div>
|
</div>
|
||||||
@@ -341,7 +341,7 @@
|
|||||||
|
|
||||||
{% if library_module_enabled %}
|
{% if library_module_enabled %}
|
||||||
<article class="workflow-step" data-step-index="2" data-step-key="library">
|
<article class="workflow-step" data-step-index="2" data-step-key="library">
|
||||||
<h3>Bibliotek-Bereich</h3>
|
<h3>Bibliothek-Bereich</h3>
|
||||||
<p>Dieser Bereich ist speziell für Bücher und Medienausleihe.</p>
|
<p>Dieser Bereich ist speziell für Bücher und Medienausleihe.</p>
|
||||||
<ul>
|
<ul>
|
||||||
{% if is_admin %}
|
{% if is_admin %}
|
||||||
@@ -358,7 +358,7 @@
|
|||||||
</ul>
|
</ul>
|
||||||
|
|
||||||
<div class="tutorial-actions">
|
<div class="tutorial-actions">
|
||||||
<a class="btn btn-outline-primary btn-sm" href="{{ url_for('library_view') }}">Zur Bibliotek</a>
|
<a class="btn btn-outline-primary btn-sm" href="{{ url_for('library_view') }}">Zur Bibliothek</a>
|
||||||
{% if is_admin %}
|
{% if is_admin %}
|
||||||
<a class="btn btn-outline-secondary btn-sm" href="{{ url_for('library_loans_admin') }}">Ausleihen ansehen</a>
|
<a class="btn btn-outline-secondary btn-sm" href="{{ url_for('library_loans_admin') }}">Ausleihen ansehen</a>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
|
|||||||
+166
-59
@@ -761,6 +761,21 @@
|
|||||||
<h1>{{ page_title|default('Artikel hochladen') }}</h1>
|
<h1>{{ page_title|default('Artikel hochladen') }}</h1>
|
||||||
<form method="POST" action="{{ url_for('upload_item') }}" enctype="multipart/form-data">
|
<form method="POST" action="{{ url_for('upload_item') }}" enctype="multipart/form-data">
|
||||||
<input type="hidden" name="upload_mode" value="{{ upload_mode|default('item') }}">
|
<input type="hidden" name="upload_mode" value="{{ upload_mode|default('item') }}">
|
||||||
|
|
||||||
|
{% if show_library_features %}
|
||||||
|
<div class="form-group">
|
||||||
|
<label for="isbn">ISBN/Barcode (für Bild-Suche):</label>
|
||||||
|
<div class="isbn-input-group">
|
||||||
|
<input type="text" id="isbn" name="isbn" placeholder="ISBN oder Barcode eingeben..." required>
|
||||||
|
<button type="button" id="scan-isbn-btn" class="fetch-isbn-button">Barcode scannen</button>
|
||||||
|
<button type="button" class="fetch-isbn-button" onclick="fetchBookInfo('upload')">Informationen abrufen</button>
|
||||||
|
</div>
|
||||||
|
<div id="isbn-scanner" style="width:100%; max-width:520px; display:none; margin-top:10px;"></div>
|
||||||
|
<small id="isbn-scan-status" style="display:block; color:#666; margin-top:6px;">Scannen oder manuell eingeben. Gültige ISBNs helfen beim Abruf von Buchdaten, andere Codes werden trotzdem akzeptiert.</small>
|
||||||
|
<div id="book-info-container" class="book-info-container"></div>
|
||||||
|
</div>
|
||||||
|
{% endif %}
|
||||||
|
|
||||||
<div class="form-group">
|
<div class="form-group">
|
||||||
<label for="name">Name:</label>
|
<label for="name">Name:</label>
|
||||||
<input type="text" id="name" name="name" required>
|
<input type="text" id="name" name="name" required>
|
||||||
@@ -784,7 +799,44 @@
|
|||||||
<label for="beschreibung">Beschreibung:</label>
|
<label for="beschreibung">Beschreibung:</label>
|
||||||
<textarea id="beschreibung" name="beschreibung" required></textarea>
|
<textarea id="beschreibung" name="beschreibung" required></textarea>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<div class="form-group">
|
||||||
|
<label for="scan_mode">Erfassungs-Modus:</label>
|
||||||
|
<select id="scan_mode" name="scan_mode" class="form-control" onchange="toggleScanMode()">
|
||||||
|
<option value="single">Einzel-Code (Scanner stoppt nach 1 Scan) ↓ </option>
|
||||||
|
<option value="continuous">Fortlaufend scannen (Mehrere Codes nacheinander)</option>
|
||||||
|
<option value="range">Code-Bereich generieren (z.B. ABC-001 bis ABC-010)</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div id="range_generator_group" class="form-group" style="display:none; background: #f9f9f9; padding: 15px; border-radius: 5px; border: 1px solid #ddd; margin-bottom: 15px;">
|
||||||
|
<label style="font-weight: bold;">Code-Bereich automatisch generieren:</label>
|
||||||
|
<div style="display: flex; gap: 10px; margin-bottom: 10px; align-items: center;">
|
||||||
|
<input type="text" id="range_prefix" placeholder="Präfix optional (z.B. IT-)" class="form-control" style="flex: 2;">
|
||||||
|
<input type="number" id="range_start" placeholder="Start (z.B. 1)" class="form-control" style="flex: 1;">
|
||||||
|
<span style="font-weight: bold;">bis</span>
|
||||||
|
<input type="text" id="range_end" placeholder="Ende (z.B. 020)" class="form-control" style="flex: 1;">
|
||||||
|
</div>
|
||||||
|
<small style="display:block; color:#666; margin-bottom: 10px;">Tipp: Der Präfix ist optional. Die Anzahl der Ziffern im "Ende"-Feld bestimmt die führenden Nullen (z.B. Ende "050" macht aus Start "1" einen "001").</small>
|
||||||
|
<button type="button" class="btn btn-secondary" onclick="generateCodeRange()">Bereich generieren & einfügen</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="form-group" id="primary_code_group">
|
||||||
|
<label for="code_4">Basis-Code</label>
|
||||||
|
<div style="display: flex; gap: 10px;">
|
||||||
|
<input type="text" id="code_4" name="code_4" class="form-control" placeholder="Haupt-Barcode" required>
|
||||||
|
<button type="button" id="scan-code4-btn" class="btn btn-primary">Barcode scannen</button>
|
||||||
|
</div>
|
||||||
|
<div id="code4-scanner" style="display:none; margin-top: 10px;"></div>
|
||||||
|
<small id="code4-scan-status" class="form-text text-muted"></small>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="form-group" id="individual_codes_group">
|
||||||
|
<label for="individual_codes">Weitere Einzelcodes (je Zeile ein Code)</label>
|
||||||
|
<textarea id="individual_codes" name="individual_codes" rows="6" placeholder="z.B. ABC-001 ABC-002" class="form-control"></textarea>
|
||||||
|
<small style="display:block; color:#666; margin-top: 5px;">Bei Anzahl > 1 können hier individuelle Codes pro Item gesetzt werden. Der Scanner setzt immer zuerst den Basis-Code im Feld oben; weitere Einzelcodes werden hier angehängt.</small>
|
||||||
|
</div>
|
||||||
|
|
||||||
{% if show_library_features %}
|
{% if show_library_features %}
|
||||||
<!-- Library Mode: Single Customizable Filter -->
|
<!-- Library Mode: Single Customizable Filter -->
|
||||||
<div class="filter-inputs">
|
<div class="filter-inputs">
|
||||||
@@ -800,9 +852,9 @@
|
|||||||
</select>
|
</select>
|
||||||
<small style="display:block; color:#666;">Wählen Sie einen Medientyp aus zur Klassifizierung.</small>
|
<small style="display:block; color:#666;">Wählen Sie einen Medientyp aus zur Klassifizierung.</small>
|
||||||
</div>
|
</div>
|
||||||
<h3>Kategorie/Typ:</h3>
|
<h3>Kategorie/Typ/Fach:</h3>
|
||||||
<div class="form-group">
|
<div class="form-group">
|
||||||
<input type="text" name="library_category" id="library_category" placeholder="z.B. Belletristik, Sachbücher, Nachschlagewerke, etc.">
|
<input type="text" name="library_category" id="library_category" placeholder="z.B. Belletristik, Sachbücher, Nachschlagewerke, etc. (optional)">
|
||||||
<small style="display:block; color:#666;">Geben Sie hier eine beliebige Kategorie ein zur freien Klassifizierung.</small>
|
<small style="display:block; color:#666;">Geben Sie hier eine beliebige Kategorie ein zur freien Klassifizierung.</small>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -902,42 +954,6 @@
|
|||||||
<label for="anschaffungskosten">Anschaffungskosten (€)</label>
|
<label for="anschaffungskosten">Anschaffungskosten (€)</label>
|
||||||
<input id="anschaffungskosten" name="anschaffungskosten">
|
<input id="anschaffungskosten" name="anschaffungskosten">
|
||||||
</div>
|
</div>
|
||||||
<div class="form-group">
|
|
||||||
<label for="scan_mode">Erfassungs-Modus:</label>
|
|
||||||
<select id="scan_mode" name="scan_mode" class="form-control" onchange="toggleScanMode()">
|
|
||||||
<option value="single">Einzel-Code (Scanner stoppt nach 1 Scan)</option>
|
|
||||||
<option value="continuous">Fortlaufend scannen (Mehrere Codes nacheinander)</option>
|
|
||||||
<option value="range">Code-Bereich generieren (z.B. ABC-001 bis ABC-010)</option>
|
|
||||||
</select>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div id="range_generator_group" class="form-group" style="display:none; background: #f9f9f9; padding: 15px; border-radius: 5px; border: 1px solid #ddd; margin-bottom: 15px;">
|
|
||||||
<label style="font-weight: bold;">Code-Bereich automatisch generieren:</label>
|
|
||||||
<div style="display: flex; gap: 10px; margin-bottom: 10px; align-items: center;">
|
|
||||||
<input type="text" id="range_prefix" placeholder="Präfix (z.B. IT-)" class="form-control" style="flex: 2;">
|
|
||||||
<input type="number" id="range_start" placeholder="Start (z.B. 1)" class="form-control" style="flex: 1;">
|
|
||||||
<span style="font-weight: bold;">bis</span>
|
|
||||||
<input type="text" id="range_end" placeholder="Ende (z.B. 020)" class="form-control" style="flex: 1;">
|
|
||||||
</div>
|
|
||||||
<small style="display:block; color:#666; margin-bottom: 10px;">Tipp: Die Anzahl der Ziffern im "Ende"-Feld bestimmt die führenden Nullen (z.B. Ende "050" macht aus Start "1" einen "001").</small>
|
|
||||||
<button type="button" class="btn btn-secondary" onclick="generateCodeRange()">Bereich generieren & einfügen</button>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="form-group" id="primary_code_group">
|
|
||||||
<label for="code_4">Basis-Code</label>
|
|
||||||
<div style="display: flex; gap: 10px;">
|
|
||||||
<input type="text" id="code_4" name="code_4" class="form-control" placeholder="Haupt-Barcode" required>
|
|
||||||
<button type="button" id="scan-code4-btn" class="btn btn-primary">Barcode scannen</button>
|
|
||||||
</div>
|
|
||||||
<div id="code4-scanner" style="display:none; margin-top: 10px;"></div>
|
|
||||||
<small id="code4-scan-status" class="form-text text-muted"></small>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="form-group" id="individual_codes_group">
|
|
||||||
<label for="individual_codes">Weitere Einzelcodes (je Zeile ein Code)</label>
|
|
||||||
<textarea id="individual_codes" name="individual_codes" rows="6" placeholder="z.B. ABC-001 ABC-002" class="form-control"></textarea>
|
|
||||||
<small style="display:block; color:#666; margin-top: 5px;">Bei Anzahl > 1 können hier individuelle Codes pro Item gesetzt werden. Der Scanner setzt immer zuerst den Basis-Code im Feld oben; weitere Einzelcodes werden hier angehängt.</small>
|
|
||||||
</div>
|
|
||||||
<!-- Image upload (hidden for library mode) -->
|
<!-- Image upload (hidden for library mode) -->
|
||||||
<div class="form-group" {% if show_library_features %}style="display:none;"{% endif %}>
|
<div class="form-group" {% if show_library_features %}style="display:none;"{% endif %}>
|
||||||
<label for="images">Bilder/Videos:</label>
|
<label for="images">Bilder/Videos:</label>
|
||||||
@@ -946,27 +962,12 @@
|
|||||||
<!-- Add image preview area -->
|
<!-- Add image preview area -->
|
||||||
<div class="image-preview-container" id="image-preview-container"></div>
|
<div class="image-preview-container" id="image-preview-container"></div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- ISBN fields (library page only) -->
|
|
||||||
{% if show_library_features %}
|
|
||||||
<div class="form-group">
|
|
||||||
<label for="isbn">ISBN/Barcode (für Bild-Suche):</label>
|
|
||||||
<div class="isbn-input-group">
|
|
||||||
<input type="text" id="isbn" name="isbn" placeholder="ISBN oder Barcode eingeben..." required>
|
|
||||||
<button type="button" id="scan-isbn-btn" class="fetch-isbn-button">Barcode scannen</button>
|
|
||||||
<button type="button" class="fetch-isbn-button" onclick="fetchBookInfo('upload')">Informationen abrufen</button>
|
|
||||||
</div>
|
|
||||||
<div id="isbn-scanner" style="width:100%; max-width:520px; display:none; margin-top:10px;"></div>
|
|
||||||
<small id="isbn-scan-status" style="display:block; color:#666; margin-top:6px;">Scannen oder manuell eingeben. Gültige ISBNs helfen beim Abruf von Buchdaten, andere Codes werden trotzdem akzeptiert.</small>
|
|
||||||
<div id="book-info-container" class="book-info-container"></div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="form-group">
|
<div class="form-group">
|
||||||
<label for="reservierbar" style="display:inline-block; width:auto; margin-right:10px;">Reservierbar:</label>
|
<label for="reservierbar" style="display:inline-block; width:auto; margin-right:10px;">Reservierbar:</label>
|
||||||
<input type="checkbox" id="reservierbar" name="reservierbar" style="width:auto;">
|
<input type="checkbox" id="reservierbar" name="reservierbar" style="width:auto;">
|
||||||
<small style="display:block; color:#666;">Wenn deaktiviert, kann der Artikel nicht im Voraus reserviert werden (Sofort-Ausleihe bleibt möglich).</small>
|
<small style="display:block; color:#666;">Wenn deaktiviert, kann der Artikel nicht im Voraus reserviert werden (Sofort-Ausleihe bleibt möglich).</small>
|
||||||
</div>
|
</div>
|
||||||
{% endif %}
|
|
||||||
|
|
||||||
<button type="submit" class="submit-button">{{ 'Bücher hochladen' if show_library_features else 'Artikel hochladen' }}</button>
|
<button type="submit" class="submit-button">{{ 'Bücher hochladen' if show_library_features else 'Artikel hochladen' }}</button>
|
||||||
</form>
|
</form>
|
||||||
@@ -1023,6 +1024,90 @@
|
|||||||
<script>
|
<script>
|
||||||
const libraryModuleEnabled = {{ 'true' if library_module_enabled else 'false' }};
|
const libraryModuleEnabled = {{ 'true' if library_module_enabled else 'false' }};
|
||||||
|
|
||||||
|
function getFocusableFormFields(form) {
|
||||||
|
if (!form) return [];
|
||||||
|
return Array.from(form.querySelectorAll('input, select, textarea, button'))
|
||||||
|
.filter((element) => {
|
||||||
|
if (element.disabled || element.getAttribute('aria-hidden') === 'true') return false;
|
||||||
|
const style = window.getComputedStyle(element);
|
||||||
|
if (style.display === 'none' || style.visibility === 'hidden') return false;
|
||||||
|
const tagName = element.tagName.toLowerCase();
|
||||||
|
const type = (element.type || '').toLowerCase();
|
||||||
|
return tagName !== 'button' || type !== 'button';
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function focusNextFormField(currentField) {
|
||||||
|
const form = currentField && currentField.form ? currentField.form : null;
|
||||||
|
const fields = getFocusableFormFields(form || document);
|
||||||
|
const currentIndex = fields.indexOf(currentField);
|
||||||
|
|
||||||
|
if (currentIndex >= 0) {
|
||||||
|
for (let i = currentIndex + 1; i < fields.length; i++) {
|
||||||
|
const nextField = fields[i];
|
||||||
|
const nextStyle = window.getComputedStyle(nextField);
|
||||||
|
if (nextStyle.display !== 'none' && nextStyle.visibility !== 'hidden') {
|
||||||
|
nextField.focus();
|
||||||
|
if (nextField.tagName.toLowerCase() === 'select') {
|
||||||
|
nextField.click();
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (form) {
|
||||||
|
const submitButton = form.querySelector('button[type="submit"]');
|
||||||
|
if (submitButton) {
|
||||||
|
submitButton.focus();
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleIsbnLookupFromScanner() {
|
||||||
|
const isbnField = document.getElementById('isbn');
|
||||||
|
if (!isbnField) return false;
|
||||||
|
|
||||||
|
const normalizedIsbn = typeof normalizeIsbnClient === 'function' ? normalizeIsbnClient(isbnField.value) : isbnField.value.trim();
|
||||||
|
if (!normalizedIsbn) return false;
|
||||||
|
|
||||||
|
if (typeof updateIsbnLiveValidation === 'function') {
|
||||||
|
updateIsbnLiveValidation();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (typeof fetchBookInfo === 'function') {
|
||||||
|
fetchBookInfo('upload');
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
document.addEventListener('DOMContentLoaded', function () {
|
||||||
|
document.querySelectorAll('form').forEach(function (form) {
|
||||||
|
form.addEventListener('keydown', function (event) {
|
||||||
|
const target = event.target;
|
||||||
|
if (event.key !== 'Enter') return;
|
||||||
|
if (!target || target.tagName === 'TEXTAREA' && !event.shiftKey) return;
|
||||||
|
const tagName = target.tagName.toLowerCase();
|
||||||
|
const type = (target.type || '').toLowerCase();
|
||||||
|
if (!['input', 'select', 'textarea'].includes(tagName)) return;
|
||||||
|
if (['button', 'submit', 'reset', 'file', 'checkbox', 'radio', 'hidden'].includes(type)) return;
|
||||||
|
|
||||||
|
event.preventDefault();
|
||||||
|
|
||||||
|
if (target.id === 'isbn' || target.name === 'isbn') {
|
||||||
|
handleIsbnLookupFromScanner();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
focusNextFormField(target);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
// Function to check if a file is a video
|
// Function to check if a file is a video
|
||||||
function isVideoFile(filename) {
|
function isVideoFile(filename) {
|
||||||
const videoExtensions = ['.mp4', '.mov', '.avi', '.mkv', '.webm', '.flv', '.m4v', '.3gp'];
|
const videoExtensions = ['.mp4', '.mov', '.avi', '.mkv', '.webm', '.flv', '.m4v', '.3gp'];
|
||||||
@@ -1194,7 +1279,7 @@
|
|||||||
let generatedCodes = [];
|
let generatedCodes = [];
|
||||||
for (let i = start; i <= end; i++) {
|
for (let i = start; i <= end; i++) {
|
||||||
let numStr = i.toString().padStart(paddingLength, '0');
|
let numStr = i.toString().padStart(paddingLength, '0');
|
||||||
generatedCodes.push(`${prefix}${numStr}`);
|
generatedCodes.push(prefix ? `${prefix}${numStr}` : numStr);
|
||||||
}
|
}
|
||||||
|
|
||||||
const codeField = document.getElementById('code_4');
|
const codeField = document.getElementById('code_4');
|
||||||
@@ -1384,10 +1469,32 @@
|
|||||||
scanModeSelect.addEventListener('change', toggleScanMode);
|
scanModeSelect.addEventListener('change', toggleScanMode);
|
||||||
}
|
}
|
||||||
|
|
||||||
// 4. ISBN Live-Validierung
|
// 4. ISBN Live-Validierung und automatische Abfrage nach Scan/Enter
|
||||||
const isbnInput = document.getElementById('isbn');
|
const isbnInput = document.getElementById('isbn');
|
||||||
if (isbnInput && typeof updateIsbnLiveValidation === 'function') {
|
if (isbnInput) {
|
||||||
isbnInput.addEventListener('input', updateIsbnLiveValidation);
|
if (typeof updateIsbnLiveValidation === 'function') {
|
||||||
|
isbnInput.addEventListener('input', updateIsbnLiveValidation);
|
||||||
|
}
|
||||||
|
|
||||||
|
let isbnLookupTimer = null;
|
||||||
|
isbnInput.addEventListener('input', function () {
|
||||||
|
clearTimeout(isbnLookupTimer);
|
||||||
|
const normalizedIsbn = typeof normalizeIsbnClient === 'function' ? normalizeIsbnClient(isbnInput.value) : isbnInput.value.trim();
|
||||||
|
if (normalizedIsbn) {
|
||||||
|
isbnLookupTimer = setTimeout(function () {
|
||||||
|
handleIsbnLookupFromScanner();
|
||||||
|
}, 250);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
isbnInput.addEventListener('change', function () {
|
||||||
|
if (typeof normalizeIsbnClient === 'function') {
|
||||||
|
const normalizedIsbn = normalizeIsbnClient(isbnInput.value);
|
||||||
|
if (normalizedIsbn) {
|
||||||
|
handleIsbnLookupFromScanner();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
// Load predefined filter values for dropdowns
|
// Load predefined filter values for dropdowns
|
||||||
|
|||||||
@@ -17,15 +17,11 @@
|
|||||||
<div class="user-management-container">
|
<div class="user-management-container">
|
||||||
<h2>Benutzer</h2>
|
<h2>Benutzer</h2>
|
||||||
|
|
||||||
<form method="POST" action="{{ url_for('admin_anonymize_names') }}" class="mb-3">
|
<div class="mb-3">
|
||||||
<button
|
<a href="{{ url_for('register') }}" class="btn btn-success">
|
||||||
type="submit"
|
Neuen Benutzer registrieren
|
||||||
class="btn btn-outline-danger"
|
</a>
|
||||||
onclick="return confirm('Sollen alle gespeicherten Klarnamen dauerhaft in Synonym-Kuerzel umgewandelt werden?')"
|
</div>
|
||||||
>
|
|
||||||
Gespeicherte Namen anonymisieren
|
|
||||||
</button>
|
|
||||||
</form>
|
|
||||||
|
|
||||||
<div class="filter-bar mb-3">
|
<div class="filter-bar mb-3">
|
||||||
<div class="row g-2 align-items-end">
|
<div class="row g-2 align-items-end">
|
||||||
|
|||||||
+35
-17
@@ -166,6 +166,11 @@ def _find_registered_tenant_id(candidate):
|
|||||||
return None
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def _resolve_registered_tenant_id(candidate):
|
||||||
|
"""Return the canonical registered tenant id for a candidate, or None."""
|
||||||
|
return _find_registered_tenant_id(candidate)
|
||||||
|
|
||||||
|
|
||||||
def _is_ip_host(hostname):
|
def _is_ip_host(hostname):
|
||||||
hostname = str(hostname or '').strip()
|
hostname = str(hostname or '').strip()
|
||||||
if not hostname:
|
if not hostname:
|
||||||
@@ -185,6 +190,8 @@ def get_tenant_config(tenant_id=None):
|
|||||||
ctx = get_tenant_context()
|
ctx = get_tenant_context()
|
||||||
tenant_id = ctx.tenant_id if ctx and ctx.tenant_id else 'default'
|
tenant_id = ctx.tenant_id if ctx and ctx.tenant_id else 'default'
|
||||||
|
|
||||||
|
tenant_id = _resolve_registered_tenant_id(tenant_id) or tenant_id
|
||||||
|
|
||||||
if tenant_id in TENANT_REGISTRY:
|
if tenant_id in TENANT_REGISTRY:
|
||||||
return TENANT_REGISTRY[tenant_id] or {}
|
return TENANT_REGISTRY[tenant_id] or {}
|
||||||
|
|
||||||
@@ -481,20 +488,22 @@ class TenantContext:
|
|||||||
or request.args.get('tenantId', '').strip()
|
or request.args.get('tenantId', '').strip()
|
||||||
)
|
)
|
||||||
if tenant_from_query:
|
if tenant_from_query:
|
||||||
matched_tenant = _find_registered_tenant_id(tenant_from_query) or tenant_from_query
|
matched_tenant = _resolve_registered_tenant_id(tenant_from_query)
|
||||||
self.tenant_id = matched_tenant
|
if matched_tenant:
|
||||||
self.config = get_tenant_config(matched_tenant)
|
self.tenant_id = matched_tenant
|
||||||
session['tenant_id'] = matched_tenant
|
self.config = get_tenant_config(matched_tenant)
|
||||||
return self._get_db_name(matched_tenant)
|
session['tenant_id'] = matched_tenant
|
||||||
|
return self._get_db_name(matched_tenant)
|
||||||
|
|
||||||
# Priority 1: X-Tenant-ID header (for testing/internal APIs)
|
# Priority 1: X-Tenant-ID header (for testing/internal APIs)
|
||||||
tenant_from_header = request.headers.get('X-Tenant-ID', '').strip()
|
tenant_from_header = request.headers.get('X-Tenant-ID', '').strip()
|
||||||
if tenant_from_header:
|
if tenant_from_header:
|
||||||
matched_tenant = _find_registered_tenant_id(tenant_from_header) or tenant_from_header
|
matched_tenant = _resolve_registered_tenant_id(tenant_from_header)
|
||||||
self.tenant_id = matched_tenant
|
if matched_tenant:
|
||||||
self.config = get_tenant_config(matched_tenant)
|
self.tenant_id = matched_tenant
|
||||||
session['tenant_id'] = matched_tenant
|
self.config = get_tenant_config(matched_tenant)
|
||||||
return self._get_db_name(matched_tenant)
|
session['tenant_id'] = matched_tenant
|
||||||
|
return self._get_db_name(matched_tenant)
|
||||||
|
|
||||||
# Priority 2: Port/host based tenant mapping
|
# Priority 2: Port/host based tenant mapping
|
||||||
host_candidates = _request_host_candidates()
|
host_candidates = _request_host_candidates()
|
||||||
@@ -544,11 +553,11 @@ class TenantContext:
|
|||||||
if len(parts) >= 2:
|
if len(parts) >= 2:
|
||||||
potential_subdomain = parts[0]
|
potential_subdomain = parts[0]
|
||||||
if potential_subdomain not in ('www', 'api', 'admin', 'app', 'mail'):
|
if potential_subdomain not in ('www', 'api', 'admin', 'app', 'mail'):
|
||||||
matched_tenant = _find_registered_tenant_id(potential_subdomain)
|
matched_tenant = _resolve_registered_tenant_id(potential_subdomain)
|
||||||
if not matched_tenant and potential_subdomain.startswith('school'):
|
if not matched_tenant and potential_subdomain.startswith('school'):
|
||||||
matched_tenant = _find_registered_tenant_id('schule' + potential_subdomain[len('school'):])
|
matched_tenant = _resolve_registered_tenant_id('schule' + potential_subdomain[len('school'):])
|
||||||
elif not matched_tenant and potential_subdomain.startswith('schule'):
|
elif not matched_tenant and potential_subdomain.startswith('schule'):
|
||||||
matched_tenant = _find_registered_tenant_id('school' + potential_subdomain[len('schule'):])
|
matched_tenant = _resolve_registered_tenant_id('school' + potential_subdomain[len('schule'):])
|
||||||
if matched_tenant:
|
if matched_tenant:
|
||||||
self.subdomain = potential_subdomain
|
self.subdomain = potential_subdomain
|
||||||
self.tenant_id = matched_tenant
|
self.tenant_id = matched_tenant
|
||||||
@@ -565,12 +574,21 @@ class TenantContext:
|
|||||||
# Priority 4: sticky tenant from the authenticated session
|
# Priority 4: sticky tenant from the authenticated session
|
||||||
session_tenant = session.get('tenant_id', '').strip() if session.get('tenant_id') else ''
|
session_tenant = session.get('tenant_id', '').strip() if session.get('tenant_id') else ''
|
||||||
if session_tenant:
|
if session_tenant:
|
||||||
self.tenant_id = session_tenant
|
matched_tenant = _resolve_registered_tenant_id(session_tenant)
|
||||||
self.config = get_tenant_config(session_tenant)
|
if matched_tenant:
|
||||||
|
self.tenant_id = matched_tenant
|
||||||
|
self.config = get_tenant_config(matched_tenant)
|
||||||
|
session['tenant_id'] = matched_tenant
|
||||||
|
logger.info(
|
||||||
|
f"Tenant resolution by session: host={primary_host} tenant={matched_tenant} config={self.config}"
|
||||||
|
)
|
||||||
|
return self._get_db_name(matched_tenant)
|
||||||
|
session.pop('tenant_id', None)
|
||||||
logger.info(
|
logger.info(
|
||||||
f"Tenant resolution by session: host={primary_host} tenant={session_tenant} config={self.config}"
|
"Discarded stale tenant session reference: host=%s tenant=%s",
|
||||||
|
primary_host,
|
||||||
|
session_tenant,
|
||||||
)
|
)
|
||||||
return self._get_db_name(session_tenant)
|
|
||||||
|
|
||||||
# Fallback to default tenant if no tenant identifier found.
|
# Fallback to default tenant if no tenant identifier found.
|
||||||
# If no explicit 'default' tenant config exists, use configured MongoDB DB.
|
# If no explicit 'default' tenant config exists, use configured MongoDB DB.
|
||||||
|
|||||||
+282
-6
@@ -12,6 +12,250 @@ fi
|
|||||||
# Resolve script directory so config paths are deterministic even when called via sudo
|
# Resolve script directory so config paths are deterministic even when called via sudo
|
||||||
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||||
CONFIG_FILE="$SCRIPT_DIR/config.json"
|
CONFIG_FILE="$SCRIPT_DIR/config.json"
|
||||||
|
NGINX_DOMAIN_BASE="${INVENTAR_TENANT_DOMAIN_BASE:-invario-software.de}"
|
||||||
|
NGINX_PROXY_HOST="${INVENTAR_NGINX_PROXY_HOST:-172.17.0.1}"
|
||||||
|
NGINX_SITES_AVAILABLE="${INVENTAR_NGINX_SITES_AVAILABLE:-/etc/nginx/sites-available}"
|
||||||
|
NGINX_SITES_ENABLED="${INVENTAR_NGINX_SITES_ENABLED:-/etc/nginx/sites-enabled}"
|
||||||
|
NGINX_SITE_PREFIX="${INVENTAR_NGINX_SITE_PREFIX:-inventarsystem}"
|
||||||
|
CERTBOT_EMAIL="${INVENTAR_CERTBOT_EMAIL:-}"
|
||||||
|
|
||||||
|
tenant_domain() {
|
||||||
|
printf '%s.%s' "$1" "$NGINX_DOMAIN_BASE"
|
||||||
|
}
|
||||||
|
|
||||||
|
tenant_nginx_site_path() {
|
||||||
|
printf '%s/%s-%s.conf' "$NGINX_SITES_AVAILABLE" "$NGINX_SITE_PREFIX" "$1"
|
||||||
|
}
|
||||||
|
|
||||||
|
tenant_nginx_enabled_path() {
|
||||||
|
printf '%s/%s-%s.conf' "$NGINX_SITES_ENABLED" "$NGINX_SITE_PREFIX" "$1"
|
||||||
|
}
|
||||||
|
|
||||||
|
run_host_command() {
|
||||||
|
if [ "$(id -u)" -eq 0 ]; then
|
||||||
|
"$@"
|
||||||
|
elif command -v sudo >/dev/null 2>&1; then
|
||||||
|
sudo "$@"
|
||||||
|
else
|
||||||
|
return 127
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
|
||||||
|
reload_host_nginx() {
|
||||||
|
if command -v nginx >/dev/null 2>&1 || command -v sudo >/dev/null 2>&1; then
|
||||||
|
if ! run_host_command nginx -t; then
|
||||||
|
echo "Warning: nginx configuration test failed; skipping reload."
|
||||||
|
return 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
if command -v systemctl >/dev/null 2>&1; then
|
||||||
|
if ! run_host_command systemctl reload nginx; then
|
||||||
|
echo "Warning: systemctl reload nginx failed."
|
||||||
|
return 1
|
||||||
|
fi
|
||||||
|
else
|
||||||
|
if ! run_host_command nginx -s reload; then
|
||||||
|
echo "Warning: nginx reload failed."
|
||||||
|
return 1
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
|
||||||
|
write_tenant_nginx_config() {
|
||||||
|
local tenant_id="$1"
|
||||||
|
local port="$2"
|
||||||
|
local domain site_path enabled_path
|
||||||
|
|
||||||
|
domain="$(tenant_domain "$tenant_id")"
|
||||||
|
site_path="$(tenant_nginx_site_path "$tenant_id")"
|
||||||
|
enabled_path="$(tenant_nginx_enabled_path "$tenant_id")"
|
||||||
|
|
||||||
|
if [ -z "$port" ]; then
|
||||||
|
echo "Warning: No port configured for tenant '$tenant_id'; skipping nginx vhost creation."
|
||||||
|
return 0
|
||||||
|
fi
|
||||||
|
|
||||||
|
if ! run_host_command mkdir -p "$NGINX_SITES_AVAILABLE" "$NGINX_SITES_ENABLED"; then
|
||||||
|
echo "Warning: Unable to prepare nginx site directories; skipping reverse-proxy setup."
|
||||||
|
return 0
|
||||||
|
fi
|
||||||
|
|
||||||
|
local have_cert=false
|
||||||
|
|
||||||
|
if [ -f "/etc/letsencrypt/live/$domain/fullchain.pem" ] && [ -f "/etc/letsencrypt/live/$domain/privkey.pem" ]; then
|
||||||
|
have_cert=true
|
||||||
|
else
|
||||||
|
if [ "$(id -u)" -eq 0 ]; then
|
||||||
|
cat > "$site_path" <<EOF
|
||||||
|
# ==========================================
|
||||||
|
# INVENTARSYSTEM ($tenant_id)
|
||||||
|
# ==========================================
|
||||||
|
server {
|
||||||
|
listen 80;
|
||||||
|
listen [::]:80;
|
||||||
|
server_name $domain;
|
||||||
|
client_max_body_size 100M;
|
||||||
|
|
||||||
|
location / {
|
||||||
|
proxy_pass http://$NGINX_PROXY_HOST:$port;
|
||||||
|
proxy_set_header Host \$host;
|
||||||
|
proxy_set_header X-Real-IP \$remote_addr;
|
||||||
|
proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
|
||||||
|
proxy_set_header X-Forwarded-Proto \$scheme;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
EOF
|
||||||
|
else
|
||||||
|
sudo tee "$site_path" >/dev/null <<EOF
|
||||||
|
# ==========================================
|
||||||
|
# INVENTARSYSTEM ($tenant_id)
|
||||||
|
# ==========================================
|
||||||
|
server {
|
||||||
|
listen 80;
|
||||||
|
listen [::]:80;
|
||||||
|
server_name $domain;
|
||||||
|
client_max_body_size 100M;
|
||||||
|
|
||||||
|
location / {
|
||||||
|
proxy_pass http://$NGINX_PROXY_HOST:$port;
|
||||||
|
proxy_set_header Host \$host;
|
||||||
|
proxy_set_header X-Real-IP \$remote_addr;
|
||||||
|
proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
|
||||||
|
proxy_set_header X-Forwarded-Proto \$scheme;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
EOF
|
||||||
|
fi
|
||||||
|
|
||||||
|
if ! run_host_command ln -sfn "$site_path" "$enabled_path"; then
|
||||||
|
echo "Warning: Could not enable nginx site for tenant '$tenant_id'."
|
||||||
|
return 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
if ! reload_host_nginx; then
|
||||||
|
echo "Warning: Initial nginx reload failed for tenant '$tenant_id'."
|
||||||
|
fi
|
||||||
|
|
||||||
|
if command -v certbot >/dev/null 2>&1 || command -v sudo >/dev/null 2>&1; then
|
||||||
|
local certbot_args=(certbot --nginx --non-interactive --agree-tos -d "$domain")
|
||||||
|
if [ -n "$CERTBOT_EMAIL" ]; then
|
||||||
|
certbot_args+=(--email "$CERTBOT_EMAIL")
|
||||||
|
else
|
||||||
|
certbot_args+=(--register-unsafely-without-email)
|
||||||
|
fi
|
||||||
|
|
||||||
|
if ! run_host_command "${certbot_args[@]}"; then
|
||||||
|
echo "Warning: certbot failed for tenant '$tenant_id'; keeping HTTP-only vhost for now."
|
||||||
|
return 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
have_cert=true
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [ "$have_cert" != true ]; then
|
||||||
|
echo "Warning: No TLS certificate available for tenant '$tenant_id'; leaving HTTP-only nginx config in place."
|
||||||
|
return 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [ "$(id -u)" -eq 0 ]; then
|
||||||
|
cat > "$site_path" <<EOF
|
||||||
|
# ==========================================
|
||||||
|
# INVENTARSYSTEM ($tenant_id)
|
||||||
|
# ==========================================
|
||||||
|
server {
|
||||||
|
listen 443 ssl;
|
||||||
|
listen [::]:443 ssl;
|
||||||
|
server_name $domain;
|
||||||
|
client_max_body_size 100M;
|
||||||
|
|
||||||
|
ssl_certificate /etc/letsencrypt/live/$domain/fullchain.pem;
|
||||||
|
ssl_certificate_key /etc/letsencrypt/live/$domain/privkey.pem;
|
||||||
|
|
||||||
|
location / {
|
||||||
|
proxy_pass http://$NGINX_PROXY_HOST:$port;
|
||||||
|
proxy_set_header Host \$host;
|
||||||
|
proxy_set_header X-Real-IP \$remote_addr;
|
||||||
|
proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
|
||||||
|
proxy_set_header X-Forwarded-Proto \$scheme;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
# Gezielte HTTP zu HTTPS Weiterleitung für $tenant_id
|
||||||
|
server {
|
||||||
|
listen 80;
|
||||||
|
listen [::]:80;
|
||||||
|
server_name $domain;
|
||||||
|
return 301 https://$domain\$request_uri;
|
||||||
|
}
|
||||||
|
EOF
|
||||||
|
else
|
||||||
|
sudo tee "$site_path" >/dev/null <<EOF
|
||||||
|
# ==========================================
|
||||||
|
# INVENTARSYSTEM ($tenant_id)
|
||||||
|
# ==========================================
|
||||||
|
server {
|
||||||
|
listen 443 ssl;
|
||||||
|
listen [::]:443 ssl;
|
||||||
|
server_name $domain;
|
||||||
|
client_max_body_size 100M;
|
||||||
|
|
||||||
|
ssl_certificate /etc/letsencrypt/live/$domain/fullchain.pem;
|
||||||
|
ssl_certificate_key /etc/letsencrypt/live/$domain/privkey.pem;
|
||||||
|
|
||||||
|
location / {
|
||||||
|
proxy_pass http://$NGINX_PROXY_HOST:$port;
|
||||||
|
proxy_set_header Host \$host;
|
||||||
|
proxy_set_header X-Real-IP \$remote_addr;
|
||||||
|
proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
|
||||||
|
proxy_set_header X-Forwarded-Proto \$scheme;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
# Gezielte HTTP zu HTTPS Weiterleitung für $tenant_id
|
||||||
|
server {
|
||||||
|
listen 80;
|
||||||
|
listen [::]:80;
|
||||||
|
server_name $domain;
|
||||||
|
return 301 https://$domain\$request_uri;
|
||||||
|
}
|
||||||
|
EOF
|
||||||
|
fi
|
||||||
|
|
||||||
|
if ! run_host_command ln -sfn "$site_path" "$enabled_path"; then
|
||||||
|
echo "Warning: Could not enable nginx site for tenant '$tenant_id'."
|
||||||
|
return 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
if ! reload_host_nginx; then
|
||||||
|
echo "Warning: nginx reload after tenant '$tenant_id' configuration update failed."
|
||||||
|
return 1
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
|
||||||
|
remove_tenant_nginx_config() {
|
||||||
|
local tenant_id="$1"
|
||||||
|
local domain site_path enabled_path
|
||||||
|
|
||||||
|
domain="$(tenant_domain "$tenant_id")"
|
||||||
|
site_path="$(tenant_nginx_site_path "$tenant_id")"
|
||||||
|
enabled_path="$(tenant_nginx_enabled_path "$tenant_id")"
|
||||||
|
|
||||||
|
if [ -f "$enabled_path" ] || [ -L "$enabled_path" ]; then
|
||||||
|
run_host_command rm -f "$enabled_path" || true
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [ -f "$site_path" ]; then
|
||||||
|
run_host_command rm -f "$site_path" || true
|
||||||
|
fi
|
||||||
|
|
||||||
|
if command -v certbot >/dev/null 2>&1 || command -v sudo >/dev/null 2>&1; then
|
||||||
|
run_host_command certbot delete --cert-name "$domain" --non-interactive >/dev/null 2>&1 || true
|
||||||
|
fi
|
||||||
|
|
||||||
|
reload_host_nginx || true
|
||||||
|
}
|
||||||
|
|
||||||
ensure_runtime_config_json() {
|
ensure_runtime_config_json() {
|
||||||
local config_path backup_path
|
local config_path backup_path
|
||||||
@@ -206,12 +450,30 @@ import Web.modules.database.user as us
|
|||||||
tenant_id = sys.argv[1].lower()
|
tenant_id = sys.argv[1].lower()
|
||||||
mode = sys.argv[2]
|
mode = sys.argv[2]
|
||||||
sanitized = "".join(c for c in tenant_id if c.isalnum() or c == "_")
|
sanitized = "".join(c for c in tenant_id if c.isalnum() or c == "_")
|
||||||
|
db_name = f"inventar_{sanitized}" if sanitized else settings.MONGODB_DB
|
||||||
|
|
||||||
us.add_admin("admin", "admin123", "admin", "admin")
|
client = MongoClient(settings.MONGODB_HOST, settings.MONGODB_PORT)
|
||||||
us.make_admin("admin")
|
db = client[db_name]
|
||||||
|
users = db["users"]
|
||||||
|
permission_defaults = us.build_default_permission_payload("full_access")
|
||||||
|
admin_doc = {
|
||||||
|
"Username": "admin",
|
||||||
|
"Password": us.hashing("admin123"),
|
||||||
|
"Admin": True,
|
||||||
|
"active_ausleihung": None,
|
||||||
|
"name": dp.encrypt_text("admin"),
|
||||||
|
"last_name": dp.encrypt_text("admin"),
|
||||||
|
"IsStudent": False,
|
||||||
|
"PermissionPreset": permission_defaults["preset"],
|
||||||
|
"ActionPermissions": permission_defaults["actions"],
|
||||||
|
"PagePermissions": permission_defaults["pages"],
|
||||||
|
}
|
||||||
|
users.replace_one({"Username": "admin"}, admin_doc, upsert=True)
|
||||||
print("Fallback successfully applied")
|
print("Fallback successfully applied")
|
||||||
|
|
||||||
if mode == "trial":
|
if mode == "trial":
|
||||||
|
client = MongoClient(settings.MONGODB_HOST, settings.MONGODB_PORT)
|
||||||
|
db = client[db_name]
|
||||||
db.settings.update_one(
|
db.settings.update_one(
|
||||||
{"setting_type": "tenant_trial"},
|
{"setting_type": "tenant_trial"},
|
||||||
{"$set": {
|
{"$set": {
|
||||||
@@ -224,6 +486,8 @@ if mode == "trial":
|
|||||||
upsert=True,
|
upsert=True,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
client.close()
|
||||||
|
|
||||||
print(f"Tenant {sys.argv[1]} database initialized. Default admin: admin / admin123")
|
print(f"Tenant {sys.argv[1]} database initialized. Default admin: admin / admin123")
|
||||||
PY
|
PY
|
||||||
}
|
}
|
||||||
@@ -485,15 +749,18 @@ ${YELLOW}Nutzung:${RESET} $0 <befehl> [tenant_id] [optionen]
|
|||||||
|
|
||||||
${BLUE}${BOLD}VERFÜGBARE BEFEHLE:${RESET}
|
${BLUE}${BOLD}VERFÜGBARE BEFEHLE:${RESET}
|
||||||
${GREEN}add${RESET} <tenant_id> [port]
|
${GREEN}add${RESET} <tenant_id> [port]
|
||||||
Legt einen neuen Tenant an, registriert den Port und initialisiert
|
Legt einen neuen Tenant an, registriert den Port, richtet den nginx-Host
|
||||||
die MongoDB-Datenbank mit einem Standard-Admin (${YELLOW}admin / admin123${RESET}).
|
für ${YELLOW}<tenant_id>.invario-software.de${RESET} ein und initialisiert
|
||||||
|
die MongoDB-Datenbank mit einem Standard-Admin (${YELLOW}admin / admin123${RESET}).
|
||||||
|
|
||||||
${GREEN}trial${RESET} <tenant_id> [port] [tage]
|
${GREEN}trial${RESET} <tenant_id> [port] [tage]
|
||||||
Erstellt einen temporären Test-Tenant. Standardlaufzeit: 7 Tage.
|
Erstellt einen temporären Test-Tenant. Standardlaufzeit: 7 Tage.
|
||||||
Läuft automatisch ab und löscht sich selbst.
|
Läuft automatisch ab, löscht sich selbst und bekommt die gleiche nginx/
|
||||||
|
Certbot-Anbindung wie ein normaler Tenant.
|
||||||
|
|
||||||
${GREEN}remove${RESET} [-y|--yes] <tenant_id>
|
${GREEN}remove${RESET} [-y|--yes] <tenant_id>
|
||||||
Löscht einen Tenant, seine Konfiguration, Ports und die Datenbank.
|
Löscht einen Tenant, seine Konfiguration, Ports, nginx-VHost und das
|
||||||
|
zugehörige Let's-Encrypt-Zertifikat sowie die Datenbank.
|
||||||
Nutze ${RED}-y${RESET}, um die Bestätigungsabfrage zu überspringen.
|
Nutze ${RED}-y${RESET}, um die Bestätigungsabfrage zu überspringen.
|
||||||
|
|
||||||
${GREEN}restart-tenant${RESET} <tenant_id>
|
${GREEN}restart-tenant${RESET} <tenant_id>
|
||||||
@@ -554,11 +821,16 @@ case "$COMMAND" in
|
|||||||
register_tenant_port "$TENANT_ID" "$PORT_ARG"
|
register_tenant_port "$TENANT_ID" "$PORT_ARG"
|
||||||
update_runtime_ports "$PORT_ARG"
|
update_runtime_ports "$PORT_ARG"
|
||||||
sync_tenant_port_map
|
sync_tenant_port_map
|
||||||
|
if ! write_tenant_nginx_config "$TENANT_ID" "$PORT_ARG"; then
|
||||||
|
echo "Warning: nginx/certbot provisioning for '$TENANT_ID' could not be completed automatically."
|
||||||
|
fi
|
||||||
if [ -n "$(docker ps -qf 'name=app' | head -n 1)" ]; then
|
if [ -n "$(docker ps -qf 'name=app' | head -n 1)" ]; then
|
||||||
restart_app_container
|
restart_app_container
|
||||||
fi
|
fi
|
||||||
fi
|
fi
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
echo "Adding new tenant '$TENANT_ID'..."
|
echo "Adding new tenant '$TENANT_ID'..."
|
||||||
echo "Initializing database for $TENANT_ID..."
|
echo "Initializing database for $TENANT_ID..."
|
||||||
initialize_tenant_database "$TENANT_ID" "standard"
|
initialize_tenant_database "$TENANT_ID" "standard"
|
||||||
@@ -583,6 +855,9 @@ case "$COMMAND" in
|
|||||||
register_tenant_port "$TENANT_ID" "$PORT_ARG"
|
register_tenant_port "$TENANT_ID" "$PORT_ARG"
|
||||||
update_runtime_ports "$PORT_ARG"
|
update_runtime_ports "$PORT_ARG"
|
||||||
sync_tenant_port_map
|
sync_tenant_port_map
|
||||||
|
if ! write_tenant_nginx_config "$TENANT_ID" "$PORT_ARG"; then
|
||||||
|
echo "Warning: nginx/certbot provisioning for trial tenant '$TENANT_ID' could not be completed automatically."
|
||||||
|
fi
|
||||||
fi
|
fi
|
||||||
|
|
||||||
write_trial_tenant_config "$TENANT_ID" "$PORT_ARG" "$DAYS_ARG"
|
write_trial_tenant_config "$TENANT_ID" "$PORT_ARG" "$DAYS_ARG"
|
||||||
@@ -662,6 +937,7 @@ case "$COMMAND" in
|
|||||||
if [ -n "$port_to_remove" ]; then
|
if [ -n "$port_to_remove" ]; then
|
||||||
remove_runtime_port "$port_to_remove"
|
remove_runtime_port "$port_to_remove"
|
||||||
fi
|
fi
|
||||||
|
remove_tenant_nginx_config "$TENANT_ID"
|
||||||
sync_tenant_port_map
|
sync_tenant_port_map
|
||||||
if [ -n "$(docker ps -qf 'name=app' | head -n 1)" ]; then
|
if [ -n "$(docker ps -qf 'name=app' | head -n 1)" ]; then
|
||||||
restart_app_container
|
restart_app_container
|
||||||
|
|||||||
@@ -9,13 +9,13 @@ LOG_DIR="$PROJECT_DIR/logs"
|
|||||||
LOG_FILE="$LOG_DIR/update.log"
|
LOG_FILE="$LOG_DIR/update.log"
|
||||||
STATE_FILE="$PROJECT_DIR/.release-version"
|
STATE_FILE="$PROJECT_DIR/.release-version"
|
||||||
REPO_SLUG="Invario/Inventarsystem"
|
REPO_SLUG="Invario/Inventarsystem"
|
||||||
API_URL="https://git.invario-software.eu/api/v1/repos/$REPO_SLUG/releases/latest"
|
API_BASE_URL="https://git.invario-software.eu/api/v1/repos/$REPO_SLUG"
|
||||||
BUNDLE_ASSET="inventarsystem-docker-bundle.tar.gz"
|
BUNDLE_ASSET="inventarsystem-docker-bundle.tar.gz"
|
||||||
ENV_FILE="$PROJECT_DIR/.docker-build.env"
|
ENV_FILE="$PROJECT_DIR/.docker-build.env"
|
||||||
APP_IMAGE_REPO="git.invario-software.eu/invario/inventarsystem"
|
APP_IMAGE_REPO="git.invario-software.eu/invario/inventarsystem"
|
||||||
COMPOSE_FILE="docker-compose-multitenant.yml"
|
COMPOSE_FILE="docker-compose-multitenant.yml"
|
||||||
MIN_ROOT_FREE_MB="${INVENTAR_MIN_ROOT_FREE_MB:-2048}"
|
MIN_ROOT_FREE_MB="${INVENTAR_MIN_ROOT_FREE_MB:-2048}"
|
||||||
MODE="release"
|
MODE="stable"
|
||||||
|
|
||||||
mkdir -p "$LOG_DIR"
|
mkdir -p "$LOG_DIR"
|
||||||
chmod 777 "$LOG_DIR" 2>/dev/null || true
|
chmod 777 "$LOG_DIR" 2>/dev/null || true
|
||||||
@@ -119,6 +119,7 @@ usage() {
|
|||||||
Usage: $0 [options]
|
Usage: $0 [options]
|
||||||
|
|
||||||
Options:
|
Options:
|
||||||
|
-dev Install the latest prerelease build
|
||||||
--multitenant Use docker-compose-multitenant.yml (default)
|
--multitenant Use docker-compose-multitenant.yml (default)
|
||||||
-h, --help Show this help message
|
-h, --help Show this help message
|
||||||
EOF
|
EOF
|
||||||
@@ -127,6 +128,10 @@ EOF
|
|||||||
parse_args() {
|
parse_args() {
|
||||||
while [[ $# -gt 0 ]]; do
|
while [[ $# -gt 0 ]]; do
|
||||||
case "$1" in
|
case "$1" in
|
||||||
|
-dev)
|
||||||
|
MODE="development"
|
||||||
|
shift
|
||||||
|
;;
|
||||||
--multitenant)
|
--multitenant)
|
||||||
COMPOSE_FILE="docker-compose-multitenant.yml"
|
COMPOSE_FILE="docker-compose-multitenant.yml"
|
||||||
shift
|
shift
|
||||||
@@ -179,7 +184,8 @@ create_backup() {
|
|||||||
|
|
||||||
fetch_release_metadata() {
|
fetch_release_metadata() {
|
||||||
local meta_file="$1"
|
local meta_file="$1"
|
||||||
curl -fsSL "$API_URL" -o "$meta_file"
|
local endpoint="${2:-latest}"
|
||||||
|
curl -fsSL "$API_BASE_URL/releases/$endpoint" -o "$meta_file"
|
||||||
}
|
}
|
||||||
|
|
||||||
parse_latest_tag() {
|
parse_latest_tag() {
|
||||||
@@ -207,6 +213,124 @@ for asset in data.get('assets', []):
|
|||||||
PY
|
PY
|
||||||
}
|
}
|
||||||
|
|
||||||
|
parse_release_tag() {
|
||||||
|
local meta_file="$1"
|
||||||
|
python3 - <<'PY' "$meta_file"
|
||||||
|
import json, sys
|
||||||
|
with open(sys.argv[1], 'r', encoding='utf-8') as f:
|
||||||
|
data = json.load(f)
|
||||||
|
print(data.get('tag_name', '').strip())
|
||||||
|
PY
|
||||||
|
}
|
||||||
|
|
||||||
|
strip_prerelease_suffix() {
|
||||||
|
local tag="$1"
|
||||||
|
python3 - <<'PY' "$tag"
|
||||||
|
import re, sys
|
||||||
|
tag = sys.argv[1].strip()
|
||||||
|
match = re.match(r'^(v\d+\.\d+\.\d+)', tag)
|
||||||
|
print(match.group(1) if match else tag)
|
||||||
|
PY
|
||||||
|
}
|
||||||
|
|
||||||
|
compare_semver_tags() {
|
||||||
|
local left_tag="$1"
|
||||||
|
local right_tag="$2"
|
||||||
|
python3 - <<'PY' "$left_tag" "$right_tag"
|
||||||
|
import re, sys
|
||||||
|
|
||||||
|
def parse(tag):
|
||||||
|
match = re.match(r'^v(\d+)\.(\d+)\.(\d+)', tag.strip())
|
||||||
|
if not match:
|
||||||
|
return None
|
||||||
|
return tuple(int(part) for part in match.groups())
|
||||||
|
|
||||||
|
left = parse(sys.argv[1])
|
||||||
|
right = parse(sys.argv[2])
|
||||||
|
if left is None or right is None:
|
||||||
|
print('unknown')
|
||||||
|
elif left > right:
|
||||||
|
print('gt')
|
||||||
|
elif left < right:
|
||||||
|
print('lt')
|
||||||
|
else:
|
||||||
|
print('eq')
|
||||||
|
PY
|
||||||
|
}
|
||||||
|
|
||||||
|
parse_prerelease_flag() {
|
||||||
|
local meta_file="$1"
|
||||||
|
python3 - <<'PY' "$meta_file"
|
||||||
|
import json, sys
|
||||||
|
with open(sys.argv[1], 'r', encoding='utf-8') as f:
|
||||||
|
data = json.load(f)
|
||||||
|
print('true' if data.get('prerelease') else 'false')
|
||||||
|
PY
|
||||||
|
}
|
||||||
|
|
||||||
|
latest_stable_release() {
|
||||||
|
local meta_file="$1"
|
||||||
|
local releases_file="$2"
|
||||||
|
local release_count=0
|
||||||
|
|
||||||
|
if ! curl -fsSL "$API_BASE_URL/releases" -o "$releases_file"; then
|
||||||
|
return 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
if ! python3 - <<'PY' "$releases_file" "$meta_file"
|
||||||
|
import json, sys
|
||||||
|
releases_path, target_path = sys.argv[1], sys.argv[2]
|
||||||
|
with open(releases_path, 'r', encoding='utf-8') as f:
|
||||||
|
releases = json.load(f)
|
||||||
|
for release in releases:
|
||||||
|
if not release.get('prerelease') and not release.get('draft'):
|
||||||
|
with open(target_path, 'w', encoding='utf-8') as out:
|
||||||
|
json.dump(release, out)
|
||||||
|
raise SystemExit(0)
|
||||||
|
raise SystemExit(1)
|
||||||
|
PY
|
||||||
|
then
|
||||||
|
return 1
|
||||||
|
fi
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
|
latest_prerelease() {
|
||||||
|
local meta_file="$1"
|
||||||
|
local releases_file="$2"
|
||||||
|
|
||||||
|
if ! curl -fsSL "$API_BASE_URL/releases" -o "$releases_file"; then
|
||||||
|
return 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
if ! python3 - <<'PY' "$releases_file" "$meta_file"
|
||||||
|
import json, sys
|
||||||
|
releases_path, target_path = sys.argv[1], sys.argv[2]
|
||||||
|
with open(releases_path, 'r', encoding='utf-8') as f:
|
||||||
|
releases = json.load(f)
|
||||||
|
for release in releases:
|
||||||
|
if release.get('prerelease') and not release.get('draft'):
|
||||||
|
with open(target_path, 'w', encoding='utf-8') as out:
|
||||||
|
json.dump(release, out)
|
||||||
|
raise SystemExit(0)
|
||||||
|
raise SystemExit(1)
|
||||||
|
PY
|
||||||
|
then
|
||||||
|
return 1
|
||||||
|
fi
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
|
fetch_latest_release_bundle() {
|
||||||
|
local release_meta="$1"
|
||||||
|
local bundle_url
|
||||||
|
bundle_url="$(parse_asset_url "$release_meta" "$BUNDLE_ASSET")"
|
||||||
|
if [ -z "$bundle_url" ]; then
|
||||||
|
return 1
|
||||||
|
fi
|
||||||
|
printf '%s' "$bundle_url"
|
||||||
|
}
|
||||||
|
|
||||||
refresh_runtime_scripts_from_main() {
|
refresh_runtime_scripts_from_main() {
|
||||||
local start_url stop_url restart_url update_url
|
local start_url stop_url restart_url update_url
|
||||||
start_url="https://git.invario-software.eu/$REPO_SLUG/raw/branch/main/start.sh"
|
start_url="https://git.invario-software.eu/$REPO_SLUG/raw/branch/main/start.sh"
|
||||||
@@ -368,12 +492,66 @@ main() {
|
|||||||
archive_logs
|
archive_logs
|
||||||
create_backup
|
create_backup
|
||||||
|
|
||||||
# If user requested a development install, perform a simple dev deploy flow
|
# If user requested a development install, deploy the latest prerelease.
|
||||||
if [ "$MODE" = "development" ]; then
|
if [ "$MODE" = "development" ]; then
|
||||||
log_message "Requested development install"
|
log_message "Requested development install"
|
||||||
local tag="dev"
|
local tag meta_file releases_file stable_meta_file stable_tag prerelease_tag prerelease_base_tag bundle_url app_image compose_path
|
||||||
local app_image="$APP_IMAGE_REPO:$tag"
|
local tmp_dir
|
||||||
local compose_path="$PROJECT_DIR/$COMPOSE_FILE"
|
|
||||||
|
tmp_dir="$(mktemp -d)"
|
||||||
|
meta_file="$tmp_dir/prerelease.json"
|
||||||
|
stable_meta_file="$tmp_dir/stable.json"
|
||||||
|
releases_file="$tmp_dir/releases.json"
|
||||||
|
trap 'rm -rf "${tmp_dir:-}"' EXIT
|
||||||
|
|
||||||
|
if ! fetch_release_metadata "$stable_meta_file" "latest"; then
|
||||||
|
log_message "ERROR: Could not fetch latest stable release metadata"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
stable_tag="$(parse_release_tag "$stable_meta_file")"
|
||||||
|
if [ -z "$stable_tag" ]; then
|
||||||
|
log_message "ERROR: Could not determine latest stable release tag"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
if latest_prerelease "$meta_file" "$releases_file"; then
|
||||||
|
prerelease_tag="$(parse_release_tag "$meta_file")"
|
||||||
|
prerelease_base_tag="$(strip_prerelease_suffix "$prerelease_tag")"
|
||||||
|
else
|
||||||
|
prerelease_tag=""
|
||||||
|
prerelease_base_tag=""
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [ -n "$prerelease_tag" ]; then
|
||||||
|
case "$(compare_semver_tags "$stable_tag" "$prerelease_base_tag")" in
|
||||||
|
gt|eq)
|
||||||
|
log_message "Latest stable release ($stable_tag) supersedes prerelease ($prerelease_tag); using stable release"
|
||||||
|
tag="$stable_tag"
|
||||||
|
meta_file="$stable_meta_file"
|
||||||
|
;;
|
||||||
|
lt)
|
||||||
|
tag="$prerelease_tag"
|
||||||
|
;;
|
||||||
|
*)
|
||||||
|
log_message "WARNING: Could not compare stable and prerelease versions; preferring prerelease when available"
|
||||||
|
tag="$prerelease_tag"
|
||||||
|
;;
|
||||||
|
esac
|
||||||
|
else
|
||||||
|
log_message "No prerelease found; falling back to stable release $stable_tag"
|
||||||
|
tag="$stable_tag"
|
||||||
|
meta_file="$stable_meta_file"
|
||||||
|
fi
|
||||||
|
|
||||||
|
bundle_url="$(fetch_latest_release_bundle "$meta_file")"
|
||||||
|
if [ -z "$bundle_url" ]; then
|
||||||
|
log_message "ERROR: Release asset not found: $BUNDLE_ASSET"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
app_image="$APP_IMAGE_REPO:$tag"
|
||||||
|
compose_path="$PROJECT_DIR/$COMPOSE_FILE"
|
||||||
|
|
||||||
if [ ! -f "$compose_path" ]; then
|
if [ ! -f "$compose_path" ]; then
|
||||||
log_message "ERROR: compose file not found: $compose_path"
|
log_message "ERROR: compose file not found: $compose_path"
|
||||||
@@ -399,6 +577,9 @@ EOF
|
|||||||
exit 1
|
exit 1
|
||||||
fi
|
fi
|
||||||
|
|
||||||
|
download_and_extract_bundle "$bundle_url" "$tmp_dir"
|
||||||
|
refresh_runtime_scripts_from_main
|
||||||
|
|
||||||
# Bring up stack
|
# Bring up stack
|
||||||
docker compose -f "$compose_path" --env-file "$ENV_FILE" pull mongodb redis >> "$LOG_FILE" 2>&1 || true
|
docker compose -f "$compose_path" --env-file "$ENV_FILE" pull mongodb redis >> "$LOG_FILE" 2>&1 || true
|
||||||
docker compose -f "$compose_path" --env-file "$ENV_FILE" up -d --remove-orphans >> "$LOG_FILE" 2>&1
|
docker compose -f "$compose_path" --env-file "$ENV_FILE" up -d --remove-orphans >> "$LOG_FILE" 2>&1
|
||||||
@@ -409,7 +590,7 @@ EOF
|
|||||||
fi
|
fi
|
||||||
|
|
||||||
echo "$tag" > "$STATE_FILE"
|
echo "$tag" > "$STATE_FILE"
|
||||||
log_message "Development update completed successfully"
|
log_message "Development update completed successfully to prerelease $tag"
|
||||||
exit 0
|
exit 0
|
||||||
fi
|
fi
|
||||||
|
|
||||||
@@ -419,8 +600,8 @@ EOF
|
|||||||
|
|
||||||
trap 'rm -rf "${tmp_dir:-}"' EXIT
|
trap 'rm -rf "${tmp_dir:-}"' EXIT
|
||||||
|
|
||||||
log_message "Checking latest Gitea release for $REPO_SLUG..."
|
log_message "Checking latest stable Gitea release for $REPO_SLUG..."
|
||||||
if ! fetch_release_metadata "$meta_file"; then
|
if ! fetch_release_metadata "$meta_file" "latest"; then
|
||||||
log_message "WARNING: Could not fetch release metadata. Falling back to self-healing start path."
|
log_message "WARNING: Could not fetch release metadata. Falling back to self-healing start path."
|
||||||
if INVENTAR_SETUP_CRON=0 bash "$PROJECT_DIR/start.sh" >> "$LOG_FILE" 2>&1; then
|
if INVENTAR_SETUP_CRON=0 bash "$PROJECT_DIR/start.sh" >> "$LOG_FILE" 2>&1; then
|
||||||
if verify_stack_health; then
|
if verify_stack_health; then
|
||||||
@@ -436,7 +617,7 @@ EOF
|
|||||||
exit 0
|
exit 0
|
||||||
fi
|
fi
|
||||||
|
|
||||||
latest_tag="$(parse_latest_tag "$meta_file")"
|
latest_tag="$(parse_release_tag "$meta_file")"
|
||||||
if [ -z "$latest_tag" ]; then
|
if [ -z "$latest_tag" ]; then
|
||||||
log_message "WARNING: Could not determine latest release tag. Falling back to self-healing start path."
|
log_message "WARNING: Could not determine latest release tag. Falling back to self-healing start path."
|
||||||
if INVENTAR_SETUP_CRON=0 bash "$PROJECT_DIR/start.sh" >> "$LOG_FILE" 2>&1; then
|
if INVENTAR_SETUP_CRON=0 bash "$PROJECT_DIR/start.sh" >> "$LOG_FILE" 2>&1; then
|
||||||
|
|||||||
Reference in New Issue
Block a user