Compare commits
51 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 743e5b1c16 | |||
| 4e47ef0c88 | |||
| 0911b362fd | |||
| 71716f339a | |||
| 36ccee38cb | |||
| 9255c87f57 | |||
| a6b246a92b | |||
| 25f52eeeb5 | |||
| c07d4e0bdd | |||
| 0cacfb0871 | |||
| d3bfaa4580 | |||
| 36531662d3 | |||
| 35b87a9a98 | |||
| 80262aca9b | |||
| 71a8823b35 | |||
| 10e7f3e70d | |||
| e8f0d4bdc5 | |||
| c77c52271c | |||
| 7e00ed3151 | |||
| 39c9666c0f | |||
| 8eb240440b | |||
| 9dc6fe6eeb | |||
| acfa24d742 | |||
| 88f6b77455 | |||
| bc5e08142a | |||
| 373839cf03 | |||
| 8e31309c55 | |||
| e8391dbf1e | |||
| bc274da006 | |||
| f0b5edff79 | |||
| 5b95c5202e | |||
| 51c17d11f2 | |||
| 91ddc6e864 | |||
| 88f124c991 | |||
| 33c65f21b6 | |||
| fd242a6a0a | |||
| 2892024969 | |||
| 27f5280bbf | |||
| 82898e34cb | |||
| 44392c2c31 | |||
| 58d94b716f | |||
| 579a0ddb75 | |||
| 0f21e8d9ca | |||
| 12f7240cd2 | |||
| 54d8d61358 | |||
| 5052dd9de6 | |||
| bf31ee2d16 | |||
| b847930500 | |||
| 756ff55b4c | |||
| df5a3265a1 | |||
| 2c6da44af8 |
@@ -4,17 +4,20 @@ on:
|
||||
push:
|
||||
tags:
|
||||
- "v*"
|
||||
branches:
|
||||
- main
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
bump:
|
||||
description: "Version bump type (major stays fixed from latest release)"
|
||||
release_type:
|
||||
description: "Release type"
|
||||
required: false
|
||||
default: "patch"
|
||||
type: choice
|
||||
options:
|
||||
- patch
|
||||
- minor
|
||||
- major
|
||||
- minor
|
||||
- patch
|
||||
- dev
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
@@ -38,12 +41,70 @@ jobs:
|
||||
REPO: ${{ gitea.repository }}
|
||||
EVENT_NAME: ${{ gitea.event_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'
|
||||
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"
|
||||
else
|
||||
prerelease=false
|
||||
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
|
||||
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
|
||||
fi
|
||||
|
||||
if [ "${BUMP_TYPE:-}" = "major" ]; then
|
||||
if [ "${RELEASE_TYPE:-}" = "major" ]; then
|
||||
major=$((major + 1)); minor=0; patch=0
|
||||
elif [ "${BUMP_TYPE:-}" = "minor" ]; then
|
||||
elif [ "${RELEASE_TYPE:-}" = "minor" ]; then
|
||||
minor=$((minor + 1)); patch=0
|
||||
else
|
||||
patch=$((patch + 1))
|
||||
fi
|
||||
|
||||
|
||||
TAG="v${major}.${minor}.${patch}"
|
||||
fi
|
||||
|
||||
@@ -109,6 +170,7 @@ jobs:
|
||||
echo "tag=$TAG" >> "$GITHUB_OUTPUT"
|
||||
echo "image=$IMAGE" >> "$GITHUB_OUTPUT"
|
||||
echo "lower_repo=$LOWER_REPO" >> "$GITHUB_OUTPUT"
|
||||
echo "prerelease=$prerelease" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Ensure Docker CLI is available and up to date
|
||||
run: |
|
||||
@@ -148,6 +210,7 @@ jobs:
|
||||
password: ${{ secrets.REGISTRY_TOKEN }}
|
||||
|
||||
- name: Build and push release image
|
||||
if: steps.meta.outputs.prerelease != 'true'
|
||||
uses: docker/build-push-action@v6
|
||||
with:
|
||||
context: .
|
||||
@@ -157,6 +220,16 @@ jobs:
|
||||
${{ steps.meta.outputs.image }}
|
||||
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
|
||||
run: |
|
||||
mkdir -p release-bundle
|
||||
@@ -253,5 +326,6 @@ jobs:
|
||||
uses: https://gitea.com/actions/gitea-release-action@v1
|
||||
with:
|
||||
tag_name: ${{ steps.meta.outputs.tag }}
|
||||
prerelease: ${{ steps.meta.outputs.prerelease }}
|
||||
files: |
|
||||
inventarsystem-docker-bundle.tar.gz
|
||||
+539
-108
@@ -108,7 +108,7 @@ app.config['UPLOAD_FOLDER'] = cfg.UPLOAD_FOLDER
|
||||
app.config['THUMBNAIL_FOLDER'] = cfg.THUMBNAIL_FOLDER
|
||||
app.config['PREVIEW_FOLDER'] = cfg.PREVIEW_FOLDER
|
||||
app.config['ALLOWED_EXTENSIONS'] = set(cfg.ALLOWED_EXTENSIONS)
|
||||
app.config['MAX_CONTENT_LENGTH'] = max(cfg.MAX_UPLOAD_MB, cfg.IMAGE_MAX_UPLOAD_MB, cfg.VIDEO_MAX_UPLOAD_MB) * 1024 * 1024
|
||||
app.config['MAX_CONTENT_LENGTH'] = 1024 * 1024 * 1024
|
||||
app.config['SESSION_COOKIE_HTTPONLY'] = True
|
||||
app.config['SESSION_COOKIE_SAMESITE'] = 'Lax'
|
||||
app.config['SESSION_COOKIE_SECURE'] = cfg.SSL_ENABLED if os.getenv('INVENTAR_SESSION_COOKIE_SECURE') is None else os.getenv('INVENTAR_SESSION_COOKIE_SECURE', '').strip().lower() in ('1', 'true', 'yes', 'on')
|
||||
@@ -225,12 +225,95 @@ def rollover_student_card_classes(dry_run=False, *, max_class=None, graduate_lab
|
||||
if client:
|
||||
client.close()
|
||||
|
||||
summary = {'examined': examined, 'updated': updated, 'failures': failures, 'dry_run': bool(dry_run)}
|
||||
|
||||
@app.route('/api/library_return_by_code', methods=['POST'])
|
||||
def api_library_return_by_code():
|
||||
"""
|
||||
Return a library item by scanning its code only (no student card required).
|
||||
This marks active ausleihungen for the item as completed and updates item status.
|
||||
"""
|
||||
if 'username' not in session:
|
||||
return jsonify({'ok': False, 'message': 'Nicht angemeldet.'}), 401
|
||||
if not cfg.MODULES.is_enabled('library'):
|
||||
return jsonify({'ok': False, 'message': 'Bibliotheks-Modul ist deaktiviert.'}), 403
|
||||
|
||||
payload = request.get_json(silent=True) or {}
|
||||
item_code_raw = str(payload.get('item_code') or payload.get('code') or '').strip()
|
||||
if not item_code_raw:
|
||||
return jsonify({'ok': False, 'message': 'Mediencode fehlt.'}), 400
|
||||
|
||||
normalized_isbn = normalize_and_validate_isbn(item_code_raw)
|
||||
normalized_code = item_code_raw.upper()
|
||||
|
||||
client = None
|
||||
try:
|
||||
_append_audit_event_standalone('student_cards_rollover', summary)
|
||||
except Exception:
|
||||
app.logger.warning('Audit write failed for student_cards_rollover')
|
||||
return summary
|
||||
client = MongoClient(MONGODB_HOST, MONGODB_PORT)
|
||||
db = client[MONGODB_DB]
|
||||
items_col = db['items']
|
||||
ausleihungen_col = db['ausleihungen']
|
||||
|
||||
query_or = [
|
||||
{'Code_4': item_code_raw},
|
||||
{'Code_4': normalized_code},
|
||||
]
|
||||
if normalized_isbn:
|
||||
query_or.append({'ISBN': normalized_isbn})
|
||||
|
||||
item_doc = items_col.find_one({
|
||||
'ItemType': {'$in': LIBRARY_ITEM_TYPES},
|
||||
'$or': query_or
|
||||
})
|
||||
|
||||
if not item_doc:
|
||||
return jsonify({'ok': False, 'message': 'Kein Bibliotheksmedium für diesen Code gefunden.'}), 404
|
||||
|
||||
item_id = str(item_doc['_id'])
|
||||
now = datetime.datetime.now()
|
||||
|
||||
# If item already available -> nothing to return
|
||||
if item_doc.get('Verfuegbar', True):
|
||||
return jsonify({'ok': False, 'message': 'Dieses Medium ist nicht als ausgeliehen markiert.'}), 409
|
||||
|
||||
# Mark active ausleihungen as completed
|
||||
update_result = ausleihungen_col.update_many(
|
||||
{'Item': item_id, 'Status': 'active'},
|
||||
{'$set': {
|
||||
'Status': 'completed',
|
||||
'End': now,
|
||||
'LastUpdated': now
|
||||
}}
|
||||
)
|
||||
|
||||
# Update item status to available
|
||||
borrower_name = str(item_doc.get('User') or '').strip() or ''
|
||||
it.update_item_status(item_id, True, borrower_name)
|
||||
|
||||
_append_audit_event_standalone(
|
||||
event_type='ausleihung_returned_by_code',
|
||||
payload={
|
||||
'channel': 'library_return_code',
|
||||
'item_id': item_id,
|
||||
'item_name': item_doc.get('Name', ''),
|
||||
'completed_records': update_result.modified_count,
|
||||
'performed_by': session.get('username')
|
||||
}
|
||||
)
|
||||
|
||||
return jsonify({
|
||||
'ok': True,
|
||||
'action': 'returned',
|
||||
'item_id': item_id,
|
||||
'item_name': item_doc.get('Name', ''),
|
||||
'completed_records': update_result.modified_count,
|
||||
'message': f"{item_doc.get('Name', 'Medium')} wurde zurückgegeben."
|
||||
}), 200
|
||||
except Exception as e:
|
||||
app.logger.error(f"Error in library return by code: {e}")
|
||||
return jsonify({'ok': False, 'message': 'Fehler beim Verarbeiten der Rückgabe.'}), 500
|
||||
finally:
|
||||
if client:
|
||||
client.close()
|
||||
|
||||
|
||||
|
||||
# Admin route to trigger rollover manually
|
||||
@@ -665,11 +748,14 @@ def handle_unexpected_exception(e):
|
||||
|
||||
|
||||
def _csrf_error_response(message='CSRF token fehlt oder ist ungültig.'):
|
||||
if request.is_json or request.path.startswith('/api/') or request.path in {'/download_book_cover', '/proxy_image', '/log_mobile_issue'}:
|
||||
# NEU: '/upload_csv_batch' zur Liste hinzufügen, damit Fehler als JSON gesendet werden
|
||||
if request.is_json or request.path.startswith('/api/') or request.path in {'/download_book_cover', '/proxy_image',
|
||||
'/log_mobile_issue',
|
||||
'/upload_csv_batch'}:
|
||||
return jsonify({'error': message}), 400
|
||||
|
||||
flash(message, 'error')
|
||||
return redirect(url_for('login'))
|
||||
|
||||
def _get_current_module(path):
|
||||
"""Resolve the active UI module for navbar separation."""
|
||||
mod = cfg.MODULES.get_module_for_path(path)
|
||||
@@ -3246,7 +3332,12 @@ def api_library_items():
|
||||
'User': 1,
|
||||
'Ort': 1,
|
||||
'Beschreibung': 1,
|
||||
'Image': 1
|
||||
'Image': 1,
|
||||
'SeriesGroupId': 1,
|
||||
'SeriesCount': 1,
|
||||
'SeriesPosition': 1,
|
||||
'IsGroupedSubItem': 1,
|
||||
'ParentItemId': 1,
|
||||
}
|
||||
|
||||
total_count = items_db.count_documents(query)
|
||||
@@ -3274,6 +3365,10 @@ def api_library_items():
|
||||
'Beschreibung': 1,
|
||||
'Image': 1,
|
||||
'ParentItemId': 1,
|
||||
'SeriesGroupId': 1,
|
||||
'SeriesCount': 1,
|
||||
'SeriesPosition': 1,
|
||||
'IsGroupedSubItem': 1,
|
||||
}
|
||||
child_items = list(items_db.find({
|
||||
'ParentItemId': {'$in': parent_ids_list},
|
||||
@@ -3387,6 +3482,48 @@ def api_library_items():
|
||||
return jsonify({'error': 'An error occurred while fetching library items'}), 500
|
||||
|
||||
|
||||
@app.route('/api/library_group/<series_group_id>')
|
||||
def api_library_group(series_group_id):
|
||||
"""Fetch all items belonging to one library series group."""
|
||||
if 'username' not in session:
|
||||
return jsonify({'items': []}), 401
|
||||
|
||||
try:
|
||||
client = MongoClient(MONGODB_HOST, MONGODB_PORT)
|
||||
db = client[MONGODB_DB]
|
||||
items_col = db['items']
|
||||
|
||||
query = {
|
||||
'SeriesGroupId': series_group_id,
|
||||
'Deleted': {'$ne': True},
|
||||
'ItemType': {'$in': ['book', 'cd', 'dvd', 'schoolbook', 'schulbuch', 'Buch', 'Schulbuch']},
|
||||
}
|
||||
projection = {
|
||||
'Name': 1,
|
||||
'ISBN': 1,
|
||||
'Code_4': 1,
|
||||
'Code4': 1,
|
||||
'ItemType': 1,
|
||||
'Ort': 1,
|
||||
'Beschreibung': 1,
|
||||
'SeriesGroupId': 1,
|
||||
'SeriesCount': 1,
|
||||
'SeriesPosition': 1,
|
||||
'IsGroupedSubItem': 1,
|
||||
'ParentItemId': 1,
|
||||
}
|
||||
|
||||
items = list(items_col.find(query, projection).sort([('SeriesPosition', 1), ('Name', 1), ('_id', 1)]))
|
||||
for item in items:
|
||||
item['_id'] = str(item['_id'])
|
||||
|
||||
client.close()
|
||||
return jsonify({'items': items, 'count': len(items), 'series_group_id': series_group_id})
|
||||
except Exception as exc:
|
||||
app.logger.error('Error loading library group %s: %s', series_group_id, exc)
|
||||
return jsonify({'items': [], 'message': 'Gruppe konnte nicht geladen werden.'}), 500
|
||||
|
||||
|
||||
@app.route('/api/library_scan_action', methods=['POST'])
|
||||
def api_library_scan_action():
|
||||
"""
|
||||
@@ -5174,17 +5311,13 @@ def upload_item():
|
||||
|
||||
fs = get_gridfs()
|
||||
|
||||
can_access_admin_home = _page_access_allowed(permissions, 'home_admin') and _action_access_allowed(permissions, 'can_manage_settings')
|
||||
if can_access_admin_home:
|
||||
success_redirect_endpoint = 'home_admin'
|
||||
elif cfg.MODULES.is_enabled('library') and _page_access_allowed(permissions, 'home_library'):
|
||||
success_redirect_endpoint = 'home_library'
|
||||
if cfg.MODULES.is_enabled('library') and sanitize_form_value(request.form.get('item_type_input', '')) != "other":
|
||||
success_redirect_endpoint = 'library'
|
||||
else:
|
||||
success_redirect_endpoint = 'home_admin'
|
||||
|
||||
# Detect if request is from mobile device
|
||||
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
|
||||
if is_mobile:
|
||||
@@ -5391,8 +5524,7 @@ def upload_item():
|
||||
processed_count = 0
|
||||
error_count = 0
|
||||
skipped_count = 0
|
||||
|
||||
# Create a structured log entry for upload session
|
||||
|
||||
upload_session_id = str(uuid.uuid4())[:8]
|
||||
app.logger.info(f"Starting image upload session {upload_session_id} - Files: {len(images)}, User: {encrypt_text(username)}")
|
||||
|
||||
@@ -5410,7 +5542,6 @@ def upload_item():
|
||||
app.logger.info(f"{image_log_prefix} Processing: {image.filename}")
|
||||
|
||||
try:
|
||||
# 1. Validation
|
||||
is_allowed, error_message = allowed_file(image.filename, image, max_size_mb=cfg.IMAGE_MAX_UPLOAD_MB)
|
||||
if not is_allowed:
|
||||
app.logger.warning(f"{image_log_prefix} Validation failed: {error_message}")
|
||||
@@ -5421,29 +5552,29 @@ def upload_item():
|
||||
|
||||
secure_name = secure_filename(image.filename)
|
||||
|
||||
# 2. Read directly into memory (Bypasses OS-level file quirks and iOS temp-file bugs)
|
||||
image.seek(0)
|
||||
|
||||
image_bytes = image.read()
|
||||
|
||||
# 3. Process, standardize, and optimize using Pillow in-memory
|
||||
if not image_bytes:
|
||||
app.logger.error(f"{image_log_prefix} Failed to read image (0 bytes).")
|
||||
error_count += 1
|
||||
continue
|
||||
|
||||
optimized_io = io.BytesIO()
|
||||
with Image.open(io.BytesIO(image_bytes)) as img:
|
||||
# Ensure safe color mode
|
||||
if img.mode not in ('RGB', 'RGBA'):
|
||||
img = img.convert('RGBA')
|
||||
|
||||
# Standardize dimensions (e.g., max width 500px)
|
||||
max_width = 500
|
||||
if img.width > max_width:
|
||||
ratio = max_width / img.width
|
||||
new_size = (max_width, int(img.height * ratio))
|
||||
img = img.resize(new_size, Image.Resampling.LANCZOS)
|
||||
|
||||
# Export as WebP to a memory buffer
|
||||
# (WebP naturally handles transparency, drastically reduces size, and bypasses PNG signature corruption)
|
||||
img.save(optimized_io, format='WEBP', quality=85, optimize=True)
|
||||
|
||||
optimized_io.seek(0)
|
||||
|
||||
new_filename = f"{uuid.uuid4().hex}_{int(time.time())}.webp"
|
||||
|
||||
file_id = fs.put(
|
||||
@@ -5456,9 +5587,9 @@ def upload_item():
|
||||
}
|
||||
)
|
||||
|
||||
image_filenames.append(file_id)
|
||||
processed_count += 1
|
||||
image_filenames.append(new_filename)
|
||||
|
||||
processed_count += 1
|
||||
final_size_kb = len(optimized_io.getvalue()) / 1024
|
||||
app.logger.info(
|
||||
f"{image_log_prefix} Saved to GridFS as {new_filename} | ID: {file_id} | Size: {final_size_kb:.1f}KB")
|
||||
@@ -6085,10 +6216,10 @@ def bulk_delete_items():
|
||||
def edit_item(id):
|
||||
"""
|
||||
Route for editing an existing inventory item.
|
||||
|
||||
|
||||
Args:
|
||||
id (str): ID of the item to edit
|
||||
|
||||
|
||||
Returns:
|
||||
flask.Response: Redirect to admin homepage with status message
|
||||
"""
|
||||
@@ -6099,19 +6230,19 @@ def edit_item(id):
|
||||
current_permissions = us.get_effective_permissions(session['username'])
|
||||
|
||||
if not current_permissions['actions'].get('can_edit', False):
|
||||
flash('Ihnen fehlen die nötigen Berechtigungen, um diese Aktion (Löschen) auszuführen.', 'error')
|
||||
return redirect(url_for('home_admin'))
|
||||
|
||||
flash('Ihnen fehlen die nötigen Berechtigungen, um diese Aktion auszuführen.', 'error')
|
||||
return redirect(url_for('home_admin'))
|
||||
|
||||
if not cfg.MODULES.is_enabled('inventory'):
|
||||
flash('Bibliotheks-Modul ist deaktiviert.', 'error')
|
||||
return redirect(url_for('library_view'))
|
||||
|
||||
# Strip whitespace from all text fields
|
||||
|
||||
fs = get_gridfs()
|
||||
|
||||
name = sanitize_form_value(request.form.get('name'))
|
||||
ort = sanitize_form_value(request.form.get('ort'))
|
||||
beschreibung = sanitize_form_value(request.form.get('beschreibung'))
|
||||
|
||||
# Strip whitespace from all filter values
|
||||
|
||||
filter1 = sanitize_form_value(request.form.getlist('filter'))
|
||||
filter2 = sanitize_form_value(request.form.getlist('filter2'))
|
||||
filter3 = sanitize_form_value(request.form.getlist('filter3'))
|
||||
@@ -6119,7 +6250,7 @@ def edit_item(id):
|
||||
# Expand special "all values" selections for predefined filters.
|
||||
filter1 = expand_filter_selection(filter1, 1)
|
||||
filter2 = expand_filter_selection(filter2, 2)
|
||||
|
||||
|
||||
anschaffungs_jahr = sanitize_form_value(request.form.get('anschaffungsjahr'))
|
||||
anschaffungs_kosten = sanitize_form_value(request.form.get('anschaffungskosten'))
|
||||
code_4 = sanitize_form_value(request.form.get('code_4'))
|
||||
@@ -6135,91 +6266,103 @@ def edit_item(id):
|
||||
return redirect(url_for('home_admin'))
|
||||
if item_isbn:
|
||||
item_type = 'book'
|
||||
|
||||
# Check if code is unique (excluding the current item)
|
||||
|
||||
if code_4 and not it.is_code_unique(code_4, exclude_id=id):
|
||||
flash('Der Code wird bereits verwendet. Bitte wählen Sie einen anderen Code.', 'error')
|
||||
return redirect(url_for('home_admin'))
|
||||
|
||||
# Get current item to check availability status
|
||||
|
||||
current_item = it.get_item(id)
|
||||
if not current_item:
|
||||
flash('Element nicht gefunden', 'error')
|
||||
return redirect(url_for('home_admin'))
|
||||
|
||||
# Preserve current availability status
|
||||
|
||||
verfuegbar = current_item.get('Verfuegbar', True)
|
||||
|
||||
# Handle existing images - get list of images to keep
|
||||
|
||||
images_to_keep = request.form.getlist('existing_images')
|
||||
|
||||
# Get the original list of images from the item
|
||||
|
||||
original_images = current_item.get('Images', [])
|
||||
|
||||
# Keep only the images that weren't marked for deletion
|
||||
|
||||
images = [img for img in original_images if img in images_to_keep]
|
||||
|
||||
# Handle new image uploads
|
||||
|
||||
new_images = request.files.getlist('new_images')
|
||||
|
||||
# Process any new image uploads
|
||||
|
||||
for image in new_images:
|
||||
if image and image.filename:
|
||||
is_allowed, error_message = allowed_file(image.filename)
|
||||
is_allowed, error_message = allowed_file(image.filename, image)
|
||||
|
||||
if is_allowed:
|
||||
# Get the file extension
|
||||
_, ext_part = os.path.splitext(secure_filename(image.filename))
|
||||
|
||||
# Generate a completely unique filename using UUID
|
||||
unique_id = str(uuid.uuid4())
|
||||
timestamp = time.strftime("%Y%m%d%H%M%S")
|
||||
|
||||
# New filename format with UUID to ensure uniqueness
|
||||
filename = f"{unique_id}_{timestamp}{ext_part}"
|
||||
|
||||
image.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
|
||||
|
||||
# Optimize the image
|
||||
try:
|
||||
opt_result = generate_optimized_versions(filename, max_original_width=500, target_size_kb=80)
|
||||
if opt_result['success'] and opt_result['original']:
|
||||
filename = opt_result['original']
|
||||
secure_name = secure_filename(image.filename)
|
||||
|
||||
image.seek(0)
|
||||
image_bytes = image.read()
|
||||
|
||||
if not image_bytes:
|
||||
app.logger.error(f"Failed to read image in edit_item (0 bytes) for {secure_name}")
|
||||
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 = 500
|
||||
if img.width > max_width:
|
||||
ratio = max_width / img.width
|
||||
new_size = (max_width, int(img.height * ratio))
|
||||
img = img.resize(new_size, 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,
|
||||
'upload_context': 'edit_item',
|
||||
'item_id': id
|
||||
}
|
||||
)
|
||||
|
||||
images.append(new_filename)
|
||||
|
||||
except Exception as e:
|
||||
app.logger.error(f"Error optimizing image in edit_item: {e}")
|
||||
|
||||
images.append(filename)
|
||||
app.logger.error(f"Error processing new image in edit_item: {str(e)}")
|
||||
else:
|
||||
flash(error_message, 'error')
|
||||
return redirect(url_for('home_admin'))
|
||||
|
||||
# If location is not in the predefined list, maybe add it (depending on policy)
|
||||
predefined_locations = it.get_predefined_locations()
|
||||
if ort and ort not in predefined_locations:
|
||||
it.add_predefined_location(ort)
|
||||
|
||||
|
||||
result = it.update_item(
|
||||
id=id,
|
||||
name=name,
|
||||
ort=ort,
|
||||
beschreibung=beschreibung,
|
||||
images=images,
|
||||
verfuegbar=verfuegbar,
|
||||
filter1=filter1,
|
||||
filter2=filter2,
|
||||
id=id,
|
||||
name=name,
|
||||
ort=ort,
|
||||
beschreibung=beschreibung,
|
||||
images=images,
|
||||
verfuegbar=verfuegbar,
|
||||
filter1=filter1,
|
||||
filter2=filter2,
|
||||
filter3=filter3,
|
||||
ansch_jahr=anschaffungs_jahr,
|
||||
ansch_kost=anschaffungs_kosten,
|
||||
code_4=code_4,
|
||||
ansch_jahr=anschaffungs_jahr,
|
||||
ansch_kost=anschaffungs_kosten,
|
||||
code_4=code_4,
|
||||
reservierbar=reservierbar,
|
||||
isbn=item_isbn,
|
||||
item_type=item_type
|
||||
)
|
||||
|
||||
|
||||
if result:
|
||||
flash('Element erfolgreich aktualisiert (und ggf. Gruppe synchronisiert)', 'success')
|
||||
else:
|
||||
flash('Fehler beim Aktualisieren des Elements', 'error')
|
||||
|
||||
|
||||
return redirect(url_for('home_admin'))
|
||||
|
||||
|
||||
@@ -6244,17 +6387,20 @@ def update_group():
|
||||
|
||||
# 1. Shared Fields (Group Logic)
|
||||
# These apply to every item in the group
|
||||
shared_update = {
|
||||
'Name': data.get('name'),
|
||||
'Ort': data.get('ort'),
|
||||
'Beschreibung': data.get('beschreibung'),
|
||||
'Anschaffungsjahr': data.get('ansch_jahr'),
|
||||
'Anschaffungskosten': data.get('ansch_kost'),
|
||||
'Reservierbar': data.get('reservierbar'),
|
||||
'ISBN': data.get('isbn'),
|
||||
'ItemType': data.get('item_type'),
|
||||
'LastUpdated': datetime.datetime.now()
|
||||
}
|
||||
shared_update = {'LastUpdated': datetime.datetime.now()}
|
||||
for source_key, target_key in (
|
||||
('name', 'Name'),
|
||||
('ort', 'Ort'),
|
||||
('beschreibung', 'Beschreibung'),
|
||||
('ansch_jahr', 'Anschaffungsjahr'),
|
||||
('ansch_kost', 'Anschaffungskosten'),
|
||||
('reservierbar', 'Reservierbar'),
|
||||
('isbn', 'ISBN'),
|
||||
('item_type', 'ItemType'),
|
||||
):
|
||||
value = data.get(source_key)
|
||||
if value is not None:
|
||||
shared_update[target_key] = value
|
||||
|
||||
# 2. Individual Updates (Specific Code Logic)
|
||||
# Expected format: [{'id': '...', 'code_4': '...'}, ...]
|
||||
@@ -8893,6 +9039,7 @@ def logs():
|
||||
Returns:
|
||||
flask.Response: Rendered template with logs or redirect if not authenticated
|
||||
"""
|
||||
from modules.inventarsystem.data_protection import decrypt_text
|
||||
if 'username' not in session:
|
||||
flash('Ihnen ist es nicht gestattet auf dieser Internetanwendung, die eben besuchte Adrrese zu nutzen, versuchen sie es erneut nach dem sie sich mit einem berechtigten Nutzer angemeldet haben!', 'error')
|
||||
return redirect(url_for('login'))
|
||||
@@ -8911,9 +9058,6 @@ def logs():
|
||||
# Get item details - from sample data, Item is an ID
|
||||
item = it.get_item(ausleihung.get('Item'))
|
||||
item_name = item.get('Name', 'Unknown Item') if item else 'Unknown Item'
|
||||
|
||||
# Get user details - from sample data, User is a username string
|
||||
|
||||
|
||||
username = ausleihung.get('User', 'Unknown User')
|
||||
# Determine (verified) status for display
|
||||
@@ -8944,7 +9088,7 @@ def logs():
|
||||
|
||||
formatted_items.append({
|
||||
'Item': item_name,
|
||||
'User': username,
|
||||
'User': decrypt_text(username),
|
||||
'Start': start_date,
|
||||
'End': end_date,
|
||||
'Duration': duration,
|
||||
@@ -8964,7 +9108,6 @@ def logs():
|
||||
logs_collection = db['system_logs']
|
||||
extra_logs = list(logs_collection.find({'type': {'$in': ['damage_report', 'damage_repair']}}))
|
||||
|
||||
from modules.inventarsystem.data_protection import decrypt_text
|
||||
from bson.objectid import ObjectId
|
||||
|
||||
|
||||
@@ -9786,7 +9929,8 @@ def get_period_times(booking_date, period_num):
|
||||
@app.route('/my_borrowed_items')
|
||||
def my_borrowed_items():
|
||||
"""
|
||||
Zeigt alle vom aktuellen Benutzer ausgeliehenen und geplanten Objekte an.
|
||||
Zeigt alle vom aktuellen Benutzer ausgeliehenen und geplanten Objekte an,
|
||||
schließt jedoch soft-gelöschte Objekte (Deleted: True) aus.
|
||||
"""
|
||||
if 'username' not in session:
|
||||
flash('Bitte melden Sie sich an, um Ihre ausgeliehenen Objekte anzuzeigen', 'error')
|
||||
@@ -9827,7 +9971,11 @@ def my_borrowed_items():
|
||||
query_id = ObjectId(item_id)
|
||||
else:
|
||||
query_id = item_id
|
||||
item_obj = items_collection.find_one({'_id': query_id})
|
||||
|
||||
item_obj = items_collection.find_one({
|
||||
'_id': query_id,
|
||||
'Deleted': {'$ne': True}
|
||||
})
|
||||
except Exception:
|
||||
item_obj = None
|
||||
|
||||
@@ -9852,7 +10000,11 @@ def my_borrowed_items():
|
||||
elif status == 'planned':
|
||||
planned_items.append(item_obj)
|
||||
|
||||
all_borrowed_items = list(items_collection.find({'Verfuegbar': False}))
|
||||
all_borrowed_items = list(items_collection.find({
|
||||
'Verfuegbar': False,
|
||||
'Deleted': {'$ne': True}
|
||||
}))
|
||||
|
||||
for item in all_borrowed_items:
|
||||
raw_item_user = item.get('User', '')
|
||||
try:
|
||||
@@ -9869,7 +10021,6 @@ def my_borrowed_items():
|
||||
|
||||
client.close()
|
||||
|
||||
# DEBUG Logging
|
||||
app.logger.info(
|
||||
f"Passing {len(active_items)} active items and {len(planned_items)} planned items to template for user {username}")
|
||||
|
||||
@@ -11830,3 +11981,283 @@ def test_push_notification():
|
||||
except Exception as e:
|
||||
app.logger.error(f'Error sending test push: {e}')
|
||||
return jsonify({'success': False}), 500
|
||||
|
||||
|
||||
@app.route('/batch_upload', methods=['GET'])
|
||||
def batch_upload_page():
|
||||
"""
|
||||
Serves the HTML frontend for the batch CSV and image upload.
|
||||
"""
|
||||
# Check permissions if necessary, similar to your other routes
|
||||
if 'username' not in session:
|
||||
flash('Bitte melden Sie sich an.', 'error')
|
||||
return redirect(url_for('login'))
|
||||
|
||||
return render_template('upload_batch.html')
|
||||
|
||||
def clean_db_field(val):
|
||||
"""Bereinigt Werte, die fälschlicherweise als String-Listen oder mit Klammern aus der CSV kommen."""
|
||||
import ast
|
||||
import pandas as pd
|
||||
|
||||
if not val or pd.isna(val):
|
||||
return None
|
||||
|
||||
val_str = str(val).strip()
|
||||
|
||||
# Wenn es wie eine Liste aussieht (z.B. "['100177']" oder "['']")
|
||||
if val_str.startswith("[") and val_str.endswith("]"):
|
||||
try:
|
||||
parsed = ast.literal_eval(val_str)
|
||||
if isinstance(parsed, list):
|
||||
# Nimm das erste Element der Liste, wenn vorhanden
|
||||
for item in parsed:
|
||||
cleaned_item = str(item).strip()
|
||||
if cleaned_item and cleaned_item not in ("", "''", '""', "None", "nan"):
|
||||
return cleaned_item
|
||||
return None
|
||||
except Exception:
|
||||
# Fallback bei Syntaxfehlern
|
||||
inner = val_str[1:-1].strip().replace("'", "").replace('"', '')
|
||||
return inner if inner and inner not in ("''", '""') else None
|
||||
|
||||
if val_str in ("[]", "['']", '[""]', "nan", "None", "''", '""'):
|
||||
return None
|
||||
|
||||
return val_str
|
||||
|
||||
|
||||
|
||||
@app.route('/upload_csv_batch', methods=['POST'])
|
||||
def upload_csv_batch():
|
||||
"""
|
||||
Route for batch adding new items to the inventory via CSV.
|
||||
Handles CSV parsing, bulk image upload with deduplication (SHA-256 hash matching),
|
||||
GridFS storage, code generation, location syncing, and grouped item creation.
|
||||
"""
|
||||
import pandas as pd
|
||||
import ast
|
||||
import hashlib
|
||||
|
||||
username = session.get('username', 'System')
|
||||
|
||||
def generate_unique_batch_code(base_code, position):
|
||||
if base_code:
|
||||
return f"{base_code}-{position}"
|
||||
else:
|
||||
random_prefix = str(uuid.uuid4())[:6].upper()
|
||||
return f"BATCH-{random_prefix}-{position}"
|
||||
|
||||
fs = get_gridfs()
|
||||
upload_session_id = str(uuid.uuid4())[:8]
|
||||
app.logger.info(f"Starting CSV Batch upload session {upload_session_id} - User: {username}")
|
||||
|
||||
# 1. Dateien aus dem Request empfangen
|
||||
if 'csv_file' not in request.files:
|
||||
return jsonify({"success": False, "message": "Keine CSV-Datei hochgeladen"}), 400
|
||||
|
||||
csv_file = request.files['csv_file']
|
||||
uploaded_images = request.files.getlist('images')
|
||||
|
||||
# 2. CSV Einlesen und Validieren
|
||||
try:
|
||||
df = pd.read_csv(csv_file, sep=',')
|
||||
except Exception as e:
|
||||
app.logger.error(f"[Upload {upload_session_id}] Fehler beim Lesen der CSV: {str(e)}")
|
||||
return jsonify({"success": False, "message": f"Fehler beim Lesen der CSV: {str(e)}"}), 400
|
||||
|
||||
if 'Name' not in df.columns:
|
||||
return jsonify({"success": False, "message": "Die CSV muss zwingend eine 'Name' Spalte enthalten."}), 400
|
||||
|
||||
# 3. Bilder verarbeiten & Duplikate im selben Durchlauf filtern (Hash-Matching)
|
||||
image_mapping = {}
|
||||
processed_hashes = {}
|
||||
processed_count = 0
|
||||
dedup_count = 0
|
||||
error_count = 0
|
||||
|
||||
for index, image in enumerate(uploaded_images):
|
||||
if not image or not image.filename:
|
||||
continue
|
||||
|
||||
original_secure_name = secure_filename(image.filename)
|
||||
base_name_no_ext = os.path.splitext(original_secure_name)[0]
|
||||
image_log_prefix = f"[Upload {upload_session_id}][Image {index + 1}/{len(uploaded_images)}]"
|
||||
|
||||
try:
|
||||
image.seek(0)
|
||||
image_bytes = image.read()
|
||||
if not image_bytes:
|
||||
error_count += 1
|
||||
continue
|
||||
|
||||
img_hash = hashlib.sha256(image_bytes).hexdigest()
|
||||
|
||||
if img_hash in processed_hashes:
|
||||
existing_filename = processed_hashes[img_hash]
|
||||
image_mapping[base_name_no_ext] = existing_filename
|
||||
dedup_count += 1
|
||||
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 = 500
|
||||
if img.width > max_width:
|
||||
ratio = max_width / img.width
|
||||
new_size = (max_width, int(img.height * ratio))
|
||||
img = img.resize(new_size, 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': original_secure_name,
|
||||
'upload_session': upload_session_id,
|
||||
'batch_upload': True
|
||||
}
|
||||
)
|
||||
|
||||
processed_hashes[img_hash] = new_filename
|
||||
image_mapping[base_name_no_ext] = new_filename
|
||||
processed_count += 1
|
||||
|
||||
except Exception as e:
|
||||
app.logger.error(f"{image_log_prefix} Processing failed: {str(e)}")
|
||||
error_count += 1
|
||||
|
||||
# 4. Predefined Locations laden
|
||||
try:
|
||||
predefined_locations = it.get_predefined_locations()
|
||||
except Exception:
|
||||
predefined_locations = []
|
||||
|
||||
# 5. Dataframe bereinigen
|
||||
df['Name'] = df['Name'].fillna('Unbenannt').astype(str).str.strip()
|
||||
df = df.fillna({
|
||||
'Ort': 'Unbekannt',
|
||||
'Beschreibung': '',
|
||||
'Code_4': '',
|
||||
'Anschaffungsjahr': '',
|
||||
'Anschaffungskosten': ''
|
||||
})
|
||||
|
||||
# --- WICHTIG: Gruppierung über einen normalisierten Schlüssel ermöglichen ---
|
||||
# Erstellt eine unsichtbare Hilfsspalte, die Leerzeichen/Groß-Kleinschreibung ignoriert,
|
||||
# damit identische Artikel-Typen sauber als Serie erkannt werden.
|
||||
df['GroupKey'] = df['Name'].str.lower()
|
||||
|
||||
created_item_ids = []
|
||||
grouped_items = df.groupby('GroupKey')
|
||||
|
||||
for group_key, group in grouped_items:
|
||||
item_count = len(group)
|
||||
series_group_id = str(uuid.uuid4()) if item_count > 1 else None
|
||||
parent_item_id = None
|
||||
|
||||
# Originalen Namen des ersten Elements der Gruppe übernehmen
|
||||
actual_group_name = group.iloc[0]['Name']
|
||||
|
||||
# Basis-Code für automatisierte Seriencodes ermitteln
|
||||
first_row_code = clean_db_field(group.iloc[0].get('Code_4', ''))
|
||||
base_code = first_row_code if first_row_code else None
|
||||
|
||||
for position, (index, row) in enumerate(group.iterrows(), start=1):
|
||||
|
||||
ort_val = str(row['Ort']).strip()
|
||||
if ort_val and ort_val not in predefined_locations:
|
||||
try:
|
||||
it.add_predefined_location(ort_val)
|
||||
predefined_locations.append(ort_val)
|
||||
except Exception as e:
|
||||
app.logger.warning(f"Ort {ort_val} konnte nicht hinzugefügt werden: {e}")
|
||||
|
||||
# Bilder zuordnen und pro Artikel deduplizieren
|
||||
item_image_filenames = []
|
||||
if 'Images' in row and pd.notna(row['Images']):
|
||||
try:
|
||||
img_list = ast.literal_eval(str(row['Images']))
|
||||
if isinstance(img_list, list):
|
||||
for img_name in img_list:
|
||||
base_img_name = os.path.splitext(img_name)[0]
|
||||
if base_img_name in image_mapping:
|
||||
item_image_filenames.append(image_mapping[base_img_name])
|
||||
except (ValueError, SyntaxError):
|
||||
pass
|
||||
|
||||
unique_image_filenames = []
|
||||
for img in item_image_filenames:
|
||||
if img not in unique_image_filenames:
|
||||
unique_image_filenames.append(img)
|
||||
|
||||
def parse_filter_col(col_data):
|
||||
try:
|
||||
res = ast.literal_eval(str(col_data))
|
||||
return res if isinstance(res, list) else []
|
||||
except Exception:
|
||||
return []
|
||||
|
||||
filter_upload = parse_filter_col(row.get('Filter', '[]'))
|
||||
filter_upload2 = parse_filter_col(row.get('Filter2', '[]'))
|
||||
filter_upload3 = parse_filter_col(row.get('Filter3', '[]'))
|
||||
|
||||
reservierbar = bool(row.get('Reservierbar', False))
|
||||
|
||||
# Code_4 / Barcode sauber extrahieren und bereinigen
|
||||
raw_code = row.get('Code_4') or row.get('Barcode') or ''
|
||||
row_code = clean_db_field(raw_code)
|
||||
|
||||
if row_code:
|
||||
unique_code = row_code
|
||||
elif item_count > 1:
|
||||
unique_code = generate_unique_batch_code(base_code, position)
|
||||
else:
|
||||
unique_code = None
|
||||
|
||||
# DB Insert
|
||||
item_id = it.add_item(
|
||||
str(actual_group_name), # 1. Name
|
||||
ort_val, # 2. Ort
|
||||
str(row['Beschreibung']), # 3. Beschreibung
|
||||
unique_image_filenames, # 4. Image Filenames (GridFS)
|
||||
filter_upload, # 5. Filter 1
|
||||
filter_upload2, # 6. Filter 2
|
||||
filter_upload3, # 7. Filter 3
|
||||
clean_db_field(row.get('Anschaffungsjahr')), # 8. Jahr
|
||||
clean_db_field(row.get('Anschaffungskosten')),# 9. Kosten
|
||||
unique_code, # 10. Unique Code / Code_4
|
||||
reservierbar=reservierbar,
|
||||
series_group_id=series_group_id,
|
||||
series_count=item_count,
|
||||
series_position=position,
|
||||
is_grouped_sub_item=(position > 1),
|
||||
parent_item_id=parent_item_id,
|
||||
isbn=str(row.get('ISBN', '')),
|
||||
item_type=str(row.get('Item_Type', 'other')),
|
||||
library_category=str(row.get('Library_Category', '')),
|
||||
is_library=bool(row.get('Is_Library', False))
|
||||
)
|
||||
|
||||
if item_id:
|
||||
created_item_ids.append(item_id)
|
||||
if position == 1:
|
||||
parent_item_id = str(item_id)
|
||||
else:
|
||||
app.logger.error(f"Fehler beim Erstellen von Item: {actual_group_name} (Index {index})")
|
||||
|
||||
return jsonify({
|
||||
"success": True,
|
||||
"message": f"Upload erfolgreich. {len(created_item_ids)} Items importiert.",
|
||||
"created_count": len(created_item_ids),
|
||||
"images_processed": processed_count,
|
||||
"images_deduplicated": dedup_count,
|
||||
"images_failed": error_count
|
||||
}), 200
|
||||
@@ -54,10 +54,34 @@ def _clean_name_fragment(value):
|
||||
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."""
|
||||
try:
|
||||
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)
|
||||
except Exception:
|
||||
return client[cfg.MONGODB_DB]
|
||||
@@ -479,8 +503,45 @@ def check_nm_pwd(username, password):
|
||||
query = {'$or': [{'Username': username}, {'username': username}]}
|
||||
user_record_fallback = users.find_one(query)
|
||||
if user_record_fallback is None:
|
||||
logger.warning("Kein Benutzer für %r in DB %r gefunden.", dp.encrypt_text(username), db_name)
|
||||
return None
|
||||
if db_name != cfg.MONGODB_DB:
|
||||
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:
|
||||
user_record = user_record_fallback
|
||||
|
||||
@@ -497,6 +558,59 @@ def check_nm_pwd(username, password):
|
||||
finally:
|
||||
client.close()
|
||||
|
||||
def add_admin(
|
||||
username,
|
||||
password,
|
||||
name='',
|
||||
last_name='',
|
||||
is_student=False,
|
||||
permission_preset='full_access',
|
||||
action_permissions=None,
|
||||
page_permissions=None,
|
||||
tenant_id=None,
|
||||
):
|
||||
"""
|
||||
Add a new user to the database.
|
||||
"""
|
||||
if not check_password_strength(password):
|
||||
return False
|
||||
|
||||
client = MongoClient(cfg.MONGODB_HOST, cfg.MONGODB_PORT)
|
||||
try:
|
||||
db = _get_tenant_db(client, tenant_id)
|
||||
users = db['users']
|
||||
|
||||
permission_defaults = build_default_permission_payload(permission_preset)
|
||||
|
||||
if isinstance(action_permissions, dict):
|
||||
for key, value in action_permissions.items():
|
||||
permission_defaults['actions'][str(key)] = bool(value)
|
||||
|
||||
if isinstance(page_permissions, dict):
|
||||
for key, value in page_permissions.items():
|
||||
permission_defaults['pages'][str(key)] = bool(value)
|
||||
|
||||
safe_name = name.strip() if name else ''
|
||||
safe_last_name = last_name.strip() if last_name else ''
|
||||
|
||||
user_doc = {
|
||||
'Username': username,
|
||||
'Password': hashing(password),
|
||||
'Admin': True,
|
||||
'active_ausleihung': None,
|
||||
'name': dp.encrypt_text(safe_name) if safe_name else '',
|
||||
'last_name': dp.encrypt_text(safe_last_name) if safe_last_name else '',
|
||||
'IsStudent': bool(is_student),
|
||||
'PermissionPreset': permission_defaults['preset'],
|
||||
'ActionPermissions': permission_defaults['actions'],
|
||||
'PagePermissions': permission_defaults['pages'],
|
||||
}
|
||||
|
||||
users.insert_one(user_doc)
|
||||
return True
|
||||
finally:
|
||||
client.close()
|
||||
|
||||
|
||||
def add_user(
|
||||
username,
|
||||
@@ -509,6 +623,7 @@ def add_user(
|
||||
permission_preset='standard_user',
|
||||
action_permissions=None,
|
||||
page_permissions=None,
|
||||
tenant_id=None,
|
||||
):
|
||||
"""
|
||||
Add a new user to the database.
|
||||
@@ -518,7 +633,7 @@ def add_user(
|
||||
|
||||
client = MongoClient(cfg.MONGODB_HOST, cfg.MONGODB_PORT)
|
||||
try:
|
||||
db = _get_tenant_db(client)
|
||||
db = _get_tenant_db(client, tenant_id)
|
||||
users = db['users']
|
||||
|
||||
permission_defaults = build_default_permission_payload(permission_preset)
|
||||
|
||||
@@ -17,4 +17,5 @@ cryptography>=42.0.0
|
||||
pywebpush
|
||||
py-vapid>=1.9.0
|
||||
beautifulsoup4
|
||||
pywebpush
|
||||
pywebpush
|
||||
pandas
|
||||
+332
-141
@@ -355,6 +355,28 @@
|
||||
color: #6b7280;
|
||||
}
|
||||
|
||||
/* Small confirmation popup (toast) */
|
||||
.small-popup {
|
||||
position: fixed;
|
||||
bottom: 24px;
|
||||
left: 50%;
|
||||
transform: translateX(-50%);
|
||||
background: rgba(17, 24, 39, 0.96);
|
||||
color: #fff;
|
||||
padding: 12px 16px;
|
||||
border-radius: 8px;
|
||||
box-shadow: 0 6px 24px rgba(2,6,23,0.6);
|
||||
z-index: 2000;
|
||||
display: flex;
|
||||
gap: 10px;
|
||||
align-items: center;
|
||||
max-width: 90%;
|
||||
font-size: 0.95em;
|
||||
}
|
||||
.small-popup.ok { background: rgba(16,185,129,0.95); color: #032; }
|
||||
.small-popup.error { background: rgba(239,68,68,0.95); color: #210; }
|
||||
.small-popup .close-x { margin-left: 8px; cursor: pointer; font-weight: 700; }
|
||||
|
||||
/* Modal styles */
|
||||
.modal {
|
||||
display: none;
|
||||
@@ -503,8 +525,18 @@
|
||||
<option value="quick_toggle">Schnellmodus: Ausweis + Mediencode</option>
|
||||
</select>
|
||||
<input type="text" id="activeStudentCard" placeholder="Aktiver Ausweis (gescannt)" readonly>
|
||||
<input type="text" id="manualItemCode" placeholder="Manueller Mediencode (optional)" style="min-width:180px;">
|
||||
<button id="resetCardBtn" class="button" type="button">Ausweis löschen</button>
|
||||
<button id="toggleScannerBtn" class="button" type="button">Scanner starten</button>
|
||||
<label style="display:flex; align-items:center; gap:8px; margin-left:6px;">
|
||||
<input type="checkbox" id="keyboardScannerToggle">
|
||||
<span style="font-size:0.9em;">Physischer Scanner</span>
|
||||
</label>
|
||||
<label style="display:flex; align-items:center; gap:8px; margin-left:6px;">
|
||||
<input type="checkbox" id="returnOnlyToggle">
|
||||
<span style="font-size:0.9em;">Nur Rückgabe (nur Mediencode)</span>
|
||||
</label>
|
||||
<button id="manualReturnBtn" class="button" type="button" style="margin-left:6px; background:#10b981;color:white;">Rückgabe per Code</button>
|
||||
</div>
|
||||
<div id="scanStatus" class="library-scan-status">
|
||||
Hinweis: Im Schnellmodus zuerst den Schülerausweis scannen, danach den Buch-/Mediencode.
|
||||
@@ -632,6 +664,16 @@
|
||||
let activeStudentCardId = '';
|
||||
let lastScanValue = '';
|
||||
let lastScanAt = 0;
|
||||
// Keyboard-scanner support (physical scanners that act as keyboard wedges)
|
||||
let keyboardScannerEnabled = false;
|
||||
let keyboardScanBuffer = '';
|
||||
let keyboardLastKeyAt = 0;
|
||||
const KEYBOARD_SCAN_INTERCHAR_MS = 100; // max time between keystrokes to consider them one scan
|
||||
let editLibraryState = {
|
||||
itemId: '',
|
||||
seriesGroupId: '',
|
||||
groupMembers: []
|
||||
};
|
||||
|
||||
const canEditLibraryItems = (document.getElementById('libraryTableContainer')?.dataset.canEdit === '1');
|
||||
|
||||
@@ -905,6 +947,13 @@
|
||||
const currentCallback = activeScannerCallback;
|
||||
stopScanner();
|
||||
|
||||
const returnOnly = (document.getElementById('returnOnlyToggle') || {}).checked;
|
||||
if (returnOnly) {
|
||||
// direct return flow
|
||||
returnByCode(barcode);
|
||||
return;
|
||||
}
|
||||
|
||||
if (typeof currentCallback === "function") {
|
||||
currentCallback(barcode);
|
||||
} else {
|
||||
@@ -912,6 +961,50 @@
|
||||
}
|
||||
});
|
||||
|
||||
// =========================================================================
|
||||
// Keyboard scanner handling (physical scanners that send chars then Enter)
|
||||
// =========================================================================
|
||||
function keyboardScanKeydownHandler(e) {
|
||||
// Only active when explicitly enabled
|
||||
if (!keyboardScannerEnabled) return;
|
||||
|
||||
// Ignore if focus is in an input/textarea/contenteditable to avoid interfering with typing
|
||||
const active = document.activeElement;
|
||||
if (active && (active.tagName === 'INPUT' || active.tagName === 'TEXTAREA' || active.isContentEditable)) return;
|
||||
|
||||
const now = Date.now();
|
||||
|
||||
// If Enter/Return pressed -> finalize buffer
|
||||
if (e.key === 'Enter') {
|
||||
const code = keyboardScanBuffer.trim();
|
||||
keyboardScanBuffer = '';
|
||||
keyboardLastKeyAt = 0;
|
||||
if (!code) return;
|
||||
// If return-only mode is active, attempt direct return
|
||||
const returnOnly = (document.getElementById('returnOnlyToggle') || {}).checked;
|
||||
if (returnOnly) {
|
||||
returnByCode(code);
|
||||
return;
|
||||
}
|
||||
|
||||
// Process exactly like a camera scan
|
||||
handleScanSuccess(code);
|
||||
return;
|
||||
}
|
||||
|
||||
// Only accept common printable characters; ignore modifier keys
|
||||
if (e.key.length === 1) {
|
||||
// If time gap too big, start new buffer
|
||||
if (keyboardLastKeyAt && (now - keyboardLastKeyAt) > KEYBOARD_SCAN_INTERCHAR_MS) {
|
||||
keyboardScanBuffer = '';
|
||||
}
|
||||
keyboardScanBuffer += e.key;
|
||||
keyboardLastKeyAt = now;
|
||||
// Prevent default so scanner input doesn't accidentally move focus or trigger shortcuts
|
||||
e.preventDefault();
|
||||
}
|
||||
}
|
||||
|
||||
function handleScanSuccess(decodedText) {
|
||||
const scannedCode = normalizeScannedCode(decodedText);
|
||||
if (!scannedCode) return;
|
||||
@@ -935,11 +1028,46 @@
|
||||
|
||||
async function processQuickToggleScan(scannedCode) {
|
||||
if (!activeStudentCardId) {
|
||||
setActiveStudentCard(scannedCode);
|
||||
setScanStatus(`Ausweis gesetzt: ${activeStudentCardId}`, 'ok');
|
||||
return;
|
||||
}
|
||||
// If return-only mode is active, always attempt to return by code
|
||||
const returnOnly = (document.getElementById('returnOnlyToggle') || {}).checked;
|
||||
if (returnOnly) {
|
||||
await returnByCode(scannedCode);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!activeStudentCardId) {
|
||||
setActiveStudentCard(scannedCode);
|
||||
setScanStatus(`Ausweis gesetzt: ${activeStudentCardId}`, 'ok');
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
async function returnByCode(code) {
|
||||
if (!code) return;
|
||||
setScanStatus('Verarbeite Rückgabe...', 'warn');
|
||||
try {
|
||||
const resp = await fetch('/api/library_return_by_code', {
|
||||
method: 'POST',
|
||||
headers: {'Content-Type': 'application/json'},
|
||||
body: JSON.stringify({ item_code: code })
|
||||
});
|
||||
const result = await resp.json();
|
||||
if (!resp.ok || !result.ok) {
|
||||
setScanStatus(result.message || 'Rückgabe fehlgeschlagen.', 'error');
|
||||
showSmallConfirm(result.message || 'Rückgabe fehlgeschlagen.', 'error');
|
||||
return false;
|
||||
}
|
||||
setScanStatus(result.message || `Zurückgegeben: ${result.item_name || ''}`, 'ok');
|
||||
showSmallConfirm(result.message || `Zurückgegeben: ${result.item_name || ''}`, 'ok');
|
||||
await loadLibraryItems();
|
||||
return true;
|
||||
} catch (err) {
|
||||
console.error('Return by code failed:', err);
|
||||
setScanStatus('Fehler bei Rückgabe.', 'error');
|
||||
showSmallConfirm('Fehler bei Rückgabe.', 'error');
|
||||
return false;
|
||||
}
|
||||
}
|
||||
try {
|
||||
setScanStatus('Verarbeite Mediencode...', 'warn');
|
||||
const response = await fetch('/api/library_scan_action', {
|
||||
@@ -959,10 +1087,13 @@
|
||||
|
||||
if (result.action === 'borrowed') {
|
||||
setScanStatus(`Ausgeliehen: ${result.item_name}`, 'ok');
|
||||
showSmallConfirm(`Ausgeliehen: ${result.item_name}`, 'ok');
|
||||
} else if (result.action === 'returned') {
|
||||
setScanStatus(`Zurückgegeben: ${result.item_name}`, 'ok');
|
||||
showSmallConfirm(`Zurückgegeben: ${result.item_name}`, 'ok');
|
||||
} else {
|
||||
setScanStatus(result.message || 'Aktion durchgeführt.', 'ok');
|
||||
showSmallConfirm(result.message || 'Aktion durchgeführt.', 'ok');
|
||||
}
|
||||
|
||||
await loadLibraryItems();
|
||||
@@ -1075,6 +1206,21 @@
|
||||
el.classList.remove('ok', 'warn', 'error');
|
||||
if (kind) el.classList.add(kind);
|
||||
}
|
||||
|
||||
function showSmallConfirm(message, kind='ok') {
|
||||
// Append the small helper text in German
|
||||
const helper = 'Sie können fortfahren. Dies ist nur eine kleine Benachrichtigung.';
|
||||
const el = document.createElement('div');
|
||||
el.className = `small-popup ${kind === 'error' ? 'error' : 'ok'}`;
|
||||
el.innerHTML = `<div>${escapeHtml(String(message || ''))}</div><div style="opacity:0.9; margin-left:8px; font-size:0.85em;">${helper}</div><div class="close-x">×</div>`;
|
||||
document.body.appendChild(el);
|
||||
// close handler
|
||||
el.querySelector('.close-x').addEventListener('click', () => {
|
||||
if (el && el.parentNode) el.parentNode.removeChild(el);
|
||||
});
|
||||
// auto remove after 3 seconds
|
||||
setTimeout(() => { try { if (el && el.parentNode) el.parentNode.removeChild(el); } catch(e){} }, 3000);
|
||||
}
|
||||
|
||||
function setActiveStudentCard(cardId) {
|
||||
activeStudentCardId = (cardId || '').trim().toUpperCase();
|
||||
@@ -1145,6 +1291,7 @@
|
||||
const toggleBtn = document.getElementById('toggleScannerBtn');
|
||||
const resetBtn = document.getElementById('resetCardBtn');
|
||||
const modeSelect = document.getElementById('scanModeSelect');
|
||||
const keyboardToggle = document.getElementById('keyboardScannerToggle');
|
||||
|
||||
if (toggleBtn) {
|
||||
toggleBtn.addEventListener('click', async () => {
|
||||
@@ -1172,6 +1319,19 @@
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
if (keyboardToggle) {
|
||||
keyboardToggle.addEventListener('change', () => {
|
||||
keyboardScannerEnabled = !!keyboardToggle.checked;
|
||||
if (keyboardScannerEnabled) {
|
||||
document.addEventListener('keydown', keyboardScanKeydownHandler);
|
||||
setScanStatus('Physischer Scanner aktiv (Schnellmodus empfohlen).', 'ok');
|
||||
} else {
|
||||
document.removeEventListener('keydown', keyboardScanKeydownHandler);
|
||||
setScanStatus('Physischer Scanner deaktiviert.', 'warn');
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Run when DOM structure is entirely ready
|
||||
@@ -1226,44 +1386,104 @@
|
||||
});
|
||||
}
|
||||
|
||||
// Edit Modal Form processing
|
||||
const manualReturnBtn = document.getElementById('manualReturnBtn');
|
||||
const manualItemCode = document.getElementById('manualItemCode');
|
||||
if (manualReturnBtn && manualItemCode) {
|
||||
manualReturnBtn.addEventListener('click', async () => {
|
||||
const code = (manualItemCode.value || '').trim();
|
||||
if (!code) {
|
||||
alert('Bitte einen Mediencode eingeben.');
|
||||
return;
|
||||
}
|
||||
await returnByCode(code);
|
||||
});
|
||||
}
|
||||
|
||||
const editForm = document.getElementById('editLibraryForm');
|
||||
if (editForm) {
|
||||
editForm.addEventListener('submit', async function(e) {
|
||||
e.preventDefault();
|
||||
e.preventDefault();
|
||||
|
||||
const itemId = document.getElementById('editLibraryItemId').value;
|
||||
const currentItem = libraryItems.find(i => i._id === itemId);
|
||||
if (!currentItem) return;
|
||||
|
||||
const updatedData = {
|
||||
const sharedPayload = {
|
||||
name: document.getElementById('editLibraryName').value,
|
||||
item_type: document.getElementById('editLibraryType').value,
|
||||
isbn: document.getElementById('editLibraryIsbn').value,
|
||||
code_4: document.getElementById('editLibraryCode4').value,
|
||||
ort: document.getElementById('editLibraryLocation').value,
|
||||
beschreibung: document.getElementById('editLibraryDescription').value
|
||||
beschreibung: document.getElementById('editLibraryDescription').value,
|
||||
ansch_jahr: currentItem.Anschaffungsjahr || '',
|
||||
ansch_kost: currentItem.Anschaffungskosten || '',
|
||||
reservierbar: currentItem.Reservierbar !== false,
|
||||
};
|
||||
|
||||
const codeInputs = Array.from(document.querySelectorAll('#editLibraryCodesContainer input[data-item-id]'));
|
||||
const codeByItemId = new Map(codeInputs.map(input => [input.dataset.itemId, (input.value || '').trim()]));
|
||||
const groupMembers = editLibraryState.groupMembers.length > 0 ? editLibraryState.groupMembers : [currentItem];
|
||||
const isGroupedEdit = Boolean(currentItem.SeriesGroupId) && groupMembers.length > 1;
|
||||
|
||||
try {
|
||||
const response = await fetch(`/api/library_item/${itemId}/update`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'X-CSRFToken': '{{ csrf_token }}',
|
||||
'X-CSRF-Token': '{{ csrf_token }}'
|
||||
},
|
||||
body: JSON.stringify(updatedData)
|
||||
});
|
||||
if (isGroupedEdit) {
|
||||
const payload = {
|
||||
series_group_id: currentItem.SeriesGroupId,
|
||||
...sharedPayload,
|
||||
items: groupMembers.map(member => ({
|
||||
id: member._id,
|
||||
code_4: codeByItemId.get(member._id) || ''
|
||||
}))
|
||||
};
|
||||
|
||||
const result = await response.json();
|
||||
const response = await fetch('/update_group', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'X-CSRFToken': '{{ csrf_token }}',
|
||||
'X-CSRF-Token': '{{ csrf_token }}'
|
||||
},
|
||||
body: JSON.stringify(payload)
|
||||
});
|
||||
|
||||
if (response.ok && result.ok) {
|
||||
alert(result.message || 'Medium erfolgreich aktualisiert!');
|
||||
closeEditLibraryModal();
|
||||
|
||||
pagingState.loading = false;
|
||||
loadLibraryItems();
|
||||
const result = await response.json();
|
||||
if (response.ok && result.success) {
|
||||
alert(result.message || 'Gruppe erfolgreich aktualisiert!');
|
||||
closeEditLibraryModal();
|
||||
pagingState.loading = false;
|
||||
await loadLibraryItems();
|
||||
} else {
|
||||
alert(result.message || 'Fehler beim Speichern der Gruppenänderungen.');
|
||||
}
|
||||
} else {
|
||||
alert(result.message || 'Fehler beim Speichern der Änderungen.');
|
||||
const primaryCodeInput = codeInputs[0];
|
||||
const payload = {
|
||||
name: sharedPayload.name,
|
||||
item_type: sharedPayload.item_type,
|
||||
isbn: sharedPayload.isbn,
|
||||
code_4: primaryCodeInput ? primaryCodeInput.value.trim() : (currentItem.Code_4 || currentItem.Code4 || '').trim(),
|
||||
ort: sharedPayload.ort,
|
||||
beschreibung: sharedPayload.beschreibung
|
||||
};
|
||||
|
||||
const response = await fetch(`/api/library_item/${itemId}/update`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'X-CSRFToken': '{{ csrf_token }}',
|
||||
'X-CSRF-Token': '{{ csrf_token }}'
|
||||
},
|
||||
body: JSON.stringify(payload)
|
||||
});
|
||||
|
||||
const result = await response.json();
|
||||
if (response.ok && result.ok) {
|
||||
alert(result.message || 'Medium erfolgreich aktualisiert!');
|
||||
closeEditLibraryModal();
|
||||
pagingState.loading = false;
|
||||
await loadLibraryItems();
|
||||
} else {
|
||||
alert(result.message || 'Fehler beim Speichern der Änderungen.');
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Update failed:', error);
|
||||
@@ -1273,115 +1493,105 @@
|
||||
}
|
||||
});
|
||||
|
||||
window.openEditLibraryItem = function(itemId) {
|
||||
async function fetchLibraryGroupMembers(seriesGroupId) {
|
||||
if (!seriesGroupId) return [];
|
||||
|
||||
try {
|
||||
const response = await fetch(`/api/library_group/${encodeURIComponent(seriesGroupId)}`);
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP ${response.status}`);
|
||||
}
|
||||
|
||||
const payload = await response.json();
|
||||
return Array.isArray(payload.items) ? payload.items : [];
|
||||
} catch (error) {
|
||||
console.warn('Falling back to loaded library items for group editing:', error);
|
||||
return (libraryItems || []).filter(item => item.SeriesGroupId === seriesGroupId);
|
||||
}
|
||||
}
|
||||
|
||||
function renderLibraryGroupCodeFields(groupMembers, currentItemId) {
|
||||
const codesContainer = document.getElementById('editLibraryCodesContainer');
|
||||
const groupWarning = document.getElementById('editLibraryGroupWarning');
|
||||
const groupCount = document.getElementById('editLibraryGroupCount');
|
||||
const groupHint = document.getElementById('editLibraryGroupHint');
|
||||
|
||||
if (!codesContainer) return;
|
||||
|
||||
const items = Array.isArray(groupMembers) ? groupMembers.slice() : [];
|
||||
items.sort((a, b) => (a.SeriesPosition || 0) - (b.SeriesPosition || 0) || String(a.Name || '').localeCompare(String(b.Name || '')));
|
||||
|
||||
editLibraryState.groupMembers = items;
|
||||
|
||||
if (groupWarning) {
|
||||
groupWarning.style.display = items.length > 1 ? 'block' : 'none';
|
||||
}
|
||||
if (groupCount) {
|
||||
const totalCount = items.length || 1;
|
||||
const declaredCount = items[0]?.SeriesCount || totalCount;
|
||||
groupCount.textContent = `${totalCount} / ${declaredCount}`;
|
||||
}
|
||||
if (groupHint) {
|
||||
groupHint.textContent = items.length > 1
|
||||
? 'Jeder Code gehört zu einem eigenen Exemplar. Änderungen werden für alle Codes gespeichert.'
|
||||
: 'Einzelnes Exemplar. Der Code wird direkt gespeichert.';
|
||||
}
|
||||
|
||||
if (!items.length) {
|
||||
codesContainer.innerHTML = '<div style="padding:10px 0; color:#6b7280;">Keine Codes geladen.</div>';
|
||||
return;
|
||||
}
|
||||
|
||||
codesContainer.innerHTML = items.map((member, index) => {
|
||||
const codeValue = member.Code_4 || member.Code4 || '';
|
||||
const labelParts = [];
|
||||
if (member.SeriesPosition !== undefined && member.SeriesPosition !== null) {
|
||||
labelParts.push(`Exemplar ${member.SeriesPosition}`);
|
||||
} else {
|
||||
labelParts.push(`Exemplar ${index + 1}`);
|
||||
}
|
||||
if (member._id === currentItemId) {
|
||||
labelParts.push('aktuelles Medium');
|
||||
}
|
||||
return `
|
||||
<div style="display:flex; flex-direction:column; gap:6px; margin-bottom:10px;">
|
||||
<label for="editLibraryCode-${member._id}" style="font-weight:600; font-size:0.9em; color:var(--ui-text);">${escapeHtml(labelParts.join(' · '))}</label>
|
||||
<input id="editLibraryCode-${member._id}" data-item-id="${escapeHtml(member._id)}" value="${escapeHtml(codeValue)}" placeholder="Mediencode" style="width:100%; padding:8px 10px; border:1px solid #d0d7e2; border-radius:6px;">
|
||||
</div>
|
||||
`;
|
||||
}).join('');
|
||||
}
|
||||
|
||||
window.openEditLibraryItem = async function(itemId) {
|
||||
const item = libraryItems.find(i => i._id === itemId);
|
||||
if (!item) return;
|
||||
|
||||
editLibraryState.itemId = item._id;
|
||||
editLibraryState.seriesGroupId = item.SeriesGroupId || '';
|
||||
editLibraryState.groupMembers = [];
|
||||
|
||||
// 1. Felder befüllen
|
||||
document.getElementById('editLibraryItemId').value = item._id;
|
||||
document.getElementById('editLibraryName').value = item.Name;
|
||||
document.getElementById('editLibraryType').value = item.ItemType;
|
||||
document.getElementById('editLibraryIsbn').value = item.ISBN || '';
|
||||
document.getElementById('editLibraryCode4').value = item.Code_4 || '';
|
||||
document.getElementById('editLibraryLocation').value = item.Ort;
|
||||
document.getElementById('editLibraryDescription').value = item.Beschreibung;
|
||||
|
||||
// 2. Gruppen-Logik
|
||||
const warningDiv = document.getElementById('editLibraryGroupWarning');
|
||||
const codesContainer = document.getElementById('editLibraryAllCodes');
|
||||
|
||||
if (item.SeriesGroupId) {
|
||||
// Filtern aus dem aktuell geladenen Array
|
||||
let groupMembers = libraryItems.filter(i => i.SeriesGroupId === item.SeriesGroupId);
|
||||
|
||||
// SCHLÜSSEL: Wenn die Anzahl der gefundenen Elemente nicht mit SeriesCount übereinstimmt,
|
||||
// haben wir die Gruppe noch nicht vollständig geladen.
|
||||
if (groupMembers.length < (item.SeriesCount || 0)) {
|
||||
console.warn("Gruppe noch nicht vollständig geladen. Anzeige ggf. unvollständig.");
|
||||
// Optional: Zeige einen Ladehinweis im Modal
|
||||
codesContainer.textContent = "Lade restliche Gruppenmitglieder...";
|
||||
} else {
|
||||
// Daten sind vollständig -> Anzeigen
|
||||
const codeList = groupMembers
|
||||
.sort((a, b) => (a.SeriesPosition || 0) - (b.SeriesPosition || 0))
|
||||
.map(m => m.Code_4 || "---")
|
||||
.join(', ');
|
||||
|
||||
codesContainer.textContent = codeList;
|
||||
}
|
||||
|
||||
document.getElementById('editLibraryGroupCount').textContent = groupMembers.length + " / " + (item.SeriesCount || "?");
|
||||
warningDiv.style.display = 'block';
|
||||
} else {
|
||||
warningDiv.style.display = 'none';
|
||||
const codesContainer = document.getElementById('editLibraryCodesContainer');
|
||||
if (codesContainer) {
|
||||
codesContainer.innerHTML = '<div style="padding:10px 0; color:#6b7280;">Lade Codes...</div>';
|
||||
}
|
||||
|
||||
const groupMembers = item.SeriesGroupId ? await fetchLibraryGroupMembers(item.SeriesGroupId) : [item];
|
||||
renderLibraryGroupCodeFields(groupMembers.length > 0 ? groupMembers : [item], item._id);
|
||||
|
||||
document.getElementById('editLibraryModal').style.display = 'flex';
|
||||
};
|
||||
|
||||
function closeEditLibraryModal() {
|
||||
document.getElementById('editLibraryModal').style.display = 'none';
|
||||
}
|
||||
|
||||
/**
|
||||
* Event-Listener für das Formular (Initialisierung)
|
||||
*/
|
||||
document.addEventListener('DOMContentLoaded', function() {
|
||||
const editForm = document.getElementById('editLibraryForm');
|
||||
if (editForm) {
|
||||
editForm.addEventListener('submit', async function(e) {
|
||||
e.preventDefault();
|
||||
|
||||
const itemId = document.getElementById('editLibraryItemId').value;
|
||||
const currentItem = libraryItems.find(i => i._id === itemId);
|
||||
|
||||
if (!currentItem) return;
|
||||
|
||||
// 1. Alle Mitglieder der Gruppe finden, um die Code-Liste aufzubauen
|
||||
const groupMembers = libraryItems.filter(i => i.SeriesGroupId === currentItem.SeriesGroupId);
|
||||
const individualUpdates = groupMembers.map(member => ({
|
||||
id: member._id,
|
||||
// Wenn dies das bearbeitete Item ist, nimm den neuen Code, sonst den alten
|
||||
code_4: (member._id === itemId) ? document.getElementById('editLibraryCode4').value : member.Code_4
|
||||
}));
|
||||
|
||||
// 2. Payload für das Backend bauen
|
||||
const payload = {
|
||||
series_group_id: currentItem.SeriesGroupId,
|
||||
name: document.getElementById('editLibraryName').value,
|
||||
ort: document.getElementById('editLibraryLocation').value,
|
||||
beschreibung: document.getElementById('editLibraryDescription').value,
|
||||
isbn: document.getElementById('editLibraryIsbn').value,
|
||||
item_type: document.getElementById('editLibraryType').value,
|
||||
items: individualUpdates
|
||||
};
|
||||
|
||||
// 3. Request an die Gruppen-Update Route
|
||||
try {
|
||||
const response = await fetch('/update_group', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(payload)
|
||||
});
|
||||
|
||||
const result = await response.json();
|
||||
if (result.success) {
|
||||
alert('Gruppe erfolgreich synchronisiert!');
|
||||
closeEditLibraryModal();
|
||||
await loadLibraryItems(); // Daten neu laden
|
||||
// renderTable(); // Ggf. Tabelle neu rendern
|
||||
} else {
|
||||
await loadLibraryItems();
|
||||
closeEditLibraryModal();
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Update failed:', error);
|
||||
alert('Netzwerkfehler.');
|
||||
}
|
||||
});
|
||||
|
||||
}
|
||||
});
|
||||
</script>
|
||||
|
||||
<div id="editLibraryModal" class="modal" style="display:none;">
|
||||
@@ -1395,15 +1605,12 @@
|
||||
<strong style="color: #0ea5e9;">Gruppen-Range (Total: <span id="editLibraryGroupCount"></span>)</strong>
|
||||
</div>
|
||||
|
||||
<p style="margin: 5px 0; font-size: 12px; color: #555;">
|
||||
Alle aufgeführten Codes gehören zu diesem Datensatz:
|
||||
<p id="editLibraryGroupHint" style="margin: 5px 0; font-size: 12px; color: #555;">
|
||||
Änderungen an Titel, Ort und Beschreibung werden auf alle Exemplare der Gruppe übertragen.
|
||||
</p>
|
||||
|
||||
<!-- Hier werden die Codes per JS eingefügt -->
|
||||
<div id="editLibraryAllCodes" style="display: flex; flex-wrap: wrap; gap: 5px; margin-top: 10px;"></div>
|
||||
|
||||
|
||||
<div style="margin-top: 15px; font-size: 11px; background: #e0f2fe; padding: 8px; border-radius: 4px;">
|
||||
<strong>Hinweis:</strong> Änderungen an Titel/Ort/Beschreibung werden auf <strong>alle</strong> Exemplare der Range übertragen.
|
||||
<strong>Hinweis:</strong> Jeder Mediencode wird einzeln gespeichert, damit alle Exemplare der Gruppe korrekt bleiben.
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -1429,8 +1636,8 @@
|
||||
<input id="editLibraryIsbn" placeholder="optional ISBN-10/13" style="width: 100%;">
|
||||
</div>
|
||||
<div>
|
||||
<label for="editLibraryCode4">Code</label>
|
||||
<input id="editLibraryCode4" placeholder="optional Mediencode" style="width: 100%;">
|
||||
<label>Mediencodes</label>
|
||||
<div id="editLibraryCodesContainer"></div>
|
||||
</div>
|
||||
<div class="full">
|
||||
<label for="editLibraryLocation">Ort</label>
|
||||
@@ -1448,20 +1655,4 @@
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
<div id="editLibraryGroupWarning" style="display:none; background-color: #fff; padding: 15px; border-radius: 6px; margin-bottom: 20px; border: 1px solid #0ea5e9;">
|
||||
<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px; border-bottom: 1px solid #eee; padding-bottom: 10px;">
|
||||
<strong style="color: #0ea5e9;">Gruppen-Range (Total: <span id="editLibraryGroupCount"></span>)</strong>
|
||||
</div>
|
||||
|
||||
<p style="margin: 5px 0; font-size: 12px; color: #555;">
|
||||
Alle Codes in dieser Gruppe:
|
||||
</p>
|
||||
|
||||
<!-- Hier wird die Liste als Komma-Text eingefügt -->
|
||||
<div id="editLibraryAllCodes" style="font-family: monospace; font-size: 14px; font-weight: bold; color: #333; margin-top: 5px;"></div>
|
||||
|
||||
<div style="margin-top: 15px; font-size: 11px; background: #e0f2fe; padding: 8px; border-radius: 4px;">
|
||||
<strong>Hinweis:</strong> Änderungen an Titel/Ort/Beschreibung werden auf <strong>alle</strong> Exemplare der Range übertragen.
|
||||
</div>
|
||||
</div>
|
||||
{% endblock %}
|
||||
@@ -4569,12 +4569,7 @@ document.addEventListener('DOMContentLoaded', ()=>{
|
||||
<div class="detail-label">Code:</div>
|
||||
<div class="detail-value">${escapeHtml(item.Code_4 || '-')}</div>
|
||||
</div>
|
||||
|
||||
<div class="detail-group">
|
||||
<div class="detail-label">Anzahl:</div>
|
||||
<div class="detail-value">${escapeHtml(String(item.GroupedDisplayCount || 1))}</div>
|
||||
</div>
|
||||
|
||||
|
||||
${isGroupedItem ? `
|
||||
<div class="detail-group">
|
||||
<div class="detail-label">Verfügbar:</div>
|
||||
|
||||
@@ -19,7 +19,7 @@
|
||||
<div class="col-md-4">
|
||||
<div class="card mb-4">
|
||||
<div class="card-header">
|
||||
<h2 class="card-title h5 mb-0">{{ filter_names.get('1', 'Fach/Kategorie') }} (Filter 1)</h2>
|
||||
<h2 class="card-title h5 mb-0">{{ filter_names.get('1', 'Jahrgang') }} (Filter 1)</h2>
|
||||
</div>
|
||||
<div class="card-body">
|
||||
<form method="POST" action="{{ url_for('add_filter_value', filter_num=1) }}" class="mb-4">
|
||||
@@ -67,7 +67,7 @@
|
||||
<div class="col-md-4">
|
||||
<div class="card mb-4">
|
||||
<div class="card-header">
|
||||
<h2 class="card-title h5 mb-0">{{ filter_names.get('2', 'System/Bereich') }} (Filter 2)</h2>
|
||||
<h2 class="card-title h5 mb-0">{{ filter_names.get('2', 'Fach') }} (Filter 2)</h2>
|
||||
</div>
|
||||
<div class="card-body">
|
||||
<form method="POST" action="{{ url_for('add_filter_value', filter_num=2) }}" class="mb-4">
|
||||
@@ -110,54 +110,6 @@
|
||||
</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 class="alert alert-warning">
|
||||
|
||||
@@ -229,7 +229,7 @@
|
||||
<div class="container">
|
||||
<div class="student-card-header">
|
||||
<div>
|
||||
<h1>📚 Bibliotheksausweise (Bibliotek)</h1>
|
||||
<h1>📚 Bibliotheksausweise (Bibliothek)</h1>
|
||||
</div>
|
||||
<div class="export-buttons">
|
||||
<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="1">2. {{ 'Artikel erfassen' if is_admin else 'Artikel finden' }}</button>
|
||||
{% 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 %}
|
||||
<button type="button" data-target-step="{{ '3' if library_module_enabled else '2' }}">4. Alltag</button>
|
||||
</div>
|
||||
@@ -341,7 +341,7 @@
|
||||
|
||||
{% if library_module_enabled %}
|
||||
<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>
|
||||
<ul>
|
||||
{% if is_admin %}
|
||||
@@ -358,7 +358,7 @@
|
||||
</ul>
|
||||
|
||||
<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 %}
|
||||
<a class="btn btn-outline-secondary btn-sm" href="{{ url_for('library_loans_admin') }}">Ausleihen ansehen</a>
|
||||
{% endif %}
|
||||
|
||||
+166
-59
@@ -761,6 +761,21 @@
|
||||
<h1>{{ page_title|default('Artikel hochladen') }}</h1>
|
||||
<form method="POST" action="{{ url_for('upload_item') }}" enctype="multipart/form-data">
|
||||
<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">
|
||||
<label for="name">Name:</label>
|
||||
<input type="text" id="name" name="name" required>
|
||||
@@ -784,7 +799,44 @@
|
||||
<label for="beschreibung">Beschreibung:</label>
|
||||
<textarea id="beschreibung" name="beschreibung" required></textarea>
|
||||
</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 %}
|
||||
<!-- Library Mode: Single Customizable Filter -->
|
||||
<div class="filter-inputs">
|
||||
@@ -800,9 +852,9 @@
|
||||
</select>
|
||||
<small style="display:block; color:#666;">Wählen Sie einen Medientyp aus zur Klassifizierung.</small>
|
||||
</div>
|
||||
<h3>Kategorie/Typ:</h3>
|
||||
<h3>Kategorie/Typ/Fach:</h3>
|
||||
<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>
|
||||
</div>
|
||||
</div>
|
||||
@@ -902,42 +954,6 @@
|
||||
<label for="anschaffungskosten">Anschaffungskosten (€)</label>
|
||||
<input id="anschaffungskosten" name="anschaffungskosten">
|
||||
</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) -->
|
||||
<div class="form-group" {% if show_library_features %}style="display:none;"{% endif %}>
|
||||
<label for="images">Bilder/Videos:</label>
|
||||
@@ -946,27 +962,12 @@
|
||||
<!-- Add image preview area -->
|
||||
<div class="image-preview-container" id="image-preview-container"></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">
|
||||
<label for="reservierbar" style="display:inline-block; width:auto; margin-right:10px;">Reservierbar:</label>
|
||||
<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>
|
||||
</div>
|
||||
{% endif %}
|
||||
|
||||
<button type="submit" class="submit-button">{{ 'Bücher hochladen' if show_library_features else 'Artikel hochladen' }}</button>
|
||||
</form>
|
||||
@@ -1023,6 +1024,90 @@
|
||||
<script>
|
||||
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 isVideoFile(filename) {
|
||||
const videoExtensions = ['.mp4', '.mov', '.avi', '.mkv', '.webm', '.flv', '.m4v', '.3gp'];
|
||||
@@ -1194,7 +1279,7 @@
|
||||
let generatedCodes = [];
|
||||
for (let i = start; i <= end; i++) {
|
||||
let numStr = i.toString().padStart(paddingLength, '0');
|
||||
generatedCodes.push(`${prefix}${numStr}`);
|
||||
generatedCodes.push(prefix ? `${prefix}${numStr}` : numStr);
|
||||
}
|
||||
|
||||
const codeField = document.getElementById('code_4');
|
||||
@@ -1384,10 +1469,32 @@
|
||||
scanModeSelect.addEventListener('change', toggleScanMode);
|
||||
}
|
||||
|
||||
// 4. ISBN Live-Validierung
|
||||
// 4. ISBN Live-Validierung und automatische Abfrage nach Scan/Enter
|
||||
const isbnInput = document.getElementById('isbn');
|
||||
if (isbnInput && typeof updateIsbnLiveValidation === 'function') {
|
||||
isbnInput.addEventListener('input', updateIsbnLiveValidation);
|
||||
if (isbnInput) {
|
||||
if (typeof updateIsbnLiveValidation === 'function') {
|
||||
isbnInput.addEventListener('input', updateIsbnLiveValidation);
|
||||
}
|
||||
|
||||
let isbnLookupTimer = null;
|
||||
isbnInput.addEventListener('input', function () {
|
||||
clearTimeout(isbnLookupTimer);
|
||||
const normalizedIsbn = typeof normalizeIsbnClient === 'function' ? normalizeIsbnClient(isbnInput.value) : isbnInput.value.trim();
|
||||
if (normalizedIsbn) {
|
||||
isbnLookupTimer = setTimeout(function () {
|
||||
handleIsbnLookupFromScanner();
|
||||
}, 250);
|
||||
}
|
||||
});
|
||||
|
||||
isbnInput.addEventListener('change', function () {
|
||||
if (typeof normalizeIsbnClient === 'function') {
|
||||
const normalizedIsbn = normalizeIsbnClient(isbnInput.value);
|
||||
if (normalizedIsbn) {
|
||||
handleIsbnLookupFromScanner();
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
// Load predefined filter values for dropdowns
|
||||
|
||||
@@ -0,0 +1,262 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="de">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Batch Upload</title>
|
||||
|
||||
<!-- CSRF-Token für JavaScript bereitstellen -->
|
||||
<meta name="csrf-token" content="{{ session.get('_csrf_token', '') }}">
|
||||
|
||||
<style>
|
||||
body { font-family: sans-serif; padding: 20px; background: #f4f7f6; }
|
||||
.upload-container { background: white; padding: 20px; border-radius: 8px; max-width: 500px; margin: 0 auto; }
|
||||
.form-group { margin-bottom: 15px; }
|
||||
label { display: block; font-weight: bold; margin-bottom: 5px; }
|
||||
input[type="file"] { width: 100%; padding: 8px; box-sizing: border-box; }
|
||||
.btn-submit { width: 100%; padding: 10px; background: #4a90e2; color: white; border: none; border-radius: 4px; font-weight: bold; cursor: pointer; }
|
||||
.btn-submit:disabled { background: #ccc; }
|
||||
#uploadProgress { margin-top: 20px; display: none; }
|
||||
progress { width: 100%; height: 20px; }
|
||||
#logList { background: #fafafa; border: 1px solid #eee; padding: 10px; max-height: 150px; overflow-y: auto; font-size: 0.85em; list-style: none; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
<div class="upload-container">
|
||||
<h2>Inventar Batch Upload</h2>
|
||||
|
||||
<form id="batchUploadForm">
|
||||
<div class="form-group">
|
||||
<label for="csv_file">1. items.csv auswählen</label>
|
||||
<input type="file" id="csv_file" name="csv_file" accept=".csv" required>
|
||||
</div>
|
||||
|
||||
<div class="form-group">
|
||||
<label for="images">2. Bilder auswählen</label>
|
||||
<input type="file" id="images" name="images" accept="image/*" multiple required>
|
||||
</div>
|
||||
|
||||
<button type="submit" id="uploadBtn" class="btn-submit">Daten hochladen</button>
|
||||
</form>
|
||||
|
||||
<div id="uploadProgress">
|
||||
<div id="progressText">Bereite Upload vor...</div>
|
||||
<progress id="progressBar" value="0" max="100"></progress>
|
||||
<ul id="logList"></ul>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
// 1. Robuster CSV-Parser, der Zeilenumbrüche und Kommas in Texten korrekt ignoriert
|
||||
function parseCSV(csvString) {
|
||||
const rows = [];
|
||||
let currentRow = [];
|
||||
let currentCell = '';
|
||||
let insideQuotes = false;
|
||||
|
||||
for (let i = 0; i < csvString.length; i++) {
|
||||
const char = csvString[i];
|
||||
const nextChar = csvString[i + 1];
|
||||
|
||||
if (char === '"' && insideQuotes && nextChar === '"') {
|
||||
currentCell += '"';
|
||||
i++; // Escaped Quotes ("") überspringen
|
||||
} else if (char === '"') {
|
||||
insideQuotes = !insideQuotes;
|
||||
} else if (char === ',' && !insideQuotes) {
|
||||
currentRow.push(currentCell);
|
||||
currentCell = '';
|
||||
} else if ((char === '\n' || char === '\r') && !insideQuotes) {
|
||||
if (char === '\r' && nextChar === '\n') i++; // Windows Umbrüche überspringen
|
||||
currentRow.push(currentCell);
|
||||
if (currentRow.length > 1 || currentRow[0] !== '') {
|
||||
rows.push(currentRow);
|
||||
}
|
||||
currentRow = [];
|
||||
currentCell = '';
|
||||
} else {
|
||||
currentCell += char;
|
||||
}
|
||||
}
|
||||
if (currentCell !== '' || currentRow.length > 0) {
|
||||
currentRow.push(currentCell);
|
||||
if (currentRow.length > 1 || currentRow[0] !== '') {
|
||||
rows.push(currentRow);
|
||||
}
|
||||
}
|
||||
return rows;
|
||||
}
|
||||
|
||||
// 2. Baut das Array wieder sicher zu einer sauberen CSV-Zeile für das Backend zusammen
|
||||
function rowToCSV(rowArray) {
|
||||
return rowArray.map(cell => {
|
||||
if (cell === null || cell === undefined) return '';
|
||||
let cellStr = String(cell);
|
||||
if (cellStr.includes(',') || cellStr.includes('"') || cellStr.includes('\n') || cellStr.includes('\r')) {
|
||||
return '"' + cellStr.replace(/"/g, '""') + '"';
|
||||
}
|
||||
return cellStr;
|
||||
}).join(',');
|
||||
}
|
||||
|
||||
// 3. Bildnamen extrahieren
|
||||
function extractImageNames(cellValue) {
|
||||
if (!cellValue) return [];
|
||||
let raw = String(cellValue).replace(/^["']|["']$/g, '').trim();
|
||||
if (raw.startsWith('[') && raw.endsWith(']')) {
|
||||
try {
|
||||
const jsonValid = raw.replace(/'/g, '"');
|
||||
return JSON.parse(jsonValid);
|
||||
} catch (e) {
|
||||
const matches = raw.match(/['"]([^'"]+)['"]/g);
|
||||
if (matches) return matches.map(m => m.replace(/['"]/g, ''));
|
||||
}
|
||||
}
|
||||
return raw ? [raw] : [];
|
||||
}
|
||||
|
||||
document.getElementById('batchUploadForm').addEventListener('submit', async function(e) {
|
||||
e.preventDefault();
|
||||
|
||||
const csvInput = document.getElementById('csv_file');
|
||||
const imageInput = document.getElementById('images');
|
||||
const uploadBtn = document.getElementById('uploadBtn');
|
||||
const progressContainer = document.getElementById('uploadProgress');
|
||||
const progressBar = document.getElementById('progressBar');
|
||||
const progressText = document.getElementById('progressText');
|
||||
const logList = document.getElementById('logList');
|
||||
|
||||
const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content');
|
||||
|
||||
if (!csvInput.files.length) {
|
||||
alert("Bitte wähle eine CSV-Datei aus.");
|
||||
return;
|
||||
}
|
||||
|
||||
uploadBtn.disabled = true;
|
||||
progressContainer.style.display = 'block';
|
||||
logList.innerHTML = '';
|
||||
|
||||
const log = (msg) => {
|
||||
const li = document.createElement('li');
|
||||
li.textContent = msg;
|
||||
logList.appendChild(li);
|
||||
logList.scrollTop = logList.scrollHeight;
|
||||
};
|
||||
|
||||
const csvFile = csvInput.files[0];
|
||||
const allImages = Array.from(imageInput.files);
|
||||
|
||||
const imageMap = new Map();
|
||||
allImages.forEach(file => {
|
||||
imageMap.set(file.name.toLowerCase(), file);
|
||||
});
|
||||
|
||||
const BATCH_SIZE = 20;
|
||||
|
||||
try {
|
||||
const csvText = await csvFile.text();
|
||||
const allRows = parseCSV(csvText);
|
||||
|
||||
if (allRows.length <= 1) {
|
||||
throw new Error("CSV-Datei ist leer oder enthält nur Kopfzeilen.");
|
||||
}
|
||||
|
||||
const headerRow = allRows[0];
|
||||
const dataRows = allRows.slice(1);
|
||||
|
||||
log(`${dataRows.length} Einträge gefunden. Bereite Batches vor...`);
|
||||
|
||||
const imagesColIndex = headerRow.findIndex(h => h.toLowerCase().trim() === 'images');
|
||||
|
||||
const batches = [];
|
||||
for (let i = 0; i < dataRows.length; i += BATCH_SIZE) {
|
||||
batches.push(dataRows.slice(i, i + BATCH_SIZE));
|
||||
}
|
||||
|
||||
progressBar.max = batches.length;
|
||||
progressBar.value = 0;
|
||||
|
||||
// Sequenzieller Upload mit Fehlertoleranz pro Batch
|
||||
for (let b = 0; b < batches.length; b++) {
|
||||
const batchRows = batches[b];
|
||||
progressText.textContent = `Lade Batch ${b + 1} von ${batches.length} hoch...`;
|
||||
|
||||
try {
|
||||
const requiredImagesForBatch = new Set();
|
||||
|
||||
if (imagesColIndex !== -1) {
|
||||
batchRows.forEach(rowCols => {
|
||||
if (rowCols[imagesColIndex]) {
|
||||
const imgNames = extractImageNames(rowCols[imagesColIndex]);
|
||||
imgNames.forEach(name => {
|
||||
const fileMatch = imageMap.get(name.toLowerCase());
|
||||
if (fileMatch) {
|
||||
requiredImagesForBatch.add(fileMatch);
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
const batchCsvArray = [headerRow, ...batchRows];
|
||||
const batchCsvText = batchCsvArray.map(rowToCSV).join('\n');
|
||||
const batchCsvBlob = new Blob([batchCsvText], { type: 'text/csv' });
|
||||
|
||||
const formData = new FormData();
|
||||
formData.append('csv_file', batchCsvBlob, `batch_${b + 1}.csv`);
|
||||
|
||||
if (csrfToken) {
|
||||
formData.append('csrf_token', csrfToken);
|
||||
}
|
||||
|
||||
requiredImagesForBatch.forEach(imgFile => {
|
||||
formData.append('images', imgFile);
|
||||
});
|
||||
|
||||
log(`Batch ${b + 1}: ${batchRows.length} Items & ${requiredImagesForBatch.size} zugehörige Bilder.`);
|
||||
|
||||
const response = await fetch('/upload_csv_batch', {
|
||||
method: 'POST',
|
||||
body: formData,
|
||||
headers: {
|
||||
'X-CSRFToken': csrfToken || ''
|
||||
}
|
||||
});
|
||||
|
||||
const responseText = await response.text();
|
||||
let result;
|
||||
|
||||
try {
|
||||
result = JSON.parse(responseText);
|
||||
} catch (parseErr) {
|
||||
throw new Error(`Server-Fehler (Status ${response.status}). HTML statt JSON erhalten.`);
|
||||
}
|
||||
|
||||
if (!response.ok || !result.success) {
|
||||
throw new Error(result.message || `Server-Fehler ${response.status}`);
|
||||
}
|
||||
|
||||
log(`Batch ${b + 1} erfolgreich abgeschlossen.`);
|
||||
|
||||
} catch (batchErr) {
|
||||
log(`⚠️ FEHLER in Batch ${b + 1}: ${batchErr.message}. Überspringe und fahre fort...`);
|
||||
console.error(`Batch ${b + 1} fehlgeschlagen:`, batchErr);
|
||||
}
|
||||
|
||||
progressBar.value = b + 1;
|
||||
}
|
||||
|
||||
progressText.textContent = "Upload-Prozess beendet!";
|
||||
uploadBtn.disabled = false;
|
||||
|
||||
} catch (err) {
|
||||
alert("Upload abgebrochen: " + err.message);
|
||||
log("Fehler: " + err.message);
|
||||
uploadBtn.disabled = false;
|
||||
}
|
||||
});
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -17,15 +17,11 @@
|
||||
<div class="user-management-container">
|
||||
<h2>Benutzer</h2>
|
||||
|
||||
<form method="POST" action="{{ url_for('admin_anonymize_names') }}" class="mb-3">
|
||||
<button
|
||||
type="submit"
|
||||
class="btn btn-outline-danger"
|
||||
onclick="return confirm('Sollen alle gespeicherten Klarnamen dauerhaft in Synonym-Kuerzel umgewandelt werden?')"
|
||||
>
|
||||
Gespeicherte Namen anonymisieren
|
||||
</button>
|
||||
</form>
|
||||
<div class="mb-3">
|
||||
<a href="{{ url_for('register') }}" class="btn btn-success">
|
||||
Neuen Benutzer registrieren
|
||||
</a>
|
||||
</div>
|
||||
|
||||
<div class="filter-bar mb-3">
|
||||
<div class="row g-2 align-items-end">
|
||||
|
||||
+35
-17
@@ -166,6 +166,11 @@ def _find_registered_tenant_id(candidate):
|
||||
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):
|
||||
hostname = str(hostname or '').strip()
|
||||
if not hostname:
|
||||
@@ -185,6 +190,8 @@ def get_tenant_config(tenant_id=None):
|
||||
ctx = get_tenant_context()
|
||||
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:
|
||||
return TENANT_REGISTRY[tenant_id] or {}
|
||||
|
||||
@@ -481,20 +488,22 @@ class TenantContext:
|
||||
or request.args.get('tenantId', '').strip()
|
||||
)
|
||||
if tenant_from_query:
|
||||
matched_tenant = _find_registered_tenant_id(tenant_from_query) or tenant_from_query
|
||||
self.tenant_id = matched_tenant
|
||||
self.config = get_tenant_config(matched_tenant)
|
||||
session['tenant_id'] = matched_tenant
|
||||
return self._get_db_name(matched_tenant)
|
||||
matched_tenant = _resolve_registered_tenant_id(tenant_from_query)
|
||||
if matched_tenant:
|
||||
self.tenant_id = matched_tenant
|
||||
self.config = get_tenant_config(matched_tenant)
|
||||
session['tenant_id'] = matched_tenant
|
||||
return self._get_db_name(matched_tenant)
|
||||
|
||||
# Priority 1: X-Tenant-ID header (for testing/internal APIs)
|
||||
tenant_from_header = request.headers.get('X-Tenant-ID', '').strip()
|
||||
if tenant_from_header:
|
||||
matched_tenant = _find_registered_tenant_id(tenant_from_header) or tenant_from_header
|
||||
self.tenant_id = matched_tenant
|
||||
self.config = get_tenant_config(matched_tenant)
|
||||
session['tenant_id'] = matched_tenant
|
||||
return self._get_db_name(matched_tenant)
|
||||
matched_tenant = _resolve_registered_tenant_id(tenant_from_header)
|
||||
if matched_tenant:
|
||||
self.tenant_id = matched_tenant
|
||||
self.config = get_tenant_config(matched_tenant)
|
||||
session['tenant_id'] = matched_tenant
|
||||
return self._get_db_name(matched_tenant)
|
||||
|
||||
# Priority 2: Port/host based tenant mapping
|
||||
host_candidates = _request_host_candidates()
|
||||
@@ -544,11 +553,11 @@ class TenantContext:
|
||||
if len(parts) >= 2:
|
||||
potential_subdomain = parts[0]
|
||||
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'):
|
||||
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'):
|
||||
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:
|
||||
self.subdomain = potential_subdomain
|
||||
self.tenant_id = matched_tenant
|
||||
@@ -565,12 +574,21 @@ class TenantContext:
|
||||
# Priority 4: sticky tenant from the authenticated session
|
||||
session_tenant = session.get('tenant_id', '').strip() if session.get('tenant_id') else ''
|
||||
if session_tenant:
|
||||
self.tenant_id = session_tenant
|
||||
self.config = get_tenant_config(session_tenant)
|
||||
matched_tenant = _resolve_registered_tenant_id(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(
|
||||
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.
|
||||
# If no explicit 'default' tenant config exists, use configured MongoDB DB.
|
||||
|
||||
+308
-89
@@ -12,6 +12,250 @@ fi
|
||||
# Resolve script directory so config paths are deterministic even when called via sudo
|
||||
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
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() {
|
||||
local config_path backup_path
|
||||
@@ -201,65 +445,35 @@ sys.path.insert(0, "/app/Web")
|
||||
from Web.modules.database import settings
|
||||
from pymongo import MongoClient
|
||||
import Web.modules.inventarsystem.data_protection as dp
|
||||
import Web.modules.database.user as us
|
||||
|
||||
tenant_id = sys.argv[1].lower()
|
||||
mode = sys.argv[2]
|
||||
sanitized = "".join(c for c in tenant_id if c.isalnum() or c == "_")
|
||||
db_name = f"inventar_{sanitized}"
|
||||
client = MongoClient(settings.MONGODB_HOST, int(settings.MONGODB_PORT))
|
||||
db_name = f"inventar_{sanitized}" if sanitized else settings.MONGODB_DB
|
||||
|
||||
client = MongoClient(settings.MONGODB_HOST, settings.MONGODB_PORT)
|
||||
db = client[db_name]
|
||||
|
||||
pw_bytes = "admin123".encode("utf-8")
|
||||
random_salt = os.urandom(16)
|
||||
hashed = hashlib.scrypt(pw_bytes, salt=random_salt, n=16384, r=8, p=1)
|
||||
hashed_pw_string = f"v1${random_salt.hex()}${hashed.hex()}"
|
||||
|
||||
action_permissions = {
|
||||
"can_borrow": True,
|
||||
"can_insert": True,
|
||||
"can_edit": True,
|
||||
"can_delete": True,
|
||||
"can_manage_users": True,
|
||||
"can_manage_settings": True,
|
||||
"can_view_logs": True,
|
||||
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"],
|
||||
}
|
||||
|
||||
page_permissions = {
|
||||
"home": True,
|
||||
"tutorial_page": True,
|
||||
"my_borrowed_items": True,
|
||||
"notifications_view": True,
|
||||
"impressum": True,
|
||||
"license": True,
|
||||
"library_view": True,
|
||||
"terminplan": True,
|
||||
"home_admin": True,
|
||||
"upload_admin": True,
|
||||
"library_admin": True,
|
||||
"admin_borrowings": True,
|
||||
"library_loans_admin": True,
|
||||
"admin_damaged_items": True,
|
||||
"admin_audit_dashboard": True,
|
||||
"logs": True,
|
||||
"manage_filters": True,
|
||||
"manage_locations": True,
|
||||
}
|
||||
|
||||
if db.users.count_documents({"Username": dp.encrypt_text("admin")}) == 0:
|
||||
db.users.insert_one({
|
||||
"Username": dp.encrypt_text("admin"),
|
||||
"Password": hashed_pw_string,
|
||||
"Admin": True,
|
||||
"active_ausleihung": None,
|
||||
"name": dp.encrypt_text("Admin"),
|
||||
"last_name": dp.encrypt_text("User"),
|
||||
"IsStudent": False,
|
||||
"PermissionPreset": "full_access",
|
||||
"ActionPermissions": action_permissions,
|
||||
"PagePermissions": page_permissions,
|
||||
})
|
||||
users.replace_one({"Username": "admin"}, admin_doc, upsert=True)
|
||||
print("Fallback successfully applied")
|
||||
|
||||
if mode == "trial":
|
||||
client = MongoClient(settings.MONGODB_HOST, settings.MONGODB_PORT)
|
||||
db = client[db_name]
|
||||
db.settings.update_one(
|
||||
{"setting_type": "tenant_trial"},
|
||||
{"$set": {
|
||||
@@ -272,6 +486,8 @@ if mode == "trial":
|
||||
upsert=True,
|
||||
)
|
||||
|
||||
client.close()
|
||||
|
||||
print(f"Tenant {sys.argv[1]} database initialized. Default admin: admin / admin123")
|
||||
PY
|
||||
}
|
||||
@@ -533,15 +749,18 @@ ${YELLOW}Nutzung:${RESET} $0 <befehl> [tenant_id] [optionen]
|
||||
|
||||
${BLUE}${BOLD}VERFÜGBARE BEFEHLE:${RESET}
|
||||
${GREEN}add${RESET} <tenant_id> [port]
|
||||
Legt einen neuen Tenant an, registriert den Port und initialisiert
|
||||
die MongoDB-Datenbank mit einem Standard-Admin (${YELLOW}admin / admin123${RESET}).
|
||||
Legt einen neuen Tenant an, registriert den Port, richtet den nginx-Host
|
||||
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]
|
||||
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>
|
||||
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.
|
||||
|
||||
${GREEN}restart-tenant${RESET} <tenant_id>
|
||||
@@ -602,11 +821,16 @@ case "$COMMAND" in
|
||||
register_tenant_port "$TENANT_ID" "$PORT_ARG"
|
||||
update_runtime_ports "$PORT_ARG"
|
||||
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
|
||||
restart_app_container
|
||||
fi
|
||||
fi
|
||||
|
||||
|
||||
|
||||
echo "Adding new tenant '$TENANT_ID'..."
|
||||
echo "Initializing database for $TENANT_ID..."
|
||||
initialize_tenant_database "$TENANT_ID" "standard"
|
||||
@@ -631,6 +855,9 @@ case "$COMMAND" in
|
||||
register_tenant_port "$TENANT_ID" "$PORT_ARG"
|
||||
update_runtime_ports "$PORT_ARG"
|
||||
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
|
||||
|
||||
write_trial_tenant_config "$TENANT_ID" "$PORT_ARG" "$DAYS_ARG"
|
||||
@@ -643,11 +870,11 @@ case "$COMMAND" in
|
||||
initialize_tenant_database "$TENANT_ID" "trial"
|
||||
echo "Trial tenant '$TENANT_ID' successfully configured. It will expire after $DAYS_ARG day(s) and self-delete."
|
||||
;;
|
||||
|
||||
|
||||
remove)
|
||||
FORCE_REMOVE=false
|
||||
TENANT_ARG="${2:-}"
|
||||
|
||||
|
||||
if [ "$TENANT_ARG" = "--yes" ] || [ "$TENANT_ARG" = "-y" ]; then
|
||||
FORCE_REMOVE=true
|
||||
TENANT_ID="${3:-}"
|
||||
@@ -672,40 +899,31 @@ case "$COMMAND" in
|
||||
echo "Removing tenant '$TENANT_ID'..."
|
||||
APP_CONTAINER=$(docker ps -qf "name=app" | head -n 1)
|
||||
port_to_remove=""
|
||||
|
||||
|
||||
if [ -n "$APP_CONTAINER" ]; then
|
||||
# Zuerst die Datenbank via PyMongo hart droppen (Erzwungenes Löschen)
|
||||
port_to_remove="$(docker exec "$APP_CONTAINER" python3 - "$TENANT_ID" <<'PY'
|
||||
import sys, re
|
||||
sys.path.insert(0, '/app')
|
||||
sys.path.insert(0, '/app/Web')
|
||||
from tenant import delete_tenant, get_tenant_config
|
||||
from Web.modules.database import settings
|
||||
from pymongo import MongoClient
|
||||
# MongoDB-Datenbank via PyMongo direkt im Container droppen
|
||||
docker exec -i "$APP_CONTAINER" python3 -c '
|
||||
import sys, os
|
||||
try:
|
||||
import pymongo
|
||||
tenant_id = sys.argv[1]
|
||||
mongo_uri = os.environ.get("MONGO_URI", "mongodb://localhost:27017/")
|
||||
client = pymongo.MongoClient(mongo_uri, serverSelectionTimeoutMS=2000)
|
||||
db_name = f"inventar_{tenant_id}"
|
||||
if db_name in client.list_database_names():
|
||||
client.drop_database(db_name)
|
||||
print(f"Dropped database: {db_name}")
|
||||
except Exception as e:
|
||||
print(f"Error dropping database: {e}", file=sys.stderr)
|
||||
' "$TENANT_ID" > /dev/null 2>&1
|
||||
|
||||
tenant_id = sys.argv[1]
|
||||
tenant_cfg = get_tenant_config(tenant_id)
|
||||
port = tenant_cfg.get('port')
|
||||
# Konfiguration und Port via Host-Funktion bereinigen und Port ermitteln
|
||||
if port_to_remove="$(remove_tenant_port "$TENANT_ID" 2>/dev/null)"; then
|
||||
:
|
||||
else
|
||||
port_to_remove=""
|
||||
fi
|
||||
|
||||
# Datenbanknamen exakt rekonstruieren
|
||||
sanitized = "".join(c for c in tenant_id if c.isalnum() or c == "_")
|
||||
db_name = f"inventar_{sanitized}"
|
||||
|
||||
try:
|
||||
client = MongoClient(settings.MONGODB_HOST, int(settings.MONGODB_PORT))
|
||||
client.drop_database(db_name)
|
||||
print(f"MongoDB database '{db_name}' dropped successfully.", file=sys.stderr)
|
||||
except Exception as e:
|
||||
print(f"Warning: Could not drop database '{db_name}': {e}", file=sys.stderr)
|
||||
|
||||
if not delete_tenant(tenant_id):
|
||||
print(f'Error: failed to delete tenant {tenant_id}', file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
if port is not None:
|
||||
print(port)
|
||||
PY
|
||||
)"
|
||||
echo "Tenant '$TENANT_ID' database and config removed."
|
||||
else
|
||||
echo "Warning: Application container not running. Tenant database may still exist in MongoDB."
|
||||
@@ -719,6 +937,7 @@ PY
|
||||
if [ -n "$port_to_remove" ]; then
|
||||
remove_runtime_port "$port_to_remove"
|
||||
fi
|
||||
remove_tenant_nginx_config "$TENANT_ID"
|
||||
sync_tenant_port_map
|
||||
if [ -n "$(docker ps -qf 'name=app' | head -n 1)" ]; then
|
||||
restart_app_container
|
||||
@@ -728,7 +947,7 @@ PY
|
||||
else
|
||||
echo "Removed tenant '$TENANT_ID'. No port mapping was present."
|
||||
fi
|
||||
;;
|
||||
;;
|
||||
|
||||
restart-tenant)
|
||||
TENANT_ID="${2:-}"
|
||||
|
||||
+2
-1
@@ -17,4 +17,5 @@ cryptography>=42.0.0
|
||||
pywebpush
|
||||
py-vapid>=1.9.0
|
||||
beautifulsoup4
|
||||
pywebpush
|
||||
pywebpush
|
||||
pandas
|
||||
@@ -9,13 +9,13 @@ LOG_DIR="$PROJECT_DIR/logs"
|
||||
LOG_FILE="$LOG_DIR/update.log"
|
||||
STATE_FILE="$PROJECT_DIR/.release-version"
|
||||
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"
|
||||
ENV_FILE="$PROJECT_DIR/.docker-build.env"
|
||||
APP_IMAGE_REPO="git.invario-software.eu/invario/inventarsystem"
|
||||
COMPOSE_FILE="docker-compose-multitenant.yml"
|
||||
MIN_ROOT_FREE_MB="${INVENTAR_MIN_ROOT_FREE_MB:-2048}"
|
||||
MODE="release"
|
||||
MODE="stable"
|
||||
|
||||
mkdir -p "$LOG_DIR"
|
||||
chmod 777 "$LOG_DIR" 2>/dev/null || true
|
||||
@@ -119,6 +119,7 @@ usage() {
|
||||
Usage: $0 [options]
|
||||
|
||||
Options:
|
||||
-dev Install the latest prerelease build
|
||||
--multitenant Use docker-compose-multitenant.yml (default)
|
||||
-h, --help Show this help message
|
||||
EOF
|
||||
@@ -127,6 +128,10 @@ EOF
|
||||
parse_args() {
|
||||
while [[ $# -gt 0 ]]; do
|
||||
case "$1" in
|
||||
-dev)
|
||||
MODE="development"
|
||||
shift
|
||||
;;
|
||||
--multitenant)
|
||||
COMPOSE_FILE="docker-compose-multitenant.yml"
|
||||
shift
|
||||
@@ -179,7 +184,8 @@ create_backup() {
|
||||
|
||||
fetch_release_metadata() {
|
||||
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() {
|
||||
@@ -207,6 +213,124 @@ for asset in data.get('assets', []):
|
||||
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() {
|
||||
local start_url stop_url restart_url update_url
|
||||
start_url="https://git.invario-software.eu/$REPO_SLUG/raw/branch/main/start.sh"
|
||||
@@ -368,12 +492,66 @@ main() {
|
||||
archive_logs
|
||||
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
|
||||
log_message "Requested development install"
|
||||
local tag="dev"
|
||||
local app_image="$APP_IMAGE_REPO:$tag"
|
||||
local compose_path="$PROJECT_DIR/$COMPOSE_FILE"
|
||||
local tag meta_file releases_file stable_meta_file stable_tag prerelease_tag prerelease_base_tag bundle_url app_image compose_path
|
||||
local tmp_dir
|
||||
|
||||
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
|
||||
log_message "ERROR: compose file not found: $compose_path"
|
||||
@@ -399,6 +577,9 @@ EOF
|
||||
exit 1
|
||||
fi
|
||||
|
||||
download_and_extract_bundle "$bundle_url" "$tmp_dir"
|
||||
refresh_runtime_scripts_from_main
|
||||
|
||||
# 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" up -d --remove-orphans >> "$LOG_FILE" 2>&1
|
||||
@@ -409,7 +590,7 @@ EOF
|
||||
fi
|
||||
|
||||
echo "$tag" > "$STATE_FILE"
|
||||
log_message "Development update completed successfully"
|
||||
log_message "Development update completed successfully to prerelease $tag"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
@@ -419,8 +600,8 @@ EOF
|
||||
|
||||
trap 'rm -rf "${tmp_dir:-}"' EXIT
|
||||
|
||||
log_message "Checking latest Gitea release for $REPO_SLUG..."
|
||||
if ! fetch_release_metadata "$meta_file"; then
|
||||
log_message "Checking latest stable Gitea release for $REPO_SLUG..."
|
||||
if ! fetch_release_metadata "$meta_file" "latest"; then
|
||||
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 verify_stack_health; then
|
||||
@@ -436,7 +617,7 @@ EOF
|
||||
exit 0
|
||||
fi
|
||||
|
||||
latest_tag="$(parse_latest_tag "$meta_file")"
|
||||
latest_tag="$(parse_release_tag "$meta_file")"
|
||||
if [ -z "$latest_tag" ]; then
|
||||
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
|
||||
|
||||
Reference in New Issue
Block a user