Compare commits

...

24 Commits

Author SHA1 Message Date
Aiirondev_dev f847faea3e feat: Improve module import paths and add package initialization files 2026-05-20 17:43:06 +02:00
Aiirondev_dev 4c58dceb02 feat: Enhance error handling for URL resolution and unexpected exceptions 2026-05-20 17:06:22 +02:00
Aiirondev_dev db80693c6a fix: Update link to library admin in invoice template 2026-05-20 16:54:17 +02:00
Aiirondev_dev d451d58fc4 fix: Remove redundant conditional check for tag validation in release workflow 2026-05-20 16:40:56 +02:00
Aiirondev_dev 726520c9de feat: Simplify latest release tag fetching and bump strategy in release workflow 2026-05-20 16:36:53 +02:00
Aiirondev_dev fabac77877 feat: Add major version bump option and update release options documentation 2026-05-20 16:34:30 +02:00
Aiirondev_dev bb2832c273 feat: Remove local development image tar creation and update development bundle documentation 2026-05-20 16:32:27 +02:00
Aiirondev_dev ed122995ee feat: Add push_dev option for development image in release workflow and update tag handling 2026-05-20 16:26:09 +02:00
Aiirondev_dev 634feda9da feat: Refactor script copying to use loops for optional files in release bundle 2026-05-20 15:50:41 +02:00
Aiirondev_dev fb8be06e81 feat: Enhance version bump strategy and improve local image handling in release workflow 2026-05-20 15:40:27 +02:00
Aiirondev_dev 6ad1720461 feat: Add development bump option and update release conditions in workflow 2026-05-20 15:35:55 +02:00
Aiirondev_dev 0c27d7ac86 feat: Add Excel, PDF export, and user generation modules
- Implemented `excel_export.py` for generating library item exports in Excel format.
- Created `pdf_export.py` for generating audit reports compliant with DIN 5008 standards, including detailed event tables and signature blocks.
- Developed `generate_user.py` for interactive user creation with validation for usernames and passwords.
- Introduced `module_registry.py` for managing module states and path matching.
- Added a basic `__init__.py` in the `terminplaner` module for initialization.
2026-05-20 15:30:23 +02:00
Aiirondev_dev b3fc470c88 feat: add library route for viewing library items and reposition export route 2026-05-19 21:51:00 +02:00
Aiirondev_dev 541ca7172b feat: update get_version function to read application image from .docker-build.env 2026-05-19 21:06:44 +02:00
Aiirondev_dev 001a9fae17 feat: add get_version function to retrieve application version from .release-version file 2026-05-19 20:55:53 +02:00
Aiirondev_dev b572704381 feat: add runtime config initialization in manage-tenant.sh and update health check method in docker-compose 2026-05-19 20:53:50 +02:00
Aiirondev_dev 8b114b5b8e feat: enhance item card layout in table view for better spacing and alignment 2026-05-19 10:05:29 +02:00
Aiirondev_dev 96771d192c feat: add export functionality for library items and include 'schulbuch' type 2026-05-19 09:53:04 +02:00
Aiirondev_dev 073652c63d feat: optimize rootMargin for better performance based on layout 2026-05-18 23:38:13 +02:00
Aiirondev_dev 23d9d0871a feat: implement customizable filter names and update management interfaces 2026-05-18 23:20:52 +02:00
Aiirondev_dev 576d31a384 feat: add edit functionality for predefined filter values in filter management 2026-05-18 22:01:37 +02:00
Aiirondev_dev c43bb30301 feat: enhance bookmark and favorite button styles for dark mode 2026-05-18 18:30:14 +02:00
Aiirondev_dev 7eeea1d319 feat: update dark theme colors and add border radius for improved aesthetics 2026-05-18 17:49:42 +02:00
Aiirondev_dev 56486bcbb2 feat: update address details in impressum section 2026-05-18 17:39:19 +02:00
58 changed files with 830 additions and 1219 deletions
+122 -65
View File
@@ -14,6 +14,16 @@ on:
options: options:
- patch - patch
- minor - minor
- major
- development
push_dev:
description: "If true, push the :dev image to GHCR for development releases"
required: false
default: "false"
type: choice
options:
- "true"
- "false"
permissions: permissions:
contents: write contents: write
@@ -38,57 +48,46 @@ jobs:
EVENT_NAME: ${{ github.event_name }} EVENT_NAME: ${{ github.event_name }}
REF_NAME: ${{ github.ref_name }} REF_NAME: ${{ github.ref_name }}
BUMP_TYPE: ${{ github.event.inputs.bump || 'patch' }} BUMP_TYPE: ${{ github.event.inputs.bump || 'patch' }}
PUSH_DEV: ${{ github.event.inputs.push_dev || 'false' }}
run: | run: |
if [ "$EVENT_NAME" = "push" ] && [ -n "$REF_NAME" ]; then if [ "$EVENT_NAME" = "push" ] && [ -n "$REF_NAME" ]; then
TAG="$REF_NAME" TAG="$REF_NAME"
else else
TAG="$(python3 - <<'PY' # Fetch latest release tag via GitHub API (fall back to v3.0.0)
import json latest_tag="v3.0.0"
import os if meta_json=$(curl -fsSL -H "Authorization: Bearer $GH_TOKEN" -H "Accept: application/vnd.github+json" "https://api.github.com/repos/$REPO/releases/latest" 2>/dev/null); then
import re tag_name=$(printf "%s" "$meta_json" | sed -n 's/.*"tag_name"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' | head -n1)
import urllib.request if [ -n "$tag_name" ]; then
latest_tag="$tag_name"
fi
fi
repo = os.environ["REPO"] if [[ "$latest_tag" =~ ^v([0-9]+)\.([0-9]+)\.([0-9]+)$ ]]; then
token = os.environ.get("GH_TOKEN", "") major=${BASH_REMATCH[1]}
bump = os.environ.get("BUMP_TYPE", "patch").strip().lower() minor=${BASH_REMATCH[2]}
patch=${BASH_REMATCH[3]}
else
major=3; minor=0; patch=0
fi
req = urllib.request.Request( # Bump strategy: major / minor / patch
f"https://api.github.com/repos/{repo}/releases/latest", if [ "${BUMP_TYPE:-}" = "major" ]; then
headers={ major=$((major + 1)); minor=0; patch=0
"Authorization": f"Bearer {token}", elif [ "${BUMP_TYPE:-}" = "minor" ]; then
"Accept": "application/vnd.github+json", minor=$((minor + 1)); patch=0
"User-Agent": "legendary-octo-garbanzo-release-workflow", else
}, patch=$((patch + 1))
) fi
latest_tag = "v3.0.0" if [ "${BUMP_TYPE:-}" = "development" ]; then
try: TAG="v${major}.${minor}.${patch}-dev"
with urllib.request.urlopen(req, timeout=20) as resp: else
data = json.loads(resp.read().decode("utf-8")) TAG="v${major}.${minor}.${patch}"
latest_tag = (data.get("tag_name") or latest_tag).strip() fi
except Exception:
pass
m = re.match(r"^v(\d+)\.(\d+)\.(\d+)$", latest_tag)
if not m:
major, minor, patch = 3, 0, 0
else:
major, minor, patch = map(int, m.groups())
# Keep major fixed from latest release; only bump minor/patch.
if bump == "minor":
minor += 1
patch = 0
else:
patch += 1
print(f"v{major}.{minor}.{patch}")
PY
)"
fi fi
if ! echo "$TAG" | grep -Eq '^v[0-9]+\.[0-9]+\.[0-9]+$'; then if ! echo "$TAG" | grep -Eq '^v[0-9]+\.[0-9]+\.[0-9]+(-dev(\.[0-9]+)?)?$'; then
echo "Error: tag '$TAG' is not valid semver (vX.Y.Z)" echo "Error: tag '$TAG' is not valid semver (vX.Y.Z or vX.Y.Z-dev)"
exit 1 exit 1
fi fi
@@ -105,21 +104,35 @@ jobs:
LATEST_MAJOR="3" LATEST_MAJOR="3"
fi fi
if [ "$TAG_MAJOR" != "$LATEST_MAJOR" ]; then # If not explicitly bumping major, disallow changing major version
if [ "${BUMP_TYPE:-}" != "major" ] && [ "$TAG_MAJOR" != "$LATEST_MAJOR" ]; then
echo "Error: major version must stay v$LATEST_MAJOR.x.x (got $TAG)" echo "Error: major version must stay v$LATEST_MAJOR.x.x (got $TAG)"
exit 1 exit 1
fi fi
while git rev-parse -q --verify "refs/tags/$TAG" >/dev/null; do # Ensure tag uniqueness: if tag exists append numeric suffix
BASE="${TAG%.*}" if git rev-parse -q --verify "refs/tags/$TAG" >/dev/null; then
PATCH="${TAG##*.}" i=1
PATCH="$((PATCH + 1))" base="$TAG"
TAG="$BASE.$PATCH" while git rev-parse -q --verify "refs/tags/${base}.${i}" >/dev/null; do
done i="$((i + 1))"
done
TAG="${base}.${i}"
fi
IMAGE="ghcr.io/aiirondev/legendary-octo-garbanzo:${TAG}" IMAGE="ghcr.io/aiirondev/legendary-octo-garbanzo:${TAG}"
echo "tag=$TAG" >> "$GITHUB_OUTPUT" echo "tag=$TAG" >> "$GITHUB_OUTPUT"
echo "image=$IMAGE" >> "$GITHUB_OUTPUT" echo "image=$IMAGE" >> "$GITHUB_OUTPUT"
if [ "${BUMP_TYPE:-}" = "development" ]; then
echo "is_development=true" >> "$GITHUB_OUTPUT"
else
echo "is_development=false" >> "$GITHUB_OUTPUT"
fi
if [ "${BUMP_TYPE:-}" = "development" ] && [ "${PUSH_DEV:-}" = "true" ]; then
echo "push_dev=true" >> "$GITHUB_OUTPUT"
else
echo "push_dev=false" >> "$GITHUB_OUTPUT"
fi
- name: Create and push tag for manual releases - name: Create and push tag for manual releases
if: github.event_name == 'workflow_dispatch' if: github.event_name == 'workflow_dispatch'
@@ -141,6 +154,7 @@ jobs:
password: ${{ secrets.GITHUB_TOKEN }} password: ${{ secrets.GITHUB_TOKEN }}
- name: Build and push release image - name: Build and push release image
if: steps.meta.outputs.is_development != 'true'
uses: docker/build-push-action@v6 uses: docker/build-push-action@v6
with: with:
context: . context: .
@@ -150,10 +164,39 @@ jobs:
${{ steps.meta.outputs.image }} ${{ steps.meta.outputs.image }}
ghcr.io/aiirondev/legendary-octo-garbanzo:latest ghcr.io/aiirondev/legendary-octo-garbanzo:latest
- name: Build and push development image (:dev)
if: steps.meta.outputs.is_development == 'true' && steps.meta.outputs.push_dev == 'true'
uses: docker/build-push-action@v6
with:
context: .
file: ./Dockerfile
push: true
tags: |
ghcr.io/aiirondev/legendary-octo-garbanzo:dev
- name: Build local image tar for offline deploy - name: Build local image tar for offline deploy
run: | run: |
docker pull "${{ steps.meta.outputs.image }}" set -euo pipefail
docker save "${{ steps.meta.outputs.image }}" | gzip > "inventarsystem-image-${{ steps.meta.outputs.tag }}.tar.gz" IMG="${{ steps.meta.outputs.image }}"
TAG="${{ steps.meta.outputs.tag }}"
if docker image inspect "$IMG" >/dev/null 2>&1; then
echo "Using local image $IMG"
docker save "$IMG" | gzip > "inventarsystem-image-${TAG}.tar.gz"
exit 0
fi
echo "Local image $IMG not found, trying to pull"
if docker pull "$IMG" >/dev/null 2>&1; then
docker save "$IMG" | gzip > "inventarsystem-image-${TAG}.tar.gz"
exit 0
fi
echo "Pull failed, attempting local docker build as fallback"
docker build -t "$IMG" .
docker save "$IMG" | gzip > "inventarsystem-image-${TAG}.tar.gz"
# development tar omitted: dev releases will be versioned (vX.Y.Z-dev) and handled by update.sh using the tag
- name: Create release-only docker bundle - name: Create release-only docker bundle
run: | run: |
@@ -224,29 +267,43 @@ jobs:
redis_data: redis_data:
EOF EOF
cp start.sh release-bundle/start.sh # Copy runtime scripts and config if present
cp stop.sh release-bundle/stop.sh for f in start.sh stop.sh restart.sh backup.sh config.json update.sh; do
cp restart.sh release-bundle/restart.sh if [ -f "$f" ]; then
cp backup.sh release-bundle/backup.sh cp "$f" "release-bundle/$(basename "$f")"
cp config.json release-bundle/config.json fi
cp update.sh release-bundle/update.sh done
# Multitenant scripts & docs # Multitenant scripts & docs (optional)
cp docker-compose-multitenant.yml release-bundle/docker-compose-multitenant.yml for f in docker-compose-multitenant.yml manage-tenant.sh run-tenant-cmd.sh MULTITENANT_DEPLOYMENT.md MULTITENANT_PYTHON_API.md; do
cp manage-tenant.sh release-bundle/manage-tenant.sh if [ -f "$f" ]; then
cp run-tenant-cmd.sh release-bundle/run-tenant-cmd.sh cp "$f" "release-bundle/$(basename "$f")"
cp MULTITENANT_DEPLOYMENT.md release-bundle/MULTITENANT_DEPLOYMENT.md fi
cp MULTITENANT_PYTHON_API.md release-bundle/MULTITENANT_PYTHON_API.md done
chmod +x release-bundle/start.sh release-bundle/stop.sh release-bundle/restart.sh release-bundle/backup.sh release-bundle/update.sh release-bundle/manage-tenant.sh release-bundle/run-tenant-cmd.sh cat > release-bundle/DEVELOPMENT.md <<EOF
This is a development prerelease bundle for tag: ${{ steps.meta.outputs.tag }}
This prerelease is intentionally separate from normal releases and will not be used by default.
To install this prerelease on a target host run:
./update.sh ${{ steps.meta.outputs.tag }}
EOF
# Make any shipped scripts executable
find release-bundle -maxdepth 1 -type f -name '*.sh' -exec chmod +x {} \; || true
tar -czf inventarsystem-docker-bundle.tar.gz -C release-bundle . tar -czf inventarsystem-docker-bundle.tar.gz -C release-bundle .
- name: Create or update GitHub Release - name: Create or update GitHub Release
uses: softprops/action-gh-release@v2 uses: softprops/action-gh-release@v2
with: with:
tag_name: ${{ steps.meta.outputs.tag }} tag_name: ${{ steps.meta.outputs.tag }}
prerelease: ${{ steps.meta.outputs.is_development }}
files: | files: |
inventarsystem-docker-bundle.tar.gz inventarsystem-docker-bundle.tar.gz
inventarsystem-image-${{ steps.meta.outputs.tag }}.tar.gz inventarsystem-image-${{ steps.meta.outputs.tag }}.tar.gz
fail_on_unmatched_files: true inventarsystem-image-dev.tar.gz
fail_on_unmatched_files: false
generate_release_notes: true generate_release_notes: true
+38
View File
@@ -0,0 +1,38 @@
Release-Optionen
=================
Diese Datei beschreibt die Eingabeoptionen des CI-Workflows `.github/workflows/release-docker.yml`.
Inputs (workflow_dispatch)
- `bump` (choice)
- `patch` (Standard): Erhöht nur die Patch-Version (vX.Y.Z -> vX.Y.Z+1).
- `minor`: Erhöht die Minor-Version und setzt Patch auf 0 (vX.Y.Z -> vX.Y+1.0).
- `major`: Erhöht die Major-Version und setzt Minor/Patch auf 0 (vX.Y.Z -> vX+1.0.0).
- `development`: Erzeugt einen Development-Release mit Suffix `-dev` (z. B. `v3.1.4-dev`).
- `push_dev` (choice, optional)
- `false` (Standard): Bei `bump=development` wird das `:dev`-Image NICHT automatisch an GHCR gepusht.
- `true`: Bei `bump=development` wird zusätzlich das Image `ghcr.io/aiirondev/legendary-octo-garbanzo:dev` gepusht.
Verhalten/Anmerkungen
- Development releases werden als GitHub Release erzeugt und als `prerelease` markiert, damit sie nicht automatisch von normalen UpdateFlows genutzt werden.
- Es gibt pro Release genau einen ReleaseEintrag (für DevReleases mit `-dev` Suffix). Es wird kein separates `inventarsystem-image-dev.tar.gz` mehr erzeugt; das Update/Deployment erfolgt über den ReleaseTag / ImageTag.
- `update.sh` unterstützt weiterhin `dev`/`development`-Modus und akzeptiert nun auch explizite ReleaseTags wie `v3.1.4-dev`.
Beispiele
- Patch-Release (manuell):
- GitHub UI: Run workflow → `bump=patch`
- CLI mit `gh`:
gh workflow run release-docker.yml --repo AIIrondev/legendary-octo-garbanzo --field bump=patch
- Development prerelease (ohne Push des :dev Images):
- GitHub UI: Run workflow → `bump=development` (leave `push_dev=false`)
- Ergebnis: Release `vX.Y.Z-dev` als prerelease, Image wird nicht automatisch als `:dev` gepusht.
- Development prerelease + push des :dev Images:
- GitHub UI: Run workflow → `bump=development`, `push_dev=true`
- CLI Beispiel:
gh workflow run release-docker.yml --repo AIIrondev/legendary-octo-garbanzo --field bump=development --field push_dev=true
Empfehlung
- Verwende `bump=development` für experimentelle/early releases; Nutzer müssen explizit `./update.sh vX.Y.Z-dev` ausführen, um auf diese Version zu upgraden.
+1
View File
@@ -0,0 +1 @@
# Web package initialization
+155 -14
View File
@@ -28,13 +28,26 @@ Features:
from flask import Flask, render_template, request, redirect, url_for, session, flash, send_from_directory, get_flashed_messages, jsonify, Response, make_response, send_file, abort from flask import Flask, render_template, request, redirect, url_for, session, flash, send_from_directory, get_flashed_messages, jsonify, Response, make_response, send_file, abort
from werkzeug.utils import secure_filename from werkzeug.utils import secure_filename
from werkzeug.middleware.proxy_fix import ProxyFix from werkzeug.middleware.proxy_fix import ProxyFix
from werkzeug.exceptions import HTTPException
from werkzeug.routing import BuildError
from jinja2 import TemplateNotFound from jinja2 import TemplateNotFound
import user as us import os
import items as it import sys
import ausleihung as au
import audit_log as al # Ensure imports work regardless of whether gunicorn starts in /app or /app/Web.
_CURRENT_DIR = os.path.dirname(os.path.abspath(__file__))
_PROJECT_ROOT = os.path.dirname(_CURRENT_DIR)
if _PROJECT_ROOT not in sys.path:
sys.path.insert(0, _PROJECT_ROOT)
if _CURRENT_DIR not in sys.path:
sys.path.insert(0, _CURRENT_DIR)
import Web.modules.database.user as us
import Web.modules.database.items as it
import Web.modules.database.ausleihung as au
import Web.modules.logs.audit_log as al
import push_notifications as pn import push_notifications as pn
import pdf_export import Web.modules.inventarsystem.pdf_export as pdf_export
import datetime import datetime
from apscheduler.schedulers.background import BackgroundScheduler from apscheduler.schedulers.background import BackgroundScheduler
from bson.objectid import ObjectId from bson.objectid import ObjectId
@@ -42,7 +55,6 @@ from urllib.parse import urlparse, urlunparse
import requests import requests
import csv import csv
import ipaddress import ipaddress
import os
import json import json
import datetime import datetime
import time import time
@@ -63,13 +75,12 @@ except Exception:
# import qrcode # import qrcode
# from qrcode.constants import ERROR_CORRECT_L # from qrcode.constants import ERROR_CORRECT_L
import threading import threading
import sys
import shutil import shutil
import uuid import uuid
from PIL import Image, ImageOps from PIL import Image, ImageOps
import mimetypes import mimetypes
import subprocess import subprocess
from data_protection import ( from Web.modules.inventarsystem.data_protection import (
decrypt_document_fields, decrypt_document_fields,
encrypt_document_fields, encrypt_document_fields,
encrypt_soft_deleted_media_pack, encrypt_soft_deleted_media_pack,
@@ -77,8 +88,8 @@ from data_protection import (
# Set base directory and centralized settings # Set base directory and centralized settings
BASE_DIR = os.path.dirname(os.path.abspath(__file__)) BASE_DIR = os.path.dirname(os.path.abspath(__file__))
import settings as cfg import Web.modules.database.settings as cfg
from settings import MongoClient from Web.modules.database.settings import MongoClient
from tenant import get_tenant_context from tenant import get_tenant_context
@@ -166,7 +177,7 @@ SCHEDULER_INTERVAL = cfg.SCHEDULER_INTERVAL_MIN
SSL_CERT = cfg.SSL_CERT SSL_CERT = cfg.SSL_CERT
SSL_KEY = cfg.SSL_KEY SSL_KEY = cfg.SSL_KEY
LIBRARY_ITEM_TYPES = ['book', 'cd', 'dvd', 'media'] LIBRARY_ITEM_TYPES = ['book', 'cd', 'dvd', 'media', 'schulbuch']
INVOICE_CURRENCY = 'EUR' INVOICE_CURRENCY = 'EUR'
NOTIFICATION_STATUS_CACHE_TTL = max(3, int(os.getenv('INVENTAR_NOTIFICATION_STATUS_CACHE_TTL', '8'))) NOTIFICATION_STATUS_CACHE_TTL = max(3, int(os.getenv('INVENTAR_NOTIFICATION_STATUS_CACHE_TTL', '8')))
@@ -373,7 +384,7 @@ def _enforce_module_access():
if name != 'inventory' and cfg.MODULES.is_enabled('inventory'): if name != 'inventory' and cfg.MODULES.is_enabled('inventory'):
return redirect(url_for('home')) return redirect(url_for('home'))
elif name != 'library' and cfg.MODULES.is_enabled('library'): elif name != 'library' and cfg.MODULES.is_enabled('library'):
return redirect(url_for('library_view')) return redirect('/library')
return redirect(url_for('my_borrowed_items')) return redirect(url_for('my_borrowed_items'))
@@ -433,6 +444,41 @@ def handle_not_found(e):
return redirect(url_for('login')) return redirect(url_for('login'))
@app.errorhandler(BuildError)
def handle_build_error(e):
"""Handle url_for endpoint mismatches without crashing the whole request."""
app.logger.error(f"BuildError while resolving endpoint: {e}", exc_info=True)
if request.is_json or request.path.startswith('/api/'):
return jsonify({'error': 'Route resolution failed', 'status': 500}), 500
# Known fallback for legacy library endpoint naming issues.
if 'library_view' in str(e):
return redirect('/library')
if 'username' in session:
return redirect(url_for('home'))
return redirect(url_for('login'))
@app.errorhandler(Exception)
def handle_unexpected_exception(e):
"""Last-resort handler to avoid raw 500 pages for unhandled exceptions."""
if isinstance(e, HTTPException):
return e
app.logger.error('Unhandled exception', exc_info=True)
if request.is_json or request.path.startswith('/api/'):
return jsonify({'error': 'Internal server error', 'status': 500}), 500
if 'username' in session:
try:
return render_template('error.html', error_code=500, error_message='Interner Serverfehler.'), 500
except Exception:
return 'Internal Server Error', 500
return redirect(url_for('login'))
def _csrf_error_response(message='CSRF token fehlt oder ist ungültig.'): 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'}: if request.is_json or request.path.startswith('/api/') or request.path in {'/download_book_cover', '/proxy_image', '/log_mobile_issue'}:
return jsonify({'error': message}), 400 return jsonify({'error': message}), 400
@@ -2640,7 +2686,7 @@ def home():
if not cfg.MODULES.is_enabled('inventory'): if not cfg.MODULES.is_enabled('inventory'):
if cfg.MODULES.is_enabled('library'): if cfg.MODULES.is_enabled('library'):
return redirect(url_for('library_view')) return redirect('/library')
else: else:
return "Weder Inventar- noch Bibliotheks-Modul sind aktiviert.", 403 return "Weder Inventar- noch Bibliotheks-Modul sind aktiviert.", 403
@@ -2716,6 +2762,49 @@ def tutorial_page():
student_max_borrow_days=cfg.STUDENT_MAX_BORROW_DAYS student_max_borrow_days=cfg.STUDENT_MAX_BORROW_DAYS
) )
@app.route('/library/export', defaults={'scope': 'all'})
@app.route('/library/export/<scope>')
def library_export_excel(scope='all'):
if 'username' not in session:
return redirect(url_for('login'))
username = session['username']
is_admin_user = us.check_admin(username)
import Web.modules.inventarsystem.excel_export as excel_export
client = MongoClient(MONGODB_HOST, MONGODB_PORT)
db = client[cfg.MONGODB_DB]
items_collection = db['items']
query = {'ItemType': {'$in': LIBRARY_ITEM_TYPES}, 'Deleted': {'$ne': True}}
if scope == 'borrowed_by_me':
query['User'] = username
query['Verfuegbar'] = False
filename = f"Bibliothek_Ausgeliehen_{username}.xlsx"
elif scope == 'all_borrowed':
if not is_admin_user:
return redirect('/library')
query['Verfuegbar'] = False
filename = "Bibliothek_Alle_Ausleihen.xlsx"
elif scope == 'schulbuecher':
query['ItemType'] = 'schulbuch'
filename = "Schulbuecher_Bestand.xlsx"
else:
# 'all'
filename = "Bibliothek_Gesamtbestand.xlsx"
items = list(items_collection.find(query))
client.close()
excel_file = excel_export.generate_library_excel(items)
return flask.send_file(
excel_file,
mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
as_attachment=True,
download_name=filename
)
@app.route('/library') @app.route('/library')
def library_view(): def library_view():
""" """
@@ -8589,11 +8678,15 @@ def manage_filters():
filter2_values = it.get_predefined_filter_values(2) filter2_values = it.get_predefined_filter_values(2)
filter3_values = it.get_predefined_filter_values(3) filter3_values = it.get_predefined_filter_values(3)
# Get custom filter names
filter_names = it.get_filter_names()
return render_template( return render_template(
'manage_filters.html', 'manage_filters.html',
filter1_values=filter1_values, filter1_values=filter1_values,
filter2_values=filter2_values, filter2_values=filter2_values,
filter3_values=filter3_values, filter3_values=filter3_values,
filter_names=filter_names,
library_module_enabled=cfg.MODULES.is_enabled('library'), library_module_enabled=cfg.MODULES.is_enabled('library'),
student_cards_module_enabled=cfg.MODULES.is_enabled('student_cards') student_cards_module_enabled=cfg.MODULES.is_enabled('student_cards')
) )
@@ -8657,6 +8750,41 @@ def remove_filter_value(filter_num, value):
return redirect(url_for('manage_filters')) return redirect(url_for('manage_filters'))
@app.route('/edit_filter_value/<int:filter_num>/<string:old_value>', methods=['POST'])
def edit_filter_value(filter_num, old_value):
"""
Edit a predefined value from the specified filter.
Args:
filter_num (int): Filter number (1, 2 or 3)
old_value (str): Value to edit
Returns:
flask.Response: Redirect to filter management page
"""
if 'username' not in session or not us.check_admin(session['username']):
return jsonify({'success': False, 'error': 'Not authorized'}), 403
new_value = sanitize_form_value(request.form.get('new_value'))
if not new_value:
flash('Bitte geben Sie einen neuen Wert ein', 'error')
return redirect(url_for('manage_filters'))
if new_value == FILTER_SELECT_ALL_TOKEN:
flash('Dieser Wert ist reserviert und kann nicht als Filterwert gespeichert werden.', 'error')
return redirect(url_for('manage_filters'))
# Update the value from the filter
success = it.edit_predefined_filter_value(filter_num, old_value, new_value)
if success:
flash(f'Wert "{old_value}" wurde in "{new_value}" bei Filter {filter_num} geändert', 'success')
else:
flash(f'Fehler beim Ändern des Wertes oder Wert existiert bereits in Filter {filter_num}', 'error')
return redirect(url_for('manage_filters'))
@app.route('/get_predefined_filter_values/<int:filter_num>') @app.route('/get_predefined_filter_values/<int:filter_num>')
def get_predefined_filter_values(filter_num): def get_predefined_filter_values(filter_num):
""" """
@@ -9623,14 +9751,27 @@ def admin_school_settings():
try: try:
updated_school = cfg.update_school_info(school_info) updated_school = cfg.update_school_info(school_info)
current_school = updated_school current_school = updated_school
# Also process filter names
filter_name_1 = request.form.get('filter_name_1')
if filter_name_1: it.set_filter_name(1, filter_name_1.strip())
filter_name_2 = request.form.get('filter_name_2')
if filter_name_2: it.set_filter_name(2, filter_name_2.strip())
filter_name_3 = request.form.get('filter_name_3')
if filter_name_3: it.set_filter_name(3, filter_name_3.strip())
flash('Schulstammdaten wurden erfolgreich gespeichert.', 'success') flash('Schulstammdaten wurden erfolgreich gespeichert.', 'success')
except Exception as exc: except Exception as exc:
app.logger.error(f'Could not update school settings: {exc}\n{traceback.format_exc()}') app.logger.error(f'Could not update school settings: {exc}\n{traceback.format_exc()}')
flash('Die Schulstammdaten konnten nicht gespeichert werden.', 'error') flash('Die Schulstammdaten konnten nicht gespeichert werden.', 'error')
# Get current filter names to display in form
filter_names = it.get_filter_names()
return render_template( return render_template(
'admin_school_settings.html', 'admin_school_settings.html',
school_info=current_school, school_info=current_school,
filter_names=filter_names,
tenant_id=tenant_id, tenant_id=tenant_id,
tenant_db=tenant_db, tenant_db=tenant_db,
library_module_enabled=cfg.MODULES.is_enabled('library'), library_module_enabled=cfg.MODULES.is_enabled('library'),
@@ -10010,7 +10151,7 @@ def reset_item(id):
try: try:
# Import the ausleihung module # Import the ausleihung module
import ausleihung as au import Web.modules.database.ausleihung as au
result = au.reset_item_completely(id) result = au.reset_item_completely(id)
-149
View File
@@ -1,149 +0,0 @@
"""
Tamper-evident audit logging helpers.
The audit chain stores each entry with a hash of the previous entry.
Any mutation in history breaks the chain verification.
"""
import datetime
import hashlib
import json
import random
import time
from pymongo.errors import DuplicateKeyError
def _stable_json(value):
"""Serialize dictionaries in a stable way for deterministic hashing."""
return json.dumps(value, sort_keys=True, separators=(",", ":"), ensure_ascii=False, default=str)
def _entry_hash(prev_hash, payload):
"""Build the chained entry hash from previous hash + canonical payload."""
base = f"{prev_hash}|{_stable_json(payload)}"
return hashlib.sha256(base.encode("utf-8")).hexdigest()
def append_audit_event(db, event_type, actor, payload, request_ip=None, source="web", max_retries=5):
"""
Append an audit event to a tamper-evident chain.
Args:
db: MongoDB database handle.
event_type (str): Event category.
actor (str): User/system who performed the action.
payload (dict): Event details.
request_ip (str, optional): Request origin.
source (str): Source subsystem.
Returns:
dict: Inserted audit entry.
"""
logs = db["audit_log"]
attempts = 0
while attempts <= max_retries:
previous = logs.find_one(sort=[("chain_index", -1)])
prev_hash = previous.get("entry_hash", "") if previous else ""
chain_index = int(previous.get("chain_index", 0)) + 1 if previous else 1
timestamp = datetime.datetime.utcnow()
entry_payload = {
"event_type": event_type,
"actor": actor or "system",
"source": source,
"ip": request_ip or "",
"payload": payload or {},
"timestamp": timestamp.isoformat() + "Z",
}
entry_hash = _entry_hash(prev_hash, entry_payload)
entry = {
**entry_payload,
"created_at": timestamp,
"prev_hash": prev_hash,
"entry_hash": entry_hash,
"chain_index": chain_index,
}
try:
logs.insert_one(entry)
return entry
except DuplicateKeyError:
attempts += 1
if attempts > max_retries:
raise
# Exponential backoff with jitter to avoid retry storms.
delay = min(0.25, (0.005 * (2 ** attempts)) + random.random() * 0.01)
time.sleep(delay)
def ensure_audit_indexes(db):
"""Create indexes required for fast and safe audit operations."""
logs = db["audit_log"]
logs.create_index("chain_index", unique=True, name="audit_chain_index_unique")
logs.create_index("created_at", name="audit_created_at_idx")
logs.create_index("event_type", name="audit_event_type_idx")
def verify_audit_chain(db):
"""Verify hash chain integrity across all stored audit entries."""
logs = db["audit_log"]
entries = list(logs.find({}, {"_id": 1, "event_type": 1, "actor": 1, "source": 1, "ip": 1, "payload": 1, "timestamp": 1, "prev_hash": 1, "entry_hash": 1, "chain_index": 1}).sort("chain_index", 1))
previous_hash = ""
previous_index = 0
mismatches = []
for entry in entries:
chain_index = int(entry.get("chain_index", 0))
prev_hash = entry.get("prev_hash", "")
entry_hash = entry.get("entry_hash", "")
payload = {
"event_type": entry.get("event_type", ""),
"actor": entry.get("actor", ""),
"source": entry.get("source", ""),
"ip": entry.get("ip", ""),
"payload": entry.get("payload", {}),
"timestamp": entry.get("timestamp", ""),
}
expected_hash = _entry_hash(previous_hash, payload)
if chain_index != previous_index + 1:
mismatches.append({
"chain_index": chain_index,
"error": "chain_index_gap",
"expected": previous_index + 1,
"found": chain_index,
})
if prev_hash != previous_hash:
mismatches.append({
"chain_index": chain_index,
"error": "prev_hash_mismatch",
"expected": previous_hash,
"found": prev_hash,
})
if entry_hash != expected_hash:
mismatches.append({
"chain_index": chain_index,
"error": "entry_hash_mismatch",
"expected": expected_hash,
"found": entry_hash,
})
previous_hash = entry_hash
previous_index = chain_index
return {
"ok": len(mismatches) == 0,
"count": len(entries),
"last_chain_index": previous_index,
"last_hash": previous_hash,
"mismatches": mismatches,
}
-45
View File
@@ -1,45 +0,0 @@
'''
Copyright 2025-2026 AIIrondev
Licensed under the Inventarsystem EULA (Endbenutzer-Lizenzvertrag).
See Legal/LICENSE for the full license text.
Unauthorized commercial use, SaaS hosting, or removal of branding is prohibited.
For commercial licensing inquiries: https://github.com/AIIrondev
'''
"""
Funktion zum Protokollieren von Statusänderungen bei Ausleihungen
"""
import os
import datetime
from bson.objectid import ObjectId
def log_status_change(ausleihung_id, old_status, new_status, user=None):
"""
Protokolliert eine Statusänderung einer Ausleihung in einer Log-Datei.
Args:
ausleihung_id: Die ID der Ausleihung
old_status: Der alte Status
new_status: Der neue Status
user: Der Benutzer, der die Änderung vorgenommen hat (optional)
"""
try:
# Erstelle Log-Verzeichnis, falls es nicht existiert
log_dir = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'logs')
if not os.path.exists(log_dir):
os.makedirs(log_dir)
# Log-Datei für Statusänderungen
log_file = os.path.join(log_dir, 'ausleihungen_status_changes.log')
# Protokolliere die Änderung
timestamp = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
user_info = f" by {user}" if user else ""
with open(log_file, 'a', encoding='utf-8') as f:
f.write(f"{timestamp}: Ausleihung {ausleihung_id} - Status changed from '{old_status}' to '{new_status}'{user_info}\n")
return True
except Exception as e:
print(f"Fehler beim Protokollieren der Statusänderung: {e}")
return False
+1
View File
@@ -0,0 +1 @@
# Web.modules package initialization
+1
View File
@@ -0,0 +1 @@
# Web.modules.bibliothek package initialization
+4
View File
@@ -0,0 +1,4 @@
"""
"""
# Log initialization
@@ -32,8 +32,8 @@ from datetime import timezone
import os import os
import json import json
import shutil import shutil
import settings as cfg import Web.modules.database.settings as cfg
from settings import MongoClient from Web.modules.database.settings import MongoClient
# Add this helper function after imports # Add this helper function after imports
def ensure_timezone_aware(dt): def ensure_timezone_aware(dt):
@@ -103,7 +103,7 @@ def get_current_status(ausleihung, log_changes=False, user=None):
if log_changes and new_status != original_status and '_id' in ausleihung: if log_changes and new_status != original_status and '_id' in ausleihung:
try: try:
# Importieren Sie das Modul nur bei Bedarf, um zirkuläre Importe zu vermeiden # Importieren Sie das Modul nur bei Bedarf, um zirkuläre Importe zu vermeiden
import ausleihung_log import Web.modules.logs.ausleihung_log as ausleihung_log
ausleihung_log.log_status_change( ausleihung_log.log_status_change(
str(ausleihung['_id']), str(ausleihung['_id']),
original_status, original_status,
+76 -2
View File
@@ -28,8 +28,8 @@ Collection Structure:
''' '''
from bson.objectid import ObjectId from bson.objectid import ObjectId
import datetime import datetime
import settings as cfg import Web.modules.database.settings as cfg
from settings import MongoClient from Web.modules.database.settings import MongoClient
LIBRARY_ITEM_TYPES = ('book', 'cd', 'dvd', 'media') LIBRARY_ITEM_TYPES = ('book', 'cd', 'dvd', 'media')
@@ -794,6 +794,80 @@ def remove_predefined_filter_value(filter_num, value):
return result.modified_count > 0 return result.modified_count > 0
def edit_predefined_filter_value(filter_num, old_value, new_value):
"""
Edit a predefined value from a filter and update all matching items.
Args:
filter_num (int): Filter number (1 for Unterrichtsfach, 2 for Jahrgangsstufe)
old_value (str): Value to replace
new_value (str): New value
Returns:
bool: True if value was updated, False otherwise
"""
client = MongoClient(cfg.MONGODB_HOST, cfg.MONGODB_PORT)
db = client[cfg.MONGODB_DB]
filter_presets = db['filter_presets']
# Check if the new value already exists
existing = filter_presets.find_one({
'filter_num': filter_num,
'values': new_value
})
if existing and old_value != new_value:
client.close()
return False
# Update the value in the filter
result = filter_presets.update_one(
{'filter_num': filter_num, 'values': old_value},
{'$set': {'values.$': new_value}}
)
if result.modified_count > 0:
items = db['items']
filter_field = 'Filter' if filter_num == 1 else f'Filter{filter_num}'
# Also update all items that use this filter
items.update_many(
{filter_field: old_value},
{'$set': {filter_field: new_value}}
)
client.close()
return result.modified_count > 0
def get_filter_names():
"""Get customized filter category names."""
client = MongoClient(cfg.MONGODB_HOST, cfg.MONGODB_PORT)
db = client[cfg.MONGODB_DB]
names_doc = db.settings.find_one({'setting_type': 'filter_names'})
client.close()
if names_doc and 'names' in names_doc:
return names_doc['names']
return {
'1': 'Fach/Kategorie',
'2': 'System/Bereich',
'3': 'Typ/Art'
}
def set_filter_name(filter_num, name):
"""Set custom name for a filter category."""
client = MongoClient(cfg.MONGODB_HOST, cfg.MONGODB_PORT)
db = client[cfg.MONGODB_DB]
names = get_filter_names()
names[str(filter_num)] = name
db.settings.update_one(
{'setting_type': 'filter_names'},
{'$set': {'names': names}},
upsert=True
)
client.close()
return True
# === LOCATION MANAGEMENT === # === LOCATION MANAGEMENT ===
def get_predefined_locations(): def get_predefined_locations():
@@ -134,8 +134,14 @@ def _get_int_env(name, default):
except ValueError: except ValueError:
return int(default) return int(default)
def get_version():
with open(os.path.join(BASE_DIR, '..', '..', '..', '.docker-build.env'), 'r') as f:
for l in f:
if l.startswith('INVENTAR_APP_IMAGE='):
return l.split(':', 1)[1].strip()
# Expose settings # Expose settings
APP_VERSION = _get(_conf, ['ver'], DEFAULTS['version']) APP_VERSION = get_version()
DEBUG = _get_bool_env('INVENTAR_DEBUG', _get(_conf, ['dbg'], DEFAULTS['debug'])) DEBUG = _get_bool_env('INVENTAR_DEBUG', _get(_conf, ['dbg'], DEFAULTS['debug']))
SECRET_KEY = str(os.getenv('INVENTAR_SECRET_KEY', _get(_conf, ['key'], DEFAULTS['secret_key']))) SECRET_KEY = str(os.getenv('INVENTAR_SECRET_KEY', _get(_conf, ['key'], DEFAULTS['secret_key'])))
HOST = _get(_conf, ['host'], DEFAULTS['host']) HOST = _get(_conf, ['host'], DEFAULTS['host'])
@@ -205,7 +211,7 @@ class _TenantAwareBool:
return f"_TenantAwareBool(module_name={self.module_name!r}, value={self.resolve()!r})" return f"_TenantAwareBool(module_name={self.module_name!r}, value={self.resolve()!r})"
from module_registry import registry as MODULES from Web.modules.module_registry import registry as MODULES
INVENTORY_MODULE_ENABLED = _TenantAwareBool('inventory', _get(_conf, ['modules', 'inventory', 'enabled'], DEFAULTS['modules']['inventory']['enabled'])) INVENTORY_MODULE_ENABLED = _TenantAwareBool('inventory', _get(_conf, ['modules', 'inventory', 'enabled'], DEFAULTS['modules']['inventory']['enabled']))
LIBRARY_MODULE_ENABLED = _TenantAwareBool('library', _get(_conf, ['modules', 'library', 'enabled'], DEFAULTS['modules']['library']['enabled'])) LIBRARY_MODULE_ENABLED = _TenantAwareBool('library', _get(_conf, ['modules', 'library', 'enabled'], DEFAULTS['modules']['library']['enabled']))
+32
View File
@@ -0,0 +1,32 @@
from pymongo import MongoClient
import Web.modules.database.settings as cfg
def get_filter_names():
client = MongoClient(cfg.MONGODB_HOST, cfg.MONGODB_PORT)
db = client[cfg.MONGODB_DB]
names = db.settings.find_one({'setting_type': 'filter_names'})
client.close()
if names:
return names.get('names', {
'1': 'Fach/Kategorie',
'2': 'System/Bereich',
'3': 'Typ/Art'
})
return {
'1': 'Fach/Kategorie',
'2': 'System/Bereich',
'3': 'Typ/Art'
}
def set_filter_name(filter_num, name):
client = MongoClient(cfg.MONGODB_HOST, cfg.MONGODB_PORT)
db = client[cfg.MONGODB_DB]
names = get_filter_names()
names[str(filter_num)] = name
db.settings.update_one(
{'setting_type': 'filter_names'},
{'$set': {'names': names}},
upsert=True
)
client.close()
return True
+2 -2
View File
@@ -17,8 +17,8 @@ import re
import secrets import secrets
import string import string
from bson.objectid import ObjectId from bson.objectid import ObjectId
import settings as cfg import Web.modules.database.settings as cfg
from settings import MongoClient from Web.modules.database.settings import MongoClient
logger = logging.getLogger('app') logger = logging.getLogger('app')
logger.setLevel(logging.DEBUG) logger.setLevel(logging.DEBUG)
+1
View File
@@ -0,0 +1 @@
# Web.modules.emailservice package initialization
+6
View File
@@ -0,0 +1,6 @@
"""
Inventar System Funktionen
"""
@@ -10,7 +10,7 @@ from datetime import datetime
from cryptography.fernet import Fernet, InvalidToken from cryptography.fernet import Fernet, InvalidToken
import settings as cfg import Web.modules.database.settings as cfg
_ENC_PREFIX = "enc::" _ENC_PREFIX = "enc::"
@@ -0,0 +1,56 @@
import io
from openpyxl import Workbook
from openpyxl.styles import Font, PatternFill
def generate_library_excel(items):
wb = Workbook()
ws = wb.active
ws.title = "Export"
headers = [
"Code", "Titel", "Autor", "Typ", "ISBN/Code",
"Filter 1", "Filter 2", "Filter 3",
"Status", "Ausgeliehen von", "Rückgabe", "Kosten"
]
ws.append(headers)
header_font = Font(bold=True, color="FFFFFF")
header_fill = PatternFill(start_color="1F2937", end_color="1F2937", fill_type="solid")
for cell in ws[1]:
cell.font = header_font
cell.fill = header_fill
for item in items:
status = "Verfuegbar" if str(item.get("Verfuegbar", "True")).lower() == "true" else "Ausgeliehen"
row = [
item.get("Code_4", ""),
item.get("Name", ""),
item.get("Author", ""),
item.get("ItemType", ""),
item.get("ISBN", ""),
item.get("Filter", ""),
item.get("Filter2", ""),
item.get("Filter3", ""),
status,
item.get("User", ""),
item.get("ReturnDate", ""),
item.get("Anschaffungskosten", "")
]
ws.append(row)
for col in ws.columns:
max_length = 0
column = col[0].column_letter
for cell in col:
try:
if len(str(cell.value)) > max_length:
max_length = len(str(cell.value))
except:
pass
ws.column_dimensions[column].width = min(max_length + 2, 50)
excel_buffer = io.BytesIO()
wb.save(excel_buffer)
excel_buffer.seek(0)
return excel_buffer
@@ -6,7 +6,7 @@
Unauthorized commercial use, SaaS hosting, or removal of branding is prohibited. Unauthorized commercial use, SaaS hosting, or removal of branding is prohibited.
For commercial licensing inquiries: https://github.com/AIIrondev For commercial licensing inquiries: https://github.com/AIIrondev
''' '''
import user import Web.modules.database.user as user
import sys import sys
import getpass import getpass
import re import re
@@ -18,7 +18,7 @@ from reportlab.pdfgen import canvas
from reportlab.lib.enums import TA_LEFT, TA_RIGHT, TA_CENTER, TA_JUSTIFY from reportlab.lib.enums import TA_LEFT, TA_RIGHT, TA_CENTER, TA_JUSTIFY
from reportlab.pdfbase import pdfmetrics from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont from reportlab.pdfbase.ttfonts import TTFont
import settings as cfg import Web.modules.database.settings as cfg
__version__ = cfg.APP_VERSION __version__ = cfg.APP_VERSION
+1
View File
@@ -0,0 +1 @@
print("hello")
+2 -2
View File
@@ -11,8 +11,8 @@ import requests
import hashlib import hashlib
import logging import logging
import settings as cfg import Web.modules.database.settings as cfg
from settings import MongoClient from Web.modules.database.settings import MongoClient
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
+34 -7
View File
@@ -22,16 +22,21 @@
} }
:root[data-theme="dark"] { :root[data-theme="dark"] {
--ui-bg: #09090b; /* Tiefes Blau-Theme (Dark Blue) */
--ui-bg-accent: #121214; --ui-bg: #0b1120;
--ui-surface: #121214; --ui-bg-accent: #111827;
--ui-surface-soft: #1e1e22; --ui-surface: #1e293b;
--ui-border: #27272a; --ui-surface-soft: #334155;
--ui-text: #fafafa; --ui-border: #475569;
--ui-text-muted: #a1a1aa; --ui-text: #f8fafc;
--ui-text-muted: #94a3b8;
--ui-title: #ffffff; --ui-title: #ffffff;
--ui-shadow-sm: 0 4px 12px rgba(0, 0, 0, 0.4), inset 0 0 0 1px rgba(255, 255, 255, 0.05); --ui-shadow-sm: 0 4px 12px rgba(0, 0, 0, 0.4), inset 0 0 0 1px rgba(255, 255, 255, 0.05);
--ui-shadow-md: 0 10px 30px rgba(0, 0, 0, 0.6), inset 0 0 0 1px rgba(255, 255, 255, 0.05); --ui-shadow-md: 0 10px 30px rgba(0, 0, 0, 0.6), inset 0 0 0 1px rgba(255, 255, 255, 0.05);
/* Abgerundetes Format im gesamten Dark Mode */
--ui-radius: 20px;
--ui-btn-radius: 99px; /* Pillenform für Buttons */
} }
/* Safe Area Support for iPad notches, Dynamic Island, and rounded corners */ /* Safe Area Support for iPad notches, Dynamic Island, and rounded corners */
@@ -60,6 +65,7 @@ body {
background-color: var(--ui-bg) !important; background-color: var(--ui-bg) !important;
color: var(--ui-text) !important; color: var(--ui-text) !important;
border: 1px solid var(--ui-border) !important; border: 1px solid var(--ui-border) !important;
border-radius: 12px !important;
box-shadow: inset 0 1px 2px rgba(0,0,0,0.3) !important; box-shadow: inset 0 1px 2px rgba(0,0,0,0.3) !important;
} }
:root[data-theme="dark"] input:focus, :root[data-theme="dark"] input:focus,
@@ -396,6 +402,10 @@ body.table-view .item-card {
background: var(--ui-surface); background: var(--ui-surface);
box-shadow: none; box-shadow: none;
scroll-snap-align: none; scroll-snap-align: none;
min-height: 60px;
display: flex;
flex-direction: column;
justify-content: space-between;
} }
body.table-view .item-card .card-content { body.table-view .item-card .card-content {
@@ -975,3 +985,20 @@ html, body {
color: var(--ui-text) !important; color: var(--ui-text) !important;
border: 1px solid var(--ui-border); border: 1px solid var(--ui-border);
} }
/* Fix Bookmark/Favorite Button in Dark Mode */
:root[data-theme="dark"] .bookmark-btn {
background: var(--ui-surface-soft) !important;
border-color: #f59e0b !important;
color: #f59e0b !important;
}
:root[data-theme="dark"] .bookmark-btn:hover,
:root[data-theme="dark"] .bookmark-btn.active {
background: #f59e0b !important;
color: var(--ui-bg) !important;
}
:root[data-theme="dark"] .favorite-item {
outline: 2px solid #f59e0b !important;
}
+19
View File
@@ -71,6 +71,25 @@
<small>Upload ersetzt das bisherige Logo. Wenn kein neues Logo gewählt wird, bleibt das aktuelle erhalten.</small> <small>Upload ersetzt das bisherige Logo. Wenn kein neues Logo gewählt wird, bleibt das aktuelle erhalten.</small>
</div> </div>
<hr style="margin: 24px 0; border: 0; border-top: 1px solid #e5e7eb;">
<h3 style="font-size: 1.1rem; margin-bottom: 16px; color: #111827;">Globales Filter-Wording</h3>
<p style="font-size: 0.9rem; color: #6b7280; margin-bottom: 16px;">Hier kannst du die globalen Bezeichnungen für die drei Haupt-Kategorien (Filter) der Anwendung ändern.</p>
<div class="form-row">
<div class="form-group">
<label for="filter_name_1">Name Filter 1</label>
<input type="text" id="filter_name_1" name="filter_name_1" value="{{ filter_names.get('1', 'Fach/Kategorie') }}" placeholder="z. B. Fach/Kategorie">
</div>
<div class="form-group">
<label for="filter_name_2">Name Filter 2</label>
<input type="text" id="filter_name_2" name="filter_name_2" value="{{ filter_names.get('2', 'System/Bereich') }}" placeholder="z. B. System/Bereich">
</div>
<div class="form-group">
<label for="filter_name_3">Name Filter 3</label>
<input type="text" id="filter_name_3" name="filter_name_3" value="{{ filter_names.get('3', 'Typ/Art') }}" placeholder="z. B. Typ/Art">
</div>
</div>
<div class="actions-row"> <div class="actions-row">
<button type="submit" class="btn btn-primary">Schulstammdaten speichern</button> <button type="submit" class="btn btn-primary">Schulstammdaten speichern</button>
<a href="{{ url_for('home_admin') }}" class="btn btn-secondary">Zurück zur Admin-Übersicht</a> <a href="{{ url_for('home_admin') }}" class="btn btn-secondary">Zurück zur Admin-Übersicht</a>
+10 -11
View File
@@ -329,7 +329,7 @@
} }
/* iPad/Tablet responsive adjustments */ /* iPad/Tablet responsive adjustments */
@media (max-width: 1024px) { @media (max-width: 768px) {
.navbar .container-fluid { .navbar .container-fluid {
gap: 6px; gap: 6px;
padding-left: max(env(safe-area-inset-left, 0), 10px); padding-left: max(env(safe-area-inset-left, 0), 10px);
@@ -1096,16 +1096,6 @@
<a class="nav-link quick-link-pill {% if current_path == url_for('my_borrowed_items') %}nav-active{% endif %}" href="{{ url_for('my_borrowed_items') }}" data-tutorial-tip="Ihre aktuellen Ausleihen und Rückgaben finden Sie hier.">Meine Ausleihen</a> <a class="nav-link quick-link-pill {% if current_path == url_for('my_borrowed_items') %}nav-active{% endif %}" href="{{ url_for('my_borrowed_items') }}" data-tutorial-tip="Ihre aktuellen Ausleihen und Rückgaben finden Sie hier.">Meine Ausleihen</a>
</li> </li>
{% endif %} {% endif %}
{% if current_permissions.pages.get('tutorial_page', True) %}
<li class="nav-item">
<a class="nav-link quick-link-pill {% if current_path == url_for('tutorial_page') %}nav-active{% endif %}" href="{{ url_for('tutorial_page') }}" data-tutorial-tip="Öffnen Sie das Tutorial, um das System Schritt für Schritt kennenzulernen.">Tutorial</a>
</li>
{% endif %}
{% endif %}
{% if 'username' in session and current_permissions.pages.get('upload_admin', True) and current_permissions.actions.get('can_insert', True) %}
<li class="nav-item">
<a class="nav-link nav-priority-link {% if current_path == url_for('upload_admin') %}nav-active{% endif %}" href="{{ url_for('upload_admin') }}" data-tutorial-tip="Hier können Sie neue Artikel ins Inventar einpflegen."> Hochladen</a>
</li>
{% endif %} {% endif %}
<li class="nav-item" data-nav-fixed="true"> <li class="nav-item" data-nav-fixed="true">
<button id="themeToggleBtn" class="btn btn-link nav-link px-3" aria-label="Dark Mode umschalten" title="Theme umschalten"> <button id="themeToggleBtn" class="btn btn-link nav-link px-3" aria-label="Dark Mode umschalten" title="Theme umschalten">
@@ -1119,6 +1109,15 @@
Mehr Optionen Mehr Optionen
</a> </a>
<ul class="dropdown-menu dropdown-menu-end" aria-labelledby="invMoreDropdown"> <ul class="dropdown-menu dropdown-menu-end" aria-labelledby="invMoreDropdown">
{% if 'username' in session %}
{% if current_permissions.pages.get('tutorial_page', True) %}
<li><a class="dropdown-item" href="{{ url_for('tutorial_page') }}">Tutorial</a></li>
{% endif %}
{% if current_permissions.pages.get('upload_admin', True) and current_permissions.actions.get('can_insert', True) %}
<li><a class="dropdown-item" href="{{ url_for('upload_admin') }}"> Hochladen</a></li>
{% endif %}
<li><hr class="dropdown-divider"></li>
{% endif %}
{% if 'username' in session and (session.get('admin', False) or is_admin) and current_permissions.actions.get('can_manage_settings', True) %} {% if 'username' in session and (session.get('admin', False) or is_admin) and current_permissions.actions.get('can_manage_settings', True) %}
<li><h6 class="dropdown-header">Verwaltung</h6></li> <li><h6 class="dropdown-header">Verwaltung</h6></li>
{% if current_permissions.pages.get('manage_filters', True) %} {% if current_permissions.pages.get('manage_filters', True) %}
+3 -3
View File
@@ -20,7 +20,7 @@
<h3 class="mb-3">Kontaktinformationen</h3> <h3 class="mb-3">Kontaktinformationen</h3>
<address class="mb-0"> <address class="mb-0">
<p><strong>Name:</strong> Invario UG</p> <p><strong>Name:</strong> Invario UG</p>
<p><strong>Adresse:</strong> Musterstraße 123<br>12345 Musterstadt<br>Deutschland</p> <p><strong>Adresse:</strong> Am Sportplatz 10<br>83052 Bruckmühl<br>Deutschland</p>
</address> </address>
<p><strong>E-Mail:</strong> <a href="mailto:info@invario.eu">info@invario.eu</a></p> <p><strong>E-Mail:</strong> <a href="mailto:info@invario.eu">info@invario.eu</a></p>
</div> </div>
@@ -29,8 +29,8 @@
<h3 class="mb-3">Verantwortlich für den Inhalt</h3> <h3 class="mb-3">Verantwortlich für den Inhalt</h3>
<p>(nach § 18 Abs. 2 MStV)</p> <p>(nach § 18 Abs. 2 MStV)</p>
<p>Invario UG<br> <p>Invario UG<br>
Musterstraße 123<br> Am Sportplatz 10<br>
12345 Musterstadt<br> 83052 Bruckmühl<br>
Deutschland</p> Deutschland</p>
</div> </div>
+1 -1
View File
@@ -124,7 +124,7 @@
</div> </div>
<div class="head-actions"> <div class="head-actions">
<a class="btn btn-outline-secondary" href="{{ url_for('library_loans_admin') }}">Zur Bibliotheks-Ausleihenverwaltung</a> <a class="btn btn-outline-secondary" href="{{ url_for('library_loans_admin') }}">Zur Bibliotheks-Ausleihenverwaltung</a>
<a class="btn btn-secondary" href="{{ url_for('library_view') }}">Bibliothek öffnen</a> <a class="btn btn-secondary" href="{{ url_for('library_admin') }}">Bibliothek öffnen</a>
</div> </div>
</div> </div>
+11
View File
@@ -477,6 +477,7 @@
<select id="filterType"> <select id="filterType">
<option value="">-- Alle Typen --</option> <option value="">-- Alle Typen --</option>
<option value="book">Buch</option> <option value="book">Buch</option>
<option value="schulbuch">Schulbuch</option>
<option value="cd">CD</option> <option value="cd">CD</option>
<option value="dvd">DVD</option> <option value="dvd">DVD</option>
<option value="other">Sonstige</option> <option value="other">Sonstige</option>
@@ -495,6 +496,15 @@
<div class="filter-buttons"> <div class="filter-buttons">
<button id="applyFilterBtn" class="button" style="background: #4f46e5; color: white;">Filter anwenden</button> <button id="applyFilterBtn" class="button" style="background: #4f46e5; color: white;">Filter anwenden</button>
<button id="clearFilterBtn" class="button" style="background: #f0f2f5; color: var(--ui-text);">Zurücksetzen</button> <button id="clearFilterBtn" class="button" style="background: #f0f2f5; color: var(--ui-text);">Zurücksetzen</button>
<div style="flex-grow: 1;"></div>
<button class="button" style="background: #10b981; color: white; display: flex; align-items: center; gap: 0.5rem;" onclick="window.location.href='/library/export/schulbuecher'">
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"></path><polyline points="14 2 14 8 20 8"></polyline><line x1="8" y1="13" x2="16" y2="13"></line><line x1="8" y1="17" x2="16" y2="17"></line><polyline points="10 9 9 9 8 9"></polyline></svg>
Schulbücher Excel
</button>
<button class="button" style="background: #10b981; color: white; display: flex; align-items: center; gap: 0.5rem;" onclick="window.location.href='/library/export/all_borrowed'">
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"></path><polyline points="14 2 14 8 20 8"></polyline><line x1="8" y1="13" x2="16" y2="13"></line><line x1="8" y1="17" x2="16" y2="17"></line><polyline points="10 9 9 9 8 9"></polyline></svg>
Alle ausgeliehen Excel
</button>
</div> </div>
</div> </div>
@@ -1174,6 +1184,7 @@
<label for="editLibraryType">Medientyp</label> <label for="editLibraryType">Medientyp</label>
<select id="editLibraryType"> <select id="editLibraryType">
<option value="book">Buch</option> <option value="book">Buch</option>
<option value="schulbuch">Schulbuch</option>
<option value="cd">CD</option> <option value="cd">CD</option>
<option value="dvd">DVD</option> <option value="dvd">DVD</option>
<option value="media">Sonstige Medien</option> <option value="media">Sonstige Medien</option>
+46 -40
View File
@@ -760,11 +760,14 @@
if (!mainItemsLoadingIndicator) { if (!mainItemsLoadingIndicator) {
mainItemsLoadingIndicator = document.createElement('div'); mainItemsLoadingIndicator = document.createElement('div');
mainItemsLoadingIndicator.id = 'main-items-loading-indicator'; mainItemsLoadingIndicator.id = 'main-items-loading-indicator';
mainItemsLoadingIndicator.className = 'items-loading-indicator'; mainItemsLoadingIndicator.className = 'items-loading-indicator empty-frames-placeholder';
mainItemsLoadingIndicator.innerHTML = ` mainItemsLoadingIndicator.innerHTML = `
<div class="loading-track"><div class="loading-fill"></div></div> <div class="empty-frame p-3 mx-2" style="flex: 1; height: 100px; border-radius: 12px; background: rgba(255,255,255,0.02); min-width: 250px;"></div>
<div class="loading-label">Weitere Objekte werden vorbereitet...</div> <div class="empty-frame p-3 mx-2" style="flex: 1; height: 100px; border-radius: 12px; background: rgba(255,255,255,0.02); min-width: 250px; display: none;" class="d-none d-md-block"></div>
<div class="empty-frame p-3 mx-2" style="flex: 1; height: 100px; border-radius: 12px; background: rgba(255,255,255,0.02); min-width: 250px; display: none;" class="d-none d-lg-block"></div>
`; `;
mainItemsLoadingIndicator.style.display = 'flex';
mainItemsLoadingIndicator.style.width = '100%';
} }
itemsContainer.appendChild(mainItemsLoadingIndicator); itemsContainer.appendChild(mainItemsLoadingIndicator);
@@ -1200,6 +1203,7 @@
card.innerHTML = card.dataset.savedHtml; card.innerHTML = card.dataset.savedHtml;
card.dataset.deloaded = 'false'; card.dataset.deloaded = 'false';
card.classList.remove('is-deloaded'); card.classList.remove('is-deloaded');
card.classList.remove('empty-frame');
const favBtn = card.querySelector('.bookmark-btn'); const favBtn = card.querySelector('.bookmark-btn');
if (favBtn) { if (favBtn) {
favBtn.addEventListener('click', (ev) => { favBtn.addEventListener('click', (ev) => {
@@ -1227,12 +1231,15 @@
card.innerHTML = ''; card.innerHTML = '';
card.dataset.deloaded = 'true'; card.dataset.deloaded = 'true';
card.classList.add('is-deloaded'); card.classList.add('is-deloaded');
card.classList.add('empty-frame');
} }
} }
} }
}); });
}, { }, {
rootMargin: isMobileLayout ? '1500px 0px 1500px 0px' : '0px 2500px 0px 2500px' // Keep approx ~120 items rendered in DOM relative to scroll position.
// Assuming ~100-400px per item/row, this margin unloads elements beyond that range.
rootMargin: isMobileLayout ? '18000px 0px 18000px 0px' : '9000px 0px 9000px 0px'
}); });
} }
@@ -3156,46 +3163,45 @@
border: 1px solid var(--ui-border); border: 1px solid var(--ui-border);
border-radius: var(--ui-radius); border-radius: var(--ui-radius);
box-shadow: var(--ui-shadow-sm); box-shadow: var(--ui-shadow-sm);
padding: 20px; padding: 15px;
width: 100%; width: 100%;
max-width: 340px; max-width: 340px;
flex: 1 1 300px; flex: 1 1 300px;
scroll-snap-align: center; scroll-snap-align: center;
cursor: pointer; cursor: pointer;
transition: transform 0.2s, box-shadow 0.2s; transition: transform 0.2s, box-shadow 0.2s;
position: relative; position: relative;
content-visibility: auto; content-visibility: auto;
contain-intrinsic-size: 300px 450px; contain-intrinsic-size: 300px 380px;
} }
.item-card:hover { .item-card:hover {
transform: translateY(-5px); transform: translateY(-5px);
box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2); box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
} }
.item-card h3 { .item-card h3 {
margin-top: 0; margin-top: 0;
} font-size: 1.15rem;
margin-bottom: 8px;
}
.item-card .description { .item-card .description {
max-height: 100px; max-height: 60px;
overflow-y: auto; overflow-y: auto;
} font-size: 0.9rem;
margin-bottom: 8px;
}
.item-card .image-container { .item-card .image-container {
position: relative; position: relative;
max-width: 300px; max-width: 300px;
margin: 10px 0; margin: 8px 0;
} }
.item-card .item-image { .item-card .item-image {
width: 100%; width: 100%;
height: auto; height: auto;
max-height: 300px; max-height: 180px;
display: none;
object-fit: cover;
}
.item-card .item-image:first-child {
display: block; display: block;
} }
+20 -9
View File
@@ -395,7 +395,7 @@
border: 1px solid var(--ui-border); border: 1px solid var(--ui-border);
border-radius: var(--ui-radius); border-radius: var(--ui-radius);
box-shadow: var(--ui-shadow-sm); box-shadow: var(--ui-shadow-sm);
padding: 20px; padding: 15px;
width: 100%; width: 100%;
max-width: 340px; max-width: 340px;
flex: 1 1 300px; flex: 1 1 300px;
@@ -404,7 +404,7 @@
transition: transform 0.2s, box-shadow 0.2s; transition: transform 0.2s, box-shadow 0.2s;
position: relative; position: relative;
content-visibility: auto; content-visibility: auto;
contain-intrinsic-size: 300px 450px; contain-intrinsic-size: 300px 380px;
} }
.item-card.bulk-selected { .item-card.bulk-selected {
@@ -420,17 +420,21 @@
.item-card h3 { .item-card h3 {
margin-top: 0; margin-top: 0;
font-size: 1.15rem;
margin-bottom: 8px;
} }
.item-card .description { .item-card .description {
max-height: 100px; max-height: 60px;
overflow-y: auto; overflow-y: auto;
font-size: 0.9rem;
margin-bottom: 8px;
} }
.item-card .image-container { .item-card .image-container {
position: relative; position: relative;
max-width: 300px; max-width: 300px;
margin: 10px 0; margin: 8px 0;
} }
.bulk-delete-row { .bulk-delete-row {
@@ -479,7 +483,7 @@
.item-card .item-image { .item-card .item-image {
width: 100%; width: 100%;
height: auto; height: auto;
max-height: 300px; max-height: 180px;
display: none; display: none;
object-fit: cover; object-fit: cover;
} }
@@ -3383,11 +3387,14 @@ document.addEventListener('DOMContentLoaded', ()=>{
if (!mainAdminItemsLoadingIndicator) { if (!mainAdminItemsLoadingIndicator) {
mainAdminItemsLoadingIndicator = document.createElement('div'); mainAdminItemsLoadingIndicator = document.createElement('div');
mainAdminItemsLoadingIndicator.id = 'main-admin-items-loading-indicator'; mainAdminItemsLoadingIndicator.id = 'main-admin-items-loading-indicator';
mainAdminItemsLoadingIndicator.className = 'items-loading-indicator'; mainAdminItemsLoadingIndicator.className = 'items-loading-indicator empty-frames-placeholder';
mainAdminItemsLoadingIndicator.innerHTML = ` mainAdminItemsLoadingIndicator.innerHTML = `
<div class="loading-track"><div class="loading-fill"></div></div> <div class="empty-frame p-3 mx-2" style="flex: 1; height: 100px; border-radius: 12px; background: rgba(255,255,255,0.02); min-width: 250px;"></div>
<div class="loading-label">Weitere Objekte werden vorbereitet...</div> <div class="empty-frame p-3 mx-2" style="flex: 1; height: 100px; border-radius: 12px; background: rgba(255,255,255,0.02); min-width: 250px; display: none;" class="d-none d-md-block"></div>
<div class="empty-frame p-3 mx-2" style="flex: 1; height: 100px; border-radius: 12px; background: rgba(255,255,255,0.02); min-width: 250px; display: none;" class="d-none d-lg-block"></div>
`; `;
mainAdminItemsLoadingIndicator.style.display = 'flex';
mainAdminItemsLoadingIndicator.style.width = '100%';
} }
itemsContainer.appendChild(mainAdminItemsLoadingIndicator); itemsContainer.appendChild(mainAdminItemsLoadingIndicator);
@@ -3812,6 +3819,7 @@ document.addEventListener('DOMContentLoaded', ()=>{
card.innerHTML = card.dataset.savedHtml; card.innerHTML = card.dataset.savedHtml;
card.dataset.deloaded = 'false'; card.dataset.deloaded = 'false';
card.classList.remove('is-deloaded'); card.classList.remove('is-deloaded');
card.classList.remove('empty-frame');
const favBtn = card.querySelector('.bookmark-btn'); const favBtn = card.querySelector('.bookmark-btn');
if (favBtn) { if (favBtn) {
favBtn.addEventListener('click', (ev) => { favBtn.addEventListener('click', (ev) => {
@@ -3840,12 +3848,15 @@ document.addEventListener('DOMContentLoaded', ()=>{
card.innerHTML = ''; card.innerHTML = '';
card.dataset.deloaded = 'true'; card.dataset.deloaded = 'true';
card.classList.add('is-deloaded'); card.classList.add('is-deloaded');
card.classList.add('empty-frame');
} }
} }
} }
}); });
}, { }, {
rootMargin: isMobileLayout ? '1500px 0px 1500px 0px' : '0px 2500px 0px 2500px' // Keep approx ~120 items rendered in DOM relative to scroll position.
// Assuming ~100-400px per item/row, this margin unloads elements beyond that range.
rootMargin: isMobileLayout ? '18000px 0px 18000px 0px' : '9000px 0px 9000px 0px'
}); });
} }
+71 -24
View File
@@ -19,7 +19,7 @@
<div class="col-md-4"> <div class="col-md-4">
<div class="card mb-4"> <div class="card mb-4">
<div class="card-header"> <div class="card-header">
<h2 class="card-title h5 mb-0">Fach/Kategorie (Filter 1)</h2> <h2 class="card-title h5 mb-0">{{ filter_names.get('1', 'Fach/Kategorie') }} (Filter 1)</h2>
</div> </div>
<div class="card-body"> <div class="card-body">
<form method="POST" action="{{ url_for('add_filter_value', filter_num=1) }}" class="mb-4"> <form method="POST" action="{{ url_for('add_filter_value', filter_num=1) }}" class="mb-4">
@@ -33,13 +33,25 @@
{% if filter1_values %} {% if filter1_values %}
<div class="list-group"> <div class="list-group">
{% for value in filter1_values %} {% for value in filter1_values %}
<div class="list-group-item d-flex justify-content-between align-items-center"> <div class="list-group-item">
{{ value }} <div class="d-flex justify-content-between align-items-center mb-2">
<form method="POST" action="{{ url_for('remove_filter_value', filter_num=1, value=value) }}" class="d-inline"> <span>{{ value }}</span>
<button type="submit" class="btn btn-sm btn-danger" <div>
onclick="return confirm('Sind Sie sicher, dass Sie den Wert \"' + '{{ value }}'.replace(/'/g, '\\\'') + '\" löschen möchten?');"> <button type="button" class="btn btn-sm btn-secondary me-1" onclick="toggleEdit('edit-1-{{ loop.index }}')">Bearbeiten</button>
Entfernen <form method="POST" action="{{ url_for('remove_filter_value', filter_num=1, value=value) }}" class="d-inline">
</button> <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-1-{{ loop.index }}" method="POST" action="{{ url_for('edit_filter_value', filter_num=1, 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-1-{{ loop.index }}')">Abbrechen</button>
</div>
</form> </form>
</div> </div>
{% endfor %} {% endfor %}
@@ -55,7 +67,7 @@
<div class="col-md-4"> <div class="col-md-4">
<div class="card mb-4"> <div class="card mb-4">
<div class="card-header"> <div class="card-header">
<h2 class="card-title h5 mb-0">System/Bereich (Filter 2)</h2> <h2 class="card-title h5 mb-0">{{ filter_names.get('2', 'System/Bereich') }} (Filter 2)</h2>
</div> </div>
<div class="card-body"> <div class="card-body">
<form method="POST" action="{{ url_for('add_filter_value', filter_num=2) }}" class="mb-4"> <form method="POST" action="{{ url_for('add_filter_value', filter_num=2) }}" class="mb-4">
@@ -69,13 +81,25 @@
{% if filter2_values %} {% if filter2_values %}
<div class="list-group"> <div class="list-group">
{% for value in filter2_values %} {% for value in filter2_values %}
<div class="list-group-item d-flex justify-content-between align-items-center"> <div class="list-group-item">
{{ value }} <div class="d-flex justify-content-between align-items-center mb-2">
<form method="POST" action="{{ url_for('remove_filter_value', filter_num=2, value=value) }}" class="d-inline"> <span>{{ value }}</span>
<button type="submit" class="btn btn-sm btn-danger" <div>
onclick="return confirm('Sind Sie sicher, dass Sie den Wert \"' + '{{ value }}'.replace(/'/g, '\\\'') + '\" löschen möchten?');"> <button type="button" class="btn btn-sm btn-secondary me-1" onclick="toggleEdit('edit-2-{{ loop.index }}')">Bearbeiten</button>
Entfernen <form method="POST" action="{{ url_for('remove_filter_value', filter_num=2, value=value) }}" class="d-inline">
</button> <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-2-{{ loop.index }}" method="POST" action="{{ url_for('edit_filter_value', filter_num=2, 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-2-{{ loop.index }}')">Abbrechen</button>
</div>
</form> </form>
</div> </div>
{% endfor %} {% endfor %}
@@ -91,7 +115,7 @@
<div class="col-md-4"> <div class="col-md-4">
<div class="card mb-4"> <div class="card mb-4">
<div class="card-header"> <div class="card-header">
<h2 class="card-title h5 mb-0">Typ/Art (Filter 3)</h2> <h2 class="card-title h5 mb-0">{{ filter_names.get('3', 'Typ/Art') }} (Filter 3)</h2>
</div> </div>
<div class="card-body"> <div class="card-body">
<form method="POST" action="{{ url_for('add_filter_value', filter_num=3) }}" class="mb-4"> <form method="POST" action="{{ url_for('add_filter_value', filter_num=3) }}" class="mb-4">
@@ -105,13 +129,25 @@
{% if filter3_values %} {% if filter3_values %}
<div class="list-group"> <div class="list-group">
{% for value in filter3_values %} {% for value in filter3_values %}
<div class="list-group-item d-flex justify-content-between align-items-center"> <div class="list-group-item">
{{ value }} <div class="d-flex justify-content-between align-items-center mb-2">
<form method="POST" action="{{ url_for('remove_filter_value', filter_num=3, value=value) }}" class="d-inline"> <span>{{ value }}</span>
<button type="submit" class="btn btn-sm btn-danger" <div>
onclick="return confirm('Sind Sie sicher, dass Sie den Wert \"' + '{{ value }}'.replace(/'/g, '\\\'') + '\" löschen möchten?');"> <button type="button" class="btn btn-sm btn-secondary me-1" onclick="toggleEdit('edit-3-{{ loop.index }}')">Bearbeiten</button>
Entfernen <form method="POST" action="{{ url_for('remove_filter_value', filter_num=3, value=value) }}" class="d-inline">
</button> <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> </form>
</div> </div>
{% endfor %} {% endfor %}
@@ -133,4 +169,15 @@
<a href="{{ url_for('home_admin') }}" class="btn btn-secondary">Zurück zur Admin-Übersicht</a> <a href="{{ url_for('home_admin') }}" class="btn btn-secondary">Zurück zur Admin-Übersicht</a>
</div> </div>
</div> </div>
<script>
function toggleEdit(id) {
const el = document.getElementById(id);
if (el.style.display === 'none') {
el.style.display = 'block';
} else {
el.style.display = 'none';
}
}
</script>
{% endblock %} {% endblock %}
+2 -2
View File
@@ -12,8 +12,8 @@ from functools import wraps
import logging import logging
import os import os
import re import re
import settings as cfg import Web.modules.database.settings as cfg
from settings import MongoClient from Web.modules.database.settings import MongoClient
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
+7 -1
View File
@@ -144,7 +144,13 @@ services:
# Health check for load balancer # Health check for load balancer
healthcheck: healthcheck:
test: ["CMD", "curl", "-f", "http://localhost:8000/health"] test:
[
"CMD",
"python",
"-c",
"import urllib.request; urllib.request.urlopen('http://127.0.0.1:8000/health', timeout=5).read(); print('OK')"
]
interval: 30s interval: 30s
timeout: 10s timeout: 10s
retries: 3 retries: 3
-1
View File
@@ -1 +0,0 @@
394722
+40
View File
@@ -11,6 +11,44 @@ fi
CONFIG_FILE="$PWD/config.json" CONFIG_FILE="$PWD/config.json"
ensure_runtime_config_json() {
local config_path backup_path
config_path="$CONFIG_FILE"
if [ -d "$config_path" ]; then
backup_path="${config_path}.dir.$(date +%Y%m%d-%H%M%S).bak"
mv "$config_path" "$backup_path"
echo "Warning: moved unexpected directory $config_path to $backup_path"
fi
if [ ! -f "$config_path" ]; then
cat > "$config_path" <<'EOF'
{
"ver": "2.6.5",
"dbg": false,
"host": "0.0.0.0",
"port": 8000,
"mongodb": {
"host": "mongodb",
"port": 27017,
"db": "Inventarsystem"
},
"modules": {
"library": {
"enabled": false
},
"student_cards": {
"enabled": false,
"default_borrow_days": 14,
"max_borrow_days": 365
}
}
}
EOF
echo "Created default runtime config at $config_path"
fi
}
show_help() { show_help() {
echo "Usage: ./manage-tenant.sh [COMMAND] [OPTIONS]" echo "Usage: ./manage-tenant.sh [COMMAND] [OPTIONS]"
echo "" echo ""
@@ -177,6 +215,8 @@ restart_app_container() {
local env_file="$PWD/.docker-build.env" local env_file="$PWD/.docker-build.env"
local compose_args=() local compose_args=()
ensure_runtime_config_json
# If HOST_WORKDIR is set (called from container), use absolute paths so docker daemon resolves them correctly # If HOST_WORKDIR is set (called from container), use absolute paths so docker daemon resolves them correctly
if [ -n "$HOST_WORKDIR" ]; then if [ -n "$HOST_WORKDIR" ]; then
compose_args+=( -f "$(readlink -f "$HOST_WORKDIR/docker-compose-multitenant.yml")" ) compose_args+=( -f "$(readlink -f "$HOST_WORKDIR/docker-compose-multitenant.yml")" )
-5
View File
@@ -1,5 +0,0 @@
#!/bin/bash
# Wrapper to run tenant management fully containerized via docker-compose
PROJECT_NAME=${COMPOSE_PROJECT_NAME:-$(basename "$PWD" | tr '[:upper:]' '[:lower:]')}
# Pass the absolute working directory to the container so docker compose can resolve paths correctly
docker compose -f docker-compose-multitenant.yml --profile tools run --rm -e COMPOSE_PROJECT_NAME="$PROJECT_NAME" -e HOST_WORKDIR="$PWD" tenant-manager "$@"
Binary file not shown.
Binary file not shown.
Binary file not shown.
-588
View File
@@ -1,588 +0,0 @@
"""
Test Suite for Ausleihung (Borrowing) System
Tests all core functionality of the borrowing/lending module
Run with: pytest test_ausleihung.py -v
"""
import pytest
import datetime
from bson.objectid import ObjectId
import sys
import os
# Add Web directory to path
sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'Web'))
import ausleihung
import settings as cfg
from settings import MongoClient
@pytest.fixture(scope='session')
def db_client():
"""Create MongoDB connection for tests"""
client = MongoClient(cfg.MONGODB_HOST, cfg.MONGODB_PORT)
yield client
client.close()
@pytest.fixture(scope='session')
def test_db(db_client):
"""Get test database"""
return db_client[cfg.MONGODB_DB]
@pytest.fixture(autouse=True)
def cleanup_test_data(test_db):
"""Clean up test data before and after each test"""
yield
# Clean up after test
test_db['ausleihungen'].delete_many({})
@pytest.fixture
def sample_ausleihung_data():
"""Fixture with sample borrowing data"""
now = datetime.datetime.now()
return {
'item_id': str(ObjectId()),
'user': 'test_user',
'start_date': now,
'end_date': now + datetime.timedelta(days=1),
'notes': 'Test borrowing',
'period': None
}
# ============================================================================
# Status Determination Tests
# ============================================================================
class TestGetCurrentStatus:
"""Test status determination based on dates"""
def test_planned_status_future_date(self):
"""Test that future borrowing is marked as 'planned'"""
future_time = datetime.datetime.now() + datetime.timedelta(days=1)
ausleihung_doc = {
'Status': 'planned',
'Start': future_time,
'End': future_time + datetime.timedelta(hours=1)
}
status = ausleihung.get_current_status(ausleihung_doc)
assert status == 'planned'
def test_active_status_during_borrowing(self):
"""Test that current borrowing is marked as 'active'"""
now = datetime.datetime.now()
start = now - datetime.timedelta(hours=1)
end = now + datetime.timedelta(hours=1)
ausleihung_doc = {
'Status': 'active',
'Start': start,
'End': end
}
status = ausleihung.get_current_status(ausleihung_doc)
assert status == 'active'
def test_completed_status_after_end_time(self):
"""Test that past borrowing is marked as 'completed'"""
now = datetime.datetime.now()
start = now - datetime.timedelta(days=2)
end = now - datetime.timedelta(hours=1)
ausleihung_doc = {
'Status': 'active',
'Start': start,
'End': end
}
status = ausleihung.get_current_status(ausleihung_doc)
assert status == 'completed'
def test_cancelled_status_remains_cancelled(self):
"""Test that cancelled status is never changed"""
future_time = datetime.datetime.now() + datetime.timedelta(days=1)
ausleihung_doc = {
'Status': 'cancelled',
'Start': future_time,
'End': future_time + datetime.timedelta(hours=1)
}
status = ausleihung.get_current_status(ausleihung_doc)
assert status == 'cancelled'
def test_active_with_no_end_time(self):
"""Test that borrowing without end time stays active if started"""
now = datetime.datetime.now()
start = now - datetime.timedelta(hours=1)
ausleihung_doc = {
'Status': 'active',
'Start': start,
'End': None
}
status = ausleihung.get_current_status(ausleihung_doc)
assert status == 'active'
# ============================================================================
# Create and Update Tests
# ============================================================================
class TestCreateAusleihung:
"""Test creating new borrowings"""
def test_create_active_ausleihung(self, test_db):
"""Test creating an immediately active borrowing"""
item_id = str(ObjectId())
user = 'test_user'
start = datetime.datetime.now()
end = start + datetime.timedelta(hours=2)
result = ausleihung.add_ausleihung(
item_id=item_id,
user=user,
start_date=start,
end_date=end,
notes='Test active',
status='active'
)
assert result is not None
# Verify in database
ausleihung_col = test_db['ausleihungen']
stored = ausleihung_col.find_one({'_id': result})
assert stored is not None
assert stored['Item'] == item_id # Correct field name
assert stored['User'] == user
assert stored['Status'] == 'active'
def test_create_planned_ausleihung(self, test_db):
"""Test creating a future/planned borrowing"""
item_id = str(ObjectId())
user = 'test_user'
future_start = datetime.datetime.now() + datetime.timedelta(days=1)
future_end = future_start + datetime.timedelta(hours=2)
result = ausleihung.add_ausleihung(
item_id=item_id,
user=user,
start_date=future_start,
end_date=future_end,
notes='Test planned',
status='planned'
)
assert result is not None
ausleihung_col = test_db['ausleihungen']
stored = ausleihung_col.find_one({'_id': result})
assert stored['Status'] == 'planned'
# Check approximately equal (within 1 second for datetime precision)
assert abs((stored['Start'] - future_start).total_seconds()) < 1
class TestUpdateAusleihung:
"""Test updating existing borrowings"""
def test_update_ausleihung_dates(self, test_db, sample_ausleihung_data):
"""Test updating borrowing dates"""
# Create initial borrowing
ausleihung_id = ausleihung.add_ausleihung(**sample_ausleihung_data)
assert ausleihung_id is not None
# Update dates
new_start = datetime.datetime.now() + datetime.timedelta(days=2)
new_end = new_start + datetime.timedelta(hours=1)
ausleihung.update_ausleihung(
id=ausleihung_id,
start=new_start,
end=new_end
)
# Verify update (within 1 second tolerance for datetime precision)
stored = test_db['ausleihungen'].find_one({'_id': ausleihung_id})
assert abs((stored['Start'] - new_start).total_seconds()) < 1
assert abs((stored['End'] - new_end).total_seconds()) < 1
def test_update_ausleihung_status(self, test_db, sample_ausleihung_data):
"""Test updating borrowing status"""
ausleihung_id = ausleihung.add_ausleihung(**sample_ausleihung_data)
ausleihung.update_ausleihung(id=ausleihung_id, status='completed')
stored = test_db['ausleihungen'].find_one({'_id': ausleihung_id})
assert stored['Status'] == 'completed'
def test_update_ausleihung_notes(self, test_db, sample_ausleihung_data):
"""Test updating borrowing notes"""
ausleihung_id = ausleihung.add_ausleihung(**sample_ausleihung_data)
new_notes = 'Updated notes'
ausleihung.update_ausleihung(id=ausleihung_id, notes=new_notes)
stored = test_db['ausleihungen'].find_one({'_id': ausleihung_id})
assert stored['Notes'] == new_notes
# ============================================================================
# Complete and Cancel Tests
# ============================================================================
class TestCompleteAusleihung:
"""Test completing borrowings"""
def test_complete_ausleihung(self, test_db, sample_ausleihung_data):
"""Test marking a borrowing as completed"""
ausleihung_id = ausleihung.add_ausleihung(**sample_ausleihung_data)
end_time = datetime.datetime.now()
ausleihung.complete_ausleihung(ausleihung_id, end_time=end_time)
stored = test_db['ausleihungen'].find_one({'_id': ausleihung_id})
assert stored['Status'] == 'completed'
assert stored['End'] == end_time or stored['End'] is not None
class TestCancelAusleihung:
"""Test canceling borrowings"""
def test_cancel_ausleihung(self, test_db, sample_ausleihung_data):
"""Test canceling a borrowing"""
ausleihung_id = ausleihung.add_ausleihung(**sample_ausleihung_data)
ausleihung.cancel_ausleihung(ausleihung_id)
stored = test_db['ausleihungen'].find_one({'_id': ausleihung_id})
assert stored['Status'] == 'cancelled'
# ============================================================================
# Query Tests
# ============================================================================
class TestGetAusleihung:
"""Test retrieving borrowings"""
def test_get_ausleihung_by_id(self, test_db, sample_ausleihung_data):
"""Test fetching a borrowing by ID"""
ausleihung_id = ausleihung.add_ausleihung(**sample_ausleihung_data)
retrieved = ausleihung.get_ausleihung(ausleihung_id)
assert retrieved is not None
assert retrieved['_id'] == ausleihung_id
assert retrieved['User'] == sample_ausleihung_data['user']
def test_get_ausleihung_by_user(self, test_db):
"""Test retrieving all borrowings for a user"""
user = 'test_user_xyz'
item1 = str(ObjectId())
item2 = str(ObjectId())
now = datetime.datetime.now()
# Create multiple borrowings for same user
ausleihung.add_ausleihung(
item_id=item1,
user=user,
start_date=now,
end_date=now + datetime.timedelta(hours=1),
status='active'
)
ausleihung.add_ausleihung(
item_id=item2,
user=user,
start_date=now + datetime.timedelta(days=1),
end_date=now + datetime.timedelta(days=1, hours=1),
status='planned'
)
# Retrieve all for user
borrowings = ausleihung.get_ausleihung_by_user(user)
assert len(borrowings) >= 2
assert all(b['User'] == user for b in borrowings)
def test_get_ausleihungen_by_status(self, test_db):
"""Test retrieving borrowings by status"""
item_id = str(ObjectId())
user = 'test_user'
now = datetime.datetime.now()
# Create active
active_id = ausleihung.add_ausleihung(
item_id=item_id,
user=user,
start_date=now - datetime.timedelta(hours=1),
end_date=now + datetime.timedelta(hours=1),
status='active'
)
# Get active borrowings
active_borrowings = ausleihung.get_active_ausleihungen()
assert any(b['_id'] == active_id for b in active_borrowings)
# ============================================================================
# Conflict Detection Tests
# ============================================================================
class TestConflictDetection:
"""Test detecting overlapping/conflicting borrowings"""
def test_no_conflict_different_items(self, test_db):
"""Test that different items don't conflict"""
item1 = str(ObjectId())
item2 = str(ObjectId())
now = datetime.datetime.now()
start = now
end = now + datetime.timedelta(hours=1)
# Create first borrowing
ausleihung.add_ausleihung(
item_id=item1,
user='user1',
start_date=start,
end_date=end,
status='active'
)
# Check conflict on different item (should be no conflict)
conflict = ausleihung.check_ausleihung_conflict(
item_id=item2,
start_date=start,
end_date=end
)
assert conflict is False
def test_conflict_same_item_overlapping(self, test_db):
"""Test that overlapping borrowings on same item are detected"""
item_id = str(ObjectId())
now = datetime.datetime.now()
# Create first borrowing
ausleihung.add_ausleihung(
item_id=item_id,
user='user1',
start_date=now,
end_date=now + datetime.timedelta(hours=2),
status='active'
)
# Try to create overlapping borrowing
conflict = ausleihung.check_ausleihung_conflict(
item_id=item_id,
start_date=now + datetime.timedelta(minutes=30),
end_date=now + datetime.timedelta(hours=3)
)
assert conflict is True or conflict == item_id # Depending on implementation
def test_no_conflict_different_times(self, test_db):
"""Test that non-overlapping borrowings don't conflict"""
item_id = str(ObjectId())
now = datetime.datetime.now()
# Create first borrowing
ausleihung.add_ausleihung(
item_id=item_id,
user='user1',
start_date=now,
end_date=now + datetime.timedelta(hours=1),
status='active'
)
# Check borrowing after first ends (should be no conflict)
conflict = ausleihung.check_ausleihung_conflict(
item_id=item_id,
start_date=now + datetime.timedelta(hours=2),
end_date=now + datetime.timedelta(hours=3)
)
assert conflict is False or conflict is None
# ============================================================================
# Period-based Borrowing Tests
# ============================================================================
class TestPeriodBookings:
"""Test period-based borrowings (school periods)"""
def test_create_period_booking(self, test_db):
"""Test creating a borrowing for a specific school period"""
item_id = str(ObjectId())
user = 'test_user'
today = datetime.datetime.now().date()
result = ausleihung.add_ausleihung(
item_id=item_id,
user=user,
start_date=datetime.datetime.combine(today, datetime.time(8, 0)),
end_date=datetime.datetime.combine(today, datetime.time(9, 0)),
period=1, # Assuming period 1 is first period
status='active'
)
assert result is not None
stored = test_db['ausleihungen'].find_one({'_id': result})
assert stored.get('Period') == 1
# ============================================================================
# Remove Tests
# ============================================================================
class TestRemoveAusleihung:
"""Test removing/deleting borrowings"""
def test_remove_ausleihung(self, test_db, sample_ausleihung_data):
"""Test deleting a borrowing record (soft delete)"""
ausleihung_id = ausleihung.add_ausleihung(**sample_ausleihung_data)
stored_before = test_db['ausleihungen'].find_one({'_id': ausleihung_id})
assert stored_before is not None
# Remove (soft delete - adds DeletedAt timestamp)
ausleihung.remove_ausleihung(ausleihung_id)
# Verify it's marked as deleted (soft delete)
stored_after = test_db['ausleihungen'].find_one({'_id': ausleihung_id})
assert stored_after is not None # Still exists
assert 'DeletedAt' in stored_after or stored_after.get('Status') == 'deleted'
# ============================================================================
# Integration Tests
# ============================================================================
class TestAusleihungLifecycle:
"""Test complete borrowing lifecycle"""
def test_full_lifecycle_active_to_complete(self, test_db):
"""Test a complete borrowing lifecycle: active → complete"""
item_id = str(ObjectId())
user = 'test_user'
now = datetime.datetime.now()
# 1. Create active borrowing
ausleihung_id = ausleihung.add_ausleihung(
item_id=item_id,
user=user,
start_date=now - datetime.timedelta(hours=1),
end_date=now + datetime.timedelta(hours=1),
status='active'
)
stored = test_db['ausleihungen'].find_one({'_id': ausleihung_id})
status = ausleihung.get_current_status(stored)
assert status == 'active'
# 2. Complete the borrowing
ausleihung.complete_ausleihung(ausleihung_id)
stored = test_db['ausleihungen'].find_one({'_id': ausleihung_id})
status = ausleihung.get_current_status(stored)
assert status == 'completed'
def test_full_lifecycle_planned_to_active_to_complete(self, test_db):
"""Test complete lifecycle: planned → active → complete"""
item_id = str(ObjectId())
user = 'test_user'
now = datetime.datetime.now()
future = now + datetime.timedelta(hours=1)
# 1. Create planned borrowing
ausleihung_id = ausleihung.add_ausleihung(
item_id=item_id,
user=user,
start_date=future,
end_date=future + datetime.timedelta(hours=1),
status='planned'
)
stored = test_db['ausleihungen'].find_one({'_id': ausleihung_id})
assert ausleihung.get_current_status(stored) == 'planned'
# 2. Update to active (simulate time passing or manual activation)
ausleihung.update_ausleihung(id=ausleihung_id, status='active')
stored = test_db['ausleihungen'].find_one({'_id': ausleihung_id})
assert stored['Status'] == 'active'
# 3. Complete
ausleihung.complete_ausleihung(ausleihung_id)
stored = test_db['ausleihungen'].find_one({'_id': ausleihung_id})
assert ausleihung.get_current_status(stored) == 'completed'
def test_cancel_planned_borrowing(self, test_db):
"""Test canceling a planned borrowing"""
item_id = str(ObjectId())
user = 'test_user'
future = datetime.datetime.now() + datetime.timedelta(days=1)
# Create planned
ausleihung_id = ausleihung.add_ausleihung(
item_id=item_id,
user=user,
start_date=future,
end_date=future + datetime.timedelta(hours=1),
status='planned'
)
# Cancel
ausleihung.cancel_ausleihung(ausleihung_id)
stored = test_db['ausleihungen'].find_one({'_id': ausleihung_id})
assert stored['Status'] == 'cancelled'
# ============================================================================
# Edge Cases
# ============================================================================
class TestEdgeCases:
"""Test edge cases and boundary conditions"""
def test_borrowing_with_same_start_and_end(self, test_db):
"""Test borrowing where start equals end"""
item_id = str(ObjectId())
user = 'test_user'
now = datetime.datetime.now()
result = ausleihung.add_ausleihung(
item_id=item_id,
user=user,
start_date=now,
end_date=now, # Same time
status='active'
)
assert result is not None
def test_borrowing_without_end_date(self, test_db):
"""Test creating borrowing without end date"""
item_id = str(ObjectId())
user = 'test_user'
now = datetime.datetime.now()
result = ausleihung.add_ausleihung(
item_id=item_id,
user=user,
start_date=now,
end_date=None,
status='active'
)
assert result is not None
stored = test_db['ausleihungen'].find_one({'_id': result})
# End field should not exist or be None if not provided
assert 'End' not in stored or stored.get('End') is None
def test_get_nonexistent_borrowing(self, test_db):
"""Test retrieving a nonexistent borrowing"""
fake_id = ObjectId()
result = ausleihung.get_ausleihung(fake_id)
assert result is None or result == {} or result == []
# ============================================================================
# Run Tests
# ============================================================================
if __name__ == '__main__':
pytest.main([__file__, '-v', '--tb=short'])
-5
View File
@@ -1,5 +0,0 @@
from Web.app import app
with app.test_client() as client:
resp = client.get('/terminplan')
print(resp.status_code)
# print(resp.data.decode('utf-8')[:200])
+54
View File
@@ -18,6 +18,7 @@ DIST_DIR="$PROJECT_DIR/dist"
COMPOSE_FILE="docker-compose-multitenant.yml" COMPOSE_FILE="docker-compose-multitenant.yml"
MIN_ROOT_FREE_MB="${INVENTAR_MIN_ROOT_FREE_MB:-2048}" MIN_ROOT_FREE_MB="${INVENTAR_MIN_ROOT_FREE_MB:-2048}"
DIST_KEEP_COUNT="${INVENTAR_DIST_KEEP_COUNT:-2}" DIST_KEEP_COUNT="${INVENTAR_DIST_KEEP_COUNT:-2}"
MODE="release"
mkdir -p "$LOG_DIR" mkdir -p "$LOG_DIR"
chmod 777 "$LOG_DIR" 2>/dev/null || true chmod 777 "$LOG_DIR" 2>/dev/null || true
@@ -152,6 +153,7 @@ Usage: $0 [options]
Options: Options:
--multitenant Use docker-compose-multitenant.yml (default) --multitenant Use docker-compose-multitenant.yml (default)
development Install development build from GHCR or local dist
-h, --help Show this help message -h, --help Show this help message
EOF EOF
} }
@@ -163,6 +165,10 @@ parse_args() {
COMPOSE_FILE="docker-compose-multitenant.yml" COMPOSE_FILE="docker-compose-multitenant.yml"
shift shift
;; ;;
development|dev)
MODE="development"
shift
;;
-h|--help) -h|--help)
usage usage
exit 0 exit 0
@@ -480,6 +486,54 @@ main() {
archive_logs archive_logs
create_backup create_backup
# If user requested a development install, perform a simple dev deploy flow
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"
if [ ! -f "$compose_path" ]; then
log_message "ERROR: compose file not found: $compose_path"
exit 1
fi
# Ensure ENV_FILE contains the development image
if [ ! -f "$ENV_FILE" ]; then
cat > "$ENV_FILE" <<EOF
NUITKA_BUILD=0
INVENTAR_HTTP_PORT=10000
INVENTAR_APP_IMAGE=$app_image
EOF
elif grep -q '^INVENTAR_APP_IMAGE=' "$ENV_FILE"; then
sed -i "s|^INVENTAR_APP_IMAGE=.*|INVENTAR_APP_IMAGE=$app_image|" "$ENV_FILE"
else
printf '\nINVENTAR_APP_IMAGE=%s\n' "$app_image" >> "$ENV_FILE"
fi
# Try local dist first, then pull from GHCR
if ! load_local_dist_image "$tag"; then
log_message "Attempting to pull development image $app_image"
if ! docker pull "$app_image" >> "$LOG_FILE" 2>&1; then
log_message "ERROR: Could not obtain development image $app_image"
exit 1
fi
fi
# Bring up stack
docker compose -f "$compose_path" --env-file "$ENV_FILE" pull app mongodb >> "$LOG_FILE" 2>&1 || true
docker compose -f "$compose_path" --env-file "$ENV_FILE" up -d --remove-orphans >> "$LOG_FILE" 2>&1
if ! verify_stack_health; then
log_message "ERROR: Development deployment failed health check"
exit 1
fi
echo "$tag" > "$STATE_FILE"
log_message "Development update completed successfully"
exit 0
fi
local tmp_dir meta_file latest_tag current_tag bundle_url local tmp_dir meta_file latest_tag current_tag bundle_url
tmp_dir="$(mktemp -d)" tmp_dir="$(mktemp -d)"
meta_file="$tmp_dir/release.json" meta_file="$tmp_dir/release.json"
-235
View File
@@ -1,235 +0,0 @@
#!/usr/bin/env python3
"""
Invario PDF Audit Export - Implementation Verification Script
This script verifies that all components of the PDF audit export system
are correctly installed and configured.
"""
import sys
import os
def verify_files():
"""Verify all required files exist."""
print("=" * 60)
print("INVARIO PDF AUDIT EXPORT - INSTALLATION VERIFICATION")
print("=" * 60)
print()
files_to_check = {
"Core Module": [
"Web/pdf_audit_export.py",
],
"Flask Integration": [
"Web/app.py", # Should contain new routes
"Web/templates/admin_audit.html", # Should contain new buttons
],
"Documentation": [
"PDF_AUDIT_EXPORT_DOCUMENTATION.md",
"PDF_IMPLEMENTATION_GUIDE.md",
"QUICK_START_PDF_EXPORT.md",
]
}
base_path = os.path.dirname(os.path.abspath(__file__))
all_ok = True
for category, files in files_to_check.items():
print(f"\n[{category}]")
for filename in files:
filepath = os.path.join(base_path, filename)
exists = os.path.exists(filepath)
status = "" if exists else ""
print(f" {status} {filename}")
if not exists:
all_ok = False
return all_ok
def verify_dependencies():
"""Verify Python dependencies are installed."""
print("\n[Python Dependencies]")
dependencies = [
("reportlab", "PDF generation"),
("qrcode", "QR code generation"),
("pillow", "Image processing"),
("flask", "Web framework"),
("pymongo", "MongoDB driver"),
]
all_ok = True
for package, description in dependencies:
try:
__import__(package)
print(f"{package:15} - {description}")
except ImportError:
print(f"{package:15} - {description}")
all_ok = False
return all_ok
def verify_routes():
"""Verify new routes are defined in app.py."""
print("\n[Flask Routes]")
routes_to_check = [
"/admin/audit/export/pdf/quick",
"/admin/audit/export/pdf/official",
]
app_py_path = "Web/app.py"
if not os.path.exists(app_py_path):
print(" ✗ app.py not found")
return False
with open(app_py_path, 'r') as f:
app_content = f.read()
all_ok = True
for route in routes_to_check:
if route in app_content:
print(f"{route}")
else:
print(f"{route}")
all_ok = False
return all_ok
def verify_template():
"""Verify template updates are in place."""
print("\n[HTML Template Updates]")
template_path = "Web/templates/admin_audit.html"
if not os.path.exists(template_path):
print(" ✗ admin_audit.html not found")
return False
with open(template_path, 'r') as f:
template_content = f.read()
checks = {
"DIN 5008 Info Box": "DIN 5008",
"PDF Quick-Check Button": "admin_audit_export_pdf_quick",
"PDF Official Button": "admin_audit_export_pdf_official",
}
all_ok = True
for check_name, check_string in checks.items():
if check_string in template_content:
print(f"{check_name}")
else:
print(f"{check_name}")
all_ok = False
return all_ok
def get_statistics():
"""Get implementation statistics."""
print("\n[Implementation Statistics]")
stats = {
"Web/pdf_audit_export.py": "PDF Export Module",
"PDF_AUDIT_EXPORT_DOCUMENTATION.md": "Technical Documentation",
"PDF_IMPLEMENTATION_GUIDE.md": "Implementation Guide",
"QUICK_START_PDF_EXPORT.md": "Quick Start Guide",
}
total_lines = 0
for filename, description in stats.items():
if os.path.exists(filename):
with open(filename, 'r') as f:
lines = len(f.readlines())
print(f" {filename:45} {lines:5} lines - {description}")
total_lines += lines
print(f"\n Total documentation: {total_lines} lines")
def print_next_steps():
"""Print next steps for the user."""
print("\n" + "=" * 60)
print("NEXT STEPS")
print("=" * 60)
print("""
1. CONFIGURE SCHOOL INFO (Optional)
Edit config.json and add:
{
"school": {
"name": "Your School Name",
"address": "School Address",
"postal_code": "12345",
"city": "City Name",
"school_number": "123456",
"it_admin": "Admin Name"
}
}
2. RESTART THE SYSTEM
./start.sh
or: python Web/app.py
3. TEST PDF EXPORTS
- Login to http://localhost:8000/admin/audit
- Click "🚀 Schnell-Check" for compact PDF
- Click "📋 Amtlicher Bericht" for full DIN 5008 report
4. VERIFY COMPLIANCE
- Check PDF opens in your PDF reader
- Verify school info is correct
- Test signature fields
- Verify barrierefreiheit (accessibility)
5. DEPLOY TO PRODUCTION
- Update your deployment scripts
- Document new export procedures
- Train staff on Quick-Check vs Official Report
""")
def main():
"""Run all verifications."""
print()
checks = [
("File Structure", verify_files),
("Dependencies", verify_dependencies),
("Flask Routes", verify_routes),
("HTML Template", verify_template),
]
all_passed = True
for name, check_func in checks:
try:
passed = check_func()
if not passed:
all_passed = False
except Exception as e:
print(f"\n✗ Error during {name} check: {e}")
all_passed = False
# Get statistics
get_statistics()
# Print results
print("\n" + "=" * 60)
if all_passed:
print("✓ ALL VERIFICATION CHECKS PASSED!")
print("=" * 60)
print_next_steps()
else:
print("✗ SOME VERIFICATION CHECKS FAILED")
print("=" * 60)
print("\nPlease check the errors above and verify:")
print("1. All files are in the correct locations")
print("2. All dependencies are installed")
print("3. app.py and admin_audit.html have been updated")
sys.exit(1)
print("\n" + "=" * 60)
print("For detailed documentation, see:")
print(" - QUICK_START_PDF_EXPORT.md (Start here!)")
print(" - PDF_IMPLEMENTATION_GUIDE.md (Technical details)")
print(" - PDF_AUDIT_EXPORT_DOCUMENTATION.md (Requirements)")
print("=" * 60 + "\n")
if __name__ == "__main__":
main()