Compare commits

...

143 Commits

Author SHA1 Message Date
52f559199d added configuration over https / http 2025-11-01 17:20:45 +01:00
ebe9d4aa19 added vite dependency to the backend 2025-11-01 15:58:14 +01:00
07ab9586cc removed unnecessary comments 2025-11-01 15:22:47 +01:00
72430462f6 fixed ipSecurityCheck 2025-11-01 15:17:09 +01:00
c7016b5d04 added simulatnously starting frontend backend dev 2025-11-01 14:29:55 +01:00
41ddad6fa9 added apiClient class handling api auth and validation response from backend 2025-11-01 13:47:29 +01:00
29c66f0228 cleaned up vite.config.ts 2025-11-01 12:06:55 +01:00
0614b2f3f8 updated network for proxy use 2025-11-01 11:28:16 +01:00
00b48c1f41 changed dev routing away from faulty proxy 2025-10-31 14:24:56 +01:00
cae2b83649 added seperate transaction for pragma statement 2025-10-31 13:33:12 +01:00
a69e934075 fixed handleSubmit missing input 2025-10-31 12:51:22 +01:00
3ad497dd76 changed static password length statements 6 -> 8 2025-10-31 12:37:52 +01:00
b302c447f8 admin has to confirm current password as well on self password change 2025-10-31 12:30:54 +01:00
6cc8c91317 updated validation handling together with shiftplan 2025-10-31 00:27:50 +01:00
0b35bb6dc6 updated validation handling together with employeeform 2025-10-30 23:39:21 +01:00
4ef8e7b1f3 error handling in frontend together with validation in backend 2025-10-30 21:52:34 +01:00
14dce28698 added admin check for deletion and updates 2025-10-30 21:07:27 +01:00
82a30f6bb8 added Validation rules 2025-10-30 19:13:09 +01:00
0623957993 added Validation rules 2025-10-30 18:10:44 +01:00
5809bb8b09 added stepsetup for initial admin setup 2025-10-30 15:26:25 +01:00
fbd0f03eb2 password requirements allow more special chars 2025-10-29 11:12:37 +01:00
86166048e8 password requirements more strict 2025-10-29 11:05:05 +01:00
0363505126 added right env variable usage for frontend wiht meta.env 2025-10-29 09:44:41 +01:00
1231c8362f removed all cors statemnts 2025-10-29 00:34:12 +01:00
663eb61352 added basic route for production 2025-10-28 23:54:28 +01:00
23f1dd7aa0 updated docker entry point 2025-10-28 23:33:00 +01:00
5319ed5d7a added entrypoint for docker 2025-10-28 23:07:40 +01:00
65ebf1748b removed invalid terser option 2025-10-28 22:21:54 +01:00
4321763a2b added missing dependency 2025-10-28 22:16:19 +01:00
24525043e9 added missing dpendencie 2025-10-28 22:12:30 +01:00
d870523685 added security features from terser 2025-10-28 22:04:24 +01:00
50a1f1a9b9 npm run build iwhtout --only=production flag 2025-10-28 21:30:54 +01:00
1927937109 added corrected password needs 2025-10-28 20:13:09 +01:00
b3b3250f23 dropping console on production 2025-10-28 19:20:19 +01:00
5f8a6bef31 added express payload validation 2025-10-28 18:58:58 +01:00
a838ba44e8 moved pragma statements into schema.sql 2025-10-28 17:58:16 +01:00
1057fd9954 moved pragma statements in initializedatabase 2025-10-28 17:49:06 +01:00
bc73fcebd3 added pragma statements in .sql 2025-10-28 17:39:45 +01:00
82533ae616 added .env.production to .gitignore 2025-10-28 17:33:26 +01:00
840b4384a5 using static frontend build path for static expresss 2025-10-28 17:29:15 +01:00
5a8b7e89d7 removed unused imports 2025-10-28 16:49:53 +01:00
289c80eea1 removed unused .css files 2025-10-28 16:45:57 +01:00
1884a16220 changed setup button color 2025-10-28 15:58:24 +01:00
478578308d changed noting 2025-10-26 17:15:08 +01:00
93a52aa196 changed production routing for frontend build 2025-10-26 16:56:50 +01:00
donpat1to
b11c55c1d9 Update docker.yml 2025-10-26 16:13:43 +01:00
16302f2105 changed tagging logic for latest versions 2025-10-26 16:09:02 +01:00
57aff5c858 changed tagging logic for latest versions 2025-10-26 16:07:52 +01:00
b4abe459c2 changed tagging logic for latest versions 2025-10-26 15:35:07 +01:00
06bc27a6ce Merge branch 'main' of https://github.com/donpat1to/Schichtenplaner 2025-10-26 12:53:52 +01:00
0aad8f0a56 fixed footer 2025-10-26 12:40:16 +01:00
b52e9d57c7 new package lock generated 2025-10-26 12:24:20 +01:00
15f3183bc0 added esbuild 2025-10-26 12:14:24 +01:00
ca3a5d1c0e changed install to only-production 2025-10-26 12:13:37 +01:00
6a1509d807 removed esbuild 2025-10-26 11:44:39 +01:00
donpat1to
308ae74e37 Update LICENSE-COMMERCIAL 2025-10-26 10:27:11 +01:00
e876f5eb02 fixed login ui 2025-10-26 10:24:07 +01:00
dabd2dff3b added ecosystem file to builder 2025-10-26 09:54:32 +01:00
84d7be052d added expicit copying database schema.sql 2025-10-26 01:51:08 +02:00
9460f10278 added expicit copying database schema.sql 2025-10-26 01:42:34 +02:00
6e1927fe2f added expicit copying database schema.sql 2025-10-26 01:37:13 +02:00
e5a6fc73fe not using rollup package 2025-10-26 01:24:41 +02:00
c773740634 using npm install instead of npm ci 2025-10-26 01:18:25 +02:00
23acd88ced compiling allowed unused values 2025-10-25 13:32:01 +02:00
aa1a2d4d72 removed invalid statement in compileroptions 2025-10-25 13:27:45 +02:00
cf3866ee21 added copying all files so package-lock findable 2025-10-25 13:20:56 +02:00
7ab3e0a5fb removed unreachable cache dir 2025-10-25 13:12:12 +02:00
41aa77e45d fixed unreachable cache dir 2025-10-25 13:07:25 +02:00
8e782a5290 added vite config 2025-10-25 12:44:18 +02:00
3856f93484 ignoring peerdepencdecies in frontend build 2025-10-25 11:50:07 +02:00
dae255e2c1 changed from workspace build to independet build 2025-10-25 11:41:53 +02:00
8f96368f5a changed mode_modules dir cause of workspace configuration 2025-10-25 11:27:49 +02:00
636b892ece fixed monorepo package struct 2025-10-25 00:41:09 +02:00
8be6a7b474 changed version dependencies 2025-10-25 00:28:15 +02:00
a2b2b76665 changed version dependencies 2025-10-25 00:24:03 +02:00
6d00ab695c changed version dependencies 2025-10-25 00:19:22 +02:00
2608acc2d9 added test env 2025-10-25 00:11:02 +02:00
4dacf94077 added neccessary env 2025-10-25 00:04:00 +02:00
5e7c5aabfb added community version 2025-10-24 23:52:57 +02:00
05fa87c638 added routing in app.tsx 2025-10-24 17:52:47 +02:00
875db3aeb7 added singlerepo structure 2025-10-24 15:58:43 +02:00
809a838e27 changing repo structure 2025-10-23 23:53:57 +02:00
8d020a0dac Add private premium submodule 2025-10-23 21:36:25 +02:00
92840c2424 added license 2025-10-23 21:16:27 +02:00
ce1c6b08b1 added password unvewiling and relative boxing 2025-10-23 20:01:21 +02:00
b9a88bce1c added password unveiling on login 2025-10-23 19:17:51 +02:00
b60e5ccdd2 changed login ui 2025-10-23 17:56:31 +02:00
f5aa376e31 changed static paths to relative api paths so useable without cors 2025-10-23 15:38:17 +02:00
e82e584f76 changed static paths to relative api paths so useable without cors 2025-10-23 14:45:15 +02:00
e177c3d2a6 changed frontend path 2025-10-23 14:19:29 +02:00
de23ea00ee added debugging for routing 2025-10-23 14:02:36 +02:00
d78ba474d8 removed express static fallback 2025-10-23 00:39:28 +02:00
5c7786bc19 added schema detection for prod dev 2025-10-23 00:24:23 +02:00
15107cdc63 removed routing 2025-10-22 23:31:38 +02:00
22266c765b api endpoints changed 2025-10-22 22:21:44 +02:00
a66609a40c pm2 not in home directory -> /app/ 2025-10-22 21:57:26 +02:00
87dda38bc3 updated user to have a home laufwerk 2025-10-22 21:42:47 +02:00
9de501c7eb changed user creation into debian style 2025-10-22 21:28:48 +02:00
5c6a50ddcf changed alpine production build to debian prod build 2025-10-22 21:22:09 +02:00
017f5fb2e0 copy database files manually 2025-10-22 21:01:46 +02:00
527954befd fix database paht 2025-10-22 20:50:36 +02:00
e7d30151b7 copy database files manually 2025-10-22 20:30:08 +02:00
4a006a2e69 copy database files manually 2025-10-22 20:27:01 +02:00
4b699b05d3 changed production stage from debian to alpine 2025-10-22 20:16:45 +02:00
dcac0307a2 copying no database folder seperate 2025-10-22 20:11:43 +02:00
a0cc859935 Merge branch 'staging' of https://github.com/donpat1to/Schichtenplaner into staging 2025-10-22 20:01:03 +02:00
49afd75ed3 copying database folder seperate 2025-10-22 19:21:13 +02:00
ebb9e3f4fe copying database folder seperate 2025-10-22 19:17:46 +02:00
48f140f930 changed docker.yml only triggering workflow on push 2025-10-22 15:08:52 +02:00
b6b31659e3 changed ecosystem file type as well in Dockerfile 2025-10-22 14:42:25 +02:00
42e343777a changed ecosystem file type as well in Dockerfile 2025-10-22 14:42:01 +02:00
aa7af272d8 moved js file to es module compatible cjs file type 2025-10-22 14:39:15 +02:00
a0d96925c5 added id-token: write 2025-10-22 10:46:15 +02:00
donpat1to
28283fa8bc Update docker.yml 2025-10-22 09:28:41 +02:00
donpat1to
fdff2853bd Update docker.yml 2025-10-22 09:19:37 +02:00
09e08ff615 changed from alpine to debian 2025-10-22 00:54:52 +02:00
fb4a2f6f20 changed from alpine to debian 2025-10-22 00:54:43 +02:00
faaab74f07 added second check python package testing to simple health check 2025-10-22 00:49:34 +02:00
90e10b9cc2 added second check python package testing to simple health check 2025-10-22 00:44:04 +02:00
0821ca7711 changed python package testing to simple health check 2025-10-22 00:38:14 +02:00
02c1253f4f changed python package testing to simple health check 2025-10-22 00:33:00 +02:00
26417aaf88 changed python package testing to simple health check 2025-10-22 00:28:28 +02:00
eb8945ae97 updated python package testing to json format 2025-10-22 00:20:53 +02:00
980cfab637 updated python package testing to json format 2025-10-22 00:14:45 +02:00
accdc70165 changed pyhton package testing to json format 2025-10-22 00:03:58 +02:00
9ac0309917 changed python install to alpine python install 2025-10-21 23:53:12 +02:00
afe5e85add changed pip3 to pip 2025-10-21 23:44:37 +02:00
4689966783 changed to simple python installation 2025-10-21 23:42:11 +02:00
45509b1dbd changed up pyhton installation 2025-10-21 23:36:59 +02:00
590cf2d10f removed python installation for frontend 2025-10-21 23:29:24 +02:00
d43162aff6 removed unvalid paht 2025-10-21 23:24:47 +02:00
fd00c47b20 renamen module exports 2025-10-21 23:12:02 +02:00
3ff51f64eb if jest nono - nono tests 2025-10-21 23:02:11 +02:00
f64fb08566 added jest for tests 2025-10-21 22:57:33 +02:00
5e248c662f added test checks before running tests 2025-10-21 22:50:22 +02:00
b3a3a5680e added handling in case of desynced package.json package-lock.json 2025-10-21 22:42:06 +02:00
364fb41f0e removed dependencie worker_threads native 2025-10-21 22:36:54 +02:00
fb0d0b6711 added ci 2025-10-21 22:31:00 +02:00
eb33f47071 added ci 2025-10-21 22:20:26 +02:00
5809e6c44c fixed role naming instandhalter -> maintenance 2025-10-21 20:23:12 +02:00
2200ef6937 Remove progress_data from tracking 2025-10-21 18:15:40 +02:00
d6e0b45f07 changed gitignore 2025-10-21 18:13:46 +02:00
a45647bd87 changed gitignore 2025-10-21 18:02:12 +02:00
130 changed files with 12652 additions and 24352 deletions

27
.env.template Normal file
View File

@@ -0,0 +1,27 @@
# === SCHICHTPLANER DOCKER COMPOSE ENVIRONMENT VARIABLES ===
# Diese Datei wird von docker-compose automatisch geladen
# Security
JWT_SECRET=${JWT_SECRET:-your-secret-key-please-change}
NODE_ENV=${NODE_ENV:-production}
# Database
DB_PATH=${DB_PATH:-/app/data/database.db}
# Server
PORT=${PORT:-3002}
# App Configuration
APP_TITLE="Shift Planning App"
ENABLE_PRO=${ENABLE_PRO:-false}
# Trust Proxy Configuration
TRUST_PROXY_ENABLED=false
TRUSTED_PROXY_IPS= # Your load balancer/reverse proxy IPs
TRUSTED_PROXY_HEADER=x-forwarded-for
# Rate Limiting Configuration
RATE_LIMIT_WINDOW_MS=900000
RATE_LIMIT_MAX_REQUESTS=100
RATE_LIMIT_SKIP_PATHS=/api/health,/api/status
RATE_LIMIT_WHITELIST=127.0.0.1,::1

180
.github/workflows/docker.yml vendored Normal file
View File

@@ -0,0 +1,180 @@
name: CI/CD Pipeline
on:
workflow_dispatch:
push:
branches: [ "development", "main", "staging" ]
tags: [ "v*.*.*" ]
env:
REGISTRY: ghcr.io
IMAGE_NAME: ${{ github.repository }}
jobs:
set-tag:
name: Set Tag Name
runs-on: ubuntu-latest
outputs:
tag_name: ${{ steps.set_tag.outputs.tag_name }}
is_main_branch: ${{ steps.branch_check.outputs.is_main }}
steps:
- name: Checkout code
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Check if main branch
id: branch_check
run: |
if [[ "${{ github.ref }}" == "refs/heads/main" || "${{ github.ref }}" == "refs/heads/master" ]]; then
echo "is_main=true" >> $GITHUB_OUTPUT
else
echo "is_main=false" >> $GITHUB_OUTPUT
fi
- name: Determine next semantic version tag
id: set_tag
run: |
git fetch --tags
# Find latest tag matching vX.Y.Z
latest_tag=$(git tag --list 'v*.*.*' --sort=-v:refname | head -n 1)
echo "Latest tag found: $latest_tag"
if [[ -z "$latest_tag" ]]; then
major=0
minor=0
patch=0
echo "No existing tags found, starting from v0.0.0"
else
version="${latest_tag#v}"
IFS='.' read -r major minor patch <<< "$version"
echo "Parsed version: major=$major, minor=$minor, patch=$patch"
fi
if [[ "${{ github.ref }}" == "refs/heads/main" || "${{ github.ref }}" == "refs/heads/master" ]]; then
major=$((major + 1))
minor=0
patch=0
echo "Main branch - major version bump"
elif [[ "${{ github.ref }}" == "refs/heads/development" ]]; then
minor=$((minor + 1))
patch=0
echo "Development branch - minor version bump"
else
patch=$((patch + 1))
echo "Other branch - patch version bump"
fi
new_tag="v${major}.${minor}.${patch}"
echo "tag_name=${new_tag}" >> $GITHUB_OUTPUT
echo "Next version tag: ${new_tag}"
test:
runs-on: ubuntu-latest
needs: set-tag
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: '20'
- name: Install backend dependencies
working-directory: ./backend
run: npm install
- name: Run TypeScript check
working-directory: ./backend
run: npx tsc --noEmit
- name: Run backend tests
working-directory: ./backend
run: |
if [ -f "node_modules/.bin/jest" ]; then
npm test
else
echo "⚠️ Jest not installed. Skipping tests."
fi
- name: Setup Python
uses: actions/setup-python@v4
with:
python-version: '3.11'
- name: Install Python dependencies
run: pip install ortools
- name: Test Python integration
run: |
python -c "from ortools.sat.python import cp_model; print('OR-Tools available')"
- name: Display next version
run: |
echo "Next version will be: ${{ needs.set-tag.outputs.tag_name }}"
build-and-push:
needs: [set-tag, test]
runs-on: ubuntu-latest
if: github.event_name == 'push'
permissions:
contents: write
packages: write
id-token: write
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
- name: Log in to GitHub Container Registry
uses: docker/login-action@v3
with:
registry: ${{ env.REGISTRY }}
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Extract metadata
id: meta
uses: docker/metadata-action@v5
with:
images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
tags: |
type=raw,value=${{ needs.set-tag.outputs.tag_name }}
type=raw,value=latest,enable=${{ fromJSON(needs.set-tag.outputs.is_main_branch) }}
- name: Build and push Docker image
uses: docker/build-push-action@v5
with:
context: .
file: ./Dockerfile
platforms: linux/amd64,linux/arm64
push: true
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
cache-from: type=gha
cache-to: type=gha,mode=max
- name: Create Git Tag
if: success()
run: |
git config --local user.email "action@github.com"
git config --local user.name "GitHub Action"
git tag ${{ needs.set-tag.outputs.tag_name }}
git push origin ${{ needs.set-tag.outputs.tag_name }}
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- name: Display pushed images
run: |
echo "Docker images pushed successfully!"
echo "- Image: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}"
echo "- Tags: ${{ steps.meta.outputs.tags }}"
echo "- New version: ${{ needs.set-tag.outputs.tag_name }}"
echo "- Is main branch: ${{ needs.set-tag.outputs.is_main_branch }}"

139
.gitignore vendored Normal file
View File

@@ -0,0 +1,139 @@
# Dependencies
backend/node_modules/
frontend/node_modules/
/.pnp
.pnp.js
# Testing
/coverage
# Production
/build
# Misc
.DS_Store
.env.local
.env.development.local
.env.test.local
.env.production.local
.env
# Logs
npm-debug.log*
yarn-debug.log*
yarn-error.log*
# IDEs
.vscode/
.idea/
*.swp
*.swo
# OS generated files
.DS_Store
.DS_Store?
._*
.Spotlight-V100
.Trashes
ehthumbs.db
Thumbs.db
# Environment variables
.env
.env.local
.env.development.local
.env.test.local
.env.production.local
----
# Dependencies
node_modules/
npm-debug.log*
yarn-debug.log*
yarn-error.log*
# Build outputs
dist/
build/
# Environment variables
.env
.env.local
.env.development.local
.env.test.local
.env.production.local
.env.production
# Database
database/*.db
database/*.db-journal
*.sqlite
*.db
# Logs
logs
*.log
# Privat
backend/src/python-scripts/progress_data/*.json
# Runtime data
pids
*.pid
*.seed
*.pid.lock
# Coverage directory used by tools like istanbul
coverage/
# nyc test coverage
.nyc_output
# IDEs
.vscode/
.idea/
*.swp
*.swo
# OS generated files
.DS_Store
.DS_Store?
._*
.Spotlight-V100
.Trashes
ehthumbs.db
Thumbs.db
# Optional npm cache directory
.npm
# Optional eslint cache
.eslintcache
# Ignore contents of premium folder in public repo
premium/*
!premium/README-PREMIUM.md
!premium/.gitkeep
.git
.gitignore
node_modules
npm-debug.log
README.md
.env
.nyc_output
coverage
.cache
dist
build
logs
*.tsbuildinfo
# Frontend specific
frontend/dist
frontend/.vite
# Backend specific
backend/dist

3
.gitmodules vendored Normal file
View File

@@ -0,0 +1,3 @@
[submodule "premium"]
path = premium
url = https://github.com/donpat1to/Schichtenplaner-Pro.git

86
Dockerfile Normal file
View File

@@ -0,0 +1,86 @@
# Single stage build for workspaces
FROM node:20-bullseye AS builder
WORKDIR /app
# Install Python + OR-Tools
RUN apt-get update && apt-get install -y python3 python3-pip build-essential \
&& pip install --no-cache-dir ortools
# Create symlink so python3 is callable as python
RUN ln -sf /usr/bin/python3 /usr/bin/python
# Copy root package files first
COPY package*.json ./
COPY tsconfig.base.json ./
COPY ecosystem.config.cjs ./
# Install root dependencies
RUN npm install --only=production
# Copy workspace files
COPY backend/ ./backend/
COPY frontend/ ./frontend/
# Install workspace dependencies individually
RUN npm install --workspace=backend
RUN npm install --workspace=frontend
# Build backend first
RUN npm run build --only=production --workspace=backend
# Build frontend
RUN npm run build --workspace=frontend
# Verify Python and OR-Tools installation
RUN python -c "from ortools.sat.python import cp_model; print('OR-Tools installed successfully')"
# Production stage
FROM node:20-bookworm
WORKDIR /app
# Install system dependencies including gettext-base for envsubst
RUN apt-get update && apt-get install -y gettext-base && \
rm -rf /var/lib/apt/lists/*
RUN npm install -g pm2
RUN mkdir -p /app/data
# Copy application files
COPY --from=builder /app/backend/dist/ ./dist/
COPY --from=builder /app/backend/package*.json ./
COPY --from=builder /app/node_modules/ ./node_modules/
COPY --from=builder /app/frontend/dist/ ./frontend-build/
COPY --from=builder /app/ecosystem.config.cjs ./
COPY --from=builder /app/backend/src/database/ ./dist/database/
COPY --from=builder /app/backend/src/database/ ./database/
# Copy init script and env template
COPY docker-init.sh /usr/local/bin/
COPY .env.template ./
# Set execute permissions for init script
RUN chmod +x /usr/local/bin/docker-init.sh
# Create user and set permissions
RUN groupadd -g 1001 nodejs && \
useradd -m -u 1001 -s /bin/bash -g nodejs schichtplan && \
chown -R schichtplan:nodejs /app && \
chmod 755 /app && \
chmod 775 /app/data
ENV PM2_HOME=/app/.pm2
# Set entrypoint to init script and keep existing cmd
ENTRYPOINT ["/usr/local/bin/docker-init.sh"]
CMD ["pm2-runtime", "ecosystem.config.cjs"]
USER schichtplan
EXPOSE 3002
HEALTHCHECK --interval=30s --timeout=10s --start-period=40s --retries=3 \
CMD wget --no-verbose --tries=1 --spider http://localhost:3002/api/health || exit 1

21
LICENSE-COMMERCIAL Normal file
View File

@@ -0,0 +1,21 @@
COMMERCIAL LICENSE AGREEMENT
Copyright (c) 2025 Patrick Mahnke-Hartmann
This software, "Schichtenplaner", is offered under a dual licensing model.
1. Open-Source License
You may use this software under the terms of the MIT License
(see LICENSE file) for non-commercial, personal, or educational use.
2. Commercial License
Commercial use of this software requires a separate paid license.
This includes, but is not limited to:
- Use in proprietary, for-profit, or internal business applications
- Use within paid services or SaaS offerings
- Integration into commercial software or distributions
To obtain a commercial license, please contact:
📧 dev.patrick@mahnke-hartmann.de
or open an inquiry via GitHub: https://github.com/donpat1to/Schichtenplaner
Without a valid commercial license, all commercial rights are reserved.

View File

@@ -2,4 +2,14 @@
Aufteilung der Schichten unter Mitarbeitern
du knlich
## 🧾 License
This project uses a **dual license model**:
- **Community Edition:** Licensed under [MIT](./LICENSE) for personal and non-commercial use.
- **Commercial Edition:** A [commercial license](./LICENSE-COMMERCIAL) is required for any for-profit or business use.
To obtain a commercial license, contact:
📧 patrick@mahnke-hartmann.dev
[![License: MIT & Commercial](https://img.shields.io/badge/license-MIT%20%7C%20Commercial-purple)](#license)

59
backend/.gitignore vendored
View File

@@ -1,59 +0,0 @@
# Dependencies
node_modules/
npm-debug.log*
yarn-debug.log*
yarn-error.log*
# Build outputs
dist/
build/
# Environment variables
.env
.env.local
.env.development.local
.env.test.local
.env.production.local
# Database
database/*.db
database/*.db-journal
*.sqlite
*.db
# Logs
logs
*.log
# Runtime data
pids
*.pid
*.seed
*.pid.lock
# Coverage directory used by tools like istanbul
coverage/
# nyc test coverage
.nyc_output
# IDEs
.vscode/
.idea/
*.swp
*.swo
# OS generated files
.DS_Store
.DS_Store?
._*
.Spotlight-V100
.Trashes
ehthumbs.db
Thumbs.db
# Optional npm cache directory
.npm
# Optional eslint cache
.eslintcache

View File

@@ -1,8 +0,0 @@
# backend/Dockerfile
FROM node:18-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production
COPY . .
EXPOSE 3002
CMD ["node", "dist/server.js"]

View File

@@ -1,61 +0,0 @@
# Multi-stage Dockerfile for Node.js + Python application
FROM node:20-alpine AS node-base
# Install Python and build dependencies in Node stage
RUN apk add --no-cache \
python3 \
py3-pip \
build-base \
python3-dev
# Install Python dependencies
COPY python-scripts/requirements.txt /tmp/requirements.txt
RUN pip3 install --no-cache-dir -r /tmp/requirements.txt
# Set working directory
WORKDIR /app
# Copy package files
COPY package*.json ./
# Install Node.js dependencies
RUN npm ci --only=production
# Build stage
FROM node-base AS builder
# Install all dependencies (including dev dependencies)
RUN npm ci
# Copy source code
COPY . .
# Build the application
RUN npm run build
# Production stage
FROM node-base AS production
# Copy built application from builder stage
COPY --from=builder /app/dist ./dist
COPY --from=builder /app/package*.json ./
# Copy Python scripts
COPY --from=builder /app/python-scripts ./python-scripts
# Create non-root user
RUN addgroup -g 1001 -S nodejs && \
adduser -S nextjs -u 1001
# Change to non-root user
USER nextjs
# Expose port
EXPOSE 3000
# Health check
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
CMD node dist/health-check.js
# Start the application
CMD ["npm", "start"]

18
backend/jest.config.js Normal file
View File

@@ -0,0 +1,18 @@
/** @type {import('ts-jest').JestConfigWithTsJest} */
module.exports = {
preset: 'ts-jest',
testEnvironment: 'node',
roots: ['<rootDir>/src'],
testMatch: [
'**/__tests__/**/*.+(ts|tsx|js)',
'**/?(*.)+(spec|test).+(ts|tsx|js)'
],
transform: {
'^.+\.(ts|tsx)$': 'ts-jest',
},
collectCoverageFrom: [
'src/**/*.{js,ts}',
'!src/server.ts',
'!src/**/*.d.ts'
],
};

2853
backend/package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -4,29 +4,38 @@
"type": "module",
"scripts": {
"dev": "npm run build && npx tsx src/server.ts",
"dev:single": "cross-env NODE_ENV=development TRUST_PROXY_ENABLED=false npx tsx src/server.ts",
"build": "tsc",
"start": "node dist/server.js",
"prestart": "npm run build"
"prestart": "npm run build",
"test": "jest",
"test:python": "python -c \"from ortools.sat.python import cp_model; print('OR-Tools OK')\"",
"docker:build": "docker build -t schichtplan-backend .",
"docker:run": "docker run -p 3001:3001 schichtplan-backend"
},
"dependencies": {
"@types/bcrypt": "^6.0.0",
"@types/node": "24.9.2",
"vite":"7.1.12",
"bcrypt": "^6.0.0",
"bcryptjs": "^2.4.3",
"cors": "^2.8.5",
"express": "^4.18.2",
"jsonwebtoken": "^9.0.2",
"sqlite3": "^5.1.6",
"uuid": "^9.0.0",
"worker_threads": "native"
"express-rate-limit": "8.1.0",
"helmet": "8.1.0",
"express-validator": "7.3.0"
},
"devDependencies": {
"@types/bcryptjs": "^2.4.2",
"@types/cors": "^2.8.13",
"@types/express": "^4.17.17",
"@types/jsonwebtoken": "^9.0.2",
"@types/uuid": "^9.0.2",
"@types/jest": "^29.5.0",
"ts-node": "^10.9.0",
"typescript": "^5.0.0",
"tsx": "^4.0.0"
"tsx": "^4.0.0",
"cross-env": "10.1.0"
}
}

View File

@@ -64,7 +64,7 @@ export const login = async (req: Request, res: Response) => {
return res.status(400).json({ error: 'E-Mail und Passwort sind erforderlich' });
}
// UPDATED: Get user from database with role from employee_roles table
// Get user from database with role from employee_roles table
const user = await db.get<any>(
`SELECT
e.id, e.email, e.password, e.firstname, e.lastname,
@@ -155,7 +155,7 @@ export const getCurrentUser = async (req: Request, res: Response) => {
return res.status(401).json({ error: 'Nicht authentifiziert' });
}
// UPDATED: Get user with role from employee_roles table
// Get user with role from employee_roles table
const user = await db.get<any>(
`SELECT
e.id, e.email, e.firstname, e.lastname,

View File

@@ -1,5 +1,5 @@
// backend/src/controllers/employeeController.ts
import { Request, Response } from 'express';
import { Response } from 'express';
import { v4 as uuidv4 } from 'uuid';
import bcrypt from 'bcryptjs';
import { db } from '../services/databaseService.js';
@@ -314,6 +314,56 @@ export const updateEmployee = async (req: AuthRequest, res: Response): Promise<v
return;
}
// Check if user is trying to remove their own admin role
const currentUser = req.user;
if (currentUser?.userId === id && roles) {
const currentUserRoles = await db.all<{ role: string }>(
'SELECT role FROM employee_roles WHERE employee_id = ?',
[currentUser.userId]
);
const isCurrentlyAdmin = currentUserRoles.some(role => role.role === 'admin');
const willBeAdmin = roles.includes('admin');
if (isCurrentlyAdmin && !willBeAdmin) {
res.status(400).json({ error: 'You cannot remove your own admin role' });
return;
}
}
// Check admin count if roles are being updated
if (roles) {
try {
await checkAdminCount(id, roles);
} catch (error: any) {
res.status(400).json({ error: error.message });
return;
}
}
// Check if trying to deactivate the last admin
if (isActive === false) {
const isEmployeeAdmin = await db.get<{ count: number }>(
`SELECT COUNT(*) as count FROM employee_roles WHERE employee_id = ? AND role = 'admin'`,
[id]
);
if (isEmployeeAdmin && isEmployeeAdmin.count > 0) {
const otherAdminCount = await db.get<{ count: number }>(
`SELECT COUNT(*) as count
FROM employee_roles er
JOIN employees e ON er.employee_id = e.id
WHERE er.role = 'admin' AND e.is_active = 1 AND er.employee_id != ?`,
[id]
);
if (!otherAdminCount || otherAdminCount.count === 0) {
res.status(400).json({ error: 'Cannot deactivate the last admin user' });
return;
}
}
}
// Validate employee type if provided
if (employeeType) {
const validEmployeeType = await db.get(
@@ -438,7 +488,15 @@ export const deleteEmployee = async (req: AuthRequest, res: Response): Promise<v
const { id } = req.params;
console.log('🗑️ Starting deletion process for employee ID:', id);
// UPDATED: Check if employee exists with role from employee_roles
const currentUser = req.user;
// Prevent self-deletion
if (currentUser?.userId === id) {
res.status(400).json({ error: 'You cannot delete yourself' });
return;
}
// Check if employee exists with role from employee_roles
const existingEmployee = await db.get<any>(`
SELECT
e.id, e.email, e.firstname, e.lastname, e.is_active,
@@ -455,6 +513,26 @@ export const deleteEmployee = async (req: AuthRequest, res: Response): Promise<v
return;
}
const employeeRoles = await db.all<{ role: string }>(`
SELECT role FROM employee_roles WHERE employee_id = ?
`, [id]);
const isEmployeeAdmin = employeeRoles.some(role => role.role === 'admin');
// Check if this is the last admin
if (isEmployeeAdmin) {
const adminCount = await db.get<{ count: number }>(
`SELECT COUNT(*) as count
FROM employee_roles
WHERE role = 'admin'`
);
if (adminCount && adminCount.count <= 1) {
res.status(400).json({ error: 'Cannot delete the last admin user' });
return;
}
}
console.log('📝 Found employee to delete:', existingEmployee);
// Start transaction
@@ -511,7 +589,6 @@ export const deleteEmployee = async (req: AuthRequest, res: Response): Promise<v
console.error('Error during deletion transaction:', error);
throw error;
}
} catch (error) {
console.error('Error deleting employee:', error);
res.status(500).json({ error: 'Internal server error' });
@@ -558,13 +635,49 @@ export const updateAvailabilities = async (req: AuthRequest, res: Response): Pro
const { employeeId } = req.params;
const { planId, availabilities } = req.body;
// Check if employee exists
const existingEmployee = await db.get('SELECT id FROM employees WHERE id = ?', [employeeId]);
// Check if employee exists and get contract type
const existingEmployee = await db.get<any>(`
SELECT e.*, er.role
FROM employees e
LEFT JOIN employee_roles er ON e.id = er.employee_id
WHERE e.id = ?
`, [employeeId]);
if (!existingEmployee) {
res.status(404).json({ error: 'Employee not found' });
return;
}
// Check if employee is active
if (!existingEmployee.is_active) {
res.status(400).json({ error: 'Cannot set availability for inactive employee' });
return;
}
// Validate contract type requirements
const availableCount = availabilities.filter((avail: any) =>
avail.preferenceLevel === 1 || avail.preferenceLevel === 2
).length;
const contractType = existingEmployee.contract_type;
// Apply contract type minimum requirements
if (contractType === 'small' && availableCount < 2) {
res.status(400).json({
error: 'Employees with small contract must have at least 2 available shifts'
});
return;
}
if (contractType === 'large' && availableCount < 3) {
res.status(400).json({
error: 'Employees with large contract must have at least 3 available shifts'
});
return;
}
// Flexible contract has no minimum requirement
await db.run('BEGIN TRANSACTION');
try {
@@ -643,8 +756,8 @@ export const changePassword = async (req: AuthRequest, res: Response): Promise<v
return;
}
// For non-admin users, verify current password
if (currentUser?.role !== 'admin') {
// Verify current password
if (employee) {
const isValidPassword = await bcrypt.compare(currentPassword, employee.password);
if (!isValidPassword) {
res.status(400).json({ error: 'Current password is incorrect' });
@@ -653,8 +766,8 @@ export const changePassword = async (req: AuthRequest, res: Response): Promise<v
}
// Validate new password
if (!newPassword || newPassword.length < 6) {
res.status(400).json({ error: 'New password must be at least 6 characters long' });
if (!newPassword || newPassword.length < 8) {
res.status(400).json({ error: 'New password must be at least 8 characters long' });
return;
}
@@ -700,3 +813,35 @@ export const updateLastLogin = async (req: AuthRequest, res: Response): Promise<
res.status(500).json({ error: 'Internal server error' });
}
};
const checkAdminCount = async (employeeId: string, newRoles: string[]): Promise<void> => {
try {
// Count current admins excluding the employee being updated
const adminCountResult = await db.get<{ count: number }>(
`SELECT COUNT(DISTINCT employee_id) as count
FROM employee_roles
WHERE role = 'admin' AND employee_id != ?`,
[employeeId]
);
const currentAdminCount = adminCountResult?.count || 0;
// Check ALL current roles for the employee
const currentEmployeeRoles = await db.all<{ role: string }>(
`SELECT role FROM employee_roles WHERE employee_id = ?`,
[employeeId]
);
const currentRoles = currentEmployeeRoles.map(role => role.role);
const isCurrentlyAdmin = currentRoles.includes('admin');
const willBeAdmin = newRoles.includes('admin');
// If removing admin role from the last admin, throw error
if (isCurrentlyAdmin && !willBeAdmin && currentAdminCount === 0) {
throw new Error('Cannot remove admin role from the last admin user');
}
} catch (error) {
throw error;
}
};

View File

@@ -1,7 +1,6 @@
// backend/src/controllers/setupController.ts
import { Request, Response } from 'express';
import bcrypt from 'bcrypt';
import { v4 as uuidv4 } from 'uuid';
import { randomUUID } from 'crypto';
import { db } from '../services/databaseService.js';
@@ -76,8 +75,8 @@ export const setupAdmin = async (req: Request, res: Response): Promise<void> =>
}
// Password length validation
if (password.length < 6) {
res.status(400).json({ error: 'Das Passwort muss mindestens 6 Zeichen lang sein' });
if (password.length < 8) {
res.status(400).json({ error: 'Das Passwort muss mindestens 8 Zeichen lang sein' });
return;
}

View File

@@ -5,10 +5,9 @@ import { db } from '../services/databaseService.js';
import {
CreateShiftPlanRequest,
UpdateShiftPlanRequest,
ShiftPlan
} from '../models/ShiftPlan.js';
import { AuthRequest } from '../middleware/auth.js';
import { createPlanFromPreset, TEMPLATE_PRESETS } from '../models/defaults/shiftPlanDefaults.js';
import { TEMPLATE_PRESETS } from '../models/defaults/shiftPlanDefaults.js';
async function getPlanWithDetails(planId: string) {
const plan = await db.get<any>(`

View File

@@ -1,3 +1,8 @@
PRAGMA journal_mode = WAL;
PRAGMA foreign_keys = ON;
PRAGMA secure_delete = ON;
PRAGMA auto_vacuum = INCREMENTAL;
-- Employee Types
CREATE TABLE IF NOT EXISTS employee_types (
type TEXT PRIMARY KEY,

View File

@@ -0,0 +1,25 @@
## User Settings
### \[UPDATE\] Personal availability
* Only the employee themselves can manage their availability
* Must select a valid shift plan with defined shifts
* All changes require explicit save action
### \[VIEW\] ShiftPlan assignments
* Published plans show actual assignments
* Draft plans show preview assignments (if calculated)
* Regular users can only view, not modify assignments
## System-wide
### \[ACCESS\] Role-based restrictions
* `admin`: Full access to all features
* `maintenance`: Access to shift plans and employee management (except admin users)
* `user`: Read-only access to shift plans, can manage own availability and profile
### \[DATA\] Validation rules
* Email addresses are automatically generated from firstname/lastname
* Employee status (`isActive`) controls login and planning eligibility
* Trainee status affects independence (`canWorkAlone`) automatically
* Date ranges must be valid (start before end)
* All required fields must be filled before form submission

View File

@@ -0,0 +1,37 @@
## Shift Assignment
### \[ACTION: update scheduled shift\]
* Requires valid scheduled shift ID
* Only updates assignedEmployees array
* Requires authentication with valid token
* Handles both JSON and non-JSON responses
### \[ACTION: assign shifts automatically\]
* Requires shift plan, employees, and availabilities
* Availability preferenceLevel must be 1, 2, or 3
* Constraints must be an array (converts non-array to empty array)
* All employees must have valid availability data
### \[ACTION: get scheduled shifts\]
* Requires valid plan ID
* Automatically fixes data structure inconsistencies:
- timeSlotId mapping (handles both naming conventions)
- requiredEmployees fallback to 2 if missing
- assignedEmployees fallback to empty array if missing
## Availability
### [UPDATE] availability
* planId: required valid UUID
* availabilities: required array with strict validation:
- shiftId: valid UUID
- preferenceLevel: 0 (unavailable), 1 (available), or 2 (preferred)
- notes: optional, max 500 characters
## Scheduling
### [ACTION: generate schedule]
* shiftPlan: required object with id (valid UUID)
* employees: required array with at least one employee, each with valid UUID
* availabilities: required array
* constraints: optional array

View File

@@ -0,0 +1,23 @@
## Authentication
### \[ACTION: login\]
* Requires valid email and password format:
- Minimum 8 characters
- Must contain uppercase, lowercase, number and special character
* Server validates credentials before issuing token
* Token and employee data stored in localStorage upon success
### \[ACTION: register\]
* `Password` optional but strict validation:
- Minimum 8 characters
- Must contain uppercase, lowercase, number and special character
* `firstname` 1-100 characters and must not be empty
* `lastname` 1-100 characters and must not be empty
* Requires valid email
* Role is optional during registration
* Automatically logs in user after successful registration
### \[ACTION: access protected resources\]
* Requires valid JWT token in Authorization header
* Token is automatically retrieved from localStorage
* Unauthorized requests (401) trigger automatic logout

View File

@@ -0,0 +1,23 @@
## Data Integrity
### \[GENERAL\] API communication
* All fetch requests include error handling
* Failed responses throw descriptive errors
* Token validation before protected operations
* Automatic localStorage cleanup on logout
### \[GENERAL\] data persistence
* Employee data cached in localStorage after login
* Token automatically retrieved from localStorage
* Data structure normalization for scheduled shifts
### \[GENERAL\] error handling
* Network errors are caught and logged
* HTTP errors include status codes and messages
* Failed authentication triggers cleanup and logout
## Role & Permission Notes
* The frontend services don't explicitly restrict actions by role
* Role-based restrictions are likely handled by the backend
* Frontend assumes user has permissions for requested operations
* 401 responses indicate insufficient permissions at backend level

View File

@@ -0,0 +1,75 @@
## Employee Management
### \[CREATE/UPDATE\] employee
* All employee operations require authentication
* Password changes require current password + new password
* Only authenticated users can create/update employees
### \[ACTION: delete employee\]
* Requires authentication
* Server validates permissions before deletion
### \[ACTION: update availability\]
* Requires employee ID and plan ID
* Availability updates must include valid preference levels
* Only authenticated users can update availabilities
### \[ACTION: update last login\]
* Requires employee ID
* Fails silently if update fails (logs error but doesn`t block user)
## Employee
### \[CREATE\] Employee
* `firstname` 1-100 characters and must not be empty
* `lastname` 1-100 characters and must not be empty
* `password` must be at least 8 characters (in create mode)
* `employeeType` must be `manager`, `personell`, `apprentice`, or `guest`
* `canWorkAlone` optional boolean
* `isTrainee` optional boolean
* `isActive` optional boolean (default true)
* Contract type validation:
* `manager`, `apprentice` => `contractType` = flexible
* `guest` => `contractType` = undefined/NONE
* `personell` => `contractType` = small || large
### \[UPDATE\] Employee profile
* `firstname` 1-100 characters and must not be empty
* `lastname` 1-100 characters and must not be empty
* `employeeType` must be valid type if provided
* `contractType` must be valid type if provided
* `roles` must be valid array of roles if provided
* Only the employee themselves or admins can update
### \[UPDATE\] Employee password
* `newPassword` optional but strict validation:
- Minimum 8 characters
- Must contain uppercase, lowercase, number and special character
* `newPassword` must match `confirmPassword`
* For admin password reset: no `currentPassword` required
* For self-password change: `currentPassword` required
### \[UPDATE\] Employee roles
* Only users with role `admin` can modify roles
* At least one employee must maintain `admin` role
* Users cannot remove their own admin role
### \[UPDATE\] Employee availability
* Only active employees can set availability
* Contract type requirements:
* `small` contract: minimum 2 available shifts (preference level 1 or 2)
* `large` contract: minimum 3 available shifts (preference level 1 or 2)
* `flexible` contract: no minimum requirement
* Availability can only be set for valid shift patterns in selected plan
* `shiftId` must be valid and exist in the current plan
### \[ACTION: delete\] Employee
* Only users with role `admin` can delete employees
* Cannot delete yourself
* Cannot delete the last admin user
* User confirmation required before deletion
### \[ACTION: edit\] Employee
* Admins can edit all employees
* Maintenance users can edit non-admin employees or themselves
* Regular users can only edit themselves

View File

@@ -0,0 +1,66 @@
## Shift Plan Management
### \[CREATE\] shift plan
* All operations require authentication
* 401 responses trigger automatic logout
* Scheduled shifts array is guaranteed to exist (empty array if none)
### \[CREATE\] shift plan from preset
* presetName must match existing TEMPLATE_PRESETS
* Requires name, startDate, and endDate
* isTemplate is optional (defaults to false)
### \[UPDATE\] shift plan
* Requires valid shift plan ID
* Partial updates allowed
* Authentication required
### \[ACTION: delete shift plan\]
* Requires authentication
* 401 responses trigger automatic logout
### \[ACTION: regenerate scheduled shifts\]
* Requires valid plan ID
* Authentication required
* Fails silently if regeneration fails (logs error but continues)
### \[ACTION: clear assignments\]
* Requires valid plan ID
* Authentication required
* Clears all employee assignments from scheduled shifts
## ShiftPlan
### \[CREATE\] ShiftPlan from template
* `planName` must not be empty
* `startDate` must be set
* `endDate` must be set
* `endDate` must be after `startDate`
* `selectedPreset` must be chosen (template must be selected)
* Only available template presets can be used
### \[ACTION: publish\] ShiftPlan
* Plan must be in 'draft' status
* All active employees must have set their availabilities for the plan
* Only users with roles \['admin', 'maintenance'\] can publish
* Assignment algorithm must not have critical violations (ERROR or ❌ KRITISCH)
* employee && employee.contract_type === small => mind. 1 mal availability === 1 || availability === 2
* employee && employee.contract_type === large => mind. 3 mal availability === 1 || availability === 2
### \[ACTION: recreate assignments\]
* Plan must be in 'published' status
* Only users with roles \['admin', 'maintenance'\] can recreate
* User confirmation required before clearing all assignments
### \[ACTION: delete\] ShiftPlan
* Only users with roles \['admin', 'maintenance'\] can delete
* User confirmation required before deletion
### \[ACTION: edit\] ShiftPlan
* Only users with roles \['admin', 'maintenance'\] can edit
* Can only edit plans in 'draft' status
### \[UPDATE\] ShiftPlan shifts
* `timeSlotId` must be selected from available time slots
* `requiredEmployees` must be at least 1
* `dayOfWeek` must be between 1-7

View File

@@ -52,3 +52,35 @@ export const requireRole = (roles: string[]) => {
next();
};
};
export const getClientIP = (req: Request): string => {
const trustedHeader = process.env.TRUSTED_PROXY_HEADER || 'x-forwarded-for';
const forwarded = req.headers[trustedHeader];
const realIp = req.headers['x-real-ip'];
if (forwarded) {
if (Array.isArray(forwarded)) {
return forwarded[0].split(',')[0].trim();
} else if (typeof forwarded === 'string') {
return forwarded.split(',')[0].trim();
}
}
if (realIp) {
return realIp.toString();
}
return req.socket.remoteAddress || req.ip || 'unknown';
};
export const ipSecurityCheck = (req: AuthRequest, res: Response, next: NextFunction): void => {
const clientIP = getClientIP(req);
// Log suspicious activity
const suspiciousPaths = ['/api/auth/login', '/api/auth/register'];
if (suspiciousPaths.includes(req.path)) {
console.log(`🔐 Auth attempt from IP: ${clientIP}, Path: ${req.path}`);
}
next();
}

View File

@@ -0,0 +1,145 @@
import rateLimit from 'express-rate-limit';
import { Request } from 'express';
// Secure IP extraction that works with proxy settings
const getClientIP = (req: Request): string => {
// Read from environment which header to trust
const trustedHeader = process.env.TRUSTED_PROXY_HEADER || 'x-forwarded-for';
const forwarded = req.headers[trustedHeader];
const realIp = req.headers['x-real-ip'];
const cfConnectingIp = req.headers['cf-connecting-ip']; // Cloudflare
// If we have a forwarded header and trust proxy is configured
if (forwarded) {
if (Array.isArray(forwarded)) {
const firstIP = forwarded[0].split(',')[0].trim();
console.log(`🔍 Extracted IP from ${trustedHeader}: ${firstIP} (from: ${forwarded[0]})`);
return firstIP;
} else if (typeof forwarded === 'string') {
const firstIP = forwarded.split(',')[0].trim();
console.log(`🔍 Extracted IP from ${trustedHeader}: ${firstIP} (from: ${forwarded})`);
return firstIP;
}
}
// Cloudflare support
if (cfConnectingIp) {
console.log(`🔍 Using Cloudflare IP: ${cfConnectingIp}`);
return cfConnectingIp.toString();
}
// Fallback to x-real-ip
if (realIp) {
console.log(`🔍 Using x-real-ip: ${realIp}`);
return realIp.toString();
}
// Final fallback to connection remote address
const remoteAddress = req.socket.remoteAddress || req.ip || 'unknown';
console.log(`🔍 Using remote address: ${remoteAddress}`);
return remoteAddress;
};
// Helper to check if request should be limited
const shouldSkipLimit = (req: Request): boolean => {
const skipPaths = [
'/api/health',
'/api/setup/status',
'/api/auth/validate'
];
// Skip for successful GET requests (data fetching)
if (req.method === 'GET' && req.path.startsWith('/api/')) {
return true;
}
// Skip for whitelisted IPs from environment
const whitelist = process.env.RATE_LIMIT_WHITELIST?.split(',') || [];
const clientIP = getClientIP(req);
if (whitelist.includes(clientIP)) {
console.log(`✅ IP whitelisted: ${clientIP}`);
return true;
}
return skipPaths.includes(req.path);
};
// Environment-based configuration
const getRateLimitConfig = () => {
const isProduction = process.env.NODE_ENV === 'production';
return {
windowMs: parseInt(process.env.RATE_LIMIT_WINDOW_MS || '900000'), // 15 minutes default
max: isProduction
? parseInt(process.env.RATE_LIMIT_MAX_REQUESTS || '100') // Stricter in production
: parseInt(process.env.RATE_LIMIT_MAX_REQUESTS || '1000'), // More lenient in development
// Development-specific relaxations
skip: (req: Request) => {
// Skip all GET requests in development for easier testing
if (!isProduction && req.method === 'GET') {
return true;
}
return shouldSkipLimit(req);
}
};
};
// Main API limiter - nur für POST/PUT/DELETE
export const apiLimiter = rateLimit({
...getRateLimitConfig(),
message: {
error: 'Zu viele Anfragen, bitte verlangsamen Sie Ihre Aktionen'
},
standardHeaders: true,
legacyHeaders: false,
keyGenerator: (req) => getClientIP(req),
handler: (req, res) => {
const clientIP = getClientIP(req);
console.warn(`🚨 Rate limit exceeded for IP: ${clientIP}, Path: ${req.path}, Method: ${req.method}`);
res.status(429).json({
error: 'Zu viele Anfragen',
message: 'Bitte versuchen Sie es später erneut',
retryAfter: '15 Minuten',
clientIP: process.env.NODE_ENV === 'development' ? clientIP : undefined // Only expose IP in dev
});
}
});
// Strict limiter for auth endpoints
export const authLimiter = rateLimit({
windowMs: 15 * 60 * 1000,
max: parseInt(process.env.AUTH_RATE_LIMIT_MAX_REQUESTS || '5'),
message: {
error: 'Zu viele Login-Versuche, bitte versuchen Sie es später erneut'
},
standardHeaders: true,
legacyHeaders: false,
skipSuccessfulRequests: true,
keyGenerator: (req) => getClientIP(req),
handler: (req, res) => {
const clientIP = getClientIP(req);
console.warn(`🚨 Auth rate limit exceeded for IP: ${clientIP}`);
res.status(429).json({
error: 'Zu viele Login-Versuche',
message: 'Aus Sicherheitsgründen wurde Ihr Konto temporär gesperrt',
retryAfter: '15 Minuten'
});
}
});
// Separate limiter for expensive endpoints
export const expensiveEndpointLimiter = rateLimit({
windowMs: 15 * 60 * 1000,
max: parseInt(process.env.EXPENSIVE_ENDPOINT_LIMIT || '10'),
message: {
error: 'Zu viele Anfragen für diese Ressource'
},
standardHeaders: true,
legacyHeaders: false,
keyGenerator: (req) => getClientIP(req)
});

View File

@@ -0,0 +1,550 @@
import { body, validationResult, param, query } from 'express-validator';
import { Request, Response, NextFunction } from 'express';
// ===== AUTH VALIDATION =====
export const validateLogin = [
body('email')
.isEmail()
.withMessage('Must be a valid email')
.normalizeEmail(),
body('password')
.optional()
.isLength({ min: 8 })
.withMessage('Password must be at least 8 characters')
.matches(/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?])/)
.withMessage('Password must contain uppercase, lowercase, number and special character'),
];
export const validateRegister = [
body('firstname')
.isLength({ min: 1, max: 100 })
.withMessage('First name must be between 1-100 characters')
.notEmpty()
.withMessage('First name must not be empty')
.trim()
.escape(),
body('lastname')
.isLength({ min: 1, max: 100 })
.withMessage('Last name must be between 1-100 characters')
.notEmpty()
.withMessage('Last name must not be empty')
.trim()
.escape(),
body('password')
.optional()
.isLength({ min: 8 })
.withMessage('Password must be at least 8 characters')
.matches(/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?])/)
.withMessage('Password must contain uppercase, lowercase, number and special character'),
];
// ===== EMPLOYEE VALIDATION =====
export const validateEmployee = [
body('firstname')
.isLength({ min: 1, max: 100 })
.withMessage('First name must be between 1-100 characters')
.notEmpty()
.withMessage('First name must not be empty')
.trim()
.escape(),
body('lastname')
.isLength({ min: 1, max: 100 })
.withMessage('Last name must be between 1-100 characters')
.notEmpty()
.withMessage('Last name must not be empty')
.trim()
.escape(),
body('password')
.optional()
.isLength({ min: 8 })
.withMessage('Password must be at least 8 characters')
.matches(/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?])/)
.withMessage('Password must contain uppercase, lowercase, number and special character'),
body('employeeType')
.isIn(['manager', 'personell', 'apprentice', 'guest'])
.withMessage('Employee type must be manager, personell, apprentice or guest'),
body('contractType')
.custom((value, { req }) => {
const employeeType = req.body.employeeType;
// Manager, apprentice => contractType must be flexible
if (['manager', 'apprentice'].includes(employeeType)) {
if (value !== 'flexible') {
throw new Error(`contractType must be 'flexible' for employeeType: ${employeeType}`);
}
}
// Guest => contractType must be undefined/NONE
else if (employeeType === 'guest') {
if (value !== undefined && value !== null) {
throw new Error(`contractType is not allowed for employeeType: ${employeeType}`);
}
}
// Personell => contractType must be small or large
else if (employeeType === 'personell') {
if (!['small', 'large'].includes(value)) {
throw new Error(`contractType must be 'small' or 'large' for employeeType: ${employeeType}`);
}
}
return true;
}),
body('contractType')
.optional()
.isIn(['small', 'large', 'flexible'])
.withMessage('Contract type must be small, large or flexible'),
body('roles')
.optional()
.isArray()
.withMessage('Roles must be an array'),
body('roles.*')
.optional()
.isIn(['admin', 'maintenance', 'user'])
.withMessage('Invalid role. Allowed: admin, maintenance, user'),
body('canWorkAlone')
.optional()
.isBoolean()
.withMessage('canWorkAlone must be a boolean'),
body('isTrainee')
.optional()
.isBoolean()
.withMessage('isTrainee must be a boolean'),
body('isActive')
.optional()
.isBoolean()
.withMessage('isActive must be a boolean')
];
export const validateEmployeeUpdate = [
body('firstname')
.optional()
.isLength({ min: 1, max: 100 })
.withMessage('First name must be between 1-100 characters')
.notEmpty()
.withMessage('First name must not be empty')
.trim()
.escape(),
body('lastname')
.optional()
.isLength({ min: 1, max: 100 })
.withMessage('Last name must be between 1-100 characters')
.notEmpty()
.withMessage('Last name must not be empty')
.trim()
.escape(),
body('employeeType')
.optional()
.isIn(['manager', 'personell', 'apprentice', 'guest'])
.withMessage('Employee type must be manager, personell, apprentice or guest'),
body('contractType')
.optional()
.custom((value, { req }) => {
const employeeType = req.body.employeeType;
if (!employeeType) return true; // Skip if employeeType not provided
// Same validation logic as create
if (['manager', 'apprentice'].includes(employeeType)) {
if (value !== 'flexible') {
throw new Error(`contractType must be 'flexible' for employeeType: ${employeeType}`);
}
}
else if (employeeType === 'guest') {
if (value !== undefined && value !== null) {
throw new Error(`contractType is not allowed for employeeType: ${employeeType}`);
}
}
else if (employeeType === 'personell') {
if (!['small', 'large'].includes(value)) {
throw new Error(`contractType must be 'small' or 'large' for employeeType: ${employeeType}`);
}
}
return true;
}),
body('roles')
.optional()
.isArray()
.withMessage('Roles must be an array'),
body('roles.*')
.optional()
.isIn(['admin', 'maintenance', 'user'])
.withMessage('Invalid role. Allowed: admin, maintenance, user'),
body('canWorkAlone')
.optional()
.isBoolean()
.withMessage('canWorkAlone must be a boolean'),
body('isTrainee')
.optional()
.isBoolean()
.withMessage('isTrainee must be a boolean'),
body('isActive')
.optional()
.isBoolean()
.withMessage('isActive must be a boolean')
];
export const validateChangePassword = [
body('currentPassword')
.optional()
.isLength({ min: 1 })
.withMessage('Current password is required for self-password change'),
body('newPassword')
.isLength({ min: 8 })
.withMessage('Password must be at least 8 characters')
.matches(/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?])/)
.withMessage('Password must contain uppercase, lowercase, number and special character'),
body('confirmPassword')
.custom((value, { req }) => {
if (value !== req.body.newPassword) {
throw new Error('Passwords do not match');
}
return true;
})
];
// ===== SHIFT PLAN VALIDATION =====
export const validateShiftPlan = [
body('name')
.isLength({ min: 1, max: 200 })
.withMessage('Name must be between 1-200 characters')
.trim()
.escape(),
body('description')
.optional()
.isLength({ max: 1000 })
.withMessage('Description cannot exceed 1000 characters')
.trim()
.escape(),
body('startDate')
.optional()
.isISO8601()
.withMessage('Must be a valid date (ISO format)'),
body('endDate')
.optional()
.isISO8601()
.withMessage('Must be a valid date (ISO format)'),
body('isTemplate')
.optional()
.isBoolean()
.withMessage('isTemplate must be a boolean'),
body('status')
.optional()
.isIn(['draft', 'published', 'archived', 'template'])
.withMessage('Status must be draft, published, archived or template'),
body('timeSlots')
.optional()
.isArray()
.withMessage('Time slots must be an array'),
body('timeSlots.*.name')
.isLength({ min: 1, max: 100 })
.withMessage('Time slot name must be between 1-100 characters')
.trim()
.escape(),
body('timeSlots.*.startTime')
.matches(/^([0-1]?[0-9]|2[0-3]):[0-5][0-9]$/)
.withMessage('Start time must be in HH:MM format'),
body('timeSlots.*.endTime')
.matches(/^([0-1]?[0-9]|2[0-3]):[0-5][0-9]$/)
.withMessage('End time must be in HH:MM format'),
body('timeSlots.*.description')
.optional()
.isLength({ max: 500 })
.withMessage('Time slot description cannot exceed 500 characters')
.trim()
.escape(),
body('shifts')
.optional()
.isArray()
.withMessage('Shifts must be an array'),
body('shifts.*.dayOfWeek')
.isInt({ min: 1, max: 7 })
.withMessage('Day of week must be between 1-7 (Monday-Sunday)'),
body('shifts.*.timeSlotId')
.isUUID()
.withMessage('Time slot ID must be a valid UUID'),
body('shifts.*.requiredEmployees')
.isInt({ min: 0 })
.withMessage('Required employees must be a positive integer'),
body('shifts.*.color')
.optional()
.isHexColor()
.withMessage('Color must be a valid hex color')
];
export const validateShiftPlanUpdate = [
body('name')
.optional()
.isLength({ min: 1, max: 200 })
.withMessage('Name must be between 1-200 characters')
.trim()
.escape(),
body('description')
.optional()
.isLength({ max: 1000 })
.withMessage('Description cannot exceed 1000 characters')
.trim()
.escape(),
body('startDate')
.optional()
.isISO8601()
.withMessage('Must be a valid date (ISO format)'),
body('endDate')
.optional()
.isISO8601()
.withMessage('Must be a valid date (ISO format)'),
body('status')
.optional()
.isIn(['draft', 'published', 'archived', 'template'])
.withMessage('Status must be draft, published, archived or template'),
body('timeSlots')
.optional()
.isArray()
.withMessage('Time slots must be an array'),
body('shifts')
.optional()
.isArray()
.withMessage('Shifts must be an array')
];
export const validateCreateFromPreset = [
body('presetName')
.isLength({ min: 1 })
.withMessage('Preset name is required')
.isIn(['GENERAL_STANDARD', 'ZEBRA_STANDARD'])
.withMessage('Invalid preset name'),
body('name')
.isLength({ min: 1, max: 200 })
.withMessage('Name must be between 1-200 characters')
.trim()
.escape(),
body('startDate')
.isISO8601()
.withMessage('Must be a valid date (ISO format)')
.custom((value, { req }) => {
if (req.body.endDate && new Date(value) > new Date(req.body.endDate)) {
throw new Error('Start date must be before end date');
}
return true;
}),
body('endDate')
.isISO8601()
.withMessage('Must be a valid date (ISO format)')
.custom((value, { req }) => {
if (req.body.startDate && new Date(value) < new Date(req.body.startDate)) {
throw new Error('End date must be after start date');
}
return true;
}),
body('isTemplate')
.optional()
.isBoolean()
.withMessage('isTemplate must be a boolean')
];
// ===== SCHEDULED SHIFTS VALIDATION =====
export const validateScheduledShiftUpdate = [
body('assignedEmployees')
.isArray()
.withMessage('assignedEmployees must be an array'),
body('assignedEmployees.*')
.isUUID()
.withMessage('Each assigned employee must be a valid UUID'),
body('requiredEmployees')
.optional()
.isInt({ min: 0 })
.withMessage('Required employees must be a positive integer')
];
// ===== SETUP VALIDATION =====
export const validateSetupAdmin = [
body('firstname')
.isLength({ min: 1, max: 100 })
.withMessage('First name must be between 1-100 characters')
.trim()
.escape(),
body('lastname')
.isLength({ min: 1, max: 100 })
.withMessage('Last name must be between 1-100 characters')
.trim()
.escape(),
body('password')
.optional()
.isLength({ min: 8 })
.withMessage('Password must be at least 8 characters')
.matches(/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?])/)
.withMessage('Password must contain uppercase, lowercase, number and special character'),
];
// ===== SCHEDULING VALIDATION =====
export const validateSchedulingRequest = [
body('shiftPlan')
.isObject()
.withMessage('Shift plan is required'),
body('shiftPlan.id')
.isUUID()
.withMessage('Shift plan ID must be a valid UUID'),
body('employees')
.isArray({ min: 1 })
.withMessage('At least one employee is required'),
body('employees.*.id')
.isUUID()
.withMessage('Each employee must have a valid UUID'),
body('availabilities')
.isArray()
.withMessage('Availabilities must be an array'),
body('constraints')
.optional()
.isArray()
.withMessage('Constraints must be an array')
];
// ===== AVAILABILITY VALIDATION =====
export const validateAvailabilities = [
body('planId')
.isUUID()
.withMessage('Plan ID must be a valid UUID'),
body('availabilities')
.isArray()
.withMessage('Availabilities must be an array')
.custom((availabilities, { req }) => {
// Count available shifts (preference level 1 or 2)
const availableCount = availabilities.filter((avail: any) =>
avail.preferenceLevel === 1 || avail.preferenceLevel === 2
).length;
// Basic validation - at least one available shift
if (availableCount === 0) {
throw new Error('At least one available shift is required');
}
return true;
}),
body('availabilities.*.shiftId')
.isUUID()
.withMessage('Each shift ID must be a valid UUID'),
body('availabilities.*.preferenceLevel')
.isInt({ min: 0, max: 2 })
.withMessage('Preference level must be 0 (unavailable), 1 (available), or 2 (preferred)'),
body('availabilities.*.notes')
.optional()
.isLength({ max: 500 })
.withMessage('Notes cannot exceed 500 characters')
.trim()
.escape()
];
// ===== COMMON VALIDATORS =====
export const validateId = [
param('id')
.isUUID()
.withMessage('Must be a valid UUID')
];
export const validateEmployeeId = [
param('employeeId')
.isUUID()
.withMessage('Must be a valid UUID')
];
export const validatePlanId = [
param('planId')
.isUUID()
.withMessage('Must be a valid UUID')
];
export const validatePagination = [
query('page')
.optional()
.isInt({ min: 1 })
.withMessage('Page must be a positive integer'),
query('limit')
.optional()
.isInt({ min: 1, max: 100 })
.withMessage('Limit must be between 1-100'),
query('includeInactive')
.optional()
.isBoolean()
.withMessage('includeInactive must be a boolean')
];
// ===== MIDDLEWARE TO CHECK VALIDATION RESULTS =====
export const handleValidationErrors = (req: Request, res: Response, next: NextFunction) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
const errorMessages = errors.array().map(error => ({
field: error.type === 'field' ? error.path : error.type,
message: error.msg,
value: error.msg
}));
return res.status(400).json({
error: 'Validation failed',
details: errorMessages
});
}
next();
};

View File

@@ -102,7 +102,6 @@ export const AVAILABILITY_PREFERENCES = {
} as const;
// Default availability for new employees (all shifts unavailable as level 3)
// UPDATED: Now uses shiftId instead of timeSlotId + dayOfWeek
export function createDefaultAvailabilities(employeeId: string, planId: string, shiftIds: string[]): Omit<EmployeeAvailability, 'id'>[] {
const availabilities: Omit<EmployeeAvailability, 'id'>[] = [];
@@ -120,7 +119,6 @@ export function createDefaultAvailabilities(employeeId: string, planId: string,
}
// Create complete manager availability for all days (default: only Mon-Tue available)
// NOTE: This function might need revision based on new schema requirements
export function createManagerDefaultSchedule(managerId: string, planId: string, timeSlotIds: string[]): Omit<ManagerAvailability, 'id'>[] {
const assignments: Omit<ManagerAvailability, 'id'>[] = [];

View File

@@ -18,12 +18,12 @@ function generateEmail(firstname: string, lastname: string): string {
return `${cleanFirstname}.${cleanLastname}@sp.de`;
}
// UPDATED: Validation for new employee model with employee types
// Validation for new employee model with employee types
export function validateEmployeeData(employee: CreateEmployeeRequest): string[] {
const errors: string[] = [];
if (employee.password?.length < 6) {
errors.push('Password must be at least 6 characters long');
if (employee.password?.length < 8) {
errors.push('Password must be at least 8 characters long');
}
if (!employee.firstname?.trim() || employee.firstname.trim().length < 2) {
@@ -71,7 +71,7 @@ export function generateEmployeeEmail(firstname: string, lastname: string): stri
return generateEmail(firstname, lastname);
}
// UPDATED: Business logic helpers for new employee types
// Business logic helpers for new employee types
export const isManager = (employee: Employee): boolean =>
employee.employeeType === 'manager';
@@ -90,7 +90,7 @@ export const isInternal = (employee: Employee): boolean =>
export const isExternal = (employee: Employee): boolean =>
employee.employeeType === 'guest';
// UPDATED: Trainee logic - now based on isTrainee field for personell type
// Trainee logic - now based on isTrainee field for personell type
export const isTrainee = (employee: Employee): boolean =>
employee.employeeType === 'personell' && employee.isTrainee;
@@ -107,7 +107,7 @@ export const isMaintenance = (employee: Employee): boolean =>
export const isUser = (employee: Employee): boolean =>
employee.roles?.includes('user') || false;
// UPDATED: Work alone permission - managers and experienced personell can work alone
// Work alone permission - managers and experienced personell can work alone
export const canEmployeeWorkAlone = (employee: Employee): boolean =>
employee.canWorkAlone && (isManager(employee) || isExperienced(employee));
@@ -134,7 +134,7 @@ export function validateAvailabilityData(availability: Omit<EmployeeAvailability
return errors;
}
// UPDATED: Helper to get employee type category
// Helper to get employee type category
export const getEmployeeCategory = (employee: Employee): 'internal' | 'external' => {
return isInternal(employee) ? 'internal' : 'external';
};

View File

@@ -78,7 +78,7 @@ export function calculateTotalRequiredEmployees(plan: ShiftPlan): number {
return plan.shifts.reduce((total, shift) => total + shift.requiredEmployees, 0);
}
// UPDATED: Get scheduled shift by date and time slot
// Get scheduled shift by date and time slot
export function getScheduledShiftByDateAndTime(
plan: ShiftPlan,
date: string,

View File

@@ -2,7 +2,7 @@
import { Employee } from './Employee.js';
import { ShiftPlan } from './ShiftPlan.js';
// Updated Availability interface to match new schema
// Availability interface
export interface Availability {
id: string;
employeeId: string;

View File

@@ -1,32 +0,0 @@
{
"timestamp": "2025-10-21T11:16:11.693081",
"success": true,
"metadata": {
"solveTime": 0.0218085,
"constraintsAdded": 217,
"variablesCreated": 90,
"optimal": true
},
"progress": [
{
"timestamp": 0.00886988639831543,
"objective": 1050.0,
"bound": 2100.0,
"solution_count": 1
},
{
"timestamp": 0.009304285049438477,
"objective": 1300.0,
"bound": 1300.0,
"solution_count": 2
}
],
"solution_summary": {
"assignments_count": 15,
"violations_count": 0,
"variables_count": 90,
"constraints_count": 217,
"solve_time": 0.0218085,
"optimal": true
}
}

View File

@@ -1,38 +0,0 @@
{
"timestamp": "2025-10-21T11:16:16.813066",
"success": true,
"metadata": {
"solveTime": 0.0158702,
"constraintsAdded": 217,
"variablesCreated": 90,
"optimal": true
},
"progress": [
{
"timestamp": 0.008541107177734375,
"objective": 1050.0,
"bound": 2000.0,
"solution_count": 1
},
{
"timestamp": 0.00941777229309082,
"objective": 1250.0,
"bound": 1300.0,
"solution_count": 2
},
{
"timestamp": 0.009499549865722656,
"objective": 1300.0,
"bound": 1300.0,
"solution_count": 3
}
],
"solution_summary": {
"assignments_count": 15,
"violations_count": 0,
"variables_count": 90,
"constraints_count": 217,
"solve_time": 0.0158702,
"optimal": true
}
}

View File

@@ -1,38 +0,0 @@
{
"timestamp": "2025-10-21T14:34:06.393151",
"success": true,
"metadata": {
"solveTime": 0.046477700000000004,
"constraintsAdded": 217,
"variablesCreated": 90,
"optimal": true
},
"progress": [
{
"timestamp": 0.04335761070251465,
"objective": 1050.0,
"bound": 2100.0,
"solution_count": 1
},
{
"timestamp": 0.04459857940673828,
"objective": 1250.0,
"bound": 1700.0,
"solution_count": 2
},
{
"timestamp": 0.04603719711303711,
"objective": 1300.0,
"bound": 1300.0,
"solution_count": 3
}
],
"solution_summary": {
"assignments_count": 15,
"violations_count": 0,
"variables_count": 90,
"constraints_count": 217,
"solve_time": 0.046477700000000004,
"optimal": true
}
}

View File

@@ -1,44 +0,0 @@
{
"timestamp": "2025-10-21T14:37:10.936471",
"success": true,
"metadata": {
"solveTime": 0.022602300000000002,
"constraintsAdded": 217,
"variablesCreated": 90,
"optimal": true
},
"progress": [
{
"timestamp": 0.008664369583129883,
"objective": 1050.0,
"bound": 1300.0,
"solution_count": 1
},
{
"timestamp": 0.008890628814697266,
"objective": 1150.0,
"bound": 1300.0,
"solution_count": 2
},
{
"timestamp": 0.009119987487792969,
"objective": 1250.0,
"bound": 1300.0,
"solution_count": 3
},
{
"timestamp": 0.009514808654785156,
"objective": 1300.0,
"bound": 1300.0,
"solution_count": 4
}
],
"solution_summary": {
"assignments_count": 15,
"violations_count": 0,
"variables_count": 90,
"constraints_count": 217,
"solve_time": 0.022602300000000002,
"optimal": true
}
}

View File

@@ -1,38 +0,0 @@
{
"timestamp": "2025-10-21T14:38:04.517181",
"success": true,
"metadata": {
"solveTime": 0.017061200000000002,
"constraintsAdded": 217,
"variablesCreated": 90,
"optimal": true
},
"progress": [
{
"timestamp": 0.008075952529907227,
"objective": 1000.0,
"bound": 1300.0,
"solution_count": 1
},
{
"timestamp": 0.008380889892578125,
"objective": 1200.0,
"bound": 1300.0,
"solution_count": 2
},
{
"timestamp": 0.008938789367675781,
"objective": 1300.0,
"bound": 1300.0,
"solution_count": 3
}
],
"solution_summary": {
"assignments_count": 15,
"violations_count": 0,
"variables_count": 90,
"constraints_count": 217,
"solve_time": 0.017061200000000002,
"optimal": true
}
}

View File

@@ -1,19 +0,0 @@
{
"timestamp": "2025-10-21T14:40:00.354343",
"success": false,
"metadata": {
"solveTime": 0.0013928,
"constraintsAdded": 248,
"variablesCreated": 99,
"optimal": false
},
"progress": [],
"solution_summary": {
"assignments_count": 0,
"violations_count": 0,
"variables_count": 99,
"constraints_count": 248,
"solve_time": 0.0013928,
"optimal": false
}
}

View File

@@ -1,19 +0,0 @@
{
"timestamp": "2025-10-21T14:43:01.616117",
"success": false,
"metadata": {
"solveTime": 0.0009529,
"constraintsAdded": 230,
"variablesCreated": 99,
"optimal": false
},
"progress": [],
"solution_summary": {
"assignments_count": 0,
"violations_count": 0,
"variables_count": 99,
"constraints_count": 230,
"solve_time": 0.0009529,
"optimal": false
}
}

View File

@@ -1,19 +0,0 @@
{
"timestamp": "2025-10-21T14:43:40.972769",
"success": false,
"metadata": {
"solveTime": 0.0009025000000000001,
"constraintsAdded": 230,
"variablesCreated": 99,
"optimal": false
},
"progress": [],
"solution_summary": {
"assignments_count": 0,
"violations_count": 0,
"variables_count": 99,
"constraints_count": 230,
"solve_time": 0.0009025000000000001,
"optimal": false
}
}

View File

@@ -1,19 +0,0 @@
{
"timestamp": "2025-10-21T15:15:30.967943",
"success": false,
"metadata": {
"solveTime": 0.0009660000000000001,
"constraintsAdded": 230,
"variablesCreated": 99,
"optimal": false
},
"progress": [],
"solution_summary": {
"assignments_count": 0,
"violations_count": 0,
"variables_count": 99,
"constraints_count": 230,
"solve_time": 0.0009660000000000001,
"optimal": false
}
}

View File

@@ -1,19 +0,0 @@
{
"timestamp": "2025-10-21T15:15:39.908329",
"success": false,
"metadata": {
"solveTime": 0.0009183,
"constraintsAdded": 230,
"variablesCreated": 99,
"optimal": false
},
"progress": [],
"solution_summary": {
"assignments_count": 0,
"violations_count": 0,
"variables_count": 99,
"constraints_count": 230,
"solve_time": 0.0009183,
"optimal": false
}
}

View File

@@ -1,56 +0,0 @@
{
"timestamp": "2025-10-21T15:17:28.688727",
"success": true,
"metadata": {
"solveTime": 0.0175048,
"constraintsAdded": 230,
"variablesCreated": 99,
"optimal": true
},
"progress": [
{
"timestamp": 0.0076940059661865234,
"objective": 1150.0,
"bound": 2650.0,
"solution_count": 1
},
{
"timestamp": 0.008573293685913086,
"objective": 1200.0,
"bound": 1400.0,
"solution_count": 2
},
{
"timestamp": 0.00871133804321289,
"objective": 1250.0,
"bound": 1400.0,
"solution_count": 3
},
{
"timestamp": 0.008805990219116211,
"objective": 1300.0,
"bound": 1400.0,
"solution_count": 4
},
{
"timestamp": 0.00890493392944336,
"objective": 1350.0,
"bound": 1400.0,
"solution_count": 5
},
{
"timestamp": 0.009298324584960938,
"objective": 1400.0,
"bound": 1400.0,
"solution_count": 6
}
],
"solution_summary": {
"assignments_count": 16,
"violations_count": 0,
"variables_count": 99,
"constraints_count": 230,
"solve_time": 0.0175048,
"optimal": true
}
}

View File

@@ -1,56 +0,0 @@
{
"timestamp": "2025-10-21T15:19:19.785803",
"success": true,
"metadata": {
"solveTime": 0.014216000000000001,
"constraintsAdded": 228,
"variablesCreated": 99,
"optimal": true
},
"progress": [
{
"timestamp": 0.008774042129516602,
"objective": 1200.0,
"bound": 2850.0,
"solution_count": 1
},
{
"timestamp": 0.009451627731323242,
"objective": 1250.0,
"bound": 1450.0,
"solution_count": 2
},
{
"timestamp": 0.009568452835083008,
"objective": 1300.0,
"bound": 1450.0,
"solution_count": 3
},
{
"timestamp": 0.009636402130126953,
"objective": 1350.0,
"bound": 1450.0,
"solution_count": 4
},
{
"timestamp": 0.009870052337646484,
"objective": 1400.0,
"bound": 1450.0,
"solution_count": 5
},
{
"timestamp": 0.009946584701538086,
"objective": 1450.0,
"bound": 1450.0,
"solution_count": 6
}
],
"solution_summary": {
"assignments_count": 17,
"violations_count": 0,
"variables_count": 99,
"constraints_count": 228,
"solve_time": 0.014216000000000001,
"optimal": true
}
}

View File

@@ -1,32 +0,0 @@
{
"timestamp": "2025-10-21T16:58:13.438358",
"success": true,
"metadata": {
"solveTime": 0.012495000000000001,
"constraintsAdded": 218,
"variablesCreated": 90,
"optimal": true
},
"progress": [
{
"timestamp": 0.008534908294677734,
"objective": 1050.0,
"bound": 2100.0,
"solution_count": 1
},
{
"timestamp": 0.009073495864868164,
"objective": 1300.0,
"bound": 1300.0,
"solution_count": 2
}
],
"solution_summary": {
"assignments_count": 15,
"violations_count": 0,
"variables_count": 90,
"constraints_count": 218,
"solve_time": 0.012495000000000001,
"optimal": true
}
}

View File

@@ -1,32 +0,0 @@
{
"timestamp": "2025-10-21T16:58:37.184763",
"success": true,
"metadata": {
"solveTime": 0.0245485,
"constraintsAdded": 218,
"variablesCreated": 90,
"optimal": true
},
"progress": [
{
"timestamp": 0.009514808654785156,
"objective": 1050.0,
"bound": 2100.0,
"solution_count": 1
},
{
"timestamp": 0.010115385055541992,
"objective": 1300.0,
"bound": 1300.0,
"solution_count": 2
}
],
"solution_summary": {
"assignments_count": 15,
"violations_count": 0,
"variables_count": 90,
"constraints_count": 218,
"solve_time": 0.0245485,
"optimal": true
}
}

View File

@@ -1,32 +0,0 @@
{
"timestamp": "2025-10-21T10:54:26.093544",
"success": false,
"metadata": {
"solveTime": 0,
"constraintsAdded": 0,
"variablesCreated": 0,
"optimal": false
},
"progress": [],
"solution_summary": {
"assignments_count": 0,
"violations_count": 1,
"variables_count": 0,
"constraints_count": 0,
"solve_time": 0,
"optimal": false
},
"full_result": {
"assignments": [],
"violations": [
"Error: 'SolutionCallback' object has no attribute 'HasObjective'"
],
"success": false,
"metadata": {
"solveTime": 0,
"constraintsAdded": 0,
"variablesCreated": 0,
"optimal": false
}
}
}

View File

@@ -1,19 +0,0 @@
{
"timestamp": "2025-10-21T10:59:36.646855",
"success": false,
"metadata": {
"solveTime": 0,
"constraintsAdded": 0,
"variablesCreated": 0,
"optimal": false
},
"progress": [],
"solution_summary": {
"assignments_count": 0,
"violations_count": 1,
"variables_count": 0,
"constraints_count": 0,
"solve_time": 0,
"optimal": false
}
}

View File

@@ -1,38 +0,0 @@
{
"timestamp": "2025-10-21T11:03:36.697986",
"success": true,
"metadata": {
"solveTime": 0.025875500000000003,
"constraintsAdded": 217,
"variablesCreated": 90,
"optimal": true
},
"progress": [
{
"timestamp": 0.008769989013671875,
"objective": 1050.0,
"bound": 2000.0,
"solution_count": 1
},
{
"timestamp": 0.009685516357421875,
"objective": 1250.0,
"bound": 1700.0,
"solution_count": 2
},
{
"timestamp": 0.010709047317504883,
"objective": 1300.0,
"bound": 1300.0,
"solution_count": 3
}
],
"solution_summary": {
"assignments_count": 15,
"violations_count": 0,
"variables_count": 90,
"constraints_count": 217,
"solve_time": 0.025875500000000003,
"optimal": true
}
}

View File

@@ -8,12 +8,13 @@ import {
validateToken
} from '../controllers/authController.js';
import { authMiddleware } from '../middleware/auth.js';
import { validateLogin, validateRegister, handleValidationErrors } from '../middleware/validation.js';
const router = express.Router();
// Public routes
router.post('/login', login);
router.post('/register', register);
router.post('/login', validateLogin, handleValidationErrors, login);
router.post('/register', validateRegister, handleValidationErrors, register);
router.get('/validate', validateToken);
// Protected routes (require authentication)

View File

@@ -1,4 +1,3 @@
// backend/src/routes/employees.ts
import express from 'express';
import { authMiddleware, requireRole } from '../middleware/auth.js';
import {
@@ -12,6 +11,16 @@ import {
changePassword,
updateLastLogin
} from '../controllers/employeeController.js';
import {
handleValidationErrors,
validateEmployee,
validateEmployeeUpdate,
validateChangePassword,
validateId,
validateEmployeeId,
validateAvailabilities,
validatePagination
} from '../middleware/validation.js';
const router = express.Router();
@@ -19,16 +28,18 @@ const router = express.Router();
router.use(authMiddleware);
// Employee CRUD Routes
router.get('/', authMiddleware, getEmployees);
router.get('/:id', requireRole(['admin', 'instandhalter']), getEmployee);
router.post('/', requireRole(['admin']), createEmployee);
router.put('/:id', requireRole(['admin']), updateEmployee);
router.delete('/:id', requireRole(['admin']), deleteEmployee);
router.put('/:id/password', authMiddleware, changePassword);
router.put('/:id/last-login', authMiddleware, updateLastLogin);
router.get('/', validatePagination, handleValidationErrors, authMiddleware, getEmployees);
router.get('/:id', validateId, handleValidationErrors, requireRole(['admin', 'maintenance']), getEmployee);
router.post('/', validateEmployee, handleValidationErrors, requireRole(['admin']), createEmployee);
router.put('/:id', validateId, validateEmployeeUpdate, handleValidationErrors, requireRole(['admin', 'maintenance']), updateEmployee);
router.delete('/:id', validateId, handleValidationErrors, requireRole(['admin']), deleteEmployee);
// Password & Login Routes
router.put('/:id/password', validateId, validateChangePassword, handleValidationErrors, authMiddleware, changePassword);
router.put('/:id/last-login', validateId, handleValidationErrors, authMiddleware, updateLastLogin);
// Availability Routes
router.get('/:employeeId/availabilities', authMiddleware, getAvailabilities);
router.put('/:employeeId/availabilities', authMiddleware, updateAvailabilities);
router.get('/:employeeId/availabilities', validateEmployeeId, handleValidationErrors, authMiddleware, getAvailabilities);
router.put('/:employeeId/availabilities', validateEmployeeId, validateAvailabilities, handleValidationErrors, authMiddleware, updateAvailabilities);
export default router;

View File

@@ -1,4 +1,3 @@
// backend/src/routes/scheduledShifts.ts
import express from 'express';
import { authMiddleware, requireRole } from '../middleware/auth.js';
import {
@@ -8,23 +7,21 @@ import {
getScheduledShiftsFromPlan,
updateScheduledShift
} from '../controllers/shiftPlanController.js';
import {
validateId,
validatePlanId,
validateScheduledShiftUpdate,
handleValidationErrors
} from '../middleware/validation.js';
const router = express.Router();
router.use(authMiddleware);
router.post('/:id/generate-shifts', requireRole(['admin', 'instandhalter']), generateScheduledShiftsForPlan);
router.post('/:id/regenerate-shifts', requireRole(['admin', 'instandhalter']), regenerateScheduledShifts);
// GET all scheduled shifts for a plan
router.get('/plan/:planId', authMiddleware, getScheduledShiftsFromPlan);
// GET specific scheduled shift
router.get('/:id', authMiddleware, getScheduledShift);
// UPDATE scheduled shift
router.put('/:id', authMiddleware, updateScheduledShift);
router.post('/:id/generate-shifts', validateId, handleValidationErrors, requireRole(['admin', 'maintenance']), generateScheduledShiftsForPlan);
router.post('/:id/regenerate-shifts', validateId, handleValidationErrors, requireRole(['admin', 'maintenance']), regenerateScheduledShifts);
router.get('/plan/:planId', validatePlanId, handleValidationErrors, getScheduledShiftsFromPlan);
router.get('/:id', validateId, handleValidationErrors, getScheduledShift);
router.put('/:id', validateId, validateScheduledShiftUpdate, handleValidationErrors, updateScheduledShift);
export default router;

View File

@@ -1,9 +1,10 @@
import express from 'express';
import { SchedulingService } from '../services/SchedulingService.js';
import { validateSchedulingRequest, handleValidationErrors } from '../middleware/validation.js';
const router = express.Router();
router.post('/generate-schedule', async (req, res) => {
router.post('/generate-schedule', validateSchedulingRequest, handleValidationErrors, async (req: express.Request, res: express.Response) => {
try {
const { shiftPlan, employees, availabilities, constraints } = req.body;
@@ -14,18 +15,6 @@ router.post('/generate-schedule', async (req, res) => {
constraintCount: constraints?.length
});
// Validate required data
if (!shiftPlan || !employees || !availabilities) {
return res.status(400).json({
error: 'Missing required data',
details: {
shiftPlan: !!shiftPlan,
employees: !!employees,
availabilities: !!availabilities
}
});
}
const scheduler = new SchedulingService();
const result = await scheduler.generateOptimalSchedule({
shiftPlan,

View File

@@ -1,11 +1,10 @@
// backend/src/routes/setup.ts
import express from 'express';
import bcrypt from 'bcryptjs';
import { checkSetupStatus, setupAdmin } from '../controllers/setupController.js';
import { validateSetupAdmin, handleValidationErrors } from '../middleware/validation.js';
const router = express.Router();
router.get('/status', checkSetupStatus);
router.post('/admin', setupAdmin);
router.post('/admin', validateSetupAdmin, handleValidationErrors, setupAdmin);
export default router;

View File

@@ -1,4 +1,3 @@
// backend/src/routes/shiftPlans.ts
import express from 'express';
import { authMiddleware, requireRole } from '../middleware/auth.js';
import {
@@ -10,32 +9,25 @@ import {
createFromPreset,
clearAssignments
} from '../controllers/shiftPlanController.js';
import {
validateShiftPlan,
validateShiftPlanUpdate,
validateCreateFromPreset,
handleValidationErrors,
validateId
} from '../middleware/validation.js';
const router = express.Router();
router.use(authMiddleware);
// Combined routes for both shift plans and templates
// GET all shift plans (including templates)
router.get('/' , authMiddleware, getShiftPlans);
// GET specific shift plan or template
router.get('/:id', authMiddleware, getShiftPlan);
// POST create new shift plan
router.post('/', requireRole(['admin', 'instandhalter']), createShiftPlan);
// POST create new plan from preset
router.post('/from-preset', requireRole(['admin', 'instandhalter']), createFromPreset);
// PUT update shift plan or template
router.put('/:id', requireRole(['admin', 'instandhalter']), updateShiftPlan);
// DELETE shift plan or template
router.delete('/:id', requireRole(['admin', 'instandhalter']), deleteShiftPlan);
// POST clear assignments and reset to draft
router.post('/:id/clear-assignments', requireRole(['admin', 'instandhalter']), clearAssignments);
router.get('/', getShiftPlans);
router.get('/:id', validateId, handleValidationErrors, getShiftPlan);
router.post('/', validateShiftPlan, handleValidationErrors, requireRole(['admin', 'maintenance']), createShiftPlan);
router.post('/from-preset', validateCreateFromPreset, handleValidationErrors, requireRole(['admin', 'maintenance']), createFromPreset);
router.put('/:id', validateId, validateShiftPlanUpdate, handleValidationErrors, requireRole(['admin', 'maintenance']), updateShiftPlan);
router.delete('/:id', validateId, handleValidationErrors, requireRole(['admin', 'maintenance']), deleteShiftPlan);
router.post('/:id/clear-assignments', validateId, handleValidationErrors, requireRole(['admin', 'maintenance']), clearAssignments);
export default router;

View File

@@ -53,7 +53,7 @@ async function markMigrationAsApplied(migrationName: string) {
);
}
// UPDATED: Function to handle schema changes for the new employee type system
// Function to handle schema changes for the new employee type system
async function applySchemaUpdates() {
console.log('🔄 Applying schema updates for new employee type system...');
@@ -80,7 +80,7 @@ async function applySchemaUpdates() {
PRAGMA table_info(employees)
`);
// FIXED: Check for employee_type column (not roles column)
// Check for employee_type column (not roles column)
const hasEmployeeType = employeesTableInfo.some((col: TableColumnInfo) => col.name === 'employee_type');
const hasIsTrainee = employeesTableInfo.some((col: TableColumnInfo) => col.name === 'is_trainee');

View File

@@ -8,7 +8,30 @@ const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
export async function initializeDatabase(): Promise<void> {
const schemaPath = path.join(__dirname, '../database/schema.sql');
const possiblePaths = [
path.join(__dirname, '../database/schema.sql'),
path.join(__dirname, '../../database/schema.sql'),
path.join(process.cwd(), 'database/schema.sql'),
path.join(process.cwd(), 'src/database/schema.sql'),
path.join(process.cwd(), 'dist/database/schema.sql')
];
let schemaPath: string | null = null;
for (const p of possiblePaths) {
if (fs.existsSync(p)) {
schemaPath = p;
break;
}
}
if (!schemaPath) {
throw new Error(
`❌ schema.sql not found in any of the tested paths:\n${possiblePaths.join('\n')}`
);
}
console.log(`✅ Using schema at: ${schemaPath}`);
const schema = fs.readFileSync(schemaPath, 'utf8');
try {
@@ -42,7 +65,7 @@ export async function initializeDatabase(): Promise<void> {
console.log('Existing tables found:', existingTables.map(t => t.name).join(', ') || 'none');
// UPDATED: Drop tables in correct dependency order for new schema
// Drop tables in correct dependency order for new schema
const tablesToDrop = [
'employee_availability',
'shift_assignments',
@@ -72,16 +95,40 @@ export async function initializeDatabase(): Promise<void> {
// Continue with schema creation even if table dropping fails
}
// Execute schema creation in a transaction
await db.run('BEGIN EXCLUSIVE TRANSACTION');
// Execute each statement separately for better error reporting
const statements = schema
// NEU: PRAGMA-Anweisungen außerhalb der Transaktion ausführen
console.log('Executing PRAGMA statements outside transaction...');
const pragmaStatements = schema
.split(';')
.map(stmt => stmt.trim())
.filter(stmt => stmt.length > 0)
.filter(stmt => stmt.toUpperCase().startsWith('PRAGMA'))
.map(stmt => {
return stmt.split('\n')
.filter(line => !line.trim().startsWith('--'))
.join('\n')
.trim();
});
for (const statement of pragmaStatements) {
try {
console.log('Executing PRAGMA:', statement);
await db.run(statement);
} catch (error) {
console.warn('PRAGMA statement might have failed:', statement, error);
// Continue even if PRAGMA fails
}
}
// Schema-Erstellung in Transaktion
await db.run('BEGIN EXCLUSIVE TRANSACTION');
// Nur die CREATE TABLE und andere Anweisungen (ohne PRAGMA)
const schemaStatements = schema
.split(';')
.map(stmt => stmt.trim())
.filter(stmt => stmt.length > 0)
.filter(stmt => !stmt.toUpperCase().startsWith('PRAGMA'))
.map(stmt => {
// Remove any single-line comments
return stmt.split('\n')
.filter(line => !line.trim().startsWith('--'))
.join('\n')
@@ -89,7 +136,7 @@ export async function initializeDatabase(): Promise<void> {
})
.filter(stmt => stmt.length > 0);
for (const statement of statements) {
for (const statement of schemaStatements) {
try {
console.log('Executing statement:', statement.substring(0, 50) + '...');
await db.run(statement);
@@ -101,7 +148,7 @@ export async function initializeDatabase(): Promise<void> {
}
}
// UPDATED: Insert default data in correct order
// Insert default data in correct order
try {
console.log('Inserting default employee types...');
await db.run(`INSERT OR IGNORE INTO employee_types (type, category, has_contract_type) VALUES ('manager', 'internal', 1)`);

View File

@@ -0,0 +1,26 @@
import { spawn } from 'child_process';
export function runPythonScript(scriptPath, args = []) {
return new Promise((resolve, reject) => {
const pythonProcess = spawn('python', [scriptPath, ...args]);
let stdout = '';
let stderr = '';
pythonProcess.stdout.on('data', (data) => {
stdout += data.toString();
});
pythonProcess.stderr.on('data', (data) => {
stderr += data.toString();
});
pythonProcess.on('close', (code) => {
if (code === 0) {
resolve(stdout);
} else {
reject(new Error(`Python script exited with code ${code}: ${stderr}`));
}
});
});
}

View File

@@ -1,7 +1,11 @@
// backend/src/server.ts
import express from 'express';
import cors from 'cors';
import path from 'path';
import { fileURLToPath } from 'url';
import { initializeDatabase } from './scripts/initializeDatabase.js';
import fs from 'fs';
import helmet from 'helmet';
import type { ViteDevServer } from 'vite';
// Route imports
import authRoutes from './routes/auth.js';
@@ -10,87 +14,302 @@ import shiftPlanRoutes from './routes/shiftPlans.js';
import setupRoutes from './routes/setup.js';
import scheduledShifts from './routes/scheduledShifts.js';
import schedulingRoutes from './routes/scheduling.js';
import {
apiLimiter,
authLimiter,
expensiveEndpointLimiter
} from './middleware/rateLimit.js';
import { ipSecurityCheck as authIpCheck } from './middleware/auth.js';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const app = express();
const PORT = 3002;
const isDevelopment = process.env.NODE_ENV === 'development';
// CORS und Middleware
app.use(cors());
app.use(authIpCheck);
let vite: ViteDevServer | undefined;
if (isDevelopment) {
// Dynamically import and setup Vite middleware
const setupViteDevServer = async () => {
try {
const { createServer } = await import('vite');
vite = await createServer({
server: { middlewareMode: true },
appType: 'spa'
});
app.use(vite.middlewares);
console.log('🔧 Vite dev server integrated with Express');
} catch (error) {
console.warn('⚠️ Vite integration failed, using static files:', error);
}
};
setupViteDevServer();
}
const configureStaticFiles = () => {
const staticConfig = {
maxAge: '1y',
etag: false,
immutable: true,
index: false
};
// Serve frontend build
const frontendPath = '/app/frontend-build';
if (fs.existsSync(frontendPath)) {
console.log('✅ Serving frontend from:', frontendPath);
app.use(express.static(frontendPath, staticConfig));
}
// Serve premium assets if available
const premiumPath = '/app/premium-dist';
if (fs.existsSync(premiumPath)) {
console.log('✅ Serving premium assets from:', premiumPath);
app.use('/premium-assets', express.static(premiumPath, staticConfig));
}
};
// Security configuration
if (process.env.NODE_ENV === 'production') {
console.info('Checking for JWT_SECRET');
const JWT_SECRET = process.env.JWT_SECRET;
if (!JWT_SECRET || JWT_SECRET === 'your-secret-key-please-change') {
console.error('❌ Fatal: JWT_SECRET not set or using default value');
process.exit(1);
}
}
const configureTrustProxy = (): string | string[] | boolean | number => {
const trustedProxyIps = process.env.TRUSTED_PROXY_IPS;
const trustProxyEnabled = process.env.TRUST_PROXY_ENABLED !== 'false';
// If explicitly disabled
if (!trustProxyEnabled) {
console.log('🔒 Trust proxy: Disabled');
return false;
}
// If specific IPs are provided via environment variable
if (trustedProxyIps) {
console.log('🔒 Trust proxy: Using configured IPs:', trustedProxyIps);
// Handle comma-separated list of IPs/CIDR ranges
if (trustedProxyIps.includes(',')) {
return trustedProxyIps.split(',').map(ip => ip.trim());
}
// Handle single IP/CIDR
return trustedProxyIps.trim();
}
// Default behavior for reverse proxy setup
console.log('🔒 Trust proxy: Using reverse proxy defaults (trust all)');
return true; // Trust all proxies when behind nginx
};
app.set('trust proxy', configureTrustProxy());
// Security headers
app.use(helmet({
contentSecurityPolicy: {
directives: {
defaultSrc: ["'self'"],
scriptSrc: ["'self'", "'unsafe-inline'"],
styleSrc: ["'self'", "'unsafe-inline'"],
imgSrc: ["'self'", "data:", "https:"],
connectSrc: ["'self'"],
fontSrc: ["'self'"],
objectSrc: ["'none'"],
mediaSrc: ["'self'"],
frameSrc: ["'none'"],
},
},
hsts: {
maxAge: 31536000,
includeSubDomains: true,
preload: true
}, // Enable HSTS for HTTPS
crossOriginEmbedderPolicy: false
}));
// Additional security headers
app.use((req, res, next) => {
res.setHeader('X-Content-Type-Options', 'nosniff');
res.setHeader('X-Frame-Options', 'DENY');
res.setHeader('X-XSS-Protection', '1; mode=block');
next();
});
// Middleware
app.use(express.json());
// Rate limiting - weniger restriktiv in Development
if (process.env.NODE_ENV === 'production') {
console.log('🔒 Applying production rate limiting');
app.use('/api/', apiLimiter);
} else {
console.log('🔧 Development: Relaxed rate limiting applied');
// In development, you might want to be more permissive
app.use('/api/', apiLimiter);
}
// API Routes
app.use('/api/setup', setupRoutes);
app.use('/api/auth', authRoutes);
app.use('/api/auth', authLimiter, authRoutes);
app.use('/api/employees', employeeRoutes);
app.use('/api/shift-plans', shiftPlanRoutes);
app.use('/api/scheduled-shifts', scheduledShifts);
app.use('/api/scheduling', schedulingRoutes);
// Error handling middleware should come after routes
app.use((err: any, req: express.Request, res: express.Response, next: express.NextFunction) => {
console.error('Unhandled error:', err);
res.status(500).json({ error: 'Internal server error' });
});
// 404 handler for API routes
app.use('/api/*', (req, res) => {
res.status(404).json({ error: 'API endpoint not found' });
});
app.use('/api/scheduling', expensiveEndpointLimiter, schedulingRoutes);
// Health route
app.get('/api/health', (req: any, res: any) => {
app.get('/api/health', (req: express.Request, res: express.Response) => {
res.json({
status: 'OK',
message: 'Backend läuft!',
timestamp: new Date().toISOString()
timestamp: new Date().toISOString(),
mode: process.env.NODE_ENV || 'development'
});
});
// Setup status route (additional endpoint for clarity)
app.get('/api/initial-setup', async (req: any, res: any) => {
// 🆕 IMPROVED STATIC FILE SERVING
const findFrontendBuildPath = (): string | null => {
const possiblePaths = [
// Production path (Docker)
'/app/frontend-build',
// Development paths
path.resolve(__dirname, '../../frontend/dist'),
path.resolve(__dirname, '../../frontend-build'),
path.resolve(process.cwd(), '../frontend/dist'),
path.resolve(process.cwd(), 'frontend-build'),
];
for (const testPath of possiblePaths) {
try {
const { db } = await import('./services/databaseService.js');
const adminExists = await db.get<{ 'COUNT(*)': number }>(
'SELECT COUNT(*) FROM employees WHERE role = ?',
['admin']
);
res.json({
needsInitialSetup: !adminExists || adminExists['COUNT(*)'] === 0
});
} catch (error) {
console.error('Error checking initial setup:', error);
res.status(500).json({ error: 'Internal server error' });
if (fs.existsSync(testPath)) {
const indexPath = path.join(testPath, 'index.html');
if (fs.existsSync(indexPath)) {
console.log('✅ Found frontend build at:', testPath);
return testPath;
}
}
} catch (error) {
// Silent catch - just try next path
}
}
return null;
};
const frontendBuildPath = findFrontendBuildPath();
configureStaticFiles();
if (frontendBuildPath) {
app.use(express.static(frontendBuildPath));
console.log('✅ Static file serving configured');
} else {
console.log(isDevelopment ?
'🔧 Development: Frontend served by Vite dev server (localhost:3003)' :
'❌ Production: No frontend build found'
);
}
// Root route
app.get('/', async (req, res) => {
// In development with Vite middleware
if (vite) {
try {
const template = fs.readFileSync(
path.resolve(__dirname, '../../frontend/index.html'),
'utf-8'
);
const html = await vite.transformIndexHtml(req.url, template);
res.send(html);
} catch (error) {
res.status(500).send('Vite dev server error');
}
return;
}
// Fallback to static file serving
if (!frontendBuildPath) {
return res.status(500).send('Frontend not available');
}
const indexPath = path.join(frontendBuildPath, 'index.html');
res.sendFile(indexPath);
});
// Client-side routing fallback
app.get('*', (req, res, next) => {
// Skip API routes
if (req.path.startsWith('/api/')) {
return next();
}
// Skip file extensions (assets)
if (req.path.match(/\.[a-z0-9]+$/i)) {
return next();
}
// Serve React app for all other routes
const frontendPath = '/app/frontend-build';
const indexPath = path.join(frontendPath, 'index.html');
if (fs.existsSync(indexPath)) {
res.sendFile(indexPath);
} else {
res.status(404).send('Frontend not available');
}
});
// Error handling
app.use((err: any, req: express.Request, res: express.Response, next: express.NextFunction) => {
console.error('Error:', err);
if (process.env.NODE_ENV === 'production') {
res.status(500).json({
error: 'Internal server error',
message: 'Something went wrong'
});
} else {
res.status(500).json({
error: 'Internal server error',
message: err.message,
stack: err.stack
});
}
});
// 404 handling
app.use('*', (req, res) => {
res.status(404).json({ error: 'Endpoint not found' });
});
// Initialize the application
const initializeApp = async () => {
try {
// Initialize database with base schema
await initializeDatabase();
//console.log('✅ Database initialized successfully');
// Apply any pending migrations
const { applyMigration } = await import('./scripts/applyMigration.js');
await applyMigration();
//console.log('✅ Database migrations applied');
// Start server only after successful initialization
app.listen(PORT, () => {
console.log('🎉 BACKEND STARTED SUCCESSFULLY!');
console.log('🎉 APPLICATION STARTED SUCCESSFULLY!');
console.log(`📍 Port: ${PORT}`);
console.log(`📍 Health: http://localhost:${PORT}/api/health`);
console.log('');
console.log(`🔧 Setup ready at: http://localhost:${PORT}/api/setup/status`);
console.log('📝 Create your admin account on first launch');
console.log(`📍 Mode: ${process.env.NODE_ENV || 'development'}`);
if (frontendBuildPath) {
console.log(`📍 Frontend: http://localhost:${PORT}`);
} else if (isDevelopment) {
console.log(`📍 Frontend (Vite): http://localhost:3003`);
}
console.log(`📍 API: http://localhost:${PORT}/api`);
});
} catch (error) {
console.error('❌ Error during initialization:', error);
process.exit(1); // Exit if initialization fails
process.exit(1);
}
};
// Start the application
initializeApp();

View File

@@ -2,8 +2,7 @@
import { Worker } from 'worker_threads';
import path from 'path';
import { fileURLToPath } from 'url';
import { Employee, EmployeeAvailability } from '../models/Employee.js';
import { ShiftPlan, ScheduledShift } from '../models/ShiftPlan.js';
import { ShiftPlan } from '../models/ShiftPlan.js';
import { ScheduleRequest, ScheduleResult, Availability, Constraint } from '../models/scheduling.js';
const __filename = fileURLToPath(import.meta.url);

View File

@@ -1,10 +1,19 @@
// backend/src/services/databaseService
import sqlite3 from 'sqlite3';
import path from 'path';
import { fileURLToPath } from 'url';
import fs from 'fs';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const dbPath = path.join(__dirname, '../../database/schichtplan.db');
const dbPath = process.env.DB_PATH || '/app/data/schichtplan.db';
// Stelle sicher, dass das Verzeichnis existiert
const dbDir = path.dirname(dbPath);
if (!fs.existsSync(dbDir)) {
fs.mkdirSync(dbDir, { recursive: true });
}
class Database {
private db: sqlite3.Database;

View File

@@ -2,8 +2,8 @@
import { parentPort, workerData } from 'worker_threads';
import { CPModel, CPSolver } from './cp-sat-wrapper.js';
import { ShiftPlan, Shift } from '../models/ShiftPlan.js';
import { Employee, EmployeeAvailability } from '../models/Employee.js';
import { Availability, Constraint, Violation, SolverOptions, Solution, Assignment } from '../models/scheduling.js';
import { Employee } from '../models/Employee.js';
import { Availability, Constraint } from '../models/scheduling.js';
interface WorkerData {
shiftPlan: ShiftPlan;

View File

@@ -1,19 +1,22 @@
// backend/tsconfig.json
{
"compilerOptions": {
"target": "ES2022",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"allowSyntheticDefaultImports": true,
"esModuleInterop": true,
"allowJs": true,
"outDir": "./dist",
"rootDir": "./src",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"resolveJsonModule": true
"resolveJsonModule": true,
"allowSyntheticDefaultImports": true
},
"include": ["src/**/*"],
"exclude": ["node_modules", "dist"]
"include": [
"src/**/*"
],
"exclude": [
"node_modules",
"dist"
]
}

View File

@@ -1,18 +1,22 @@
version: '3.8'
services:
frontend:
build: ./frontend
ports:
- "80:80"
depends_on:
- backend
backend:
build: ./backend
ports:
- "3001:3001"
schichtplaner:
container_name: schichtplaner
image: ghcr.io/donpat1to/schichtenplaner:v1.0.0
environment:
- DATABASE_URL=file:./dev.db
- JWT_SECRET=your-secret-key
- NODE_ENV=production
- JWT_SECRET=${JWT_SECRET:-your-secret-key-please-change}
ports:
- "3002:3002"
volumes:
- app_data:/app/data
restart: unless-stopped
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost:3002/api/health"]
interval: 30s
timeout: 10s
retries: 3
# Später: Database service hinzufügen
volumes:
app_data:

55
docker-init.sh Normal file
View File

@@ -0,0 +1,55 @@
#!/bin/bash
set -e
echo "🚀 Container Initialisierung gestartet..."
generate_secret() {
length=$1
tr -dc 'A-Za-z0-9!@#$%^&*()_+-=' < /dev/urandom | head -c $length
}
# Create .env if it doesn't exist
if [ ! -f /app/.env ]; then
echo "📝 Erstelle .env Datei..."
if [ -z "$JWT_SECRET" ] || [ "$JWT_SECRET" = "your-secret-key-please-change" ]; then
export JWT_SECRET=$(generate_secret 64)
echo "🔑 Automatisch sicheres JWT Secret generiert"
else
echo "🔑 Verwende vorhandenes JWT Secret aus Umgebungsvariable"
fi
# Create .env with all proxy settings
cat > /app/.env << EOF
NODE_ENV=production
JWT_SECRET=${JWT_SECRET}
TRUST_PROXY_ENABLED=${TRUST_PROXY_ENABLED:-true}
TRUSTED_PROXY_IPS=${TRUSTED_PROXY_IPS:-172.0.0.0/8,10.0.0.0/8,192.168.0.0/16}
HOSTNAME=${HOSTNAME:-localhost}
EOF
echo "✅ .env Datei erstellt"
else
echo " .env Datei existiert bereits"
# Update JWT_SECRET if provided
if [ -n "$JWT_SECRET" ] && [ "$JWT_SECRET" != "your-secret-key-please-change" ]; then
echo "🔑 Aktualisiere JWT Secret in .env Datei"
sed -i "s/^JWT_SECRET=.*/JWT_SECRET=$JWT_SECRET/" /app/.env
fi
fi
# Validate JWT_SECRET
if grep -q "JWT_SECRET=your-secret-key-please-change" /app/.env; then
echo "❌ FEHLER: Standard JWT Secret in .env gefunden!"
echo "❌ Bitte setzen Sie JWT_SECRET Umgebungsvariable"
exit 1
fi
chmod 600 /app/.env
echo "🔧 Proxy Configuration:"
echo " - TRUST_PROXY_ENABLED: ${TRUST_PROXY_ENABLED:-true}"
echo " - TRUSTED_PROXY_IPS: ${TRUSTED_PROXY_IPS:-172.0.0.0/8,10.0.0.0/8,192.168.0.0/16}"
echo "🔧 Starte Anwendung..."
exec "$@"

17
ecosystem.config.cjs Normal file
View File

@@ -0,0 +1,17 @@
// ecosystem.config.cjs
module.exports = {
apps: [{
name: 'schichtplan-app',
script: './dist/server.js',
instances: 1,
env: {
NODE_ENV: 'production',
PORT: 3002,
FRONTEND_BUILD_PATH: './frontend-build'
},
error_file: './logs/err.log',
out_file: './logs/out.log',
log_file: './logs/combined.log',
time: true
}]
};

45
frontend/.gitignore vendored
View File

@@ -1,45 +0,0 @@
# Dependencies
node_modules/
/.pnp
.pnp.js
# Testing
/coverage
# Production
/build
# Misc
.DS_Store
.env.local
.env.development.local
.env.test.local
.env.production.local
.env
# Logs
npm-debug.log*
yarn-debug.log*
yarn-error.log*
# IDEs
.vscode/
.idea/
*.swp
*.swo
# OS generated files
.DS_Store
.DS_Store?
._*
.Spotlight-V100
.Trashes
ehthumbs.db
Thumbs.db
# Environment variables
.env
.env.local
.env.development.local
.env.test.local
.env.production.local

View File

@@ -1,8 +0,0 @@
# backend/Dockerfile
FROM node:18-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production
COPY . .
EXPOSE 3001
CMD ["node", "dist/server.js"]

13
frontend/index.html Normal file
View File

@@ -0,0 +1,13 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Shift Planning App</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>

17666
frontend/package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -2,46 +2,34 @@
"name": "frontend",
"version": "0.1.0",
"private": true,
"type": "module",
"dependencies": {
"@testing-library/dom": "^10.4.1",
"@testing-library/jest-dom": "^6.9.1",
"@testing-library/react": "^16.3.0",
"@testing-library/user-event": "^13.5.0",
"@types/jest": "^27.5.2",
"@types/node": "^16.18.126",
"@types/react": "^19.2.2",
"@types/react-dom": "^19.2.1",
"react": "^19.0.0",
"react-dom": "^19.0.0",
"react-router-dom": "^6.28.0",
"date-fns": "4.1.0"
},
"devDependencies": {
"@types/node": "20.19.23",
"@types/react": "^19.0.0",
"@types/react-dom": "^19.0.0",
"@types/react-router-dom": "^5.3.3",
"react": "^19.2.0",
"react-dom": "^19.2.0",
"react-router-dom": "^7.9.3",
"react-scripts": "5.0.1",
"typescript": "^4.9.5",
"web-vitals": "^2.1.4",
"worker_threads": "native"
"@vitejs/plugin-react": "^4.3.3",
"@types/jest": "30.0.0",
"@testing-library/react": "10.4.1",
"@testing-library/jest-dom": "6.9.1",
"@testing-library/user-event": "14.6.1",
"@storybook/react": "10.0.1",
"typescript": "^5.7.3",
"vite": "^6.0.7",
"esbuild": "^0.21.0",
"terser": "5.44.0",
"babel-plugin-transform-remove-console": "6.9.4",
"framer-motion": "12.23.24"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
"dev": "vite dev",
"build": "tsc && vite build",
"preview": "vite preview"
}
}

View File

@@ -1,6 +1,6 @@
{
"short_name": "React App",
"name": "Create React App Sample",
"short_name": "SP",
"name": "schichtenplaner",
"icons": [
{
"src": "favicon.ico",

View File

@@ -1,9 +0,0 @@
import React from 'react';
import { render, screen } from '@testing-library/react';
import App from './App';
test('renders learn react link', () => {
render(<App />);
const linkElement = screen.getByText(/learn react/i);
expect(linkElement).toBeInTheDocument();
});

View File

@@ -1,4 +1,4 @@
// frontend/src/App.tsx - KORRIGIERT MIT LAYOUT
// src/App.tsx
import React from 'react';
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
import { AuthProvider, useAuth } from './contexts/AuthContext';
@@ -15,11 +15,44 @@ import EmployeeManagement from './pages/Employees/EmployeeManagement';
import Settings from './pages/Settings/Settings';
import Help from './pages/Help/Help';
import Setup from './pages/Setup/Setup';
import ErrorBoundary from './components/ErrorBoundary/ErrorBoundary';
// Free Footer Link Pages (always available)
import FAQ from './components/Layout/FooterLinks/FAQ/FAQ';
import About from './components/Layout/FooterLinks/About/About';
import Features from './components/Layout/FooterLinks/Features/Features';
import { CommunityContact, CommunityLegalPage } from './components/Layout/FooterLinks/CommunityLinks/communityLinks';
// Vite environment variables (use import.meta.env instead of process.env)
const ENABLE_PRO = import.meta.env.ENABLE_PRO === 'true';
// Conditional Premium Components
let PremiumContact: React.FC = CommunityContact;
let PremiumPrivacy: React.FC = () => <CommunityLegalPage title="Datenschutz" />;
let PremiumImprint: React.FC = () => <CommunityLegalPage title="Impressum" />;
let PremiumTerms: React.FC = () => <CommunityLegalPage title="AGB" />;
// Load premium components only when ENABLE_PRO is true
if (ENABLE_PRO) {
try {
// Use require with type assertions to avoid dynamic import issues
const premiumModule = require('@premium-frontend/components/FooterLinks');
if (premiumModule.Contact) PremiumContact = premiumModule.Contact;
if (premiumModule.Privacy) PremiumPrivacy = premiumModule.Privacy;
if (premiumModule.Imprint) PremiumImprint = premiumModule.Imprint;
if (premiumModule.Terms) PremiumTerms = premiumModule.Terms;
console.log('✅ Premium components loaded successfully');
} catch (error) {
console.warn('⚠️ Premium components not available, using community fallbacks:', error);
}
}
// Protected Route Component
const ProtectedRoute: React.FC<{ children: React.ReactNode; roles?: string[] }> = ({
children,
roles = ['admin', 'instandhalter', 'user']
roles = ['admin', 'maintenance', 'user']
}) => {
const { user, loading, hasRole } = useAuth();
@@ -49,11 +82,27 @@ const ProtectedRoute: React.FC<{ children: React.ReactNode; roles?: string[] }>
return <Layout>{children}</Layout>;
};
// Public Route Component (without Layout for footer pages)
const PublicRoute: React.FC<{ children: React.ReactNode }> = ({ children }) => {
const { user, loading } = useAuth();
if (loading) {
return (
<div style={{ textAlign: 'center', padding: '40px' }}>
<div> Lade Anwendung...</div>
</div>
);
}
return user ? <Layout>{children}</Layout> : <>{children}</>;
};
// Main App Content
const AppContent: React.FC = () => {
const { loading, needsSetup, user } = useAuth();
console.log('🏠 AppContent rendering - loading:', loading, 'needsSetup:', needsSetup, 'user:', user);
console.log('🎯 Premium features enabled:', ENABLE_PRO);
// Während des Ladens
if (loading) {
@@ -80,58 +129,39 @@ const AppContent: React.FC = () => {
console.log('✅ Showing protected routes for user:', user.email);
return (
<Routes>
<Route path="/" element={
<ProtectedRoute>
<Dashboard />
</ProtectedRoute>
} />
<Route path="/shift-plans" element={
<ProtectedRoute>
<ShiftPlanList />
</ProtectedRoute>
} />
<Route path="/shift-plans/new" element={
<ProtectedRoute roles={['admin', 'instandhalter']}>
<ShiftPlanCreate />
</ProtectedRoute>
} />
<Route path="/shift-plans/:id/edit" element={
<ProtectedRoute roles={['admin', 'instandhalter']}>
<ShiftPlanEdit />
</ProtectedRoute>
} />
<Route path="/shift-plans/:id" element={
<ProtectedRoute>
<ShiftPlanView />
</ProtectedRoute>
} />
<Route path="/employees" element={
<ProtectedRoute roles={['admin', 'instandhalter']}>
<EmployeeManagement />
</ProtectedRoute>
} />
<Route path="/settings" element={
<ProtectedRoute>
<Settings />
</ProtectedRoute>
} />
<Route path="/help" element={
<ProtectedRoute>
<Help />
</ProtectedRoute>
} />
{/* Protected Routes (require login) */}
<Route path="/" element={<ProtectedRoute><Dashboard /></ProtectedRoute>} />
<Route path="/shift-plans" element={<ProtectedRoute><ShiftPlanList /></ProtectedRoute>} />
<Route path="/shift-plans/new" element={<ProtectedRoute roles={['admin', 'maintenance']}><ShiftPlanCreate /></ProtectedRoute>} />
<Route path="/shift-plans/:id/edit" element={<ProtectedRoute roles={['admin', 'maintenance']}><ShiftPlanEdit /></ProtectedRoute>} />
<Route path="/shift-plans/:id" element={<ProtectedRoute><ShiftPlanView /></ProtectedRoute>} />
<Route path="/employees" element={<ProtectedRoute roles={['admin', 'maintenance']}><EmployeeManagement /></ProtectedRoute>} />
<Route path="/settings" element={<ProtectedRoute><Settings /></ProtectedRoute>} />
<Route path="/help" element={<ProtectedRoute><Help /></ProtectedRoute>} />
{/* Public Footer Link Pages (always available) */}
<Route path="/faq" element={<PublicRoute><FAQ /></PublicRoute>} />
<Route path="/about" element={<PublicRoute><About /></PublicRoute>} />
<Route path="/features" element={<PublicRoute><Features /></PublicRoute>} />
{/* PREMIUM Footer Link Pages (conditionally available) */}
<Route path="/contact" element={<PublicRoute><PremiumContact /></PublicRoute>} />
<Route path="/privacy" element={<PublicRoute><PremiumPrivacy /></PublicRoute>} />
<Route path="/imprint" element={<PublicRoute><PremiumImprint /></PublicRoute>} />
<Route path="/terms" element={<PublicRoute><PremiumTerms /></PublicRoute>} />
{/* Auth Routes */}
<Route path="/login" element={<Login />} />
<Route path="*" element={
<ProtectedRoute>
<Dashboard />
</ProtectedRoute>
} />
{/* Catch-all Route */}
<Route path="*" element={<ProtectedRoute><Dashboard /></ProtectedRoute>} />
</Routes>
);
};
function App() {
return (
<ErrorBoundary>
<NotificationProvider>
<AuthProvider>
<Router>
@@ -140,6 +170,7 @@ function App() {
</Router>
</AuthProvider>
</NotificationProvider>
</ErrorBoundary>
);
}

View File

@@ -0,0 +1,101 @@
// src/components/ErrorBoundary/ErrorBoundary.tsx
import React from 'react';
interface Props {
children: React.ReactNode;
fallback?: React.ReactNode;
}
interface State {
hasError: boolean;
error?: Error;
}
class ErrorBoundary extends React.Component<Props, State> {
constructor(props: Props) {
super(props);
this.state = { hasError: false };
}
static getDerivedStateFromError(error: Error): State {
return { hasError: true, error };
}
componentDidCatch(error: Error, errorInfo: React.ErrorInfo) {
console.error('🚨 Application Error:', error);
console.error('📋 Error Details:', errorInfo);
// In production, send to your error reporting service
// logErrorToService(error, errorInfo);
}
render() {
if (this.state.hasError) {
// You can render any custom fallback UI
return this.props.fallback || (
<div style={{
padding: '40px',
textAlign: 'center',
fontFamily: 'Arial, sans-serif'
}}>
<div style={{ fontSize: '48px', marginBottom: '20px' }}></div>
<h2>Oops! Something went wrong</h2>
<p style={{ margin: '20px 0', color: '#666' }}>
We encountered an unexpected error. Please try refreshing the page.
</p>
<div style={{ marginTop: '30px' }}>
<button
onClick={() => window.location.reload()}
style={{
padding: '10px 20px',
backgroundColor: '#007bff',
color: 'white',
border: 'none',
borderRadius: '4px',
cursor: 'pointer',
marginRight: '10px'
}}
>
Refresh Page
</button>
<button
onClick={() => this.setState({ hasError: false })}
style={{
padding: '10px 20px',
backgroundColor: '#6c757d',
color: 'white',
border: 'none',
borderRadius: '4px',
cursor: 'pointer'
}}
>
Try Again
</button>
</div>
{process.env.NODE_ENV === 'development' && this.state.error && (
<details style={{
marginTop: '20px',
textAlign: 'left',
background: '#f8f9fa',
padding: '15px',
borderRadius: '4px'
}}>
<summary>Error Details (Development)</summary>
<pre style={{
whiteSpace: 'pre-wrap',
fontSize: '12px',
color: '#dc3545'
}}>
{this.state.error.stack}
</pre>
</details>
)}
</div>
);
}
return this.props.children;
}
}
export default ErrorBoundary;

View File

@@ -1,4 +1,4 @@
// frontend/src/components/Layout/Footer.tsx - ELEGANT WHITE DESIGN
// frontend/src/components/Layout/Footer.tsx
import React from 'react';
const Footer: React.FC = () => {
@@ -10,12 +10,12 @@ const Footer: React.FC = () => {
borderTop: '1px solid rgba(251, 250, 246, 0.1)',
},
footerContent: {
maxWidth: '1200px',
maxWidth: '1500px',
margin: '0 auto',
padding: '3rem 2rem 2rem',
display: 'grid',
gridTemplateColumns: 'repeat(auto-fit, minmax(250px, 1fr))',
gap: '3rem',
gridTemplateColumns: 'repeat(auto-fit, minmax(100px, 1fr))',
gap: '1rem',
},
footerSection: {
display: 'flex',
@@ -182,20 +182,6 @@ const Footer: React.FC = () => {
>
Funktionen
</a>
<a
href="/pricing"
style={styles.footerLink}
onMouseEnter={(e) => {
e.currentTarget.style.color = '#FBFAF6';
e.currentTarget.style.transform = 'translateX(4px)';
}}
onMouseLeave={(e) => {
e.currentTarget.style.color = 'rgba(251, 250, 246, 0.7)';
e.currentTarget.style.transform = 'translateX(0)';
}}
>
Preise
</a>
</div>
</div>

View File

@@ -0,0 +1,76 @@
// frontend/src/components/Layout/FooterLinks/About/About.tsx
import React from 'react';
const About: React.FC = () => {
return (
<div style={{ padding: '40px 20px', maxWidth: '800px', margin: '0 auto' }}>
<h1>👨💻 Über uns</h1>
<div style={{
backgroundColor: 'white',
borderRadius: '12px',
padding: '30px',
marginTop: '20px',
boxShadow: '0 4px 6px rgba(0,0,0,0.1)',
border: '1px solid #e0e0e0',
lineHeight: 1.6
}}>
<h2 style={{ color: '#2c3e50' }}>Unser Team</h2>
<div style={{ display: 'flex', alignItems: 'center', marginTop: '20px', padding: '20px', backgroundColor: '#f8f9fa', borderRadius: '8px' }}>
<div style={{ marginRight: '20px' }}>
<div style={{
width: '80px',
height: '80px',
backgroundColor: '#3498db',
borderRadius: '50%',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
color: 'white',
fontSize: '2rem',
fontWeight: 'bold'
}}>
P
</div>
</div>
<div>
<h3 style={{ color: '#2c3e50', margin: '0 0 5px 0' }}>Patrick</h3>
<p style={{ color: '#6c757d', margin: '0 0 10px 0' }}>
Full-Stack Developer & Projektleiter
</p>
<p style={{ margin: 0, fontSize: '0.9rem' }}>
GitHub: <a href="https://github.com/donpat1to" style={{ color: '#3498db' }}>donpat1to</a><br/>
E-Mail: <a href="mailto:dev.patrick@inca-vikingo.de" style={{ color: '#3498db' }}>dev.patrick@inca-vikingo.de</a>
</p>
</div>
</div>
<h3 style={{ color: '#3498db', marginTop: '30px' }}>🚀 Unsere Mission</h3>
<p>
Wir entwickeln intelligente Lösungen für die Personalplanung,
die Zeit sparen und faire Schichtverteilung gewährleisten.
</p>
<h3 style={{ color: '#3498db', marginTop: '25px' }}>💻 Technologie</h3>
<p>
Unser Stack umfasst moderne Technologien:
</p>
<ul>
<li>Frontend: React, TypeScript</li>
<li>Backend: Node.js, Express</li>
<li>Optimierung: Google OR-Tools CP-SAT</li>
<li>Datenbank: SQLite/PostgreSQL</li>
</ul>
<h3 style={{ color: '#3498db', marginTop: '25px' }}>📈 Entwicklung</h3>
<p>
Schichtenplaner wird kontinuierlich weiterentwickelt und
basiert auf Feedback unserer Nutzer.
</p>
</div>
</div>
);
};
export default About;

View File

@@ -0,0 +1,38 @@
// frontend/src/components/Layout/FooterLinks/CommunityLinks/communityLinks.tsx
import React from 'react';
export const CommunityContact: React.FC = () => (
<div style={{ padding: '40px 20px', maxWidth: '800px', margin: '0 auto' }}>
<h1>📞 Kontakt</h1>
<div style={{ backgroundColor: 'white', borderRadius: '12px', padding: '30px', marginTop: '20px' }}>
<h2 style={{ color: '#2c3e50' }}>Community Edition</h2>
<p>Kontaktfunktionen sind in der Premium Edition verfügbar.</p>
<p>
<a href="/features" style={{ color: '#3498db' }}>
Zu den Features
</a>
</p>
</div>
</div>
);
export const CommunityLegalPage: React.FC<{ title: string }> = ({ title }) => (
<div style={{ padding: '40px 20px', maxWidth: '800px', margin: '0 auto' }}>
<h1>📄 {title}</h1>
<div style={{ backgroundColor: 'white', borderRadius: '12px', padding: '30px', marginTop: '20px' }}>
<h2 style={{ color: '#2c3e50' }}>Community Edition</h2>
<p>Rechtliche Dokumentation ist in der Premium Edition verfügbar.</p>
<p>
<a href="/features" style={{ color: '#3498db' }}>
Erfahren Sie mehr über Premium
</a>
</p>
</div>
</div>
);
// Optional: Barrel export für einfachere Imports
export default {
CommunityContact,
CommunityLegalPage
};

View File

@@ -0,0 +1,103 @@
// frontend/src/components/Layout/FooterLinks/FAQ/FAQ.tsx
import React, { useState } from 'react';
const FAQ: React.FC = () => {
const [openItems, setOpenItems] = useState<number[]>([]);
const toggleItem = (index: number) => {
setOpenItems(prev =>
prev.includes(index)
? prev.filter(i => i !== index)
: [...prev, index]
);
};
const faqItems = [
{
question: "Wie funktioniert der Scheduling-Algorithmus?",
answer: "Unser System verwendet Google's OR-Tools CP-SAT Solver, um optimale Schichtzuweisungen basierend auf Verfügbarkeiten, Vertragstypen und Geschäftsregeln zu berechnen."
},
{
question: "Was bedeuten die Verfügbarkeits-Level 1, 2 und 3?",
answer: "Level 1: Bevorzugt (Mitarbeiter möchte diese Schicht), Level 2: Verfügbar (kann arbeiten), Level 3: Nicht verfügbar (kann nicht arbeiten)."
},
{
question: "Wie werden Vertragstypen berücksichtigt?",
answer: "Kleine Verträge: 1 Schicht pro Woche, Große Verträge: 2 Schichten pro Woche. Das System weist genau diese Anzahl zu."
},
{
question: "Kann ich manuelle Anpassungen vornehmen?",
answer: "Ja, nach dem automatischen Scheduling können Sie Zuordnungen manuell anpassen und optimieren."
},
{
question: "Was passiert bei unterbesetzten Schichten?",
answer: "Das System zeigt eine Warnung an und versucht, alternative Lösungen zu finden. In kritischen Fällen müssen manuelle Anpassungen vorgenommen werden."
},
{
question: "Wie lange dauert die Planungserstellung?",
answer: "Typischerweise maximal 105 Sekunden, abhängig von der Anzahl der Mitarbeiter und Schichten."
}
];
return (
<div style={{ padding: '40px 20px', maxWidth: '800px', margin: '0 auto' }}>
<h1> Häufige Fragen (FAQ)</h1>
<div style={{
backgroundColor: 'white',
borderRadius: '12px',
marginTop: '20px',
boxShadow: '0 4px 6px rgba(0,0,0,0.1)',
border: '1px solid #e0e0e0'
}}>
{faqItems.map((item, index) => (
<div key={index} style={{
borderBottom: index < faqItems.length - 1 ? '1px solid #e0e0e0' : 'none',
padding: '20px 30px'
}}>
<div
onClick={() => toggleItem(index)}
style={{
cursor: 'pointer',
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center'
}}
>
<h3 style={{
color: '#2c3e50',
margin: 0,
fontSize: '1.1rem'
}}>
{item.question}
</h3>
<span style={{
fontSize: '1.5rem',
color: '#3498db',
transform: openItems.includes(index) ? 'rotate(45deg)' : 'rotate(0)',
transition: 'transform 0.2s ease'
}}>
+
</span>
</div>
{openItems.includes(index) && (
<div style={{
marginTop: '15px',
padding: '15px',
backgroundColor: '#f8f9fa',
borderRadius: '8px',
color: '#6c757d',
lineHeight: 1.6
}}>
{item.answer}
</div>
)}
</div>
))}
</div>
</div>
);
};
export default FAQ;

View File

@@ -0,0 +1,111 @@
// frontend/src/components/Layou/FooterLinks/Features/Features.tsx
import React from 'react';
const Features: React.FC = () => {
const features = [
{
icon: "🤖",
title: "Automatisches Scheduling",
description: "Intelligenter Algorithmus erstellt optimale Schichtpläne basierend auf Verfügbarkeiten und Regeln"
},
{
icon: "⚡",
title: "Schnelle Berechnung",
description: "Google OR-Tools CP-SAT Solver findet Lösungen in maximal 105 Sekunden"
},
{
icon: "👥",
title: "Flexible Regelkonfiguration",
description: "Anpassbare Geschäftsregeln für Trainee-Betreuung, Alleinarbeit, Vertragstypen"
},
{
icon: "📊",
title: "Echtzeit-Validierung",
description: "Automatische Erkennung von Regelverletzungen und Konflikten"
},
{
icon: "🔒",
title: "Lokale Datenspeicherung",
description: "Alle Daten bleiben in Ihrer Infrastruktur - volle Kontrolle und Datenschutz"
},
{
icon: "🎯",
title: "Präferenz-basiert",
description: "Berücksichtigt Mitarbeiterwünsche für höhere Zufriedenheit"
}
];
return (
<div style={{ padding: '40px 20px', maxWidth: '1000px', margin: '0 auto' }}>
<h1> Funktionen</h1>
<div style={{
backgroundColor: 'white',
borderRadius: '12px',
padding: '30px',
marginTop: '20px',
boxShadow: '0 4px 6px rgba(0,0,0,0.1)',
border: '1px solid #e0e0e0'
}}>
<h2 style={{ color: '#2c3e50', textAlign: 'center', marginBottom: '40px' }}>
Alles, was Sie für die perfekte Schichtplanung benötigen
</h2>
<div style={{
display: 'grid',
gridTemplateColumns: 'repeat(auto-fit, minmax(300px, 1fr))',
gap: '30px'
}}>
{features.map((feature, index) => (
<div key={index} style={{
padding: '25px',
backgroundColor: '#f8f9fa',
borderRadius: '12px',
border: '2px solid #e9ecef',
textAlign: 'center',
transition: 'transform 0.2s ease, box-shadow 0.2s ease'
}}>
<div style={{
fontSize: '3rem',
marginBottom: '15px'
}}>
{feature.icon}
</div>
<h3 style={{
color: '#2c3e50',
margin: '0 0 15px 0'
}}>
{feature.title}
</h3>
<p style={{
color: '#6c757d',
margin: 0,
lineHeight: 1.5
}}>
{feature.description}
</p>
</div>
))}
</div>
<div style={{
marginTop: '40px',
padding: '25px',
backgroundColor: '#e8f4fd',
borderRadius: '12px',
border: '2px solid #b8d4f0',
textAlign: 'center'
}}>
<h3 style={{ color: '#2980b9', margin: '0 0 15px 0' }}>
🚀 Starter Sie durch
</h3>
<p style={{ color: '#2c3e50', margin: 0 }}>
Erstellen Sie Ihren ersten optimierten Schichtplan in wenigen Minuten.
</p>
</div>
</div>
</div>
);
};
export default Features;

View File

@@ -1,220 +0,0 @@
/* Layout.css - Professionelles Design */
.layout {
min-height: 100vh;
display: flex;
flex-direction: column;
}
/* Header */
.header {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
position: sticky;
top: 0;
z-index: 1000;
}
.header-content {
max-width: 1200px;
margin: 0 auto;
padding: 0 20px;
display: flex;
align-items: center;
justify-content: space-between;
height: 70px;
}
.logo h1 {
margin: 0;
font-size: 1.5rem;
font-weight: 700;
}
/* Desktop Navigation */
.desktop-nav {
display: flex;
gap: 2rem;
align-items: center;
}
.nav-link {
color: white;
text-decoration: none;
padding: 0.5rem 1rem;
border-radius: 6px;
transition: all 0.3s ease;
font-weight: 500;
}
.nav-link:hover {
background: rgba(255, 255, 255, 0.1);
transform: translateY(-1px);
}
/* User Menu */
.user-menu {
display: flex;
align-items: center;
gap: 1rem;
}
.user-info {
font-weight: 500;
}
.logout-btn {
background: rgba(255, 255, 255, 0.1);
color: white;
border: 1px solid rgba(255, 255, 255, 0.3);
padding: 0.5rem 1rem;
border-radius: 6px;
cursor: pointer;
transition: all 0.3s ease;
}
.logout-btn:hover {
background: rgba(255, 255, 255, 0.2);
}
/* Mobile Menu Button */
.mobile-menu-btn {
display: none;
background: none;
border: none;
color: white;
font-size: 1.5rem;
cursor: pointer;
padding: 0.5rem;
}
/* Mobile Navigation */
.mobile-nav {
display: none;
flex-direction: column;
background: white;
padding: 1rem;
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}
.mobile-nav-link {
color: #333;
text-decoration: none;
padding: 1rem;
border-bottom: 1px solid #eee;
transition: background-color 0.3s ease;
}
.mobile-nav-link:hover {
background-color: #f5f5f5;
}
.mobile-user-info {
padding: 1rem;
border-top: 1px solid #eee;
margin-top: 1rem;
}
.mobile-logout-btn {
background: #667eea;
color: white;
border: none;
padding: 0.5rem 1rem;
border-radius: 6px;
cursor: pointer;
margin-top: 0.5rem;
width: 100%;
}
/* Main Content */
.main-content {
flex: 1;
background-color: #f8f9fa;
min-height: calc(100vh - 140px);
}
.content-container {
max-width: 1200px;
margin: 0 auto;
padding: 2rem 20px;
}
/* Footer */
.footer {
background: #2c3e50;
color: white;
margin-top: auto;
}
.footer-content {
max-width: 1200px;
margin: 0 auto;
padding: 2rem 20px;
display: grid;
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
gap: 2rem;
}
.footer-section h3,
.footer-section h4 {
margin-bottom: 1rem;
color: #ecf0f1;
}
.footer-section a {
color: #bdc3c7;
text-decoration: none;
display: block;
margin-bottom: 0.5rem;
transition: color 0.3s ease;
}
.footer-section a:hover {
color: #3498db;
}
.footer-bottom {
border-top: 1px solid #34495e;
padding: 1rem 20px;
text-align: center;
color: #95a5a6;
}
/* Responsive Design */
@media (max-width: 768px) {
.desktop-nav,
.user-menu {
display: none;
}
.mobile-menu-btn {
display: block;
}
.mobile-nav {
display: flex;
}
.header-content {
padding: 0 15px;
}
.content-container {
padding: 1rem 15px;
}
.footer-content {
grid-template-columns: 1fr;
text-align: center;
}
}
@media (max-width: 480px) {
.logo h1 {
font-size: 1.2rem;
}
.content-container {
padding: 1rem 10px;
}
}

View File

@@ -1,4 +1,4 @@
// frontend/src/components/Layout/Layout.tsx - ELEGANT WHITE DESIGN
// frontend/src/components/Layout/Layout.tsx
import React from 'react';
import Navigation from './Navigation';
import Footer from './Footer';

View File

@@ -1,4 +1,4 @@
// frontend/src/components/Layout/Navigation.tsx - ELEGANT WHITE DESIGN
// frontend/src/components/Layout/Navigation.tsx
import React, { useState, useEffect } from 'react';
import { useAuth } from '../../contexts/AuthContext';
import PillNav from '../PillNav/PillNav';
@@ -30,11 +30,11 @@ const Navigation: React.FC = () => {
};
const navigationItems = [
{ path: '/', label: 'Dashboard', roles: ['admin', 'instandhalter', 'user'] },
{ path: '/shift-plans', label: 'Schichtpläne', roles: ['admin', 'instandhalter', 'user'] },
{ path: '/employees', label: 'Mitarbeiter', roles: ['admin', 'instandhalter'] },
{ path: '/help', label: 'Hilfe', roles: ['admin', 'instandhalter', 'user'] },
{ path: '/settings', label: 'Einstellungen', roles: ['admin', 'instandhalter', 'user'] },
{ path: '/', label: 'Dashboard', roles: ['admin', 'maintenance', 'user'] },
{ path: '/shift-plans', label: 'Schichtpläne', roles: ['admin', 'maintenance', 'user'] },
{ path: '/employees', label: 'Mitarbeiter', roles: ['admin', 'maintenance'] },
{ path: '/help', label: 'Hilfe', roles: ['admin', 'maintenance', 'user'] },
{ path: '/settings', label: 'Einstellungen', roles: ['admin', 'maintenance', 'user'] },
];
const filteredNavigation = navigationItems.filter(item =>

View File

@@ -1,88 +0,0 @@
/* frontend/src/components/PillNav/PillNav.module.css */
.pillNavContainer {
display: flex;
gap: 8px;
overflow-x: auto;
padding: 4px;
scrollbar-width: none;
-ms-overflow-style: none;
}
.pillNavContainer::-webkit-scrollbar {
display: none;
}
.pill {
padding: 8px 16px;
border-radius: 9999px;
border: 1px solid;
font-size: 14px;
font-weight: 500;
cursor: pointer;
transition: all 0.2s ease-in-out;
white-space: nowrap;
outline: none;
}
.pill:focus-visible {
outline: 2px solid #3b82f6;
outline-offset: 2px;
}
/* Solid Variant */
.pillSolid {
background-color: transparent;
color: #6b7280;
border-color: #d1d5db;
}
.pillSolidActive {
background-color: #2563eb;
color: white;
border-color: #2563eb;
}
.pillSolid:hover:not(.pillSolidActive) {
background-color: #f3f4f6;
color: #374151;
border-color: #9ca3af;
transform: translateY(-1px);
}
/* Outline Variant */
.pillOutline {
background-color: transparent;
color: #6b7280;
border-color: #d1d5db;
}
.pillOutlineActive {
color: #2563eb;
border-color: #2563eb;
font-weight: 600;
}
.pillOutline:hover:not(.pillOutlineActive) {
background-color: #f3f4f6;
color: #374151;
border-color: #9ca3af;
transform: translateY(-1px);
}
/* Ghost Variant */
.pillGhost {
background-color: transparent;
color: #6b7280;
border-color: transparent;
}
.pillGhostActive {
background-color: #f3f4f6;
color: #111827;
}
.pillGhost:hover:not(.pillGhostActive) {
background-color: #f9fafb;
color: #374151;
transform: translateY(-1px);
}

View File

@@ -1,4 +1,4 @@
// frontend/src/components/PillNav/PillNav.tsx - ELEGANT WHITE DESIGN
// frontend/src/components/PillNav/PillNav.tsx
import React, { useEffect, useRef } from 'react';
export interface PillNavItem {

View File

@@ -1,3 +0,0 @@
// frontend/src/components/PillNav/index.ts
export { default } from './PillNav';
export type { PillNavProps, PillNavItem } from './PillNav';

View File

@@ -0,0 +1,79 @@
import React from 'react';
import type { Meta, StoryObj } from '@storybook/react';
import StepSetup from './StepSetup';
const meta: Meta<typeof StepSetup> = {
title: 'Components/StepSetup',
component: StepSetup,
parameters: {
layout: 'padded',
},
tags: ['autodocs'],
};
export default meta;
type Story = StoryObj<typeof StepSetup>;
const defaultSteps = [
{ id: 'step-1', title: 'Account Setup', subtitle: 'Create your account' },
{ id: 'step-2', title: 'Profile Information', subtitle: 'Add personal details' },
{ id: 'step-3', title: 'Preferences', subtitle: 'Customize your experience', optional: true },
{ id: 'step-4', title: 'Confirmation', subtitle: 'Review and confirm' },
];
export const Horizontal: Story = {
args: {
steps: defaultSteps,
defaultCurrent: 1,
orientation: 'horizontal',
},
};
export const Vertical: Story = {
args: {
steps: defaultSteps,
defaultCurrent: 1,
orientation: 'vertical',
},
parameters: {
layout: 'padded',
},
};
export const ClickableFalse: Story = {
args: {
steps: defaultSteps,
current: 2,
clickable: false,
},
name: 'Non-Clickable Steps',
};
export const AnimatedFalse: Story = {
args: {
steps: defaultSteps,
defaultCurrent: 1,
animated: false,
},
name: 'Without Animation',
};
export const DifferentSizes: Story = {
render: () => (
<div className="space-y-8">
<div>
<h3 className="text-sm font-medium mb-2">Small</h3>
<StepSetup steps={defaultSteps} size="sm" defaultCurrent={1} />
</div>
<div>
<h3 className="text-sm font-medium mb-2">Medium (default)</h3>
<StepSetup steps={defaultSteps} size="md" defaultCurrent={1} />
</div>
<div>
<h3 className="text-sm font-medium mb-2">Large</h3>
<StepSetup steps={defaultSteps} size="lg" defaultCurrent={1} />
</div>
</div>
),
name: 'Different Sizes',
};

View File

@@ -0,0 +1,127 @@
import React from 'react';
import { render, screen, fireEvent } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import '@testing-library/jest-dom';
import StepSetup from './StepSetup';
const mockSteps = [
{ id: 'step-1', title: 'First Step', subtitle: 'Description 1' },
{ id: 'step-2', title: 'Second Step' },
{ id: 'step-3', title: 'Third Step', subtitle: 'Description 3', optional: true },
];
describe('StepSetup', () => {
// a) Test verschiedener Step-Counts
test('renders correct number of steps', () => {
render(<StepSetup steps={mockSteps} />);
expect(screen.getByText('First Step')).toBeInTheDocument();
expect(screen.getByText('Second Step')).toBeInTheDocument();
expect(screen.getByText('Third Step')).toBeInTheDocument();
});
test('renders empty state correctly', () => {
render(<StepSetup steps={[]} />);
expect(screen.getByText('No steps available')).toBeInTheDocument();
});
// b) Keyboard-Navigation und Klicks
test('handles click navigation when clickable', async () => {
const user = userEvent.setup();
const onChange = jest.fn();
render(<StepSetup steps={mockSteps} clickable={true} onChange={onChange} />);
const secondStep = screen.getByRole('tab', { name: /second step/i });
await user.click(secondStep);
expect(onChange).toHaveBeenCalledWith(1);
});
test('handles keyboard navigation', async () => {
const user = userEvent.setup();
const onChange = jest.fn();
render(
<StepSetup
steps={mockSteps}
defaultCurrent={0}
onChange={onChange}
/>
);
const firstStep = screen.getByRole('tab', { name: /first step/i });
firstStep.focus();
// Right arrow to next step
await user.keyboard('{ArrowRight}');
expect(onChange).toHaveBeenCalledWith(1);
// Home key to first step
await user.keyboard('{Home}');
expect(onChange).toHaveBeenCalledWith(0);
// End key to last step
await user.keyboard('{End}');
expect(onChange).toHaveBeenCalledWith(2);
});
// c) ARIA-Attribute Tests
test('has correct ARIA attributes', () => {
render(<StepSetup steps={mockSteps} current={1} />);
const tablist = screen.getByRole('tablist');
expect(tablist).toBeInTheDocument();
const tabs = screen.getAllByRole('tab');
expect(tabs).toHaveLength(3);
// Second step should be selected
expect(tabs[1]).toHaveAttribute('aria-selected', 'true');
expect(tabs[1]).toHaveAttribute('aria-current', 'step');
});
// d) Controlled vs Uncontrolled Tests
test('works in controlled mode', () => {
const onChange = jest.fn();
const { rerender } = render(
<StepSetup steps={mockSteps} current={0} onChange={onChange} />
);
// Click should call onChange but not change internal state in controlled mode
const secondStep = screen.getByRole('tab', { name: /second step/i });
fireEvent.click(secondStep);
expect(onChange).toHaveBeenCalledWith(1);
// Current step should still be first (controlled by prop)
expect(screen.getByRole('tab', { name: /first step/i }))
.toHaveAttribute('aria-selected', 'true');
// Update prop should change current step
rerender(<StepSetup steps={mockSteps} current={1} onChange={onChange} />);
expect(screen.getByRole('tab', { name: /second step/i }))
.toHaveAttribute('aria-selected', 'true');
});
test('works in uncontrolled mode', () => {
const onChange = jest.fn();
render(<StepSetup steps={mockSteps} defaultCurrent={0} onChange={onChange} />);
const secondStep = screen.getByRole('tab', { name: /second step/i });
fireEvent.click(secondStep);
expect(onChange).toHaveBeenCalledWith(1);
expect(secondStep).toHaveAttribute('aria-selected', 'true');
});
test('clamps out-of-range current values', () => {
render(<StepSetup steps={mockSteps} current={10} />);
// Should clamp to last step
const lastStep = screen.getByRole('tab', { name: /third step/i });
expect(lastStep).toHaveAttribute('aria-selected', 'true');
});
});

View File

@@ -0,0 +1,516 @@
import React, {
useState,
useEffect,
useId,
useCallback,
KeyboardEvent
} from 'react';
import { motion, MotionConfig, SpringOptions } from 'framer-motion';
// ===== TYP-DEFINITIONEN =====
export interface Step {
id: string;
title: string;
subtitle?: string;
optional?: boolean;
}
export interface StepSetupProps {
/** Array der Schritte mit ID, Titel und optionalen Eigenschaften */
steps: Step[];
/** Kontrollierter aktueller Schritt-Index */
current?: number;
/** Unkontrollierter Standard-Schritt-Index */
defaultCurrent?: number;
/** Callback bei Schrittänderung */
onChange?: (index: number) => void;
/** Ausrichtung des Steppers */
orientation?: 'horizontal' | 'vertical';
/** Ob Steps anklickbar sind */
clickable?: boolean;
/** Größe der Step-Komponente */
size?: 'sm' | 'md' | 'lg';
/** Animation aktivieren/deaktivieren */
animated?: boolean;
/** Zusätzliche CSS-Klassen */
className?: string;
}
export interface StepState {
currentStep: number;
isControlled: boolean;
}
// ===== HOOK FÜR ZUSTANDSVERWALTUNG =====
export const useStepSetup = (props: StepSetupProps) => {
const {
steps,
current,
defaultCurrent = 0,
onChange,
clickable = true
} = props;
const [internalStep, setInternalStep] = useState(defaultCurrent);
const isControlled = current !== undefined;
const currentStep = isControlled ? current : internalStep;
// Clamp den Schritt-Index auf gültigen Bereich
const clampedStep = Math.max(0, Math.min(currentStep, steps.length - 1));
const setStep = useCallback((newStep: number) => {
const clampedNewStep = Math.max(0, Math.min(newStep, steps.length - 1));
if (!isControlled) {
setInternalStep(clampedNewStep);
}
onChange?.(clampedNewStep);
}, [isControlled, onChange, steps.length]);
const goToNext = useCallback(() => {
if (clampedStep < steps.length - 1) {
setStep(clampedStep + 1);
}
}, [clampedStep, steps.length, setStep]);
const goToPrev = useCallback(() => {
if (clampedStep > 0) {
setStep(clampedStep - 1);
}
}, [clampedStep, setStep]);
const goToStep = useCallback((index: number) => {
if (clickable) {
setStep(index);
}
}, [clickable, setStep]);
// Warnung bei Duplicate IDs (nur in Development)
useEffect(() => {
if (process.env.NODE_ENV !== 'production') {
const stepIds = steps.map(step => step.id);
const duplicateIds = stepIds.filter((id, index) => stepIds.indexOf(id) !== index);
if (duplicateIds.length > 0) {
console.warn(
`StepSetup: Duplicate step IDs found: ${duplicateIds.join(', ')}. ` +
`Step IDs should be unique.`
);
}
}
}, [steps]);
return {
currentStep: clampedStep,
setStep,
goToNext,
goToPrev,
goToStep,
isControlled
};
};
// ===== ANIMATIONS-KONFIGURATION =====
const getAnimationConfig = (animated: boolean): { reduced: { duration: number }; normal: SpringOptions } => ({
reduced: { duration: 0 }, // Keine Animation
normal: {
stiffness: 500,
damping: 30,
mass: 0.5
}
});
// ===== HILFSFUNKTIONEN =====
/**
* Berechnet die Step-Größenklassen basierend auf der size-Prop
*/
const getSizeClasses = (size: StepSetupProps['size'] = 'md') => {
const sizes = {
sm: {
step: 'w-8 h-8 text-sm',
icon: 'w-4 h-4',
title: 'text-sm',
subtitle: 'text-xs'
},
md: {
step: 'w-10 h-10 text-base',
icon: 'w-5 h-5',
title: 'text-base',
subtitle: 'text-sm'
},
lg: {
step: 'w-12 h-12 text-lg',
icon: 'w-6 h-6',
title: 'text-lg',
subtitle: 'text-base'
}
};
return sizes[size];
};
/**
* Prüft ob prefers-reduced-motion aktiv ist
*/
const prefersReducedMotion = (): boolean => {
if (typeof window === 'undefined') return false;
return window.matchMedia('(prefers-reduced-motion: reduce)').matches;
};
// ===== STEP ICON KOMPONENTE =====
interface StepIconProps {
stepIndex: number;
currentStep: number;
size: StepSetupProps['size'];
animated: boolean;
}
const StepNumber: React.FC<{ number: number; isCurrent?: boolean; isCompleted?: boolean }> = ({
number,
isCurrent = false,
isCompleted = false
}) => {
const baseClasses = `
w-6 h-6
flex items-center justify-center
rounded-full text-xs font-medium
transition-all duration-200
`;
if (isCompleted) {
return (
<div className={`${baseClasses} bg-blue-500 text-white`}>
</div>
);
}
if (isCurrent) {
return (
<div className={`${baseClasses} bg-blue-500 text-white ring-2 ring-blue-500 ring-opacity-20`}>
{number}
</div>
);
}
return (
<div className={`${baseClasses} bg-gray-200 text-gray-600`}>
{number}
</div>
);
};
const StepIcon: React.FC<StepIconProps> = ({
stepIndex,
currentStep,
size,
animated
}) => {
const isCompleted = stepIndex < currentStep;
const isCurrent = stepIndex === currentStep;
const sizeClasses = getSizeClasses(size);
const animationConfig = getAnimationConfig(animated);
const shouldAnimate = animated && !prefersReducedMotion();
const baseClasses = `
${sizeClasses.step}
flex items-center justify-center
rounded-full border-2 font-medium
transition-all duration-200
`;
if (isCompleted) {
const completedClasses = `
${baseClasses}
border-blue-500 bg-white
`;
const iconContent = shouldAnimate ? (
<motion.div
initial={{ scale: 0, rotate: -180 }}
animate={{ scale: 1, rotate: 0 }}
transition={animationConfig.normal}
>
<StepNumber number={stepIndex + 1} isCompleted />
</motion.div>
) : (
<StepNumber number={stepIndex + 1} isCompleted />
);
return (
<div className={completedClasses}>
{iconContent}
</div>
);
}
if (isCurrent) {
const currentClasses = `
${baseClasses}
border-blue-500 bg-white
`;
const stepNumber = shouldAnimate ? (
<motion.div
key={stepIndex}
initial={{ scale: 0 }}
animate={{ scale: 1 }}
transition={animationConfig.normal}
>
<StepNumber number={stepIndex + 1} isCurrent />
</motion.div>
) : (
<StepNumber number={stepIndex + 1} isCurrent />
);
return <div className={currentClasses}>{stepNumber}</div>;
}
const upcomingClasses = `
${baseClasses}
border-gray-300 bg-white
`;
return (
<div className={upcomingClasses}>
<StepNumber number={stepIndex + 1} />
</div>
);
};
// ===== HAUPTKOMPONENTE =====
/**
* Eine zugängliche, animierte Step/Progress-Komponente mit Unterstützung für
* kontrollierte und unkontrollierte Verwendung.
*
* @example
* ```tsx
* <StepSetup
* steps={[
* { id: 's1', title: 'First Step', subtitle: 'Optional description' },
* { id: 's2', title: 'Second Step' }
* ]}
* defaultCurrent={0}
* onChange={(index) => console.log('Step changed:', index)}
* />
* ```
*/
const StepSetup: React.FC<StepSetupProps> = (props) => {
const {
steps,
orientation = 'horizontal',
clickable = true,
size = 'md',
animated = true,
className = ''
} = props;
const {
currentStep,
goToStep
} = useStepSetup(props);
const listId = useId();
const shouldAnimate = animated && !prefersReducedMotion();
const sizeClasses = getSizeClasses(size);
// Fallback für leere Steps
if (!steps || steps.length === 0) {
return (
<div
className={`flex items-center justify-center p-4 text-gray-500 ${className}`}
role="status"
aria-live="polite"
>
No steps available
</div>
);
}
// Tastatur-Navigation Handler
const handleKeyDown = (
event: KeyboardEvent<HTMLButtonElement>,
stepIndex: number
) => {
if (!clickable) return;
const isHorizontal = orientation === 'horizontal';
switch (event.key) {
case 'Enter':
case ' ':
event.preventDefault();
goToStep(stepIndex);
break;
case 'ArrowRight':
case 'ArrowDown':
if ((isHorizontal && event.key === 'ArrowRight') ||
(!isHorizontal && event.key === 'ArrowDown')) {
event.preventDefault();
const nextStep = Math.min(stepIndex + 1, steps.length - 1);
goToStep(nextStep);
}
break;
case 'ArrowLeft':
case 'ArrowUp':
if ((isHorizontal && event.key === 'ArrowLeft') ||
(!isHorizontal && event.key === 'ArrowUp')) {
event.preventDefault();
const prevStep = Math.max(stepIndex - 1, 0);
goToStep(prevStep);
}
break;
case 'Home':
event.preventDefault();
goToStep(0);
break;
case 'End':
event.preventDefault();
goToStep(steps.length - 1);
break;
}
};
// Container-Klassen basierend auf Ausrichtung
const containerClasses = `
flex ${orientation === 'vertical' ? 'flex-col' : 'flex-row'}
${orientation === 'horizontal' ? 'items-center justify-center gap-8' : 'gap-6'}
${className}
`;
const StepContent = shouldAnimate ? motion.div : 'div';
return (
<MotionConfig reducedMotion={prefersReducedMotion() ? "always" : "user"}>
<nav
className={containerClasses.trim()}
aria-label="Progress steps"
role="tablist"
>
{steps.map((step, index) => {
const isCompleted = index < currentStep;
const isCurrent = index === currentStep;
const isClickable = clickable && (isCompleted || isCurrent || step.optional);
// Für horizontale Ausrichtung: flex-col mit zentrierten Items
const stepClasses = `
flex flex-col items-center
gap-3
${isClickable ? 'cursor-pointer' : 'cursor-not-allowed'}
transition-colors duration-200
${orientation === 'horizontal' ? 'flex-1' : ''}
`;
const contentClasses = `
flex flex-col items-center text-center
${orientation === 'vertical' ? 'flex-1' : ''}
`;
// Verbindungslinie nur für horizontale Ausrichtung
const connectorClasses = `
flex-1 h-0.5 mt-5
${isCompleted ? 'bg-blue-500' : 'bg-gray-200'}
transition-colors duration-200
${orientation === 'horizontal' ? '' : 'hidden'}
`;
return (
<React.Fragment key={step.id}>
<StepContent
className={stepClasses}
layout={shouldAnimate ? "position" : false}
transition={shouldAnimate ? getAnimationConfig(animated).normal : undefined}
>
<div className="flex items-center w-full">
{/* Verbindungslinie vor dem Step (außer beim ersten) */}
{index > 0 && orientation === 'horizontal' && (
<div
className={connectorClasses}
aria-hidden="true"
/>
)}
<button
type="button"
onClick={() => isClickable && goToStep(index)}
onKeyDown={(e) => handleKeyDown(e, index)}
disabled={!isClickable}
className={`
flex items-center justify-center
focus:outline-none focus:ring-2
focus:ring-blue-500 focus:ring-offset-2 rounded-full
${!isClickable ? 'opacity-50' : ''}
${orientation === 'horizontal' ? 'mx-2' : ''}
`}
role="tab"
aria-selected={isCurrent}
aria-controls={`${listId}-${step.id}`}
id={`${listId}-tab-${step.id}`}
tabIndex={isCurrent ? 0 : -1}
aria-current={isCurrent ? 'step' : undefined}
aria-disabled={!isClickable}
>
<StepIcon
stepIndex={index}
currentStep={currentStep}
size={size}
animated={animated}
/>
</button>
{/* Verbindungslinie nach dem Step (außer beim letzten) */}
{index < steps.length - 1 && orientation === 'horizontal' && (
<div
className={connectorClasses}
aria-hidden="true"
/>
)}
</div>
{/* Step Titel und Untertitel */}
<div className={contentClasses}>
<span
className={`
font-medium
${isCurrent ? 'text-blue-600' : isCompleted ? 'text-gray-900' : 'text-gray-500'}
${sizeClasses.title}
`}
id={`${listId}-title-${step.id}`}
>
{step.title}
{step.optional && (
<span className="text-gray-400 text-sm ml-1">(Optional)</span>
)}
</span>
{step.subtitle && (
<span
className={`
${isCurrent ? 'text-gray-700' : 'text-gray-500'}
${sizeClasses.subtitle}
`}
id={`${listId}-subtitle-${step.id}`}
>
{step.subtitle}
</span>
)}
</div>
</StepContent>
</React.Fragment>
);
})}
</nav>
</MotionConfig>
);
};
export default StepSetup;

View File

@@ -20,6 +20,7 @@ interface AuthContextType {
}
const AuthContext = createContext<AuthContextType | undefined>(undefined);
const API_BASE_URL = import.meta.env.VITE_API_URL || '/api';
interface AuthProviderProps {
children: ReactNode;
@@ -48,12 +49,21 @@ export const AuthProvider: React.FC<AuthProviderProps> = ({ children }) => {
const checkSetupStatus = async (): Promise<void> => {
try {
console.log('🔍 Checking setup status...');
const response = await fetch('http://localhost:3002/api/setup/status');
const startTime = Date.now();
const response = await fetch(`${API_BASE_URL}/setup/status`, {
signal: AbortSignal.timeout(5000)
});
console.log(`✅ Setup status response received in ${Date.now() - startTime}ms`);
if (!response.ok) {
console.error('❌ Setup status response not OK:', response.status, response.statusText);
throw new Error('Setup status check failed');
}
const data = await response.json();
console.log('✅ Setup status response:', data);
console.log('✅ Setup status response data:', data);
setNeedsSetup(data.needsSetup === true);
} catch (error) {
console.error('❌ Error checking setup status:', error);
@@ -72,7 +82,7 @@ export const AuthProvider: React.FC<AuthProviderProps> = ({ children }) => {
return;
}
const response = await fetch('http://localhost:3002/api/auth/me', {
const response = await fetch(`${API_BASE_URL}/auth/me`, {
headers: {
'Authorization': `Bearer ${token}`
}
@@ -94,7 +104,6 @@ export const AuthProvider: React.FC<AuthProviderProps> = ({ children }) => {
}
};
// Add the updateUser function
const updateUser = (userData: Employee) => {
console.log('🔄 Updating user in auth context:', userData);
setUser(userData);
@@ -104,7 +113,7 @@ export const AuthProvider: React.FC<AuthProviderProps> = ({ children }) => {
try {
console.log('🔐 Attempting login for:', credentials.email);
const response = await fetch('http://localhost:3002/api/auth/login', {
const response = await fetch(`${API_BASE_URL}/auth/login`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
@@ -160,6 +169,8 @@ export const AuthProvider: React.FC<AuthProviderProps> = ({ children }) => {
initializeAuth();
}, []);
const calculatedNeedsSetup = needsSetup === null ? true : needsSetup;
const value: AuthContextType = {
user,
login,
@@ -167,7 +178,7 @@ export const AuthProvider: React.FC<AuthProviderProps> = ({ children }) => {
hasRole,
loading,
refreshUser,
needsSetup: needsSetup === null ? true : needsSetup,
needsSetup: calculatedNeedsSetup,
checkSetupStatus,
updateUser,
};

View File

@@ -1,4 +1,4 @@
// frontend/src/design/DesignSystem.tsx
// frontend/src/design/DesignSystem.txt
export const designTokens = {
colors: {
// Primary Colors

View File

@@ -0,0 +1,73 @@
// frontend/src/hooks/useBackendValidation.ts
import { useState, useCallback } from 'react';
import { ValidationError } from '../services/errorService';
import { useNotification } from '../contexts/NotificationContext';
export const useBackendValidation = () => {
const [validationErrors, setValidationErrors] = useState<ValidationError[]>([]);
const [isSubmitting, setIsSubmitting] = useState(false);
const { showNotification } = useNotification();
const clearErrors = useCallback(() => {
setValidationErrors([]);
}, []);
const getFieldError = useCallback((fieldName: string): string | null => {
const error = validationErrors.find(error => error.field === fieldName);
return error ? error.message : null;
}, [validationErrors]);
const hasErrors = useCallback((fieldName?: string): boolean => {
if (fieldName) {
return validationErrors.some(error => error.field === fieldName);
}
return validationErrors.length > 0;
}, [validationErrors]);
const executeWithValidation = useCallback(
async <T>(apiCall: () => Promise<T>): Promise<T> => {
setIsSubmitting(true);
clearErrors();
try {
const result = await apiCall();
return result;
} catch (error: any) {
if (error.validationErrors && Array.isArray(error.validationErrors)) {
setValidationErrors(error.validationErrors);
// Show specific validation error messages from backend
error.validationErrors.forEach((validationError: ValidationError, index: number) => {
setTimeout(() => {
showNotification({
type: 'error',
title: 'Validierungsfehler',
message: `${validationError.field ? `${validationError.field}: ` : ''}${validationError.message}`
});
}, index * 500); // Stagger the notifications
});
} else {
// Show notification for other errors
showNotification({
type: 'error',
title: 'Fehler',
message: error.message || 'Ein unerwarteter Fehler ist aufgetreten'
});
}
throw error;
} finally {
setIsSubmitting(false);
}
},
[clearErrors, showNotification]
);
return {
validationErrors,
isSubmitting,
clearErrors,
getFieldError,
hasErrors,
executeWithValidation,
};
};

View File

@@ -1,3 +1,14 @@
/* Reset and base styles */
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
#root {
min-height: 100vh;
}
body {
margin: 0;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',

View File

@@ -1,19 +0,0 @@
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
const root = ReactDOM.createRoot(
document.getElementById('root') as HTMLElement
);
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);
// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();

10
frontend/src/main.tsx Normal file
View File

@@ -0,0 +1,10 @@
import React from 'react'
import ReactDOM from 'react-dom/client'
import App from './App.tsx'
import './index.css'
ReactDOM.createRoot(document.getElementById('root')!).render(
<React.StrictMode>
<App />
</React.StrictMode>,
)

View File

@@ -102,7 +102,7 @@ export const AVAILABILITY_PREFERENCES = {
} as const;
// Default availability for new employees (all shifts unavailable as level 3)
// UPDATED: Now uses shiftId instead of timeSlotId + dayOfWeek
// Now uses shiftId instead of timeSlotId + dayOfWeek
export function createDefaultAvailabilities(employeeId: string, planId: string, shiftIds: string[]): Omit<EmployeeAvailability, 'id'>[] {
const availabilities: Omit<EmployeeAvailability, 'id'>[] = [];

View File

@@ -18,12 +18,12 @@ function generateEmail(firstname: string, lastname: string): string {
return `${cleanFirstname}.${cleanLastname}@sp.de`;
}
// UPDATED: Validation for new employee model with employee types
// Validation for new employee model with employee types
export function validateEmployeeData(employee: CreateEmployeeRequest): string[] {
const errors: string[] = [];
if (employee.password?.length < 6) {
errors.push('Password must be at least 6 characters long');
if (employee.password?.length < 8) {
errors.push('Password must be at least 8 characters long');
}
if (!employee.firstname?.trim() || employee.firstname.trim().length < 2) {
@@ -71,7 +71,7 @@ export function generateEmployeeEmail(firstname: string, lastname: string): stri
return generateEmail(firstname, lastname);
}
// UPDATED: Business logic helpers for new employee types
// Business logic helpers for new employee types
export const isManager = (employee: Employee): boolean =>
employee.employeeType === 'manager';
@@ -90,7 +90,7 @@ export const isInternal = (employee: Employee): boolean =>
export const isExternal = (employee: Employee): boolean =>
employee.employeeType === 'guest';
// UPDATED: Trainee logic - now based on isTrainee field for personell type
// Trainee logic - now based on isTrainee field for personell type
export const isTrainee = (employee: Employee): boolean =>
employee.employeeType === 'personell' && employee.isTrainee;
@@ -107,7 +107,7 @@ export const isMaintenance = (employee: Employee): boolean =>
export const isUser = (employee: Employee): boolean =>
employee.roles?.includes('user') || false;
// UPDATED: Work alone permission - managers and experienced personell can work alone
// Work alone permission - managers and experienced personell can work alone
export const canEmployeeWorkAlone = (employee: Employee): boolean =>
employee.canWorkAlone && (isManager(employee) || isExperienced(employee));
@@ -134,7 +134,7 @@ export function validateAvailabilityData(availability: Omit<EmployeeAvailability
return errors;
}
// UPDATED: Helper to get employee type category
// Helper to get employee type category
export const getEmployeeCategory = (employee: Employee): 'internal' | 'external' => {
return isInternal(employee) ? 'internal' : 'external';
};

View File

@@ -78,7 +78,7 @@ export function calculateTotalRequiredEmployees(plan: ShiftPlan): number {
return plan.shifts.reduce((total, shift) => total + shift.requiredEmployees, 0);
}
// UPDATED: Get scheduled shift by date and time slot
// Get scheduled shift by date and time slot
export function getScheduledShiftByDateAndTime(
plan: ShiftPlan,
date: string,

View File

@@ -2,7 +2,7 @@
import { Employee } from './Employee.js';
import { ShiftPlan } from './ShiftPlan.js';
// Updated Availability interface to match new schema
// Availability interface to match
export interface Availability {
id: string;
employeeId: string;

View File

@@ -1,18 +1,21 @@
// frontend/src/pages/Auth/Login.tsx - KORRIGIERT
import React, { useState, useEffect } from 'react';
// frontend/src/pages/Auth/Login.tsx
import React, { useState, useEffect, useRef } from 'react';
import { useNavigate } from 'react-router-dom';
import { useAuth } from '../../contexts/AuthContext';
import { useNotification } from '../../contexts/NotificationContext';
import { employeeService } from '../../services/employeeService';
const Login: React.FC = () => {
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [showPassword, setShowPassword] = useState(false);
const [loading, setLoading] = useState(false);
const { login, user } = useAuth();
const { showNotification } = useNotification();
const navigate = useNavigate();
const holdTimeoutRef = useRef<NodeJS.Timeout | null>(null);
const passwordInputRef = useRef<HTMLInputElement>(null);
useEffect(() => {
if (user) {
console.log('✅ User already logged in, redirecting to dashboard');
@@ -20,6 +23,47 @@ const Login: React.FC = () => {
}
}, [user, navigate]);
// Cleanup timeouts on unmount
useEffect(() => {
return () => {
if (holdTimeoutRef.current) {
clearTimeout(holdTimeoutRef.current);
}
};
}, []);
const handleMouseDown = () => {
// Start timeout to show password after a brief delay (300ms)
holdTimeoutRef.current = setTimeout(() => {
setShowPassword(true);
}, 300);
};
const handleMouseUp = () => {
// Clear the timeout if user releases before delay completes
if (holdTimeoutRef.current) {
clearTimeout(holdTimeoutRef.current);
holdTimeoutRef.current = null;
}
// Always hide password on release
setShowPassword(false);
};
const handleTouchStart = (e: React.TouchEvent) => {
e.preventDefault(); // Prevent context menu on mobile
handleMouseDown();
};
const handleTouchEnd = (e: React.TouchEvent) => {
e.preventDefault();
handleMouseUp();
};
// Prevent context menu on long press
const handleContextMenu = (e: React.MouseEvent) => {
e.preventDefault();
};
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
setLoading(true);
@@ -35,7 +79,6 @@ const Login: React.FC = () => {
message: `Willkommen zurück!`
});
// Navigiere zur Startseite
navigate('/');
} catch (error: any) {
@@ -50,7 +93,6 @@ const Login: React.FC = () => {
}
};
// Wenn bereits eingeloggt, zeige Ladeanzeige
if (user) {
return (
<div style={{ textAlign: 'center', padding: '40px' }}>
@@ -77,7 +119,7 @@ const Login: React.FC = () => {
}}>
<h2 style={{ textAlign: 'center', marginBottom: '30px' }}>Anmeldung</h2>
<div style={{ marginBottom: '20px' }}>
<div style={{ marginBottom: '20px', width: '100%' }}>
<label style={{ display: 'block', marginBottom: '8px', fontWeight: 'bold' }}>
E-Mail
</label>
@@ -97,24 +139,57 @@ const Login: React.FC = () => {
/>
</div>
<div style={{ marginBottom: '30px' }}>
<div style={{ marginBottom: '30px', width: '100%' }}>
<label style={{ display: 'block', marginBottom: '8px', fontWeight: 'bold' }}>
Passwort
</label>
<div style={{ position: 'relative' }}>
<input
type="password"
ref={passwordInputRef}
type={showPassword ? 'text' : 'password'}
value={password}
onChange={(e) => setPassword(e.target.value)}
required
style={{
width: '100%',
padding: '10px',
paddingRight: '10px',
border: '1px solid #ddd',
borderRadius: '4px',
fontSize: '16px'
}}
placeholder="Ihr Passwort"
/>
<button
type="button"
onMouseDown={handleMouseDown}
onMouseUp={handleMouseUp}
onMouseLeave={handleMouseUp} // Handle mouse leaving while pressed
onTouchStart={handleTouchStart}
onTouchEnd={handleTouchEnd}
onTouchCancel={handleTouchEnd} // Handle touch cancellation
onContextMenu={handleContextMenu}
style={{
position: 'absolute',
right: '10px',
top: '50%',
transform: 'translateY(-50%)',
background: 'none',
border: 'none',
cursor: 'pointer',
padding: '1px',
borderRadius: '1px',
backgroundColor: showPassword ? '#e0e0e0' : 'transparent',
transition: 'background-color 0.2s',
userSelect: 'none',
WebkitUserSelect: 'none',
touchAction: 'manipulation'
}}
title="Gedrückt halten zum Anzeigen des Passworts"
>
{showPassword ? '👁' : '👁'}
</button>
</div>
</div>
<button
@@ -123,7 +198,7 @@ const Login: React.FC = () => {
style={{
width: '100%',
padding: '12px',
backgroundColor: loading ? '#ccc' : '#007bff',
backgroundColor: loading ? '#ccc' : '#51258f',
color: 'white',
border: 'none',
borderRadius: '4px',

View File

@@ -393,7 +393,7 @@ const Dashboard: React.FC = () => {
</div>
{/* Quick Actions - Nur für Admins/Instandhalter */}
{hasRole(['admin', 'instandhalter']) && (
{hasRole(['admin', 'maintenance']) && (
<div style={{ marginBottom: '30px' }}>
<h2 style={{ marginBottom: '15px', color: '#2c3e50' }}>Schnellaktionen</h2>
<div style={{
@@ -535,7 +535,7 @@ const Dashboard: React.FC = () => {
<div style={{ textAlign: 'center', padding: '20px', color: '#666' }}>
<div style={{ fontSize: '48px', marginBottom: '10px' }}>📅</div>
<div>Kein aktiver Schichtplan</div>
{hasRole(['admin', 'instandhalter']) && (
{hasRole(['admin', 'maintenance']) && (
<Link to="/shift-plans/new">
<button style={{
marginTop: '10px',
@@ -643,7 +643,7 @@ const Dashboard: React.FC = () => {
)}
{/* Letzte Schichtpläne (für Admins/Instandhalter) */}
{hasRole(['admin', 'instandhalter']) && (
{hasRole(['admin', 'maintenance']) && (
<div style={{
backgroundColor: 'white',
padding: '20px',

Some files were not shown because too many files have changed in this diff Show More