Compare commits
12 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0abc1c6b02 | ||
|
|
5bf4106db2 | ||
|
|
2432e9a17f | ||
|
|
e3f8f14f6a | ||
|
|
0376e71066 | ||
|
|
8ef2cbe68e | ||
|
|
b75bf9bb30 | ||
|
|
25d3d553ff | ||
|
|
c11565aaf8 | ||
|
|
2b7a89174a | ||
|
|
10464d34ff | ||
|
|
28097607b6 |
@@ -4,7 +4,7 @@ RUN apk add --no-cache libc6-compat openssl
|
|||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
|
|
||||||
COPY package.json package-lock.json* ./
|
COPY package.json package-lock.json* ./
|
||||||
RUN npm ci --ignore-scripts
|
RUN npm ci --ignore-scripts --legacy-peer-deps
|
||||||
|
|
||||||
# Stage 2: Builder
|
# Stage 2: Builder
|
||||||
FROM node:20-alpine AS builder
|
FROM node:20-alpine AS builder
|
||||||
@@ -46,7 +46,7 @@ COPY --from=builder /app/node_modules/.bin/prisma ./node_modules/.bin/prisma
|
|||||||
COPY --from=builder /app/node_modules/bcryptjs ./node_modules/bcryptjs
|
COPY --from=builder /app/node_modules/bcryptjs ./node_modules/bcryptjs
|
||||||
COPY --from=builder /app/node_modules/stripe ./node_modules/stripe
|
COPY --from=builder /app/node_modules/stripe ./node_modules/stripe
|
||||||
COPY --from=builder /app/package.json ./package.json
|
COPY --from=builder /app/package.json ./package.json
|
||||||
RUN npm install --omit=dev socket.io@4.7.4 @react-pdf/renderer@3.4.2 qrcode@1.5.3 --no-save
|
RUN npm install --omit=dev --legacy-peer-deps socket.io@4.7.4 @react-pdf/renderer@4.3.2 qrcode@1.5.4 --no-save
|
||||||
COPY server-custom.js ./server-custom.js
|
COPY server-custom.js ./server-custom.js
|
||||||
COPY docker-entrypoint.sh ./docker-entrypoint.sh
|
COPY docker-entrypoint.sh ./docker-entrypoint.sh
|
||||||
|
|
||||||
|
|||||||
@@ -24,7 +24,7 @@ services:
|
|||||||
- USER_UID=1000
|
- USER_UID=1000
|
||||||
- USER_GID=1000
|
- USER_GID=1000
|
||||||
- GITEA__database__DB_TYPE=sqlite3
|
- GITEA__database__DB_TYPE=sqlite3
|
||||||
- GITEA__server__ROOT_URL=http://192.168.1.183:3100
|
- GITEA__server__ROOT_URL=https://git.purepixel.ch
|
||||||
- GITEA__server__HTTP_PORT=3000
|
- GITEA__server__HTTP_PORT=3000
|
||||||
- GITEA__server__LFS_START_SERVER=true
|
- GITEA__server__LFS_START_SERVER=true
|
||||||
volumes:
|
volumes:
|
||||||
@@ -43,3 +43,4 @@ volumes:
|
|||||||
networks:
|
networks:
|
||||||
lageplan_lageplan-net:
|
lageplan_lageplan-net:
|
||||||
external: true
|
external: true
|
||||||
|
|
||||||
|
|||||||
@@ -77,7 +77,7 @@ services:
|
|||||||
|
|
||||||
# ─── Lageplan Web App ──────────────────────
|
# ─── Lageplan Web App ──────────────────────
|
||||||
web:
|
web:
|
||||||
image: lageplan-web:latest
|
image: 192.168.1.183:3100/adminpepe/lageplan:latest
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
environment:
|
environment:
|
||||||
DATABASE_URL: postgresql://${POSTGRES_USER:-lageplan}:${POSTGRES_PASSWORD:-lageplan_secret}@db:5432/${POSTGRES_DB:-lageplan}
|
DATABASE_URL: postgresql://${POSTGRES_USER:-lageplan}:${POSTGRES_PASSWORD:-lageplan_secret}@db:5432/${POSTGRES_DB:-lageplan}
|
||||||
|
|||||||
@@ -31,15 +31,27 @@ const nextConfig = {
|
|||||||
key: 'Cross-Origin-Opener-Policy',
|
key: 'Cross-Origin-Opener-Policy',
|
||||||
value: 'same-origin',
|
value: 'same-origin',
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
key: 'Strict-Transport-Security',
|
||||||
|
value: 'max-age=63072000; includeSubDomains; preload',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'X-DNS-Prefetch-Control',
|
||||||
|
value: 'on',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'X-XSS-Protection',
|
||||||
|
value: '1; mode=block',
|
||||||
|
},
|
||||||
{
|
{
|
||||||
key: 'Content-Security-Policy',
|
key: 'Content-Security-Policy',
|
||||||
value: [
|
value: [
|
||||||
"default-src 'self'",
|
"default-src 'self'",
|
||||||
"script-src 'self' 'unsafe-inline' 'unsafe-eval'",
|
"script-src 'self' 'unsafe-inline' 'unsafe-eval' blob:",
|
||||||
"style-src 'self' 'unsafe-inline'",
|
"style-src 'self' 'unsafe-inline'",
|
||||||
"img-src 'self' data: blob: https://*.tile.openstreetmap.org https://api.maptiler.com http://localhost:9000 http://minio:9000",
|
"img-src 'self' data: blob: https://*.tile.openstreetmap.org https://api.maptiler.com https://server.arcgisonline.com https://wmts.geo.admin.ch https://wmts0.geo.admin.ch https://wmts1.geo.admin.ch https://wmts2.geo.admin.ch https://wmts3.geo.admin.ch https://wmts4.geo.admin.ch http://localhost:9000 http://minio:9000",
|
||||||
"font-src 'self' data:",
|
"font-src 'self' data:",
|
||||||
"connect-src 'self' ws: wss: https://api.maptiler.com https://*.tile.openstreetmap.org https://api.open-meteo.com",
|
"connect-src 'self' ws: wss: https://api.maptiler.com https://*.tile.openstreetmap.org https://api.open-meteo.com https://server.arcgisonline.com https://wmts.geo.admin.ch https://wmts0.geo.admin.ch https://wmts1.geo.admin.ch https://wmts2.geo.admin.ch https://wmts3.geo.admin.ch https://wmts4.geo.admin.ch",
|
||||||
"frame-ancestors 'self'",
|
"frame-ancestors 'self'",
|
||||||
"base-uri 'self'",
|
"base-uri 'self'",
|
||||||
"form-action 'self'",
|
"form-action 'self'",
|
||||||
|
|||||||
362
package-lock.json
generated
362
package-lock.json
generated
@@ -1,12 +1,12 @@
|
|||||||
{
|
{
|
||||||
"name": "lageplan",
|
"name": "lageplan",
|
||||||
"version": "1.0.0",
|
"version": "1.0.1",
|
||||||
"lockfileVersion": 3,
|
"lockfileVersion": 3,
|
||||||
"requires": true,
|
"requires": true,
|
||||||
"packages": {
|
"packages": {
|
||||||
"": {
|
"": {
|
||||||
"name": "lageplan",
|
"name": "lageplan",
|
||||||
"version": "1.0.0",
|
"version": "1.0.1",
|
||||||
"hasInstallScript": true,
|
"hasInstallScript": true,
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@dnd-kit/core": "^6.1.0",
|
"@dnd-kit/core": "^6.1.0",
|
||||||
@@ -26,7 +26,7 @@
|
|||||||
"@radix-ui/react-tabs": "^1.1.0",
|
"@radix-ui/react-tabs": "^1.1.0",
|
||||||
"@radix-ui/react-toast": "^1.2.0",
|
"@radix-ui/react-toast": "^1.2.0",
|
||||||
"@radix-ui/react-tooltip": "^1.1.0",
|
"@radix-ui/react-tooltip": "^1.1.0",
|
||||||
"@react-pdf/renderer": "^3.4.4",
|
"@react-pdf/renderer": "^4.3.2",
|
||||||
"bcryptjs": "^2.4.3",
|
"bcryptjs": "^2.4.3",
|
||||||
"class-variance-authority": "^0.7.0",
|
"class-variance-authority": "^0.7.0",
|
||||||
"clsx": "^2.1.0",
|
"clsx": "^2.1.0",
|
||||||
@@ -2878,176 +2878,12 @@
|
|||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
"node_modules/@react-pdf/fns": {
|
"node_modules/@react-pdf/fns": {
|
||||||
"version": "2.2.1",
|
|
||||||
"resolved": "https://registry.npmjs.org/@react-pdf/fns/-/fns-2.2.1.tgz",
|
|
||||||
"integrity": "sha512-s78aDg0vDYaijU5lLOCsUD+qinQbfOvcNeaoX9AiE7+kZzzCo6B/nX+l48cmt9OosJmvZvE9DWR9cLhrhOi2pA==",
|
|
||||||
"license": "MIT",
|
|
||||||
"dependencies": {
|
|
||||||
"@babel/runtime": "^7.20.13"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/@react-pdf/font": {
|
|
||||||
"version": "2.5.2",
|
|
||||||
"resolved": "https://registry.npmjs.org/@react-pdf/font/-/font-2.5.2.tgz",
|
|
||||||
"integrity": "sha512-Ud0EfZ2FwrbvwAWx8nz+KKLmiqACCH9a/N/xNDOja0e/YgSnqTpuyHegFBgIMKjuBtO5dNvkb4dXkxAhGe/ayw==",
|
|
||||||
"license": "MIT",
|
|
||||||
"dependencies": {
|
|
||||||
"@babel/runtime": "^7.20.13",
|
|
||||||
"@react-pdf/types": "^2.6.0",
|
|
||||||
"cross-fetch": "^3.1.5",
|
|
||||||
"fontkit": "^2.0.2",
|
|
||||||
"is-url": "^1.2.4"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/@react-pdf/image": {
|
|
||||||
"version": "2.3.6",
|
|
||||||
"resolved": "https://registry.npmjs.org/@react-pdf/image/-/image-2.3.6.tgz",
|
|
||||||
"integrity": "sha512-7iZDYZrZlJqNzS6huNl2XdMcLFUo68e6mOdzQeJ63d5eApdthhSHBnkGzHfLhH5t8DCpZNtClmklzuLL63ADfw==",
|
|
||||||
"license": "MIT",
|
|
||||||
"dependencies": {
|
|
||||||
"@babel/runtime": "^7.20.13",
|
|
||||||
"@react-pdf/png-js": "^2.3.1",
|
|
||||||
"cross-fetch": "^3.1.5",
|
|
||||||
"jay-peg": "^1.0.2"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/@react-pdf/layout": {
|
|
||||||
"version": "3.13.0",
|
|
||||||
"resolved": "https://registry.npmjs.org/@react-pdf/layout/-/layout-3.13.0.tgz",
|
|
||||||
"integrity": "sha512-lpPj/EJYHFOc0ALiJwLP09H28B4ADyvTjxOf67xTF+qkWd+dq1vg7dw3wnYESPnWk5T9NN+HlUenJqdYEY9AvA==",
|
|
||||||
"license": "MIT",
|
|
||||||
"dependencies": {
|
|
||||||
"@babel/runtime": "^7.20.13",
|
|
||||||
"@react-pdf/fns": "2.2.1",
|
|
||||||
"@react-pdf/image": "^2.3.6",
|
|
||||||
"@react-pdf/pdfkit": "^3.2.0",
|
|
||||||
"@react-pdf/primitives": "^3.1.1",
|
|
||||||
"@react-pdf/stylesheet": "^4.3.0",
|
|
||||||
"@react-pdf/textkit": "^4.4.1",
|
|
||||||
"@react-pdf/types": "^2.6.0",
|
|
||||||
"cross-fetch": "^3.1.5",
|
|
||||||
"emoji-regex": "^10.3.0",
|
|
||||||
"queue": "^6.0.1",
|
|
||||||
"yoga-layout": "^2.0.1"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/@react-pdf/pdfkit": {
|
|
||||||
"version": "3.2.0",
|
|
||||||
"resolved": "https://registry.npmjs.org/@react-pdf/pdfkit/-/pdfkit-3.2.0.tgz",
|
|
||||||
"integrity": "sha512-OBfCcnTC6RpD9uv9L2woF60Zj1uQxhLFzTBXTdcYE9URzPE/zqXIyzpXEA4Vf3TFbvBCgFE2RzJ2ZUS0asq7yA==",
|
|
||||||
"license": "MIT",
|
|
||||||
"dependencies": {
|
|
||||||
"@babel/runtime": "^7.20.13",
|
|
||||||
"@react-pdf/png-js": "^2.3.1",
|
|
||||||
"browserify-zlib": "^0.2.0",
|
|
||||||
"crypto-js": "^4.2.0",
|
|
||||||
"fontkit": "^2.0.2",
|
|
||||||
"jay-peg": "^1.0.2",
|
|
||||||
"vite-compatible-readable-stream": "^3.6.1"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/@react-pdf/png-js": {
|
|
||||||
"version": "2.3.1",
|
|
||||||
"resolved": "https://registry.npmjs.org/@react-pdf/png-js/-/png-js-2.3.1.tgz",
|
|
||||||
"integrity": "sha512-pEZ18I4t1vAUS4lmhvXPmXYP4PHeblpWP/pAlMMRkEyP7tdAeHUN7taQl9sf9OPq7YITMY3lWpYpJU6t4CZgZg==",
|
|
||||||
"license": "MIT",
|
|
||||||
"dependencies": {
|
|
||||||
"browserify-zlib": "^0.2.0"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/@react-pdf/primitives": {
|
|
||||||
"version": "3.1.1",
|
|
||||||
"resolved": "https://registry.npmjs.org/@react-pdf/primitives/-/primitives-3.1.1.tgz",
|
|
||||||
"integrity": "sha512-miwjxLwTnO3IjoqkTVeTI+9CdyDggwekmSLhVCw+a/7FoQc+gF3J2dSKwsHvAcVFM0gvU8mzCeTofgw0zPDq0w==",
|
|
||||||
"license": "MIT"
|
|
||||||
},
|
|
||||||
"node_modules/@react-pdf/render": {
|
|
||||||
"version": "3.5.0",
|
|
||||||
"resolved": "https://registry.npmjs.org/@react-pdf/render/-/render-3.5.0.tgz",
|
|
||||||
"integrity": "sha512-gFOpnyqCgJ6l7VzfJz6rG1i2S7iVSD8bUHDjPW9Mze8TmyksHzN2zBH3y7NbsQOw1wU6hN4NhRmslrsn+BRDPA==",
|
|
||||||
"license": "MIT",
|
|
||||||
"dependencies": {
|
|
||||||
"@babel/runtime": "^7.20.13",
|
|
||||||
"@react-pdf/fns": "2.2.1",
|
|
||||||
"@react-pdf/primitives": "^3.1.1",
|
|
||||||
"@react-pdf/textkit": "^4.4.1",
|
|
||||||
"@react-pdf/types": "^2.6.0",
|
|
||||||
"abs-svg-path": "^0.1.1",
|
|
||||||
"color-string": "^1.9.1",
|
|
||||||
"normalize-svg-path": "^1.1.0",
|
|
||||||
"parse-svg-path": "^0.1.2",
|
|
||||||
"svg-arc-to-cubic-bezier": "^3.2.0"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/@react-pdf/renderer": {
|
|
||||||
"version": "3.4.5",
|
|
||||||
"resolved": "https://registry.npmjs.org/@react-pdf/renderer/-/renderer-3.4.5.tgz",
|
|
||||||
"integrity": "sha512-O1N8q45bTs7YuC+x9afJSKQWDYQy2RjoCxlxEGdbCwP+WD5G6dWRUWXlc8F0TtzU3uFglYMmDab2YhXTmnVN9g==",
|
|
||||||
"license": "MIT",
|
|
||||||
"dependencies": {
|
|
||||||
"@babel/runtime": "^7.20.13",
|
|
||||||
"@react-pdf/font": "^2.5.2",
|
|
||||||
"@react-pdf/layout": "^3.13.0",
|
|
||||||
"@react-pdf/pdfkit": "^3.2.0",
|
|
||||||
"@react-pdf/primitives": "^3.1.1",
|
|
||||||
"@react-pdf/render": "^3.5.0",
|
|
||||||
"@react-pdf/types": "^2.6.0",
|
|
||||||
"events": "^3.3.0",
|
|
||||||
"object-assign": "^4.1.1",
|
|
||||||
"prop-types": "^15.6.2",
|
|
||||||
"queue": "^6.0.1",
|
|
||||||
"scheduler": "^0.17.0"
|
|
||||||
},
|
|
||||||
"peerDependencies": {
|
|
||||||
"react": "^16.8.0 || ^17.0.0 || ^18.0.0"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/@react-pdf/stylesheet": {
|
|
||||||
"version": "4.3.0",
|
|
||||||
"resolved": "https://registry.npmjs.org/@react-pdf/stylesheet/-/stylesheet-4.3.0.tgz",
|
|
||||||
"integrity": "sha512-x7IVZOqRrUum9quuDeFXBveXwBht+z/6B0M+z4a4XjfSg1vZVvzoTl07Oa1yvQ/4yIC5yIkG2TSMWeKnDB+hrw==",
|
|
||||||
"license": "MIT",
|
|
||||||
"dependencies": {
|
|
||||||
"@babel/runtime": "^7.20.13",
|
|
||||||
"@react-pdf/fns": "2.2.1",
|
|
||||||
"@react-pdf/types": "^2.6.0",
|
|
||||||
"color-string": "^1.9.1",
|
|
||||||
"hsl-to-hex": "^1.0.0",
|
|
||||||
"media-engine": "^1.0.3",
|
|
||||||
"postcss-value-parser": "^4.1.0"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/@react-pdf/textkit": {
|
|
||||||
"version": "4.4.1",
|
|
||||||
"resolved": "https://registry.npmjs.org/@react-pdf/textkit/-/textkit-4.4.1.tgz",
|
|
||||||
"integrity": "sha512-Jl9wdTqIvJ5pX+vAGz0EOhP7ut5Two9H6CzTKo/YYPeD79cM2yTXF3JzTERBC28y7LR0Waq9D2LHQjI+b/EYUQ==",
|
|
||||||
"license": "MIT",
|
|
||||||
"dependencies": {
|
|
||||||
"@babel/runtime": "^7.20.13",
|
|
||||||
"@react-pdf/fns": "2.2.1",
|
|
||||||
"bidi-js": "^1.0.2",
|
|
||||||
"hyphen": "^1.6.4",
|
|
||||||
"unicode-properties": "^1.4.1"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/@react-pdf/types": {
|
|
||||||
"version": "2.9.2",
|
|
||||||
"resolved": "https://registry.npmjs.org/@react-pdf/types/-/types-2.9.2.tgz",
|
|
||||||
"integrity": "sha512-dufvpKId9OajLLbgn9q7VLUmyo1Jf+iyGk2ZHmCL8nIDtL8N1Ejh9TH7+pXXrR0tdie1nmnEb5Bz9U7g4hI4/g==",
|
|
||||||
"license": "MIT",
|
|
||||||
"dependencies": {
|
|
||||||
"@react-pdf/font": "^4.0.4",
|
|
||||||
"@react-pdf/primitives": "^4.1.1",
|
|
||||||
"@react-pdf/stylesheet": "^6.1.2"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/@react-pdf/types/node_modules/@react-pdf/fns": {
|
|
||||||
"version": "3.1.2",
|
"version": "3.1.2",
|
||||||
"resolved": "https://registry.npmjs.org/@react-pdf/fns/-/fns-3.1.2.tgz",
|
"resolved": "https://registry.npmjs.org/@react-pdf/fns/-/fns-3.1.2.tgz",
|
||||||
"integrity": "sha512-qTKGUf0iAMGg2+OsUcp9ffKnKi41RukM/zYIWMDJ4hRVYSr89Q7e3wSDW/Koqx3ea3Uy/z3h2y3wPX6Bdfxk6g==",
|
"integrity": "sha512-qTKGUf0iAMGg2+OsUcp9ffKnKi41RukM/zYIWMDJ4hRVYSr89Q7e3wSDW/Koqx3ea3Uy/z3h2y3wPX6Bdfxk6g==",
|
||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
"node_modules/@react-pdf/types/node_modules/@react-pdf/font": {
|
"node_modules/@react-pdf/font": {
|
||||||
"version": "4.0.4",
|
"version": "4.0.4",
|
||||||
"resolved": "https://registry.npmjs.org/@react-pdf/font/-/font-4.0.4.tgz",
|
"resolved": "https://registry.npmjs.org/@react-pdf/font/-/font-4.0.4.tgz",
|
||||||
"integrity": "sha512-8YtgGtL511txIEc9AjiilpZ7yjid8uCd8OGUl6jaL3LIHnrToUupSN4IzsMQpVTCMYiDLFnDNQzpZsOYtRS/Pg==",
|
"integrity": "sha512-8YtgGtL511txIEc9AjiilpZ7yjid8uCd8OGUl6jaL3LIHnrToUupSN4IzsMQpVTCMYiDLFnDNQzpZsOYtRS/Pg==",
|
||||||
@@ -3059,7 +2895,34 @@
|
|||||||
"is-url": "^1.2.4"
|
"is-url": "^1.2.4"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@react-pdf/types/node_modules/@react-pdf/pdfkit": {
|
"node_modules/@react-pdf/image": {
|
||||||
|
"version": "3.0.4",
|
||||||
|
"resolved": "https://registry.npmjs.org/@react-pdf/image/-/image-3.0.4.tgz",
|
||||||
|
"integrity": "sha512-z0ogVQE0bKqgXQ5smgzIU857rLV7bMgVdrYsu3UfXDDLSzI7QPvzf6MFTFllX6Dx2rcsF13E01dqKPtJEM799g==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"@react-pdf/png-js": "^3.0.0",
|
||||||
|
"jay-peg": "^1.1.1"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@react-pdf/layout": {
|
||||||
|
"version": "4.4.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/@react-pdf/layout/-/layout-4.4.2.tgz",
|
||||||
|
"integrity": "sha512-gNu2oh8MiGR+NJZYTJ4c4q0nWCESBI6rKFiodVhE7OeVAjtzZzd6l65wsN7HXdWJqOZD3ttD97iE+tf5SOd/Yg==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"@react-pdf/fns": "3.1.2",
|
||||||
|
"@react-pdf/image": "^3.0.4",
|
||||||
|
"@react-pdf/primitives": "^4.1.1",
|
||||||
|
"@react-pdf/stylesheet": "^6.1.2",
|
||||||
|
"@react-pdf/textkit": "^6.1.0",
|
||||||
|
"@react-pdf/types": "^2.9.2",
|
||||||
|
"emoji-regex-xs": "^1.0.0",
|
||||||
|
"queue": "^6.0.1",
|
||||||
|
"yoga-layout": "^3.2.1"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@react-pdf/pdfkit": {
|
||||||
"version": "4.1.0",
|
"version": "4.1.0",
|
||||||
"resolved": "https://registry.npmjs.org/@react-pdf/pdfkit/-/pdfkit-4.1.0.tgz",
|
"resolved": "https://registry.npmjs.org/@react-pdf/pdfkit/-/pdfkit-4.1.0.tgz",
|
||||||
"integrity": "sha512-Wm/IOAv0h/U5Ra94c/PltFJGcpTUd/fwVMVeFD6X9tTTPCttIwg0teRG1Lqq617J8K4W7jpL/B0HTH0mjp3QpQ==",
|
"integrity": "sha512-Wm/IOAv0h/U5Ra94c/PltFJGcpTUd/fwVMVeFD6X9tTTPCttIwg0teRG1Lqq617J8K4W7jpL/B0HTH0mjp3QpQ==",
|
||||||
@@ -3075,7 +2938,7 @@
|
|||||||
"vite-compatible-readable-stream": "^3.6.1"
|
"vite-compatible-readable-stream": "^3.6.1"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@react-pdf/types/node_modules/@react-pdf/png-js": {
|
"node_modules/@react-pdf/png-js": {
|
||||||
"version": "3.0.0",
|
"version": "3.0.0",
|
||||||
"resolved": "https://registry.npmjs.org/@react-pdf/png-js/-/png-js-3.0.0.tgz",
|
"resolved": "https://registry.npmjs.org/@react-pdf/png-js/-/png-js-3.0.0.tgz",
|
||||||
"integrity": "sha512-eSJnEItZ37WPt6Qv5pncQDxLJRK15eaRwPT+gZoujP548CodenOVp49GST8XJvKMFt9YqIBzGBV/j9AgrOQzVA==",
|
"integrity": "sha512-eSJnEItZ37WPt6Qv5pncQDxLJRK15eaRwPT+gZoujP548CodenOVp49GST8XJvKMFt9YqIBzGBV/j9AgrOQzVA==",
|
||||||
@@ -3084,13 +2947,68 @@
|
|||||||
"browserify-zlib": "^0.2.0"
|
"browserify-zlib": "^0.2.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@react-pdf/types/node_modules/@react-pdf/primitives": {
|
"node_modules/@react-pdf/primitives": {
|
||||||
"version": "4.1.1",
|
"version": "4.1.1",
|
||||||
"resolved": "https://registry.npmjs.org/@react-pdf/primitives/-/primitives-4.1.1.tgz",
|
"resolved": "https://registry.npmjs.org/@react-pdf/primitives/-/primitives-4.1.1.tgz",
|
||||||
"integrity": "sha512-IuhxYls1luJb7NUWy6q5avb1XrNaVj9bTNI40U9qGRuS6n7Hje/8H8Qi99Z9UKFV74bBP3DOf3L1wV2qZVgVrQ==",
|
"integrity": "sha512-IuhxYls1luJb7NUWy6q5avb1XrNaVj9bTNI40U9qGRuS6n7Hje/8H8Qi99Z9UKFV74bBP3DOf3L1wV2qZVgVrQ==",
|
||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
"node_modules/@react-pdf/types/node_modules/@react-pdf/stylesheet": {
|
"node_modules/@react-pdf/reconciler": {
|
||||||
|
"version": "2.0.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/@react-pdf/reconciler/-/reconciler-2.0.0.tgz",
|
||||||
|
"integrity": "sha512-7zaPRujpbHSmCpIrZ+b9HSTJHthcVZzX0Wx7RzvQGsGBUbHP4p6s5itXrAIOuQuPvDepoHGNOvf6xUuMVvdoyw==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"object-assign": "^4.1.1",
|
||||||
|
"scheduler": "0.25.0-rc-603e6108-20241029"
|
||||||
|
},
|
||||||
|
"peerDependencies": {
|
||||||
|
"react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@react-pdf/render": {
|
||||||
|
"version": "4.3.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/@react-pdf/render/-/render-4.3.2.tgz",
|
||||||
|
"integrity": "sha512-el5KYM1sH/PKcO4tRCIm8/AIEmhtraaONbwCrBhFdehoGv6JtgnXiMxHGAvZbI5kEg051GbyP+XIU6f6YbOu6Q==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"@babel/runtime": "^7.20.13",
|
||||||
|
"@react-pdf/fns": "3.1.2",
|
||||||
|
"@react-pdf/primitives": "^4.1.1",
|
||||||
|
"@react-pdf/textkit": "^6.1.0",
|
||||||
|
"@react-pdf/types": "^2.9.2",
|
||||||
|
"abs-svg-path": "^0.1.1",
|
||||||
|
"color-string": "^1.9.1",
|
||||||
|
"normalize-svg-path": "^1.1.0",
|
||||||
|
"parse-svg-path": "^0.1.2",
|
||||||
|
"svg-arc-to-cubic-bezier": "^3.2.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@react-pdf/renderer": {
|
||||||
|
"version": "4.3.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/@react-pdf/renderer/-/renderer-4.3.2.tgz",
|
||||||
|
"integrity": "sha512-EhPkj35gO9rXIyyx29W3j3axemvVY5RigMmlK4/6Ku0pXB8z9PEE/sz4ZBOShu2uot6V4xiCR3aG+t9IjJJlBQ==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"@babel/runtime": "^7.20.13",
|
||||||
|
"@react-pdf/fns": "3.1.2",
|
||||||
|
"@react-pdf/font": "^4.0.4",
|
||||||
|
"@react-pdf/layout": "^4.4.2",
|
||||||
|
"@react-pdf/pdfkit": "^4.1.0",
|
||||||
|
"@react-pdf/primitives": "^4.1.1",
|
||||||
|
"@react-pdf/reconciler": "^2.0.0",
|
||||||
|
"@react-pdf/render": "^4.3.2",
|
||||||
|
"@react-pdf/types": "^2.9.2",
|
||||||
|
"events": "^3.3.0",
|
||||||
|
"object-assign": "^4.1.1",
|
||||||
|
"prop-types": "^15.6.2",
|
||||||
|
"queue": "^6.0.1"
|
||||||
|
},
|
||||||
|
"peerDependencies": {
|
||||||
|
"react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@react-pdf/stylesheet": {
|
||||||
"version": "6.1.2",
|
"version": "6.1.2",
|
||||||
"resolved": "https://registry.npmjs.org/@react-pdf/stylesheet/-/stylesheet-6.1.2.tgz",
|
"resolved": "https://registry.npmjs.org/@react-pdf/stylesheet/-/stylesheet-6.1.2.tgz",
|
||||||
"integrity": "sha512-E3ftGRYUQGKiN3JOgtGsLDo0hGekA6dmkmi/MYACytmPTKxQRBSO3126MebmCq+t1rgU9uRlREIEawJ+8nzSbw==",
|
"integrity": "sha512-E3ftGRYUQGKiN3JOgtGsLDo0hGekA6dmkmi/MYACytmPTKxQRBSO3126MebmCq+t1rgU9uRlREIEawJ+8nzSbw==",
|
||||||
@@ -3104,6 +3022,29 @@
|
|||||||
"postcss-value-parser": "^4.1.0"
|
"postcss-value-parser": "^4.1.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/@react-pdf/textkit": {
|
||||||
|
"version": "6.1.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/@react-pdf/textkit/-/textkit-6.1.0.tgz",
|
||||||
|
"integrity": "sha512-sFlzDC9CDFrJsnL3B/+NHrk9+Advqk7iJZIStiYQDdskbow8GF/AGYrpIk+vWSnh35YxaGbHkqXq53XOxnyrjQ==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"@react-pdf/fns": "3.1.2",
|
||||||
|
"bidi-js": "^1.0.2",
|
||||||
|
"hyphen": "^1.6.4",
|
||||||
|
"unicode-properties": "^1.4.1"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@react-pdf/types": {
|
||||||
|
"version": "2.9.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/@react-pdf/types/-/types-2.9.2.tgz",
|
||||||
|
"integrity": "sha512-dufvpKId9OajLLbgn9q7VLUmyo1Jf+iyGk2ZHmCL8nIDtL8N1Ejh9TH7+pXXrR0tdie1nmnEb5Bz9U7g4hI4/g==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"@react-pdf/font": "^4.0.4",
|
||||||
|
"@react-pdf/primitives": "^4.1.1",
|
||||||
|
"@react-pdf/stylesheet": "^6.1.2"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/@rtsao/scc": {
|
"node_modules/@rtsao/scc": {
|
||||||
"version": "1.1.0",
|
"version": "1.1.0",
|
||||||
"resolved": "https://registry.npmjs.org/@rtsao/scc/-/scc-1.1.0.tgz",
|
"resolved": "https://registry.npmjs.org/@rtsao/scc/-/scc-1.1.0.tgz",
|
||||||
@@ -4753,15 +4694,6 @@
|
|||||||
"url": "https://opencollective.com/express"
|
"url": "https://opencollective.com/express"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/cross-fetch": {
|
|
||||||
"version": "3.2.0",
|
|
||||||
"resolved": "https://registry.npmjs.org/cross-fetch/-/cross-fetch-3.2.0.tgz",
|
|
||||||
"integrity": "sha512-Q+xVJLoGOeIMXZmbUK4HYk+69cQH6LudR0Vu/pRm2YlU/hDV9CiS0gKUMaWY5f2NeUH9C1nV3bsTlCo0FsTV1Q==",
|
|
||||||
"license": "MIT",
|
|
||||||
"dependencies": {
|
|
||||||
"node-fetch": "^2.7.0"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/cross-spawn": {
|
"node_modules/cross-spawn": {
|
||||||
"version": "7.0.6",
|
"version": "7.0.6",
|
||||||
"resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz",
|
"resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz",
|
||||||
@@ -5082,10 +5014,10 @@
|
|||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "ISC"
|
"license": "ISC"
|
||||||
},
|
},
|
||||||
"node_modules/emoji-regex": {
|
"node_modules/emoji-regex-xs": {
|
||||||
"version": "10.6.0",
|
"version": "1.0.0",
|
||||||
"resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-10.6.0.tgz",
|
"resolved": "https://registry.npmjs.org/emoji-regex-xs/-/emoji-regex-xs-1.0.0.tgz",
|
||||||
"integrity": "sha512-toUI84YS5YmxW219erniWD0CIVOo46xGKColeNQRgOzDorgBi1v4D71/OFzgD9GO2UGKIv1C3Sp8DAn0+j5w7A==",
|
"integrity": "sha512-LRlerrMYoIDrT6jgpeZ2YYl/L8EulRTt5hQcYjy5AInh7HWXKimpqx68aknBFpGL2+/IcogTcaydJEgaTmOpDg==",
|
||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
"node_modules/engine.io": {
|
"node_modules/engine.io": {
|
||||||
@@ -7747,26 +7679,6 @@
|
|||||||
"semver": "bin/semver.js"
|
"semver": "bin/semver.js"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/node-fetch": {
|
|
||||||
"version": "2.7.0",
|
|
||||||
"resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.7.0.tgz",
|
|
||||||
"integrity": "sha512-c4FRfUm/dbcWZ7U+1Wq0AwCyFL+3nt2bEw05wfxSz+DWpWsitgmSgYmy2dQdWyKC1694ELPqMs/YzUSNozLt8A==",
|
|
||||||
"license": "MIT",
|
|
||||||
"dependencies": {
|
|
||||||
"whatwg-url": "^5.0.0"
|
|
||||||
},
|
|
||||||
"engines": {
|
|
||||||
"node": "4.x || >=6.0.0"
|
|
||||||
},
|
|
||||||
"peerDependencies": {
|
|
||||||
"encoding": "^0.1.0"
|
|
||||||
},
|
|
||||||
"peerDependenciesMeta": {
|
|
||||||
"encoding": {
|
|
||||||
"optional": true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/node-releases": {
|
"node_modules/node-releases": {
|
||||||
"version": "2.0.27",
|
"version": "2.0.27",
|
||||||
"resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.27.tgz",
|
"resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.27.tgz",
|
||||||
@@ -9043,14 +8955,10 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/scheduler": {
|
"node_modules/scheduler": {
|
||||||
"version": "0.17.0",
|
"version": "0.25.0-rc-603e6108-20241029",
|
||||||
"resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.17.0.tgz",
|
"resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.25.0-rc-603e6108-20241029.tgz",
|
||||||
"integrity": "sha512-7rro8Io3tnCPuY4la/NuI5F2yfESpnfZyT6TtkXnSWVkcu0BCDJ+8gk5ozUaFaxpIyNuWAPXrH0yFcSi28fnDA==",
|
"integrity": "sha512-pFwF6H1XrSdYYNLfOcGlM28/j8CGLu8IvdrxqhjWULe2bPcKiKW4CV+OWqR/9fT52mywx65l7ysNkjLKBda7eA==",
|
||||||
"license": "MIT",
|
"license": "MIT"
|
||||||
"dependencies": {
|
|
||||||
"loose-envify": "^1.1.0",
|
|
||||||
"object-assign": "^4.1.1"
|
|
||||||
}
|
|
||||||
},
|
},
|
||||||
"node_modules/selecto": {
|
"node_modules/selecto": {
|
||||||
"version": "1.26.3",
|
"version": "1.26.3",
|
||||||
@@ -9897,12 +9805,6 @@
|
|||||||
"node": ">=8.0"
|
"node": ">=8.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/tr46": {
|
|
||||||
"version": "0.0.3",
|
|
||||||
"resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz",
|
|
||||||
"integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==",
|
|
||||||
"license": "MIT"
|
|
||||||
},
|
|
||||||
"node_modules/ts-api-utils": {
|
"node_modules/ts-api-utils": {
|
||||||
"version": "2.4.0",
|
"version": "2.4.0",
|
||||||
"resolved": "https://registry.npmjs.org/ts-api-utils/-/ts-api-utils-2.4.0.tgz",
|
"resolved": "https://registry.npmjs.org/ts-api-utils/-/ts-api-utils-2.4.0.tgz",
|
||||||
@@ -10346,22 +10248,6 @@
|
|||||||
"@zxing/text-encoding": "0.9.0"
|
"@zxing/text-encoding": "0.9.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/webidl-conversions": {
|
|
||||||
"version": "3.0.1",
|
|
||||||
"resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz",
|
|
||||||
"integrity": "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==",
|
|
||||||
"license": "BSD-2-Clause"
|
|
||||||
},
|
|
||||||
"node_modules/whatwg-url": {
|
|
||||||
"version": "5.0.0",
|
|
||||||
"resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz",
|
|
||||||
"integrity": "sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==",
|
|
||||||
"license": "MIT",
|
|
||||||
"dependencies": {
|
|
||||||
"tr46": "~0.0.3",
|
|
||||||
"webidl-conversions": "^3.0.0"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/which": {
|
"node_modules/which": {
|
||||||
"version": "2.0.2",
|
"version": "2.0.2",
|
||||||
"resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz",
|
"resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz",
|
||||||
@@ -10667,9 +10553,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/yoga-layout": {
|
"node_modules/yoga-layout": {
|
||||||
"version": "2.0.1",
|
"version": "3.2.1",
|
||||||
"resolved": "https://registry.npmjs.org/yoga-layout/-/yoga-layout-2.0.1.tgz",
|
"resolved": "https://registry.npmjs.org/yoga-layout/-/yoga-layout-3.2.1.tgz",
|
||||||
"integrity": "sha512-tT/oChyDXelLo2A+UVnlW9GU7CsvFMaEnd9kVFsaiCQonFAXd3xrHhkLYu+suwwosrAEQ746xBU+HvYtm1Zs2Q==",
|
"integrity": "sha512-0LPOt3AxKqMdFBZA3HBAt/t/8vIKq7VaQYbuA8WxCgung+p9TVyKRYdpvCb80HcdTN2NkbIKbhNwKUfm3tQywQ==",
|
||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
"node_modules/zod": {
|
"node_modules/zod": {
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "lageplan",
|
"name": "lageplan",
|
||||||
"version": "1.0.0",
|
"version": "1.0.5",
|
||||||
"description": "Feuerwehr Lageplan - Krokier-App für Einsatzdokumentation",
|
"description": "Feuerwehr Lageplan - Krokier-App für Einsatzdokumentation",
|
||||||
"private": true,
|
"private": true,
|
||||||
"scripts": {
|
"scripts": {
|
||||||
@@ -34,7 +34,7 @@
|
|||||||
"@radix-ui/react-tabs": "^1.1.0",
|
"@radix-ui/react-tabs": "^1.1.0",
|
||||||
"@radix-ui/react-toast": "^1.2.0",
|
"@radix-ui/react-toast": "^1.2.0",
|
||||||
"@radix-ui/react-tooltip": "^1.1.0",
|
"@radix-ui/react-tooltip": "^1.1.0",
|
||||||
"@react-pdf/renderer": "^3.4.4",
|
"@react-pdf/renderer": "^4.3.2",
|
||||||
"bcryptjs": "^2.4.3",
|
"bcryptjs": "^2.4.3",
|
||||||
"class-variance-authority": "^0.7.0",
|
"class-variance-authority": "^0.7.0",
|
||||||
"clsx": "^2.1.0",
|
"clsx": "^2.1.0",
|
||||||
|
|||||||
BIN
public/logo-icon-maskable.png
Normal file
BIN
public/logo-icon-maskable.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 264 KiB |
@@ -20,7 +20,13 @@
|
|||||||
"src": "/logo-icon.png",
|
"src": "/logo-icon.png",
|
||||||
"sizes": "192x192",
|
"sizes": "192x192",
|
||||||
"type": "image/png",
|
"type": "image/png",
|
||||||
"purpose": "any maskable"
|
"purpose": "any"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"src": "/logo-icon-maskable.png",
|
||||||
|
"sizes": "192x192",
|
||||||
|
"type": "image/png",
|
||||||
|
"purpose": "maskable"
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"screenshots": [],
|
"screenshots": [],
|
||||||
|
|||||||
119
public/sw.js
119
public/sw.js
@@ -1,6 +1,10 @@
|
|||||||
const TILE_CACHE = 'lageplan-tiles-v2'
|
const TILE_CACHE = 'lageplan-tiles-v3'
|
||||||
const STATIC_CACHE = 'lageplan-static-v2'
|
const STATIC_CACHE = 'lageplan-static-v3'
|
||||||
const APP_CACHE = 'lageplan-app-v2'
|
const APP_CACHE = 'lageplan-app-v3'
|
||||||
|
const API_CACHE = 'lageplan-api-v3'
|
||||||
|
|
||||||
|
// API routes that should be cached for offline use
|
||||||
|
const CACHEABLE_API = ['/api/icons', '/api/hose-types', '/api/dictionary']
|
||||||
|
|
||||||
// Pre-cache essential app shell on install
|
// Pre-cache essential app shell on install
|
||||||
self.addEventListener('install', (event) => {
|
self.addEventListener('install', (event) => {
|
||||||
@@ -8,6 +12,8 @@ self.addEventListener('install', (event) => {
|
|||||||
caches.open(APP_CACHE).then((cache) =>
|
caches.open(APP_CACHE).then((cache) =>
|
||||||
cache.addAll([
|
cache.addAll([
|
||||||
'/app',
|
'/app',
|
||||||
|
'/login',
|
||||||
|
'/',
|
||||||
'/logo.svg',
|
'/logo.svg',
|
||||||
'/logo-icon.png',
|
'/logo-icon.png',
|
||||||
'/manifest.json',
|
'/manifest.json',
|
||||||
@@ -17,7 +23,6 @@ self.addEventListener('install', (event) => {
|
|||||||
self.skipWaiting()
|
self.skipWaiting()
|
||||||
})
|
})
|
||||||
|
|
||||||
// Cache strategy: Network First for API, Cache First for tiles, Stale While Revalidate for static assets
|
|
||||||
self.addEventListener('fetch', (event) => {
|
self.addEventListener('fetch', (event) => {
|
||||||
const url = event.request.url
|
const url = event.request.url
|
||||||
const { pathname } = new URL(url)
|
const { pathname } = new URL(url)
|
||||||
@@ -25,19 +30,71 @@ self.addEventListener('fetch', (event) => {
|
|||||||
// Skip non-GET requests
|
// Skip non-GET requests
|
||||||
if (event.request.method !== 'GET') return
|
if (event.request.method !== 'GET') return
|
||||||
|
|
||||||
// API requests: network only (don't cache dynamic data)
|
// Never intercept Socket.IO — let it pass through directly
|
||||||
|
if (pathname.startsWith('/socket.io')) return
|
||||||
|
|
||||||
|
// Cacheable API routes: Network First with cache fallback (icons, hose-types, dictionary)
|
||||||
|
if (CACHEABLE_API.some(p => pathname.startsWith(p))) {
|
||||||
|
event.respondWith(
|
||||||
|
caches.open(API_CACHE).then((cache) =>
|
||||||
|
fetch(event.request).then((response) => {
|
||||||
|
if (response.ok) cache.put(event.request, response.clone())
|
||||||
|
return response
|
||||||
|
}).catch(() =>
|
||||||
|
cache.match(event.request).then((cached) => cached || new Response('{"error":"offline"}', {
|
||||||
|
status: 503, headers: { 'Content-Type': 'application/json' }
|
||||||
|
}))
|
||||||
|
)
|
||||||
|
)
|
||||||
|
)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Projects API: Network First with cache fallback
|
||||||
|
if (pathname === '/api/projects' || pathname.match(/^\/api\/projects\/[^/]+$/)) {
|
||||||
|
event.respondWith(
|
||||||
|
caches.open(API_CACHE).then((cache) =>
|
||||||
|
fetch(event.request).then((response) => {
|
||||||
|
if (response.ok) cache.put(event.request, response.clone())
|
||||||
|
return response
|
||||||
|
}).catch(() =>
|
||||||
|
cache.match(event.request).then((cached) => cached || new Response('{"error":"offline"}', {
|
||||||
|
status: 503, headers: { 'Content-Type': 'application/json' }
|
||||||
|
}))
|
||||||
|
)
|
||||||
|
)
|
||||||
|
)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Features API: Network First with cache fallback
|
||||||
|
if (pathname.match(/^\/api\/projects\/[^/]+\/features$/)) {
|
||||||
|
event.respondWith(
|
||||||
|
caches.open(API_CACHE).then((cache) =>
|
||||||
|
fetch(event.request).then((response) => {
|
||||||
|
if (response.ok) cache.put(event.request, response.clone())
|
||||||
|
return response
|
||||||
|
}).catch(() =>
|
||||||
|
cache.match(event.request).then((cached) => cached || new Response('{"error":"offline"}', {
|
||||||
|
status: 503, headers: { 'Content-Type': 'application/json' }
|
||||||
|
}))
|
||||||
|
)
|
||||||
|
)
|
||||||
|
)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Other API requests: network only
|
||||||
if (pathname.startsWith('/api/')) return
|
if (pathname.startsWith('/api/')) return
|
||||||
|
|
||||||
// Cache map tiles from OpenStreetMap (Cache First)
|
// Cache map tiles from OpenStreetMap / MapTiler (Cache First — tiles don't change)
|
||||||
if (url.includes('tile.openstreetmap.org') || url.includes('api.maptiler.com')) {
|
if (url.includes('tile.openstreetmap.org') || url.includes('api.maptiler.com')) {
|
||||||
event.respondWith(
|
event.respondWith(
|
||||||
caches.open(TILE_CACHE).then((cache) =>
|
caches.open(TILE_CACHE).then((cache) =>
|
||||||
cache.match(event.request).then((cached) => {
|
cache.match(event.request).then((cached) => {
|
||||||
if (cached) return cached
|
if (cached) return cached
|
||||||
return fetch(event.request).then((response) => {
|
return fetch(event.request).then((response) => {
|
||||||
if (response.ok) {
|
if (response.ok) cache.put(event.request, response.clone())
|
||||||
cache.put(event.request, response.clone())
|
|
||||||
}
|
|
||||||
return response
|
return response
|
||||||
}).catch(() => new Response('', { status: 503 }))
|
}).catch(() => new Response('', { status: 503 }))
|
||||||
})
|
})
|
||||||
@@ -46,7 +103,23 @@ self.addEventListener('fetch', (event) => {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// Static assets (JS, CSS, images): Stale While Revalidate
|
// Next.js build chunks (_next/static): Cache First (hashed filenames = immutable)
|
||||||
|
if (pathname.startsWith('/_next/static/')) {
|
||||||
|
event.respondWith(
|
||||||
|
caches.open(STATIC_CACHE).then((cache) =>
|
||||||
|
cache.match(event.request).then((cached) => {
|
||||||
|
if (cached) return cached
|
||||||
|
return fetch(event.request).then((response) => {
|
||||||
|
if (response.ok) cache.put(event.request, response.clone())
|
||||||
|
return response
|
||||||
|
}).catch(() => new Response('', { status: 503 }))
|
||||||
|
})
|
||||||
|
)
|
||||||
|
)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Other static assets (JS, CSS, images, fonts): Stale While Revalidate
|
||||||
if (pathname.match(/\.(js|css|png|jpg|jpeg|svg|ico|woff2?)$/)) {
|
if (pathname.match(/\.(js|css|png|jpg|jpeg|svg|ico|woff2?)$/)) {
|
||||||
event.respondWith(
|
event.respondWith(
|
||||||
caches.open(STATIC_CACHE).then((cache) =>
|
caches.open(STATIC_CACHE).then((cache) =>
|
||||||
@@ -62,8 +135,8 @@ self.addEventListener('fetch', (event) => {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// App pages: Network First with cache fallback
|
// App pages / navigation: Network First with cache fallback
|
||||||
if (pathname === '/app' || pathname === '/' || pathname.startsWith('/app')) {
|
if (event.request.mode === 'navigate' || pathname === '/app' || pathname === '/' || pathname.startsWith('/app')) {
|
||||||
event.respondWith(
|
event.respondWith(
|
||||||
fetch(event.request).then((response) => {
|
fetch(event.request).then((response) => {
|
||||||
if (response.ok) {
|
if (response.ok) {
|
||||||
@@ -81,7 +154,7 @@ self.addEventListener('fetch', (event) => {
|
|||||||
|
|
||||||
// Clean old caches on activation
|
// Clean old caches on activation
|
||||||
self.addEventListener('activate', (event) => {
|
self.addEventListener('activate', (event) => {
|
||||||
const currentCaches = [TILE_CACHE, STATIC_CACHE, APP_CACHE]
|
const currentCaches = [TILE_CACHE, STATIC_CACHE, APP_CACHE, API_CACHE]
|
||||||
event.waitUntil(
|
event.waitUntil(
|
||||||
caches.keys().then((keys) =>
|
caches.keys().then((keys) =>
|
||||||
Promise.all(
|
Promise.all(
|
||||||
@@ -92,3 +165,23 @@ self.addEventListener('activate', (event) => {
|
|||||||
).then(() => self.clients.claim())
|
).then(() => self.clients.claim())
|
||||||
)
|
)
|
||||||
})
|
})
|
||||||
|
|
||||||
|
// Listen for sync events (Background Sync for queued saves)
|
||||||
|
self.addEventListener('sync', (event) => {
|
||||||
|
if (event.tag === 'sync-saves') {
|
||||||
|
event.waitUntil(syncQueuedSaves())
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
// Process queued saves from IndexedDB/localStorage
|
||||||
|
async function syncQueuedSaves() {
|
||||||
|
try {
|
||||||
|
const clients = await self.clients.matchAll()
|
||||||
|
clients.forEach(client => client.postMessage({ type: 'SYNC_START' }))
|
||||||
|
|
||||||
|
// Read queue from a BroadcastChannel or let the main thread handle it
|
||||||
|
clients.forEach(client => client.postMessage({ type: 'FLUSH_SYNC_QUEUE' }))
|
||||||
|
} catch (e) {
|
||||||
|
console.error('[SW] Sync error:', e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -2,9 +2,16 @@ import { NextRequest, NextResponse } from 'next/server'
|
|||||||
import { getSession } from '@/lib/auth'
|
import { getSession } from '@/lib/auth'
|
||||||
import { prisma } from '@/lib/db'
|
import { prisma } from '@/lib/db'
|
||||||
import bcrypt from 'bcryptjs'
|
import bcrypt from 'bcryptjs'
|
||||||
|
import { rateLimit, getClientIp, rateLimitResponse } from '@/lib/rate-limit'
|
||||||
|
|
||||||
|
const changePwLimiter = rateLimit({ id: 'change-pw', max: 5, windowSeconds: 60 * 15 })
|
||||||
|
|
||||||
export async function POST(req: NextRequest) {
|
export async function POST(req: NextRequest) {
|
||||||
try {
|
try {
|
||||||
|
const ip = getClientIp(req)
|
||||||
|
const rl = changePwLimiter.check(ip)
|
||||||
|
if (!rl.success) return rateLimitResponse(rl.resetAt)
|
||||||
|
|
||||||
const user = await getSession()
|
const user = await getSession()
|
||||||
if (!user) return NextResponse.json({ error: 'Nicht autorisiert' }, { status: 401 })
|
if (!user) return NextResponse.json({ error: 'Nicht autorisiert' }, { status: 401 })
|
||||||
|
|
||||||
@@ -14,8 +21,8 @@ export async function POST(req: NextRequest) {
|
|||||||
return NextResponse.json({ error: 'Beide Felder sind erforderlich' }, { status: 400 })
|
return NextResponse.json({ error: 'Beide Felder sind erforderlich' }, { status: 400 })
|
||||||
}
|
}
|
||||||
|
|
||||||
if (newPassword.length < 6) {
|
if (newPassword.length < 8) {
|
||||||
return NextResponse.json({ error: 'Neues Kennwort muss mindestens 6 Zeichen lang sein' }, { status: 400 })
|
return NextResponse.json({ error: 'Neues Kennwort muss mindestens 8 Zeichen lang sein' }, { status: 400 })
|
||||||
}
|
}
|
||||||
|
|
||||||
const dbUser = await (prisma as any).user.findUnique({
|
const dbUser = await (prisma as any).user.findUnique({
|
||||||
|
|||||||
70
src/app/api/auth/delete-account/route.ts
Normal file
70
src/app/api/auth/delete-account/route.ts
Normal file
@@ -0,0 +1,70 @@
|
|||||||
|
import { NextRequest, NextResponse } from 'next/server'
|
||||||
|
import { prisma } from '@/lib/db'
|
||||||
|
import { getSession } from '@/lib/auth'
|
||||||
|
import bcrypt from 'bcryptjs'
|
||||||
|
import { cookies } from 'next/headers'
|
||||||
|
import { deleteAccountLimiter, getClientIp, rateLimitResponse } from '@/lib/rate-limit'
|
||||||
|
|
||||||
|
// POST: User deletes their own account
|
||||||
|
export async function POST(req: NextRequest) {
|
||||||
|
try {
|
||||||
|
const ip = getClientIp(req)
|
||||||
|
const rl = deleteAccountLimiter.check(ip)
|
||||||
|
if (!rl.success) return rateLimitResponse(rl.resetAt)
|
||||||
|
|
||||||
|
const session = await getSession()
|
||||||
|
if (!session) return NextResponse.json({ error: 'Nicht autorisiert' }, { status: 401 })
|
||||||
|
|
||||||
|
const { password } = await req.json()
|
||||||
|
if (!password) {
|
||||||
|
return NextResponse.json({ error: 'Passwort erforderlich' }, { status: 400 })
|
||||||
|
}
|
||||||
|
|
||||||
|
// Verify password
|
||||||
|
const user = await (prisma as any).user.findUnique({
|
||||||
|
where: { id: session.id },
|
||||||
|
select: { id: true, password: true, role: true },
|
||||||
|
})
|
||||||
|
if (!user) return NextResponse.json({ error: 'Benutzer nicht gefunden' }, { status: 404 })
|
||||||
|
|
||||||
|
const validPw = await bcrypt.compare(password, user.password)
|
||||||
|
if (!validPw) {
|
||||||
|
return NextResponse.json({ error: 'Falsches Passwort' }, { status: 403 })
|
||||||
|
}
|
||||||
|
|
||||||
|
// If user is the only TENANT_ADMIN, they must delete the org first or transfer ownership
|
||||||
|
if (session.tenantId && session.role === 'TENANT_ADMIN') {
|
||||||
|
const adminCount = await (prisma as any).tenantMembership.count({
|
||||||
|
where: { tenantId: session.tenantId, role: 'TENANT_ADMIN' },
|
||||||
|
})
|
||||||
|
if (adminCount <= 1) {
|
||||||
|
return NextResponse.json({
|
||||||
|
error: 'Sie sind der einzige Administrator. Bitte löschen Sie die Organisation unter Einstellungen oder übertragen Sie die Admin-Rolle.',
|
||||||
|
}, { status: 400 })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log(`[Account Delete] User ${session.id} (${session.email}) deleting own account`)
|
||||||
|
|
||||||
|
// Clean up user data
|
||||||
|
try { await (prisma as any).upgradeRequest.deleteMany({ where: { requestedById: session.id } }) } catch {}
|
||||||
|
try { await (prisma as any).iconAsset.updateMany({ where: { ownerId: session.id }, data: { ownerId: null } }) } catch {}
|
||||||
|
try { await (prisma as any).project.updateMany({ where: { ownerId: session.id }, data: { ownerId: null } }) } catch {}
|
||||||
|
|
||||||
|
// Remove memberships
|
||||||
|
await (prisma as any).tenantMembership.deleteMany({ where: { userId: session.id } })
|
||||||
|
|
||||||
|
// Delete user
|
||||||
|
await (prisma as any).user.delete({ where: { id: session.id } })
|
||||||
|
|
||||||
|
// Clear auth cookie
|
||||||
|
;(await cookies()).delete('auth-token')
|
||||||
|
|
||||||
|
console.log(`[Account Delete] User ${session.email} deleted successfully`)
|
||||||
|
|
||||||
|
return NextResponse.json({ success: true, message: 'Konto wurde gelöscht' })
|
||||||
|
} catch (error: any) {
|
||||||
|
console.error('[Account Delete] Error:', error?.message || error)
|
||||||
|
return NextResponse.json({ error: 'Löschung fehlgeschlagen' }, { status: 500 })
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -2,9 +2,14 @@ import { NextRequest, NextResponse } from 'next/server'
|
|||||||
import { prisma } from '@/lib/db'
|
import { prisma } from '@/lib/db'
|
||||||
import { randomBytes } from 'crypto'
|
import { randomBytes } from 'crypto'
|
||||||
import { sendEmail, getSmtpConfig } from '@/lib/email'
|
import { sendEmail, getSmtpConfig } from '@/lib/email'
|
||||||
|
import { forgotPasswordLimiter, getClientIp, rateLimitResponse } from '@/lib/rate-limit'
|
||||||
|
|
||||||
export async function POST(req: NextRequest) {
|
export async function POST(req: NextRequest) {
|
||||||
try {
|
try {
|
||||||
|
const ip = getClientIp(req)
|
||||||
|
const rl = forgotPasswordLimiter.check(ip)
|
||||||
|
if (!rl.success) return rateLimitResponse(rl.resetAt)
|
||||||
|
|
||||||
const { email } = await req.json()
|
const { email } = await req.json()
|
||||||
if (!email) {
|
if (!email) {
|
||||||
return NextResponse.json({ error: 'E-Mail erforderlich' }, { status: 400 })
|
return NextResponse.json({ error: 'E-Mail erforderlich' }, { status: 400 })
|
||||||
|
|||||||
@@ -3,9 +3,14 @@ import { cookies } from 'next/headers'
|
|||||||
import { login, createToken } from '@/lib/auth'
|
import { login, createToken } from '@/lib/auth'
|
||||||
import { loginSchema } from '@/lib/validations'
|
import { loginSchema } from '@/lib/validations'
|
||||||
import { prisma } from '@/lib/db'
|
import { prisma } from '@/lib/db'
|
||||||
|
import { loginLimiter, getClientIp, rateLimitResponse } from '@/lib/rate-limit'
|
||||||
|
|
||||||
export async function POST(request: NextRequest) {
|
export async function POST(request: NextRequest) {
|
||||||
try {
|
try {
|
||||||
|
const ip = getClientIp(request)
|
||||||
|
const rl = loginLimiter.check(ip)
|
||||||
|
if (!rl.success) return rateLimitResponse(rl.resetAt)
|
||||||
|
|
||||||
const body = await request.json()
|
const body = await request.json()
|
||||||
|
|
||||||
const validated = loginSchema.safeParse(body)
|
const validated = loginSchema.safeParse(body)
|
||||||
|
|||||||
@@ -4,16 +4,21 @@ import { hashPassword } from '@/lib/auth'
|
|||||||
import { sendEmail } from '@/lib/email'
|
import { sendEmail } from '@/lib/email'
|
||||||
import { randomBytes } from 'crypto'
|
import { randomBytes } from 'crypto'
|
||||||
import { z } from 'zod'
|
import { z } from 'zod'
|
||||||
|
import { registerLimiter, getClientIp, rateLimitResponse } from '@/lib/rate-limit'
|
||||||
|
|
||||||
const registerSchema = z.object({
|
const registerSchema = z.object({
|
||||||
organizationName: z.string().min(2, 'Organisationsname zu kurz').max(200),
|
organizationName: z.string().min(2, 'Organisationsname zu kurz').max(200),
|
||||||
name: z.string().min(2, 'Name zu kurz').max(200),
|
name: z.string().min(2, 'Name zu kurz').max(200),
|
||||||
email: z.string().email('Ungültige E-Mail-Adresse'),
|
email: z.string().email('Ungültige E-Mail-Adresse'),
|
||||||
password: z.string().min(6, 'Passwort muss mindestens 6 Zeichen haben'),
|
password: z.string().min(8, 'Passwort muss mindestens 8 Zeichen haben'),
|
||||||
})
|
})
|
||||||
|
|
||||||
export async function POST(req: NextRequest) {
|
export async function POST(req: NextRequest) {
|
||||||
try {
|
try {
|
||||||
|
const ip = getClientIp(req)
|
||||||
|
const rl = registerLimiter.check(ip)
|
||||||
|
if (!rl.success) return rateLimitResponse(rl.resetAt)
|
||||||
|
|
||||||
const body = await req.json()
|
const body = await req.json()
|
||||||
const data = registerSchema.parse(body)
|
const data = registerSchema.parse(body)
|
||||||
|
|
||||||
|
|||||||
75
src/app/api/auth/resend-verification/route.ts
Normal file
75
src/app/api/auth/resend-verification/route.ts
Normal file
@@ -0,0 +1,75 @@
|
|||||||
|
import { NextRequest, NextResponse } from 'next/server'
|
||||||
|
import { prisma } from '@/lib/db'
|
||||||
|
import { sendEmail } from '@/lib/email'
|
||||||
|
import { randomBytes } from 'crypto'
|
||||||
|
import { resendVerificationLimiter, getClientIp, rateLimitResponse } from '@/lib/rate-limit'
|
||||||
|
|
||||||
|
export async function POST(req: NextRequest) {
|
||||||
|
try {
|
||||||
|
const ip = getClientIp(req)
|
||||||
|
const rl = resendVerificationLimiter.check(ip)
|
||||||
|
if (!rl.success) return rateLimitResponse(rl.resetAt)
|
||||||
|
|
||||||
|
const { email } = await req.json()
|
||||||
|
|
||||||
|
if (!email) {
|
||||||
|
return NextResponse.json({ error: 'E-Mail-Adresse erforderlich.' }, { status: 400 })
|
||||||
|
}
|
||||||
|
|
||||||
|
const user = await (prisma as any).user.findUnique({
|
||||||
|
where: { email },
|
||||||
|
include: { memberships: { include: { tenant: true } } },
|
||||||
|
})
|
||||||
|
|
||||||
|
if (!user) {
|
||||||
|
// Don't reveal whether user exists
|
||||||
|
return NextResponse.json({ success: true, message: 'Falls ein Konto mit dieser E-Mail existiert, wurde eine neue Bestätigungsmail gesendet.' })
|
||||||
|
}
|
||||||
|
|
||||||
|
if (user.emailVerified) {
|
||||||
|
return NextResponse.json({ success: true, message: 'Ihre E-Mail-Adresse ist bereits bestätigt. Sie können sich anmelden.' })
|
||||||
|
}
|
||||||
|
|
||||||
|
// Generate new verification token
|
||||||
|
const verificationToken = randomBytes(32).toString('hex')
|
||||||
|
await (prisma as any).user.update({
|
||||||
|
where: { id: user.id },
|
||||||
|
data: { emailVerificationToken: verificationToken },
|
||||||
|
})
|
||||||
|
|
||||||
|
// Build verification URL
|
||||||
|
let baseUrl = process.env.NEXTAUTH_URL || req.headers.get('origin') || `${req.headers.get('x-forwarded-proto') || 'https'}://${req.headers.get('host')}` || 'http://localhost:3000'
|
||||||
|
if (baseUrl && !baseUrl.startsWith('http://') && !baseUrl.startsWith('https://')) {
|
||||||
|
baseUrl = `https://${baseUrl}`
|
||||||
|
}
|
||||||
|
const verifyUrl = `${baseUrl}/api/auth/verify-email?token=${verificationToken}`
|
||||||
|
|
||||||
|
const orgName = user.memberships?.[0]?.tenant?.name || 'Lageplan'
|
||||||
|
|
||||||
|
await sendEmail(
|
||||||
|
user.email,
|
||||||
|
'E-Mail-Adresse bestätigen — Lageplan',
|
||||||
|
`<div style="font-family:sans-serif;max-width:600px;margin:0 auto;">
|
||||||
|
<div style="background:#dc2626;color:white;padding:20px 24px;border-radius:12px 12px 0 0;">
|
||||||
|
<h1 style="margin:0;font-size:22px;">E-Mail bestätigen</h1>
|
||||||
|
</div>
|
||||||
|
<div style="border:1px solid #e5e7eb;border-top:none;padding:24px;border-radius:0 0 12px 12px;">
|
||||||
|
<p>Hallo <strong>${user.name}</strong>,</p>
|
||||||
|
<p>Bitte bestätigen Sie Ihre E-Mail-Adresse, um Ihr Konto für <strong>${orgName}</strong> zu aktivieren.</p>
|
||||||
|
<div style="text-align:center;margin:24px 0;">
|
||||||
|
<a href="${verifyUrl}" style="background:#dc2626;color:white;padding:12px 32px;text-decoration:none;border-radius:8px;font-weight:600;display:inline-block;">
|
||||||
|
E-Mail bestätigen
|
||||||
|
</a>
|
||||||
|
</div>
|
||||||
|
<p style="color:#666;font-size:13px;">Falls der Button nicht funktioniert, kopieren Sie diesen Link:<br/>
|
||||||
|
<a href="${verifyUrl}" style="word-break:break-all;">${verifyUrl}</a></p>
|
||||||
|
</div>
|
||||||
|
</div>`
|
||||||
|
)
|
||||||
|
|
||||||
|
return NextResponse.json({ success: true, message: 'Bestätigungsmail wurde erneut gesendet. Bitte prüfen Sie Ihren Posteingang.' })
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Resend verification error:', error)
|
||||||
|
return NextResponse.json({ error: 'Fehler beim Senden der Bestätigungsmail.' }, { status: 500 })
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,16 +1,21 @@
|
|||||||
import { NextRequest, NextResponse } from 'next/server'
|
import { NextRequest, NextResponse } from 'next/server'
|
||||||
import { prisma } from '@/lib/db'
|
import { prisma } from '@/lib/db'
|
||||||
import { hashPassword } from '@/lib/auth'
|
import { hashPassword } from '@/lib/auth'
|
||||||
|
import { resetPasswordLimiter, getClientIp, rateLimitResponse } from '@/lib/rate-limit'
|
||||||
|
|
||||||
export async function POST(req: NextRequest) {
|
export async function POST(req: NextRequest) {
|
||||||
try {
|
try {
|
||||||
|
const ip = getClientIp(req)
|
||||||
|
const rl = resetPasswordLimiter.check(ip)
|
||||||
|
if (!rl.success) return rateLimitResponse(rl.resetAt)
|
||||||
|
|
||||||
const { token, password } = await req.json()
|
const { token, password } = await req.json()
|
||||||
if (!token || !password) {
|
if (!token || !password) {
|
||||||
return NextResponse.json({ error: 'Token und Passwort erforderlich' }, { status: 400 })
|
return NextResponse.json({ error: 'Token und Passwort erforderlich' }, { status: 400 })
|
||||||
}
|
}
|
||||||
|
|
||||||
if (password.length < 6) {
|
if (password.length < 8) {
|
||||||
return NextResponse.json({ error: 'Passwort muss mindestens 6 Zeichen lang sein' }, { status: 400 })
|
return NextResponse.json({ error: 'Passwort muss mindestens 8 Zeichen lang sein' }, { status: 400 })
|
||||||
}
|
}
|
||||||
|
|
||||||
const user = await (prisma as any).user.findFirst({
|
const user = await (prisma as any).user.findFirst({
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ import { NextRequest, NextResponse } from 'next/server'
|
|||||||
import { prisma } from '@/lib/db'
|
import { prisma } from '@/lib/db'
|
||||||
import { sendEmail, getSmtpConfig } from '@/lib/email'
|
import { sendEmail, getSmtpConfig } from '@/lib/email'
|
||||||
import { z } from 'zod'
|
import { z } from 'zod'
|
||||||
|
import { contactLimiter, getClientIp, rateLimitResponse } from '@/lib/rate-limit'
|
||||||
|
|
||||||
const contactSchema = z.object({
|
const contactSchema = z.object({
|
||||||
name: z.string().min(1).max(200),
|
name: z.string().min(1).max(200),
|
||||||
@@ -23,6 +24,10 @@ async function getContactEmail(): Promise<string> {
|
|||||||
|
|
||||||
export async function POST(req: NextRequest) {
|
export async function POST(req: NextRequest) {
|
||||||
try {
|
try {
|
||||||
|
const ip = getClientIp(req)
|
||||||
|
const rl = contactLimiter.check(ip)
|
||||||
|
if (!rl.success) return rateLimitResponse(rl.resetAt)
|
||||||
|
|
||||||
const body = await req.json()
|
const body = await req.json()
|
||||||
const data = contactSchema.parse(body)
|
const data = contactSchema.parse(body)
|
||||||
|
|
||||||
|
|||||||
@@ -6,21 +6,22 @@ import { getProjectWithTenantCheck } from '@/lib/tenant'
|
|||||||
|
|
||||||
export async function GET(
|
export async function GET(
|
||||||
request: NextRequest,
|
request: NextRequest,
|
||||||
{ params }: { params: { id: string } }
|
{ params }: { params: Promise<{ id: string }> }
|
||||||
) {
|
) {
|
||||||
try {
|
try {
|
||||||
|
const { id } = await params
|
||||||
const user = await getSession()
|
const user = await getSession()
|
||||||
if (!user) {
|
if (!user) {
|
||||||
return NextResponse.json({ error: 'Nicht autorisiert' }, { status: 401 })
|
return NextResponse.json({ error: 'Nicht autorisiert' }, { status: 401 })
|
||||||
}
|
}
|
||||||
|
|
||||||
const project = await getProjectWithTenantCheck(params.id, user)
|
const project = await getProjectWithTenantCheck(id, user)
|
||||||
if (!project) {
|
if (!project) {
|
||||||
return NextResponse.json({ error: 'Projekt nicht gefunden' }, { status: 404 })
|
return NextResponse.json({ error: 'Projekt nicht gefunden' }, { status: 404 })
|
||||||
}
|
}
|
||||||
|
|
||||||
const features = await (prisma as any).feature.findMany({
|
const features = await (prisma as any).feature.findMany({
|
||||||
where: { projectId: params.id },
|
where: { projectId: id },
|
||||||
orderBy: { createdAt: 'asc' },
|
orderBy: { createdAt: 'asc' },
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -33,9 +34,10 @@ export async function GET(
|
|||||||
|
|
||||||
export async function POST(
|
export async function POST(
|
||||||
request: NextRequest,
|
request: NextRequest,
|
||||||
{ params }: { params: { id: string } }
|
{ params }: { params: Promise<{ id: string }> }
|
||||||
) {
|
) {
|
||||||
try {
|
try {
|
||||||
|
const { id } = await params
|
||||||
const user = await getSession()
|
const user = await getSession()
|
||||||
if (!user) {
|
if (!user) {
|
||||||
return NextResponse.json({ error: 'Nicht autorisiert' }, { status: 401 })
|
return NextResponse.json({ error: 'Nicht autorisiert' }, { status: 401 })
|
||||||
@@ -45,7 +47,7 @@ export async function POST(
|
|||||||
return NextResponse.json({ error: 'Keine Berechtigung' }, { status: 403 })
|
return NextResponse.json({ error: 'Keine Berechtigung' }, { status: 403 })
|
||||||
}
|
}
|
||||||
|
|
||||||
const project = await getProjectWithTenantCheck(params.id, user)
|
const project = await getProjectWithTenantCheck(id, user)
|
||||||
if (!project) {
|
if (!project) {
|
||||||
return NextResponse.json({ error: 'Projekt nicht gefunden' }, { status: 404 })
|
return NextResponse.json({ error: 'Projekt nicht gefunden' }, { status: 404 })
|
||||||
}
|
}
|
||||||
@@ -66,7 +68,7 @@ export async function POST(
|
|||||||
|
|
||||||
const feature = await (prisma as any).feature.create({
|
const feature = await (prisma as any).feature.create({
|
||||||
data: {
|
data: {
|
||||||
projectId: params.id,
|
projectId: id,
|
||||||
type: validated.data.type,
|
type: validated.data.type,
|
||||||
geometry: validated.data.geometry,
|
geometry: validated.data.geometry,
|
||||||
properties: validated.data.properties || {},
|
properties: validated.data.properties || {},
|
||||||
@@ -82,9 +84,10 @@ export async function POST(
|
|||||||
|
|
||||||
export async function PUT(
|
export async function PUT(
|
||||||
request: NextRequest,
|
request: NextRequest,
|
||||||
{ params }: { params: { id: string } }
|
{ params }: { params: Promise<{ id: string }> }
|
||||||
) {
|
) {
|
||||||
try {
|
try {
|
||||||
|
const { id } = await params
|
||||||
const user = await getSession()
|
const user = await getSession()
|
||||||
if (!user) {
|
if (!user) {
|
||||||
return NextResponse.json({ error: 'Nicht autorisiert' }, { status: 401 })
|
return NextResponse.json({ error: 'Nicht autorisiert' }, { status: 401 })
|
||||||
@@ -94,11 +97,11 @@ export async function PUT(
|
|||||||
return NextResponse.json({ error: 'Keine Berechtigung' }, { status: 403 })
|
return NextResponse.json({ error: 'Keine Berechtigung' }, { status: 403 })
|
||||||
}
|
}
|
||||||
|
|
||||||
const project = await getProjectWithTenantCheck(params.id, user)
|
const project = await getProjectWithTenantCheck(id, user)
|
||||||
if (!project) {
|
if (!project) {
|
||||||
const exists = await (prisma as any).project.findUnique({ where: { id: params.id }, select: { id: true, tenantId: true, ownerId: true } })
|
const exists = await (prisma as any).project.findUnique({ where: { id }, select: { id: true, tenantId: true, ownerId: true } })
|
||||||
if (!exists) {
|
if (!exists) {
|
||||||
console.warn(`[Features PUT] Project ${params.id} not in DB`)
|
console.warn(`[Features PUT] Project ${id} not in DB`)
|
||||||
return NextResponse.json({ error: 'Projekt nicht gefunden' }, { status: 404 })
|
return NextResponse.json({ error: 'Projekt nicht gefunden' }, { status: 404 })
|
||||||
}
|
}
|
||||||
console.warn(`[Features PUT] Access denied: user=${user.id} tenant=${user.tenantId}, project owner=${exists.ownerId} tenant=${exists.tenantId}`)
|
console.warn(`[Features PUT] Access denied: user=${user.id} tenant=${user.tenantId}, project owner=${exists.ownerId} tenant=${exists.tenantId}`)
|
||||||
@@ -113,13 +116,13 @@ export async function PUT(
|
|||||||
const { features } = body as { features: Array<{ id?: string; type: string; geometry: object; properties?: object }> }
|
const { features } = body as { features: Array<{ id?: string; type: string; geometry: object; properties?: object }> }
|
||||||
|
|
||||||
await (prisma as any).feature.deleteMany({
|
await (prisma as any).feature.deleteMany({
|
||||||
where: { projectId: params.id },
|
where: { projectId: id },
|
||||||
})
|
})
|
||||||
|
|
||||||
if (features && features.length > 0) {
|
if (features && features.length > 0) {
|
||||||
await (prisma as any).feature.createMany({
|
await (prisma as any).feature.createMany({
|
||||||
data: features.map((f: any) => ({
|
data: features.map((f: any) => ({
|
||||||
projectId: params.id,
|
projectId: id,
|
||||||
type: f.type,
|
type: f.type,
|
||||||
geometry: f.geometry,
|
geometry: f.geometry,
|
||||||
properties: f.properties || {},
|
properties: f.properties || {},
|
||||||
@@ -128,7 +131,7 @@ export async function PUT(
|
|||||||
}
|
}
|
||||||
|
|
||||||
const updatedFeatures = await (prisma as any).feature.findMany({
|
const updatedFeatures = await (prisma as any).feature.findMany({
|
||||||
where: { projectId: params.id },
|
where: { projectId: id },
|
||||||
})
|
})
|
||||||
|
|
||||||
return NextResponse.json({ features: updatedFeatures })
|
return NextResponse.json({ features: updatedFeatures })
|
||||||
|
|||||||
@@ -4,18 +4,19 @@ import { getSession } from '@/lib/auth'
|
|||||||
import { getProjectWithTenantCheck } from '@/lib/tenant'
|
import { getProjectWithTenantCheck } from '@/lib/tenant'
|
||||||
|
|
||||||
// PUT: Toggle confirmed/ok on a check item
|
// PUT: Toggle confirmed/ok on a check item
|
||||||
export async function PUT(req: NextRequest, { params }: { params: { id: string; itemId: string } }) {
|
export async function PUT(req: NextRequest, { params }: { params: Promise<{ id: string; itemId: string }> }) {
|
||||||
try {
|
try {
|
||||||
|
const { id, itemId } = await params
|
||||||
const user = await getSession()
|
const user = await getSession()
|
||||||
if (!user) return NextResponse.json({ error: 'Nicht autorisiert' }, { status: 401 })
|
if (!user) return NextResponse.json({ error: 'Nicht autorisiert' }, { status: 401 })
|
||||||
if (user.role === 'VIEWER') return NextResponse.json({ error: 'Keine Berechtigung' }, { status: 403 })
|
if (user.role === 'VIEWER') return NextResponse.json({ error: 'Keine Berechtigung' }, { status: 403 })
|
||||||
|
|
||||||
const project = await getProjectWithTenantCheck(params.id, user)
|
const project = await getProjectWithTenantCheck(id, user)
|
||||||
if (!project) return NextResponse.json({ error: 'Projekt nicht gefunden' }, { status: 404 })
|
if (!project) return NextResponse.json({ error: 'Projekt nicht gefunden' }, { status: 404 })
|
||||||
|
|
||||||
// Verify item belongs to this project
|
// Verify item belongs to this project
|
||||||
const existing = await (prisma as any).journalCheckItem.findFirst({
|
const existing = await (prisma as any).journalCheckItem.findFirst({
|
||||||
where: { id: params.itemId, projectId: params.id },
|
where: { id: itemId, projectId: id },
|
||||||
})
|
})
|
||||||
if (!existing) return NextResponse.json({ error: 'Element nicht gefunden' }, { status: 404 })
|
if (!existing) return NextResponse.json({ error: 'Element nicht gefunden' }, { status: 404 })
|
||||||
|
|
||||||
@@ -32,7 +33,7 @@ export async function PUT(req: NextRequest, { params }: { params: { id: string;
|
|||||||
}
|
}
|
||||||
|
|
||||||
const item = await (prisma as any).journalCheckItem.update({
|
const item = await (prisma as any).journalCheckItem.update({
|
||||||
where: { id: params.itemId },
|
where: { id: itemId },
|
||||||
data,
|
data,
|
||||||
})
|
})
|
||||||
return NextResponse.json(item)
|
return NextResponse.json(item)
|
||||||
@@ -43,22 +44,23 @@ export async function PUT(req: NextRequest, { params }: { params: { id: string;
|
|||||||
}
|
}
|
||||||
|
|
||||||
// DELETE
|
// DELETE
|
||||||
export async function DELETE(req: NextRequest, { params }: { params: { id: string; itemId: string } }) {
|
export async function DELETE(req: NextRequest, { params }: { params: Promise<{ id: string; itemId: string }> }) {
|
||||||
try {
|
try {
|
||||||
|
const { id, itemId } = await params
|
||||||
const user = await getSession()
|
const user = await getSession()
|
||||||
if (!user) return NextResponse.json({ error: 'Nicht autorisiert' }, { status: 401 })
|
if (!user) return NextResponse.json({ error: 'Nicht autorisiert' }, { status: 401 })
|
||||||
if (user.role === 'VIEWER') return NextResponse.json({ error: 'Keine Berechtigung' }, { status: 403 })
|
if (user.role === 'VIEWER') return NextResponse.json({ error: 'Keine Berechtigung' }, { status: 403 })
|
||||||
|
|
||||||
const project = await getProjectWithTenantCheck(params.id, user)
|
const project = await getProjectWithTenantCheck(id, user)
|
||||||
if (!project) return NextResponse.json({ error: 'Projekt nicht gefunden' }, { status: 404 })
|
if (!project) return NextResponse.json({ error: 'Projekt nicht gefunden' }, { status: 404 })
|
||||||
|
|
||||||
// Verify item belongs to this project
|
// Verify item belongs to this project
|
||||||
const existing = await (prisma as any).journalCheckItem.findFirst({
|
const existing = await (prisma as any).journalCheckItem.findFirst({
|
||||||
where: { id: params.itemId, projectId: params.id },
|
where: { id: itemId, projectId: id },
|
||||||
})
|
})
|
||||||
if (!existing) return NextResponse.json({ error: 'Element nicht gefunden' }, { status: 404 })
|
if (!existing) return NextResponse.json({ error: 'Element nicht gefunden' }, { status: 404 })
|
||||||
|
|
||||||
await (prisma as any).journalCheckItem.delete({ where: { id: params.itemId } })
|
await (prisma as any).journalCheckItem.delete({ where: { id: itemId } })
|
||||||
return NextResponse.json({ ok: true })
|
return NextResponse.json({ ok: true })
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Error deleting check item:', error)
|
console.error('Error deleting check item:', error)
|
||||||
|
|||||||
@@ -4,13 +4,14 @@ import { getSession } from '@/lib/auth'
|
|||||||
import { getProjectWithTenantCheck } from '@/lib/tenant'
|
import { getProjectWithTenantCheck } from '@/lib/tenant'
|
||||||
|
|
||||||
// POST: Add check item (or initialize from templates)
|
// POST: Add check item (or initialize from templates)
|
||||||
export async function POST(req: NextRequest, { params }: { params: { id: string } }) {
|
export async function POST(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
|
||||||
try {
|
try {
|
||||||
|
const { id } = await params
|
||||||
const user = await getSession()
|
const user = await getSession()
|
||||||
if (!user) return NextResponse.json({ error: 'Nicht autorisiert' }, { status: 401 })
|
if (!user) return NextResponse.json({ error: 'Nicht autorisiert' }, { status: 401 })
|
||||||
if (user.role === 'VIEWER') return NextResponse.json({ error: 'Keine Berechtigung' }, { status: 403 })
|
if (user.role === 'VIEWER') return NextResponse.json({ error: 'Keine Berechtigung' }, { status: 403 })
|
||||||
|
|
||||||
const project = await getProjectWithTenantCheck(params.id, user)
|
const project = await getProjectWithTenantCheck(id, user)
|
||||||
if (!project) return NextResponse.json({ error: 'Projekt nicht gefunden' }, { status: 404 })
|
if (!project) return NextResponse.json({ error: 'Projekt nicht gefunden' }, { status: 404 })
|
||||||
|
|
||||||
const body = await req.json()
|
const body = await req.json()
|
||||||
@@ -18,7 +19,7 @@ export async function POST(req: NextRequest, { params }: { params: { id: string
|
|||||||
// If 'initFromTemplates' is true, create check items from templates (only if none exist)
|
// If 'initFromTemplates' is true, create check items from templates (only if none exist)
|
||||||
if (body.initFromTemplates) {
|
if (body.initFromTemplates) {
|
||||||
const existing = await (prisma as any).journalCheckItem.findMany({
|
const existing = await (prisma as any).journalCheckItem.findMany({
|
||||||
where: { projectId: params.id },
|
where: { projectId: id },
|
||||||
})
|
})
|
||||||
if (existing.length > 0) {
|
if (existing.length > 0) {
|
||||||
return NextResponse.json(existing)
|
return NextResponse.json(existing)
|
||||||
@@ -31,7 +32,7 @@ export async function POST(req: NextRequest, { params }: { params: { id: string
|
|||||||
templates.map((tpl: any, i: number) =>
|
templates.map((tpl: any, i: number) =>
|
||||||
(prisma as any).journalCheckItem.create({
|
(prisma as any).journalCheckItem.create({
|
||||||
data: {
|
data: {
|
||||||
projectId: params.id,
|
projectId: id,
|
||||||
label: tpl.label,
|
label: tpl.label,
|
||||||
sortOrder: i,
|
sortOrder: i,
|
||||||
},
|
},
|
||||||
@@ -44,7 +45,7 @@ export async function POST(req: NextRequest, { params }: { params: { id: string
|
|||||||
// Single item creation
|
// Single item creation
|
||||||
const item = await (prisma as any).journalCheckItem.create({
|
const item = await (prisma as any).journalCheckItem.create({
|
||||||
data: {
|
data: {
|
||||||
projectId: params.id,
|
projectId: id,
|
||||||
label: body.label || '',
|
label: body.label || '',
|
||||||
sortOrder: body.sortOrder || 0,
|
sortOrder: body.sortOrder || 0,
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -4,17 +4,18 @@ import { getSession } from '@/lib/auth'
|
|||||||
import { getProjectWithTenantCheck } from '@/lib/tenant'
|
import { getProjectWithTenantCheck } from '@/lib/tenant'
|
||||||
|
|
||||||
// PUT: Update a journal entry — only toggle done status allowed directly
|
// PUT: Update a journal entry — only toggle done status allowed directly
|
||||||
export async function PUT(req: NextRequest, { params }: { params: { id: string; entryId: string } }) {
|
export async function PUT(req: NextRequest, { params }: { params: Promise<{ id: string; entryId: string }> }) {
|
||||||
try {
|
try {
|
||||||
|
const { id, entryId } = await params
|
||||||
const user = await getSession()
|
const user = await getSession()
|
||||||
if (!user) return NextResponse.json({ error: 'Nicht autorisiert' }, { status: 401 })
|
if (!user) return NextResponse.json({ error: 'Nicht autorisiert' }, { status: 401 })
|
||||||
if (user.role === 'VIEWER') return NextResponse.json({ error: 'Keine Berechtigung' }, { status: 403 })
|
if (user.role === 'VIEWER') return NextResponse.json({ error: 'Keine Berechtigung' }, { status: 403 })
|
||||||
|
|
||||||
const project = await getProjectWithTenantCheck(params.id, user)
|
const project = await getProjectWithTenantCheck(id, user)
|
||||||
if (!project) return NextResponse.json({ error: 'Projekt nicht gefunden' }, { status: 404 })
|
if (!project) return NextResponse.json({ error: 'Projekt nicht gefunden' }, { status: 404 })
|
||||||
|
|
||||||
const existing = await (prisma as any).journalEntry.findFirst({
|
const existing = await (prisma as any).journalEntry.findFirst({
|
||||||
where: { id: params.entryId, projectId: params.id },
|
where: { id: entryId, projectId: id },
|
||||||
})
|
})
|
||||||
if (!existing) return NextResponse.json({ error: 'Eintrag nicht gefunden' }, { status: 404 })
|
if (!existing) return NextResponse.json({ error: 'Eintrag nicht gefunden' }, { status: 404 })
|
||||||
|
|
||||||
@@ -23,7 +24,7 @@ export async function PUT(req: NextRequest, { params }: { params: { id: string;
|
|||||||
// Only done toggle is allowed as direct edit
|
// Only done toggle is allowed as direct edit
|
||||||
if (body.done !== undefined) {
|
if (body.done !== undefined) {
|
||||||
const entry = await (prisma as any).journalEntry.update({
|
const entry = await (prisma as any).journalEntry.update({
|
||||||
where: { id: params.entryId },
|
where: { id: entryId },
|
||||||
data: { done: body.done, doneAt: body.done ? new Date() : null },
|
data: { done: body.done, doneAt: body.done ? new Date() : null },
|
||||||
})
|
})
|
||||||
return NextResponse.json(entry)
|
return NextResponse.json(entry)
|
||||||
@@ -38,17 +39,18 @@ export async function PUT(req: NextRequest, { params }: { params: { id: string;
|
|||||||
|
|
||||||
// POST: Create a correction for a journal entry (replaces DELETE)
|
// POST: Create a correction for a journal entry (replaces DELETE)
|
||||||
// Marks the original as corrected (strikethrough) and creates a new correction entry below it
|
// Marks the original as corrected (strikethrough) and creates a new correction entry below it
|
||||||
export async function POST(req: NextRequest, { params }: { params: { id: string; entryId: string } }) {
|
export async function POST(req: NextRequest, { params }: { params: Promise<{ id: string; entryId: string }> }) {
|
||||||
try {
|
try {
|
||||||
|
const { id, entryId } = await params
|
||||||
const user = await getSession()
|
const user = await getSession()
|
||||||
if (!user) return NextResponse.json({ error: 'Nicht autorisiert' }, { status: 401 })
|
if (!user) return NextResponse.json({ error: 'Nicht autorisiert' }, { status: 401 })
|
||||||
if (user.role === 'VIEWER') return NextResponse.json({ error: 'Keine Berechtigung' }, { status: 403 })
|
if (user.role === 'VIEWER') return NextResponse.json({ error: 'Keine Berechtigung' }, { status: 403 })
|
||||||
|
|
||||||
const project = await getProjectWithTenantCheck(params.id, user)
|
const project = await getProjectWithTenantCheck(id, user)
|
||||||
if (!project) return NextResponse.json({ error: 'Projekt nicht gefunden' }, { status: 404 })
|
if (!project) return NextResponse.json({ error: 'Projekt nicht gefunden' }, { status: 404 })
|
||||||
|
|
||||||
const existing = await (prisma as any).journalEntry.findFirst({
|
const existing = await (prisma as any).journalEntry.findFirst({
|
||||||
where: { id: params.entryId, projectId: params.id },
|
where: { id: entryId, projectId: id },
|
||||||
})
|
})
|
||||||
if (!existing) return NextResponse.json({ error: 'Eintrag nicht gefunden' }, { status: 404 })
|
if (!existing) return NextResponse.json({ error: 'Eintrag nicht gefunden' }, { status: 404 })
|
||||||
|
|
||||||
@@ -69,7 +71,7 @@ export async function POST(req: NextRequest, { params }: { params: { id: string;
|
|||||||
|
|
||||||
// Mark original as corrected
|
// Mark original as corrected
|
||||||
await (prisma as any).journalEntry.update({
|
await (prisma as any).journalEntry.update({
|
||||||
where: { id: params.entryId },
|
where: { id: entryId },
|
||||||
data: { isCorrected: true },
|
data: { isCorrected: true },
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -81,7 +83,7 @@ export async function POST(req: NextRequest, { params }: { params: { id: string;
|
|||||||
who: body.who || existing.who || user.name,
|
who: body.who || existing.who || user.name,
|
||||||
sortOrder: existing.sortOrder + 1,
|
sortOrder: existing.sortOrder + 1,
|
||||||
correctionOfId: existing.id,
|
correctionOfId: existing.id,
|
||||||
projectId: params.id,
|
projectId: id,
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|||||||
@@ -4,19 +4,20 @@ import { getSession } from '@/lib/auth'
|
|||||||
import { getProjectWithTenantCheck } from '@/lib/tenant'
|
import { getProjectWithTenantCheck } from '@/lib/tenant'
|
||||||
|
|
||||||
// POST: Add a new journal entry
|
// POST: Add a new journal entry
|
||||||
export async function POST(req: NextRequest, { params }: { params: { id: string } }) {
|
export async function POST(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
|
||||||
try {
|
try {
|
||||||
|
const { id } = await params
|
||||||
const user = await getSession()
|
const user = await getSession()
|
||||||
if (!user) return NextResponse.json({ error: 'Nicht autorisiert' }, { status: 401 })
|
if (!user) return NextResponse.json({ error: 'Nicht autorisiert' }, { status: 401 })
|
||||||
if (user.role === 'VIEWER') return NextResponse.json({ error: 'Keine Berechtigung' }, { status: 403 })
|
if (user.role === 'VIEWER') return NextResponse.json({ error: 'Keine Berechtigung' }, { status: 403 })
|
||||||
|
|
||||||
const project = await getProjectWithTenantCheck(params.id, user)
|
const project = await getProjectWithTenantCheck(id, user)
|
||||||
if (!project) return NextResponse.json({ error: 'Projekt nicht gefunden' }, { status: 404 })
|
if (!project) return NextResponse.json({ error: 'Projekt nicht gefunden' }, { status: 404 })
|
||||||
|
|
||||||
const body = await req.json()
|
const body = await req.json()
|
||||||
const entry = await (prisma as any).journalEntry.create({
|
const entry = await (prisma as any).journalEntry.create({
|
||||||
data: {
|
data: {
|
||||||
projectId: params.id,
|
projectId: id,
|
||||||
time: body.time ? new Date(body.time) : new Date(),
|
time: body.time ? new Date(body.time) : new Date(),
|
||||||
what: body.what || '',
|
what: body.what || '',
|
||||||
who: body.who || null,
|
who: body.who || null,
|
||||||
|
|||||||
@@ -4,18 +4,19 @@ import { getSession } from '@/lib/auth'
|
|||||||
import { getProjectWithTenantCheck } from '@/lib/tenant'
|
import { getProjectWithTenantCheck } from '@/lib/tenant'
|
||||||
|
|
||||||
// PUT: Update a pendenz
|
// PUT: Update a pendenz
|
||||||
export async function PUT(req: NextRequest, { params }: { params: { id: string; pendenzId: string } }) {
|
export async function PUT(req: NextRequest, { params }: { params: Promise<{ id: string; pendenzId: string }> }) {
|
||||||
try {
|
try {
|
||||||
|
const { id, pendenzId } = await params
|
||||||
const user = await getSession()
|
const user = await getSession()
|
||||||
if (!user) return NextResponse.json({ error: 'Nicht autorisiert' }, { status: 401 })
|
if (!user) return NextResponse.json({ error: 'Nicht autorisiert' }, { status: 401 })
|
||||||
if (user.role === 'VIEWER') return NextResponse.json({ error: 'Keine Berechtigung' }, { status: 403 })
|
if (user.role === 'VIEWER') return NextResponse.json({ error: 'Keine Berechtigung' }, { status: 403 })
|
||||||
|
|
||||||
const project = await getProjectWithTenantCheck(params.id, user)
|
const project = await getProjectWithTenantCheck(id, user)
|
||||||
if (!project) return NextResponse.json({ error: 'Projekt nicht gefunden' }, { status: 404 })
|
if (!project) return NextResponse.json({ error: 'Projekt nicht gefunden' }, { status: 404 })
|
||||||
|
|
||||||
// Verify pendenz belongs to this project
|
// Verify pendenz belongs to this project
|
||||||
const existing = await (prisma as any).journalPendenz.findFirst({
|
const existing = await (prisma as any).journalPendenz.findFirst({
|
||||||
where: { id: params.pendenzId, projectId: params.id },
|
where: { id: pendenzId, projectId: id },
|
||||||
})
|
})
|
||||||
if (!existing) return NextResponse.json({ error: 'Pendenz nicht gefunden' }, { status: 404 })
|
if (!existing) return NextResponse.json({ error: 'Pendenz nicht gefunden' }, { status: 404 })
|
||||||
|
|
||||||
@@ -30,7 +31,7 @@ export async function PUT(req: NextRequest, { params }: { params: { id: string;
|
|||||||
}
|
}
|
||||||
|
|
||||||
const item = await (prisma as any).journalPendenz.update({
|
const item = await (prisma as any).journalPendenz.update({
|
||||||
where: { id: params.pendenzId },
|
where: { id: pendenzId },
|
||||||
data,
|
data,
|
||||||
})
|
})
|
||||||
return NextResponse.json(item)
|
return NextResponse.json(item)
|
||||||
@@ -41,22 +42,23 @@ export async function PUT(req: NextRequest, { params }: { params: { id: string;
|
|||||||
}
|
}
|
||||||
|
|
||||||
// DELETE
|
// DELETE
|
||||||
export async function DELETE(req: NextRequest, { params }: { params: { id: string; pendenzId: string } }) {
|
export async function DELETE(req: NextRequest, { params }: { params: Promise<{ id: string; pendenzId: string }> }) {
|
||||||
try {
|
try {
|
||||||
|
const { id, pendenzId } = await params
|
||||||
const user = await getSession()
|
const user = await getSession()
|
||||||
if (!user) return NextResponse.json({ error: 'Nicht autorisiert' }, { status: 401 })
|
if (!user) return NextResponse.json({ error: 'Nicht autorisiert' }, { status: 401 })
|
||||||
if (user.role === 'VIEWER') return NextResponse.json({ error: 'Keine Berechtigung' }, { status: 403 })
|
if (user.role === 'VIEWER') return NextResponse.json({ error: 'Keine Berechtigung' }, { status: 403 })
|
||||||
|
|
||||||
const project = await getProjectWithTenantCheck(params.id, user)
|
const project = await getProjectWithTenantCheck(id, user)
|
||||||
if (!project) return NextResponse.json({ error: 'Projekt nicht gefunden' }, { status: 404 })
|
if (!project) return NextResponse.json({ error: 'Projekt nicht gefunden' }, { status: 404 })
|
||||||
|
|
||||||
// Verify pendenz belongs to this project
|
// Verify pendenz belongs to this project
|
||||||
const existing = await (prisma as any).journalPendenz.findFirst({
|
const existing = await (prisma as any).journalPendenz.findFirst({
|
||||||
where: { id: params.pendenzId, projectId: params.id },
|
where: { id: pendenzId, projectId: id },
|
||||||
})
|
})
|
||||||
if (!existing) return NextResponse.json({ error: 'Pendenz nicht gefunden' }, { status: 404 })
|
if (!existing) return NextResponse.json({ error: 'Pendenz nicht gefunden' }, { status: 404 })
|
||||||
|
|
||||||
await (prisma as any).journalPendenz.delete({ where: { id: params.pendenzId } })
|
await (prisma as any).journalPendenz.delete({ where: { id: pendenzId } })
|
||||||
return NextResponse.json({ ok: true })
|
return NextResponse.json({ ok: true })
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Error deleting pendenz:', error)
|
console.error('Error deleting pendenz:', error)
|
||||||
|
|||||||
@@ -4,19 +4,20 @@ import { getSession } from '@/lib/auth'
|
|||||||
import { getProjectWithTenantCheck } from '@/lib/tenant'
|
import { getProjectWithTenantCheck } from '@/lib/tenant'
|
||||||
|
|
||||||
// POST: Add a new pendenz
|
// POST: Add a new pendenz
|
||||||
export async function POST(req: NextRequest, { params }: { params: { id: string } }) {
|
export async function POST(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
|
||||||
try {
|
try {
|
||||||
|
const { id } = await params
|
||||||
const user = await getSession()
|
const user = await getSession()
|
||||||
if (!user) return NextResponse.json({ error: 'Nicht autorisiert' }, { status: 401 })
|
if (!user) return NextResponse.json({ error: 'Nicht autorisiert' }, { status: 401 })
|
||||||
if (user.role === 'VIEWER') return NextResponse.json({ error: 'Keine Berechtigung' }, { status: 403 })
|
if (user.role === 'VIEWER') return NextResponse.json({ error: 'Keine Berechtigung' }, { status: 403 })
|
||||||
|
|
||||||
const project = await getProjectWithTenantCheck(params.id, user)
|
const project = await getProjectWithTenantCheck(id, user)
|
||||||
if (!project) return NextResponse.json({ error: 'Projekt nicht gefunden' }, { status: 404 })
|
if (!project) return NextResponse.json({ error: 'Projekt nicht gefunden' }, { status: 404 })
|
||||||
|
|
||||||
const body = await req.json()
|
const body = await req.json()
|
||||||
const item = await (prisma as any).journalPendenz.create({
|
const item = await (prisma as any).journalPendenz.create({
|
||||||
data: {
|
data: {
|
||||||
projectId: params.id,
|
projectId: id,
|
||||||
what: body.what || '',
|
what: body.what || '',
|
||||||
who: body.who || null,
|
who: body.who || null,
|
||||||
whenHow: body.whenHow || null,
|
whenHow: body.whenHow || null,
|
||||||
|
|||||||
@@ -4,25 +4,26 @@ import { getSession } from '@/lib/auth'
|
|||||||
import { getProjectWithTenantCheck } from '@/lib/tenant'
|
import { getProjectWithTenantCheck } from '@/lib/tenant'
|
||||||
|
|
||||||
// GET all journal data for a project (entries, check items, pendenzen)
|
// GET all journal data for a project (entries, check items, pendenzen)
|
||||||
export async function GET(req: NextRequest, { params }: { params: { id: string } }) {
|
export async function GET(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
|
||||||
try {
|
try {
|
||||||
|
const { id } = await params
|
||||||
const user = await getSession()
|
const user = await getSession()
|
||||||
if (!user) return NextResponse.json({ error: 'Nicht autorisiert' }, { status: 401 })
|
if (!user) return NextResponse.json({ error: 'Nicht autorisiert' }, { status: 401 })
|
||||||
|
|
||||||
const project = await getProjectWithTenantCheck(params.id, user)
|
const project = await getProjectWithTenantCheck(id, user)
|
||||||
if (!project) return NextResponse.json({ error: 'Projekt nicht gefunden' }, { status: 404 })
|
if (!project) return NextResponse.json({ error: 'Projekt nicht gefunden' }, { status: 404 })
|
||||||
|
|
||||||
const [entries, checkItems, pendenzen] = await Promise.all([
|
const [entries, checkItems, pendenzen] = await Promise.all([
|
||||||
(prisma as any).journalEntry.findMany({
|
(prisma as any).journalEntry.findMany({
|
||||||
where: { projectId: params.id },
|
where: { projectId: id },
|
||||||
orderBy: [{ time: 'asc' }, { sortOrder: 'asc' }, { createdAt: 'asc' }],
|
orderBy: [{ time: 'asc' }, { sortOrder: 'asc' }, { createdAt: 'asc' }],
|
||||||
}),
|
}),
|
||||||
(prisma as any).journalCheckItem.findMany({
|
(prisma as any).journalCheckItem.findMany({
|
||||||
where: { projectId: params.id },
|
where: { projectId: id },
|
||||||
orderBy: { sortOrder: 'asc' },
|
orderBy: { sortOrder: 'asc' },
|
||||||
}),
|
}),
|
||||||
(prisma as any).journalPendenz.findMany({
|
(prisma as any).journalPendenz.findMany({
|
||||||
where: { projectId: params.id },
|
where: { projectId: id },
|
||||||
orderBy: { sortOrder: 'asc' },
|
orderBy: { sortOrder: 'asc' },
|
||||||
}),
|
}),
|
||||||
])
|
])
|
||||||
|
|||||||
@@ -4,12 +4,13 @@ import { getSession } from '@/lib/auth'
|
|||||||
import { getProjectWithTenantCheck } from '@/lib/tenant'
|
import { getProjectWithTenantCheck } from '@/lib/tenant'
|
||||||
import { sendEmail } from '@/lib/email'
|
import { sendEmail } from '@/lib/email'
|
||||||
|
|
||||||
export async function POST(req: NextRequest, { params }: { params: { id: string } }) {
|
export async function POST(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
|
||||||
try {
|
try {
|
||||||
|
const { id } = await params
|
||||||
const user = await getSession()
|
const user = await getSession()
|
||||||
if (!user) return NextResponse.json({ error: 'Nicht autorisiert' }, { status: 401 })
|
if (!user) return NextResponse.json({ error: 'Nicht autorisiert' }, { status: 401 })
|
||||||
|
|
||||||
const project = await getProjectWithTenantCheck(params.id, user)
|
const project = await getProjectWithTenantCheck(id, user)
|
||||||
if (!project) return NextResponse.json({ error: 'Projekt nicht gefunden' }, { status: 404 })
|
if (!project) return NextResponse.json({ error: 'Projekt nicht gefunden' }, { status: 404 })
|
||||||
|
|
||||||
// Load tenant logo
|
// Load tenant logo
|
||||||
@@ -32,17 +33,17 @@ export async function POST(req: NextRequest, { params }: { params: { id: string
|
|||||||
|
|
||||||
// Load journal data
|
// Load journal data
|
||||||
const entries = await (prisma as any).journalEntry.findMany({
|
const entries = await (prisma as any).journalEntry.findMany({
|
||||||
where: { projectId: params.id },
|
where: { projectId: id },
|
||||||
orderBy: [{ time: 'asc' }, { sortOrder: 'asc' }],
|
orderBy: [{ time: 'asc' }, { sortOrder: 'asc' }],
|
||||||
})
|
})
|
||||||
|
|
||||||
const checkItems = await (prisma as any).journalCheckItem.findMany({
|
const checkItems = await (prisma as any).journalCheckItem.findMany({
|
||||||
where: { projectId: params.id },
|
where: { projectId: id },
|
||||||
orderBy: { sortOrder: 'asc' },
|
orderBy: { sortOrder: 'asc' },
|
||||||
})
|
})
|
||||||
|
|
||||||
const pendenzen = await (prisma as any).journalPendenz.findMany({
|
const pendenzen = await (prisma as any).journalPendenz.findMany({
|
||||||
where: { projectId: params.id },
|
where: { projectId: id },
|
||||||
orderBy: { sortOrder: 'asc' },
|
orderBy: { sortOrder: 'asc' },
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|||||||
@@ -5,13 +5,14 @@ import { getProjectWithTenantCheck } from '@/lib/tenant'
|
|||||||
import { uploadFile, deleteFile, getFileUrl } from '@/lib/minio'
|
import { uploadFile, deleteFile, getFileUrl } from '@/lib/minio'
|
||||||
|
|
||||||
// POST: Upload a plan image for a project
|
// POST: Upload a plan image for a project
|
||||||
export async function POST(req: NextRequest, { params }: { params: { id: string } }) {
|
export async function POST(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
|
||||||
try {
|
try {
|
||||||
|
const { id } = await params
|
||||||
const user = await getSession()
|
const user = await getSession()
|
||||||
if (!user) return NextResponse.json({ error: 'Nicht autorisiert' }, { status: 401 })
|
if (!user) return NextResponse.json({ error: 'Nicht autorisiert' }, { status: 401 })
|
||||||
if (user.role === 'VIEWER') return NextResponse.json({ error: 'Keine Berechtigung' }, { status: 403 })
|
if (user.role === 'VIEWER') return NextResponse.json({ error: 'Keine Berechtigung' }, { status: 403 })
|
||||||
|
|
||||||
const project = await getProjectWithTenantCheck(params.id, user)
|
const project = await getProjectWithTenantCheck(id, user)
|
||||||
if (!project) return NextResponse.json({ error: 'Projekt nicht gefunden' }, { status: 404 })
|
if (!project) return NextResponse.json({ error: 'Projekt nicht gefunden' }, { status: 404 })
|
||||||
|
|
||||||
const formData = await req.formData()
|
const formData = await req.formData()
|
||||||
@@ -37,7 +38,7 @@ export async function POST(req: NextRequest, { params }: { params: { id: string
|
|||||||
// Upload to MinIO
|
// Upload to MinIO
|
||||||
const buffer = Buffer.from(await file.arrayBuffer())
|
const buffer = Buffer.from(await file.arrayBuffer())
|
||||||
const ext = file.name.split('.').pop() || 'png'
|
const ext = file.name.split('.').pop() || 'png'
|
||||||
const fileKey = `plans/${params.id}/${Date.now()}.${ext}`
|
const fileKey = `plans/${id}/${Date.now()}.${ext}`
|
||||||
await uploadFile(fileKey, buffer, file.type)
|
await uploadFile(fileKey, buffer, file.type)
|
||||||
|
|
||||||
// Parse bounds or use default (current map view)
|
// Parse bounds or use default (current map view)
|
||||||
@@ -48,7 +49,7 @@ export async function POST(req: NextRequest, { params }: { params: { id: string
|
|||||||
|
|
||||||
// Update project
|
// Update project
|
||||||
await (prisma as any).project.update({
|
await (prisma as any).project.update({
|
||||||
where: { id: params.id },
|
where: { id },
|
||||||
data: {
|
data: {
|
||||||
planImageKey: fileKey,
|
planImageKey: fileKey,
|
||||||
planBounds: bounds,
|
planBounds: bounds,
|
||||||
@@ -70,13 +71,14 @@ export async function POST(req: NextRequest, { params }: { params: { id: string
|
|||||||
}
|
}
|
||||||
|
|
||||||
// DELETE: Remove the plan image
|
// DELETE: Remove the plan image
|
||||||
export async function DELETE(req: NextRequest, { params }: { params: { id: string } }) {
|
export async function DELETE(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
|
||||||
try {
|
try {
|
||||||
|
const { id } = await params
|
||||||
const user = await getSession()
|
const user = await getSession()
|
||||||
if (!user) return NextResponse.json({ error: 'Nicht autorisiert' }, { status: 401 })
|
if (!user) return NextResponse.json({ error: 'Nicht autorisiert' }, { status: 401 })
|
||||||
if (user.role === 'VIEWER') return NextResponse.json({ error: 'Keine Berechtigung' }, { status: 403 })
|
if (user.role === 'VIEWER') return NextResponse.json({ error: 'Keine Berechtigung' }, { status: 403 })
|
||||||
|
|
||||||
const project = await getProjectWithTenantCheck(params.id, user)
|
const project = await getProjectWithTenantCheck(id, user)
|
||||||
if (!project) return NextResponse.json({ error: 'Projekt nicht gefunden' }, { status: 404 })
|
if (!project) return NextResponse.json({ error: 'Projekt nicht gefunden' }, { status: 404 })
|
||||||
|
|
||||||
const p = project as any
|
const p = project as any
|
||||||
@@ -85,7 +87,7 @@ export async function DELETE(req: NextRequest, { params }: { params: { id: strin
|
|||||||
}
|
}
|
||||||
|
|
||||||
await (prisma as any).project.update({
|
await (prisma as any).project.update({
|
||||||
where: { id: params.id },
|
where: { id },
|
||||||
data: { planImageKey: null, planBounds: null },
|
data: { planImageKey: null, planBounds: null },
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -97,19 +99,20 @@ export async function DELETE(req: NextRequest, { params }: { params: { id: strin
|
|||||||
}
|
}
|
||||||
|
|
||||||
// PATCH: Update plan bounds (repositioning)
|
// PATCH: Update plan bounds (repositioning)
|
||||||
export async function PATCH(req: NextRequest, { params }: { params: { id: string } }) {
|
export async function PATCH(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
|
||||||
try {
|
try {
|
||||||
|
const { id } = await params
|
||||||
const user = await getSession()
|
const user = await getSession()
|
||||||
if (!user) return NextResponse.json({ error: 'Nicht autorisiert' }, { status: 401 })
|
if (!user) return NextResponse.json({ error: 'Nicht autorisiert' }, { status: 401 })
|
||||||
|
|
||||||
const project = await getProjectWithTenantCheck(params.id, user)
|
const project = await getProjectWithTenantCheck(id, user)
|
||||||
if (!project) return NextResponse.json({ error: 'Projekt nicht gefunden' }, { status: 404 })
|
if (!project) return NextResponse.json({ error: 'Projekt nicht gefunden' }, { status: 404 })
|
||||||
|
|
||||||
const body = await req.json()
|
const body = await req.json()
|
||||||
if (!body.bounds) return NextResponse.json({ error: 'Bounds erforderlich' }, { status: 400 })
|
if (!body.bounds) return NextResponse.json({ error: 'Bounds erforderlich' }, { status: 400 })
|
||||||
|
|
||||||
await (prisma as any).project.update({
|
await (prisma as any).project.update({
|
||||||
where: { id: params.id },
|
where: { id },
|
||||||
data: { planBounds: body.bounds },
|
data: { planBounds: body.bounds },
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|||||||
@@ -4,13 +4,14 @@ import { getSession } from '@/lib/auth'
|
|||||||
import { getFileStream } from '@/lib/minio'
|
import { getFileStream } from '@/lib/minio'
|
||||||
|
|
||||||
// Serve plan image (authenticated users only)
|
// Serve plan image (authenticated users only)
|
||||||
export async function GET(req: NextRequest, { params }: { params: { id: string } }) {
|
export async function GET(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
|
||||||
try {
|
try {
|
||||||
|
const { id } = await params
|
||||||
const user = await getSession()
|
const user = await getSession()
|
||||||
if (!user) return NextResponse.json({ error: 'Nicht autorisiert' }, { status: 401 })
|
if (!user) return NextResponse.json({ error: 'Nicht autorisiert' }, { status: 401 })
|
||||||
|
|
||||||
const project = await (prisma as any).project.findUnique({
|
const project = await (prisma as any).project.findUnique({
|
||||||
where: { id: params.id },
|
where: { id },
|
||||||
select: { planImageKey: true },
|
select: { planImageKey: true },
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|||||||
@@ -6,22 +6,23 @@ import { getProjectWithTenantCheck } from '@/lib/tenant'
|
|||||||
|
|
||||||
export async function GET(
|
export async function GET(
|
||||||
request: NextRequest,
|
request: NextRequest,
|
||||||
{ params }: { params: { id: string } }
|
{ params }: { params: Promise<{ id: string }> }
|
||||||
) {
|
) {
|
||||||
try {
|
try {
|
||||||
|
const { id } = await params
|
||||||
const user = await getSession()
|
const user = await getSession()
|
||||||
if (!user) {
|
if (!user) {
|
||||||
return NextResponse.json({ error: 'Nicht autorisiert' }, { status: 401 })
|
return NextResponse.json({ error: 'Nicht autorisiert' }, { status: 401 })
|
||||||
}
|
}
|
||||||
|
|
||||||
const projectBase = await getProjectWithTenantCheck(params.id, user)
|
const projectBase = await getProjectWithTenantCheck(id, user)
|
||||||
if (!projectBase) {
|
if (!projectBase) {
|
||||||
return NextResponse.json({ error: 'Projekt nicht gefunden' }, { status: 404 })
|
return NextResponse.json({ error: 'Projekt nicht gefunden' }, { status: 404 })
|
||||||
}
|
}
|
||||||
|
|
||||||
// Re-fetch with includes
|
// Re-fetch with includes
|
||||||
const project = await (prisma as any).project.findUnique({
|
const project = await (prisma as any).project.findUnique({
|
||||||
where: { id: params.id },
|
where: { id },
|
||||||
include: {
|
include: {
|
||||||
owner: {
|
owner: {
|
||||||
select: { id: true, name: true, email: true },
|
select: { id: true, name: true, email: true },
|
||||||
@@ -39,9 +40,10 @@ export async function GET(
|
|||||||
|
|
||||||
export async function PATCH(
|
export async function PATCH(
|
||||||
request: NextRequest,
|
request: NextRequest,
|
||||||
{ params }: { params: { id: string } }
|
{ params }: { params: Promise<{ id: string }> }
|
||||||
) {
|
) {
|
||||||
try {
|
try {
|
||||||
|
const { id } = await params
|
||||||
const user = await getSession()
|
const user = await getSession()
|
||||||
if (!user) {
|
if (!user) {
|
||||||
return NextResponse.json({ error: 'Nicht autorisiert' }, { status: 401 })
|
return NextResponse.json({ error: 'Nicht autorisiert' }, { status: 401 })
|
||||||
@@ -51,7 +53,7 @@ export async function PATCH(
|
|||||||
return NextResponse.json({ error: 'Keine Berechtigung' }, { status: 403 })
|
return NextResponse.json({ error: 'Keine Berechtigung' }, { status: 403 })
|
||||||
}
|
}
|
||||||
|
|
||||||
const existingProject = await getProjectWithTenantCheck(params.id, user)
|
const existingProject = await getProjectWithTenantCheck(id, user)
|
||||||
if (!existingProject) {
|
if (!existingProject) {
|
||||||
return NextResponse.json({ error: 'Projekt nicht gefunden' }, { status: 404 })
|
return NextResponse.json({ error: 'Projekt nicht gefunden' }, { status: 404 })
|
||||||
}
|
}
|
||||||
@@ -67,7 +69,7 @@ export async function PATCH(
|
|||||||
}
|
}
|
||||||
|
|
||||||
const project = await (prisma as any).project.update({
|
const project = await (prisma as any).project.update({
|
||||||
where: { id: params.id },
|
where: { id },
|
||||||
data: validated.data,
|
data: validated.data,
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -80,15 +82,16 @@ export async function PATCH(
|
|||||||
|
|
||||||
export async function DELETE(
|
export async function DELETE(
|
||||||
request: NextRequest,
|
request: NextRequest,
|
||||||
{ params }: { params: { id: string } }
|
{ params }: { params: Promise<{ id: string }> }
|
||||||
) {
|
) {
|
||||||
try {
|
try {
|
||||||
|
const { id } = await params
|
||||||
const user = await getSession()
|
const user = await getSession()
|
||||||
if (!user) {
|
if (!user) {
|
||||||
return NextResponse.json({ error: 'Nicht autorisiert' }, { status: 401 })
|
return NextResponse.json({ error: 'Nicht autorisiert' }, { status: 401 })
|
||||||
}
|
}
|
||||||
|
|
||||||
const existingProject = await getProjectWithTenantCheck(params.id, user)
|
const existingProject = await getProjectWithTenantCheck(id, user)
|
||||||
if (!existingProject) {
|
if (!existingProject) {
|
||||||
return NextResponse.json({ error: 'Projekt nicht gefunden' }, { status: 404 })
|
return NextResponse.json({ error: 'Projekt nicht gefunden' }, { status: 404 })
|
||||||
}
|
}
|
||||||
@@ -99,7 +102,7 @@ export async function DELETE(
|
|||||||
}
|
}
|
||||||
|
|
||||||
await (prisma as any).project.delete({
|
await (prisma as any).project.delete({
|
||||||
where: { id: params.id },
|
where: { id },
|
||||||
})
|
})
|
||||||
|
|
||||||
return NextResponse.json({ success: true })
|
return NextResponse.json({ success: true })
|
||||||
|
|||||||
@@ -40,10 +40,11 @@ async function resolveLogoDataUri(rapport: any): Promise<string> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// GET: Generate and serve PDF for a rapport (public, token-based)
|
// GET: Generate and serve PDF for a rapport (public, token-based)
|
||||||
export async function GET(req: NextRequest, { params }: { params: { token: string } }) {
|
export async function GET(req: NextRequest, { params }: { params: Promise<{ token: string }> }) {
|
||||||
try {
|
try {
|
||||||
|
const { token } = await params
|
||||||
const rapport = await (prisma as any).rapport.findUnique({
|
const rapport = await (prisma as any).rapport.findUnique({
|
||||||
where: { token: params.token },
|
where: { token },
|
||||||
include: {
|
include: {
|
||||||
tenant: { select: { name: true } },
|
tenant: { select: { name: true } },
|
||||||
},
|
},
|
||||||
@@ -68,10 +69,10 @@ export async function GET(req: NextRequest, { params }: { params: { token: strin
|
|||||||
const { RapportDocument } = await import('@/lib/rapport-pdf')
|
const { RapportDocument } = await import('@/lib/rapport-pdf')
|
||||||
|
|
||||||
const buffer = await renderToBuffer(
|
const buffer = await renderToBuffer(
|
||||||
React.createElement(RapportDocument, { data: pdfData })
|
React.createElement(RapportDocument, { data: pdfData }) as any
|
||||||
)
|
)
|
||||||
|
|
||||||
return new NextResponse(buffer, {
|
return new NextResponse(Buffer.from(buffer) as any, {
|
||||||
headers: {
|
headers: {
|
||||||
'Content-Type': 'application/pdf',
|
'Content-Type': 'application/pdf',
|
||||||
'Content-Disposition': `inline; filename="Rapport-${rapport.reportNumber}.pdf"`,
|
'Content-Disposition': `inline; filename="Rapport-${rapport.reportNumber}.pdf"`,
|
||||||
|
|||||||
@@ -37,10 +37,11 @@ async function resolveLogoForClient(rapport: any): Promise<string> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// GET: Public access to rapport by token (no auth required)
|
// GET: Public access to rapport by token (no auth required)
|
||||||
export async function GET(req: NextRequest, { params }: { params: { token: string } }) {
|
export async function GET(req: NextRequest, { params }: { params: Promise<{ token: string }> }) {
|
||||||
try {
|
try {
|
||||||
|
const { token } = await params
|
||||||
const rapport = await (prisma as any).rapport.findUnique({
|
const rapport = await (prisma as any).rapport.findUnique({
|
||||||
where: { token: params.token },
|
where: { token },
|
||||||
include: {
|
include: {
|
||||||
project: { select: { title: true, location: true } },
|
project: { select: { title: true, location: true } },
|
||||||
tenant: { select: { name: true } },
|
tenant: { select: { name: true } },
|
||||||
|
|||||||
@@ -4,8 +4,9 @@ import { getSession } from '@/lib/auth'
|
|||||||
import { sendEmail } from '@/lib/email'
|
import { sendEmail } from '@/lib/email'
|
||||||
|
|
||||||
// POST: Send rapport link via email
|
// POST: Send rapport link via email
|
||||||
export async function POST(req: NextRequest, { params }: { params: { token: string } }) {
|
export async function POST(req: NextRequest, { params }: { params: Promise<{ token: string }> }) {
|
||||||
try {
|
try {
|
||||||
|
const { token } = await params
|
||||||
const user = await getSession()
|
const user = await getSession()
|
||||||
if (!user) return NextResponse.json({ error: 'Nicht autorisiert' }, { status: 401 })
|
if (!user) return NextResponse.json({ error: 'Nicht autorisiert' }, { status: 401 })
|
||||||
|
|
||||||
@@ -13,7 +14,7 @@ export async function POST(req: NextRequest, { params }: { params: { token: stri
|
|||||||
if (!email) return NextResponse.json({ error: 'E-Mail-Adresse erforderlich' }, { status: 400 })
|
if (!email) return NextResponse.json({ error: 'E-Mail-Adresse erforderlich' }, { status: 400 })
|
||||||
|
|
||||||
const rapport = await (prisma as any).rapport.findUnique({
|
const rapport = await (prisma as any).rapport.findUnique({
|
||||||
where: { token: params.token },
|
where: { token },
|
||||||
include: {
|
include: {
|
||||||
tenant: { select: { name: true } },
|
tenant: { select: { name: true } },
|
||||||
project: { select: { title: true, location: true } },
|
project: { select: { title: true, location: true } },
|
||||||
|
|||||||
@@ -5,9 +5,10 @@ import { getSession, isAdmin } from '@/lib/auth'
|
|||||||
// GET: Fetch journal suggestions for a tenant (global + tenant dictionary merged)
|
// GET: Fetch journal suggestions for a tenant (global + tenant dictionary merged)
|
||||||
export async function GET(
|
export async function GET(
|
||||||
req: NextRequest,
|
req: NextRequest,
|
||||||
{ params }: { params: { tenantId: string } }
|
{ params }: { params: Promise<{ tenantId: string }> }
|
||||||
) {
|
) {
|
||||||
try {
|
try {
|
||||||
|
const { tenantId } = await params
|
||||||
const user = await getSession()
|
const user = await getSession()
|
||||||
if (!user) return NextResponse.json({ error: 'Nicht autorisiert' }, { status: 401 })
|
if (!user) return NextResponse.json({ error: 'Nicht autorisiert' }, { status: 401 })
|
||||||
|
|
||||||
@@ -18,11 +19,11 @@ export async function GET(
|
|||||||
select: { word: true },
|
select: { word: true },
|
||||||
}).catch(() => []),
|
}).catch(() => []),
|
||||||
(prisma as any).dictionaryEntry.findMany({
|
(prisma as any).dictionaryEntry.findMany({
|
||||||
where: { scope: 'TENANT', tenantId: params.tenantId },
|
where: { scope: 'TENANT', tenantId },
|
||||||
select: { word: true },
|
select: { word: true },
|
||||||
}).catch(() => []),
|
}).catch(() => []),
|
||||||
(prisma as any).tenant.findUnique({
|
(prisma as any).tenant.findUnique({
|
||||||
where: { id: params.tenantId },
|
where: { id: tenantId },
|
||||||
select: { journalSuggestions: true },
|
select: { journalSuggestions: true },
|
||||||
}),
|
}),
|
||||||
])
|
])
|
||||||
@@ -46,16 +47,17 @@ export async function GET(
|
|||||||
// PUT: Replace all journal suggestions for a tenant (admin only)
|
// PUT: Replace all journal suggestions for a tenant (admin only)
|
||||||
export async function PUT(
|
export async function PUT(
|
||||||
req: NextRequest,
|
req: NextRequest,
|
||||||
{ params }: { params: { tenantId: string } }
|
{ params }: { params: Promise<{ tenantId: string }> }
|
||||||
) {
|
) {
|
||||||
try {
|
try {
|
||||||
|
const { tenantId } = await params
|
||||||
const user = await getSession()
|
const user = await getSession()
|
||||||
if (!user || !isAdmin(user.role)) {
|
if (!user || !isAdmin(user.role)) {
|
||||||
return NextResponse.json({ error: 'Nicht autorisiert' }, { status: 403 })
|
return NextResponse.json({ error: 'Nicht autorisiert' }, { status: 403 })
|
||||||
}
|
}
|
||||||
|
|
||||||
// TENANT_ADMIN can only edit their own tenant
|
// TENANT_ADMIN can only edit their own tenant
|
||||||
if (user.role !== 'SERVER_ADMIN' && user.tenantId !== params.tenantId) {
|
if (user.role !== 'SERVER_ADMIN' && user.tenantId !== tenantId) {
|
||||||
return NextResponse.json({ error: 'Keine Berechtigung' }, { status: 403 })
|
return NextResponse.json({ error: 'Keine Berechtigung' }, { status: 403 })
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -65,7 +67,7 @@ export async function PUT(
|
|||||||
: []
|
: []
|
||||||
|
|
||||||
await (prisma as any).tenant.update({
|
await (prisma as any).tenant.update({
|
||||||
where: { id: params.tenantId },
|
where: { id: tenantId },
|
||||||
data: { journalSuggestions: suggestions },
|
data: { journalSuggestions: suggestions },
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|||||||
@@ -4,11 +4,12 @@ import { prisma } from '@/lib/db'
|
|||||||
// Public endpoint: get tenant info by slug (logo, name)
|
// Public endpoint: get tenant info by slug (logo, name)
|
||||||
export async function GET(
|
export async function GET(
|
||||||
req: NextRequest,
|
req: NextRequest,
|
||||||
{ params }: { params: { slug: string } }
|
{ params }: { params: Promise<{ slug: string }> }
|
||||||
) {
|
) {
|
||||||
try {
|
try {
|
||||||
|
const { slug } = await params
|
||||||
const tenant = await (prisma as any).tenant.findUnique({
|
const tenant = await (prisma as any).tenant.findUnique({
|
||||||
where: { slug: params.slug },
|
where: { slug },
|
||||||
select: {
|
select: {
|
||||||
id: true,
|
id: true,
|
||||||
name: true,
|
name: true,
|
||||||
|
|||||||
@@ -15,9 +15,10 @@ const processSchema = z.object({
|
|||||||
// PATCH: Approve or reject an upgrade request (SERVER_ADMIN only)
|
// PATCH: Approve or reject an upgrade request (SERVER_ADMIN only)
|
||||||
export async function PATCH(
|
export async function PATCH(
|
||||||
req: NextRequest,
|
req: NextRequest,
|
||||||
{ params }: { params: { id: string } }
|
{ params }: { params: Promise<{ id: string }> }
|
||||||
) {
|
) {
|
||||||
try {
|
try {
|
||||||
|
const { id } = await params
|
||||||
const user = await getSession()
|
const user = await getSession()
|
||||||
if (!user || !isServerAdmin(user.role)) {
|
if (!user || !isServerAdmin(user.role)) {
|
||||||
return NextResponse.json({ error: 'Nicht autorisiert' }, { status: 403 })
|
return NextResponse.json({ error: 'Nicht autorisiert' }, { status: 403 })
|
||||||
@@ -31,7 +32,7 @@ export async function PATCH(
|
|||||||
|
|
||||||
// Get the request
|
// Get the request
|
||||||
const upgradeReq = await (prisma as any).upgradeRequest.findUnique({
|
const upgradeReq = await (prisma as any).upgradeRequest.findUnique({
|
||||||
where: { id: params.id },
|
where: { id },
|
||||||
include: {
|
include: {
|
||||||
tenant: { select: { id: true, name: true, plan: true, contactEmail: true } },
|
tenant: { select: { id: true, name: true, plan: true, contactEmail: true } },
|
||||||
requestedBy: { select: { name: true, email: true } },
|
requestedBy: { select: { name: true, email: true } },
|
||||||
@@ -71,7 +72,7 @@ export async function PATCH(
|
|||||||
|
|
||||||
// Update request status
|
// Update request status
|
||||||
await (prisma as any).upgradeRequest.update({
|
await (prisma as any).upgradeRequest.update({
|
||||||
where: { id: params.id },
|
where: { id },
|
||||||
data: {
|
data: {
|
||||||
status: 'APPROVED',
|
status: 'APPROVED',
|
||||||
adminNote: validated.data.adminNote || null,
|
adminNote: validated.data.adminNote || null,
|
||||||
@@ -127,7 +128,7 @@ export async function PATCH(
|
|||||||
} else {
|
} else {
|
||||||
// Reject
|
// Reject
|
||||||
await (prisma as any).upgradeRequest.update({
|
await (prisma as any).upgradeRequest.update({
|
||||||
where: { id: params.id },
|
where: { id },
|
||||||
data: {
|
data: {
|
||||||
status: 'REJECTED',
|
status: 'REJECTED',
|
||||||
adminNote: validated.data.adminNote || null,
|
adminNote: validated.data.adminNote || null,
|
||||||
@@ -170,7 +171,7 @@ export async function PATCH(
|
|||||||
|
|
||||||
// Return updated request
|
// Return updated request
|
||||||
const updated = await (prisma as any).upgradeRequest.findUnique({
|
const updated = await (prisma as any).upgradeRequest.findUnique({
|
||||||
where: { id: params.id },
|
where: { id },
|
||||||
include: {
|
include: {
|
||||||
tenant: { select: { name: true, slug: true, plan: true, subscriptionStatus: true } },
|
tenant: { select: { name: true, slug: true, plan: true, subscriptionStatus: true } },
|
||||||
requestedBy: { select: { name: true, email: true } },
|
requestedBy: { select: { name: true, email: true } },
|
||||||
|
|||||||
@@ -19,9 +19,10 @@ import { Button } from '@/components/ui/button'
|
|||||||
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog'
|
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog'
|
||||||
import { JournalView } from '@/components/journal/journal-view'
|
import { JournalView } from '@/components/journal/journal-view'
|
||||||
import { jsPDF } from 'jspdf'
|
import { jsPDF } from 'jspdf'
|
||||||
import { Lock, Unlock, Eye } from 'lucide-react'
|
import { Lock, Unlock, Eye, AlertTriangle, WifiOff } from 'lucide-react'
|
||||||
import { getSocket } from '@/lib/socket'
|
import { getSocket, setSocketRoom } from '@/lib/socket'
|
||||||
import { CustomDragLayer } from '@/components/map/custom-drag-layer'
|
import { CustomDragLayer } from '@/components/map/custom-drag-layer'
|
||||||
|
import { addToSyncQueue, flushSyncQueue, getSyncQueue, isOnline as checkOnline } from '@/lib/offline-sync'
|
||||||
|
|
||||||
export interface Project {
|
export interface Project {
|
||||||
id: string
|
id: string
|
||||||
@@ -102,88 +103,217 @@ export default function AppPage() {
|
|||||||
sessionIdRef.current = `${Date.now()}-${Math.random().toString(36).slice(2, 10)}`
|
sessionIdRef.current = `${Date.now()}-${Math.random().toString(36).slice(2, 10)}`
|
||||||
}
|
}
|
||||||
|
|
||||||
// Capture map screenshot when switching to journal tab (including HTML symbol markers)
|
// Capture map screenshot when switching to journal tab (coordinate-based rendering)
|
||||||
const handleTabChange = useCallback(async (tab: 'map' | 'journal') => {
|
const handleTabChange = useCallback(async (tab: 'map' | 'journal') => {
|
||||||
if (tab === 'journal' && mapRef.current) {
|
if (tab === 'journal' && mapRef.current) {
|
||||||
try {
|
try {
|
||||||
const mapCanvas = mapRef.current.getCanvas()
|
const mapInstance = mapRef.current
|
||||||
if (mapCanvas) {
|
const mapCanvas = mapInstance.getCanvas() as HTMLCanvasElement
|
||||||
|
if (mapCanvas && mapCanvas.width > 0) {
|
||||||
const offscreen = document.createElement('canvas')
|
const offscreen = document.createElement('canvas')
|
||||||
offscreen.width = mapCanvas.width
|
offscreen.width = mapCanvas.width
|
||||||
offscreen.height = mapCanvas.height
|
offscreen.height = mapCanvas.height
|
||||||
const ctx = offscreen.getContext('2d')
|
const ctx = offscreen.getContext('2d')
|
||||||
if (ctx) {
|
if (ctx) {
|
||||||
ctx.drawImage(mapCanvas, 0, 0)
|
ctx.drawImage(mapCanvas, 0, 0)
|
||||||
const dpr = window.devicePixelRatio || 1
|
|
||||||
const mapContainer = mapRef.current.getContainer()
|
|
||||||
const mapRect = mapContainer.getBoundingClientRect()
|
|
||||||
|
|
||||||
// Collect all symbol images and preload them (async for URL-based images)
|
const container = mapInstance.getContainer()
|
||||||
const symbolEntries: { img: HTMLImageElement; x: number; y: number; w: number; h: number; rotation: number }[] = []
|
const dpr = mapCanvas.width / container.offsetWidth
|
||||||
const loadPromises: Promise<void>[] = []
|
const currentZoom = mapInstance.getZoom()
|
||||||
|
const currentFeatures = featuresRef.current
|
||||||
|
|
||||||
document.querySelectorAll<HTMLElement>('.symbol-marker-wrapper').forEach(wrapper => {
|
// Helper: haversine distance
|
||||||
const rect = wrapper.getBoundingClientRect()
|
const haversine = (a: number[], b: number[]): number => {
|
||||||
const inner = wrapper.querySelector<HTMLElement>('.symbol-marker')
|
const R = 6371000, toRad = Math.PI / 180
|
||||||
if (!inner) return
|
const dLat = (b[1] - a[1]) * toRad, dLng = (b[0] - a[0]) * toRad
|
||||||
const bgImage = inner.style.backgroundImage
|
const x = Math.sin(dLat / 2) ** 2 + Math.cos(a[1] * toRad) * Math.cos(b[1] * toRad) * Math.sin(dLng / 2) ** 2
|
||||||
const urlMatch = bgImage.match(/url\("?(.+?)"?\)/)
|
return R * 2 * Math.atan2(Math.sqrt(x), Math.sqrt(1 - x))
|
||||||
if (!urlMatch) return
|
|
||||||
const imgSrc = urlMatch[1]
|
|
||||||
const img = new Image()
|
|
||||||
img.crossOrigin = 'anonymous'
|
|
||||||
img.src = imgSrc
|
|
||||||
const entry = {
|
|
||||||
img,
|
|
||||||
x: (rect.left - mapRect.left) * dpr,
|
|
||||||
y: (rect.top - mapRect.top) * dpr,
|
|
||||||
w: rect.width * dpr,
|
|
||||||
h: rect.height * dpr,
|
|
||||||
rotation: parseFloat(inner.style.transform?.match(/rotate\((.+?)deg\)/)?.[1] || '0'),
|
|
||||||
}
|
|
||||||
symbolEntries.push(entry)
|
|
||||||
if (!img.complete) {
|
|
||||||
loadPromises.push(new Promise<void>((resolve) => {
|
|
||||||
img.onload = () => resolve()
|
|
||||||
img.onerror = () => resolve()
|
|
||||||
}))
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
// Wait for all symbol images to load (max 3s timeout)
|
|
||||||
if (loadPromises.length > 0) {
|
|
||||||
await Promise.race([
|
|
||||||
Promise.all(loadPromises),
|
|
||||||
new Promise(r => setTimeout(r, 3000)),
|
|
||||||
])
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Draw all symbol markers
|
// Helper: load image as promise
|
||||||
symbolEntries.forEach(({ img, x, y, w, h, rotation }) => {
|
const loadImage = (src: string): Promise<HTMLImageElement> => new Promise((resolve, reject) => {
|
||||||
if (img.complete && img.naturalWidth > 0) {
|
const img = new Image()
|
||||||
ctx.save()
|
img.crossOrigin = 'anonymous'
|
||||||
ctx.translate(x + w / 2, y + h / 2)
|
img.onload = () => resolve(img)
|
||||||
if (rotation) ctx.rotate((rotation * Math.PI) / 180)
|
img.onerror = reject
|
||||||
ctx.drawImage(img, -w / 2, -h / 2, w, h)
|
img.src = src
|
||||||
ctx.restore()
|
|
||||||
}
|
|
||||||
})
|
})
|
||||||
|
|
||||||
// Draw text markers
|
// 1. Draw symbol features (coordinate-based)
|
||||||
document.querySelectorAll<HTMLElement>('.text-marker').forEach(el => {
|
for (const f of currentFeatures.filter(f => f.type === 'symbol')) {
|
||||||
const rect = el.getBoundingClientRect()
|
if (f.geometry.type !== 'Point') continue
|
||||||
const x = (rect.left - mapRect.left) * dpr
|
const coords = f.geometry.coordinates as [number, number]
|
||||||
const y = (rect.top - mapRect.top) * dpr
|
const pixel = mapInstance.project(coords)
|
||||||
const text = el.textContent || ''
|
const px = pixel.x * dpr
|
||||||
const fontSize = parseFloat(el.style.fontSize || '14') * dpr
|
const py = pixel.y * dpr
|
||||||
const color = el.style.color || '#000'
|
const scale = (f.properties.scale as number) || 1
|
||||||
|
const rotation = (f.properties.rotation as number) || 0
|
||||||
|
const baseSize = 32
|
||||||
|
const placementZoom = (f.properties.placementZoom as number) || 17
|
||||||
|
const zoomFactor = Math.pow(2, currentZoom - placementZoom)
|
||||||
|
const size = Math.max(8, Math.min(400, baseSize * scale * zoomFactor)) * dpr
|
||||||
|
|
||||||
|
const iconId = f.properties.iconId as string
|
||||||
|
const imageUrl = f.properties.imageUrl as string
|
||||||
|
let imgSrc = imageUrl || ''
|
||||||
|
if (!imgSrc && iconId) {
|
||||||
|
const { getSymbolById, getSymbolDataUri } = await import('@/lib/fw-symbols')
|
||||||
|
const sym = getSymbolById(iconId)
|
||||||
|
if (sym) imgSrc = getSymbolDataUri(sym)
|
||||||
|
}
|
||||||
|
if (imgSrc) {
|
||||||
|
try {
|
||||||
|
const img = await loadImage(imgSrc)
|
||||||
|
const imgAspect = img.naturalWidth / img.naturalHeight
|
||||||
|
let drawW = size, drawH = size
|
||||||
|
if (imgAspect > 1) drawH = size / imgAspect
|
||||||
|
else drawW = size * imgAspect
|
||||||
|
ctx.save()
|
||||||
|
ctx.translate(px, py)
|
||||||
|
ctx.rotate((rotation * Math.PI) / 180)
|
||||||
|
ctx.drawImage(img, -drawW / 2, -drawH / 2, drawW, drawH)
|
||||||
|
ctx.restore()
|
||||||
|
} catch {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. Draw arrowheads for arrow features
|
||||||
|
for (const f of currentFeatures.filter(f => f.type === 'arrow')) {
|
||||||
|
if (f.geometry.type !== 'LineString') continue
|
||||||
|
const lineCoords = f.geometry.coordinates as number[][]
|
||||||
|
if (lineCoords.length < 2) continue
|
||||||
|
const p1 = lineCoords[lineCoords.length - 2]
|
||||||
|
const p2 = lineCoords[lineCoords.length - 1]
|
||||||
|
const px1 = mapInstance.project(p1 as [number, number])
|
||||||
|
const px2 = mapInstance.project(p2 as [number, number])
|
||||||
|
const angle = Math.atan2(px2.y - px1.y, px2.x - px1.x)
|
||||||
|
const color = (f.properties.color as string) || '#000000'
|
||||||
|
const arrowSize = 14 * dpr
|
||||||
|
|
||||||
ctx.save()
|
ctx.save()
|
||||||
ctx.font = `bold ${fontSize}px sans-serif`
|
ctx.translate(px2.x * dpr, px2.y * dpr)
|
||||||
|
ctx.rotate(angle + Math.PI / 2)
|
||||||
|
ctx.beginPath()
|
||||||
|
ctx.moveTo(0, -arrowSize)
|
||||||
|
ctx.lineTo(-arrowSize * 0.7, arrowSize * 0.3)
|
||||||
|
ctx.lineTo(arrowSize * 0.7, arrowSize * 0.3)
|
||||||
|
ctx.closePath()
|
||||||
ctx.fillStyle = color
|
ctx.fillStyle = color
|
||||||
ctx.textBaseline = 'top'
|
ctx.fill()
|
||||||
ctx.fillText(text, x, y)
|
|
||||||
ctx.restore()
|
ctx.restore()
|
||||||
})
|
}
|
||||||
|
|
||||||
|
// 3. Draw line/polygon labels at midpoints
|
||||||
|
for (const f of currentFeatures.filter(f => f.properties.label && (f.geometry.type === 'LineString' || f.geometry.type === 'Polygon'))) {
|
||||||
|
const label = f.properties.label as string
|
||||||
|
let midpoint: [number, number]
|
||||||
|
|
||||||
|
if (f.geometry.type === 'LineString') {
|
||||||
|
const coords = f.geometry.coordinates as number[][]
|
||||||
|
const midIdx = Math.floor(coords.length / 2)
|
||||||
|
if (coords.length === 2) {
|
||||||
|
midpoint = [(coords[0][0] + coords[1][0]) / 2, (coords[0][1] + coords[1][1]) / 2]
|
||||||
|
} else {
|
||||||
|
midpoint = coords[midIdx] as [number, number]
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
const ring = (f.geometry.coordinates as number[][][])[0]
|
||||||
|
const len = ring.length - 1
|
||||||
|
let cx = 0, cy = 0
|
||||||
|
for (let i = 0; i < len; i++) { cx += ring[i][0]; cy += ring[i][1] }
|
||||||
|
midpoint = [cx / len, cy / len]
|
||||||
|
}
|
||||||
|
|
||||||
|
const pixel = mapInstance.project(midpoint)
|
||||||
|
const px = pixel.x * dpr
|
||||||
|
const py = pixel.y * dpr
|
||||||
|
const isDanger = f.type === 'dangerzone'
|
||||||
|
const bgColor = isDanger ? 'rgba(220,38,38,0.85)' : 'rgba(0,0,0,0.75)'
|
||||||
|
const borderColor = isDanger ? '#dc2626' : 'rgba(255,255,255,0.5)'
|
||||||
|
|
||||||
|
// Build label text with line info
|
||||||
|
let displayText = label
|
||||||
|
let infoText = ''
|
||||||
|
if (f.geometry.type === 'LineString') {
|
||||||
|
const lineCoords = f.geometry.coordinates as number[][]
|
||||||
|
let totalLen = 0
|
||||||
|
for (let i = 1; i < lineCoords.length; i++) {
|
||||||
|
totalLen += haversine(lineCoords[i - 1], lineCoords[i])
|
||||||
|
}
|
||||||
|
const hoseCount = Math.ceil(totalLen / 20)
|
||||||
|
const lenText = totalLen < 1000 ? `${Math.round(totalLen)}m` : `${(totalLen / 1000).toFixed(2)}km`
|
||||||
|
infoText = `${lenText} / ${hoseCount} Schl.`
|
||||||
|
}
|
||||||
|
|
||||||
|
const fontSize1 = 11 * dpr
|
||||||
|
const fontSize2 = 8 * dpr
|
||||||
|
const padX = 6 * dpr
|
||||||
|
const padY = 3 * dpr
|
||||||
|
|
||||||
|
ctx.save()
|
||||||
|
ctx.font = `bold ${fontSize1}px system-ui, sans-serif`
|
||||||
|
const w1 = ctx.measureText(displayText).width
|
||||||
|
let w2 = 0
|
||||||
|
if (infoText) {
|
||||||
|
ctx.font = `${fontSize2}px system-ui, sans-serif`
|
||||||
|
w2 = ctx.measureText(infoText).width
|
||||||
|
}
|
||||||
|
const boxW = Math.max(w1, w2) + padX * 2
|
||||||
|
const boxH = fontSize1 + (infoText ? fontSize2 + 2 * dpr : 0) + padY * 2
|
||||||
|
const radius = 3 * dpr
|
||||||
|
|
||||||
|
// Background
|
||||||
|
ctx.fillStyle = bgColor
|
||||||
|
ctx.beginPath()
|
||||||
|
ctx.roundRect(px - boxW / 2, py - boxH / 2, boxW, boxH, radius)
|
||||||
|
ctx.fill()
|
||||||
|
// Border
|
||||||
|
ctx.strokeStyle = borderColor
|
||||||
|
ctx.lineWidth = 1 * dpr
|
||||||
|
ctx.beginPath()
|
||||||
|
ctx.roundRect(px - boxW / 2, py - boxH / 2, boxW, boxH, radius)
|
||||||
|
ctx.stroke()
|
||||||
|
// Label text
|
||||||
|
ctx.fillStyle = '#ffffff'
|
||||||
|
ctx.font = `bold ${fontSize1}px system-ui, sans-serif`
|
||||||
|
ctx.textAlign = 'center'
|
||||||
|
ctx.textBaseline = 'middle'
|
||||||
|
const textY = infoText ? py - fontSize2 / 2 : py
|
||||||
|
ctx.fillText(displayText, px, textY)
|
||||||
|
// Info text
|
||||||
|
if (infoText) {
|
||||||
|
ctx.font = `${fontSize2}px system-ui, sans-serif`
|
||||||
|
ctx.globalAlpha = 0.8
|
||||||
|
ctx.fillText(infoText, px, py + fontSize1 / 2 + 1 * dpr)
|
||||||
|
ctx.globalAlpha = 1
|
||||||
|
}
|
||||||
|
ctx.restore()
|
||||||
|
}
|
||||||
|
|
||||||
|
// 4. Draw text features
|
||||||
|
for (const f of currentFeatures.filter(f => f.type === 'text')) {
|
||||||
|
if (f.geometry.type !== 'Point') continue
|
||||||
|
const coords = f.geometry.coordinates as [number, number]
|
||||||
|
const pixel = mapInstance.project(coords)
|
||||||
|
const px = pixel.x * dpr
|
||||||
|
const py = pixel.y * dpr
|
||||||
|
const text = (f.properties.text as string) || ''
|
||||||
|
const fontSize = ((f.properties.fontSize as number) || 14) * dpr
|
||||||
|
const color = (f.properties.color as string) || '#000000'
|
||||||
|
|
||||||
|
ctx.save()
|
||||||
|
ctx.font = `bold ${fontSize}px system-ui, sans-serif`
|
||||||
|
ctx.textAlign = 'center'
|
||||||
|
ctx.textBaseline = 'middle'
|
||||||
|
ctx.strokeStyle = '#ffffff'
|
||||||
|
ctx.lineWidth = 3 * dpr
|
||||||
|
ctx.lineJoin = 'round'
|
||||||
|
ctx.strokeText(text, px, py)
|
||||||
|
ctx.fillStyle = color
|
||||||
|
ctx.fillText(text, px, py)
|
||||||
|
ctx.restore()
|
||||||
|
}
|
||||||
|
|
||||||
setLastMapScreenshot(offscreen.toDataURL('image/png'))
|
setLastMapScreenshot(offscreen.toDataURL('image/png'))
|
||||||
} else {
|
} else {
|
||||||
setLastMapScreenshot(mapCanvas.toDataURL('image/png'))
|
setLastMapScreenshot(mapCanvas.toDataURL('image/png'))
|
||||||
@@ -237,6 +367,54 @@ export default function AppPage() {
|
|||||||
// Ref to access the map for export
|
// Ref to access the map for export
|
||||||
const mapRef = useRef<any>(null)
|
const mapRef = useRef<any>(null)
|
||||||
|
|
||||||
|
// Offline detection
|
||||||
|
const [isOffline, setIsOffline] = useState(false)
|
||||||
|
const [syncQueueCount, setSyncQueueCount] = useState(0)
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
setIsOffline(!checkOnline())
|
||||||
|
setSyncQueueCount(getSyncQueue().length)
|
||||||
|
|
||||||
|
const goOffline = () => {
|
||||||
|
setIsOffline(true)
|
||||||
|
toast({ title: 'Offline-Modus', description: 'Änderungen werden lokal gespeichert und beim Reconnect synchronisiert.' })
|
||||||
|
}
|
||||||
|
const goOnline = async () => {
|
||||||
|
setIsOffline(false)
|
||||||
|
const queue = getSyncQueue()
|
||||||
|
if (queue.length > 0) {
|
||||||
|
toast({ title: 'Verbindung wiederhergestellt', description: `${queue.length} Änderung(en) werden synchronisiert...` })
|
||||||
|
const result = await flushSyncQueue()
|
||||||
|
setSyncQueueCount(getSyncQueue().length)
|
||||||
|
if (result.success > 0) {
|
||||||
|
toast({ title: 'Synchronisiert', description: `${result.success} Änderung(en) erfolgreich gespeichert.` })
|
||||||
|
}
|
||||||
|
if (result.failed > 0) {
|
||||||
|
toast({ title: 'Sync-Fehler', description: `${result.failed} Änderung(en) konnten nicht gespeichert werden.`, variant: 'destructive' })
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
toast({ title: 'Wieder online' })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
window.addEventListener('offline', goOffline)
|
||||||
|
window.addEventListener('online', goOnline)
|
||||||
|
|
||||||
|
// Listen for SW sync messages
|
||||||
|
if ('serviceWorker' in navigator) {
|
||||||
|
navigator.serviceWorker.addEventListener('message', (event) => {
|
||||||
|
if (event.data?.type === 'FLUSH_SYNC_QUEUE') {
|
||||||
|
flushSyncQueue().then(() => setSyncQueueCount(getSyncQueue().length))
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
window.removeEventListener('offline', goOffline)
|
||||||
|
window.removeEventListener('online', goOnline)
|
||||||
|
}
|
||||||
|
}, [])
|
||||||
|
|
||||||
// Undo/Redo history
|
// Undo/Redo history
|
||||||
const undoStackRef = useRef<DrawFeature[][]>([])
|
const undoStackRef = useRef<DrawFeature[][]>([])
|
||||||
const redoStackRef = useRef<DrawFeature[][]>([])
|
const redoStackRef = useRef<DrawFeature[][]>([])
|
||||||
@@ -329,27 +507,31 @@ export default function AppPage() {
|
|||||||
const socketRef = useRef<any>(null)
|
const socketRef = useRef<any>(null)
|
||||||
const prevProjectIdRef = useRef<string | null>(null)
|
const prevProjectIdRef = useRef<string | null>(null)
|
||||||
|
|
||||||
// Throttled socket broadcast for near-real-time sync (1.5s instead of 10s auto-save)
|
// Throttled socket broadcast for near-real-time sync
|
||||||
const lastEmitRef = useRef(0)
|
const lastEmitRef = useRef(0)
|
||||||
const emitTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)
|
const emitTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)
|
||||||
|
const currentProjectRef = useRef(currentProject)
|
||||||
|
useEffect(() => { currentProjectRef.current = currentProject }, [currentProject])
|
||||||
|
|
||||||
const broadcastFeatures = useCallback((feats: DrawFeature[]) => {
|
const broadcastFeatures = useCallback((feats: DrawFeature[]) => {
|
||||||
if (!socketRef.current || !currentProject?.id || !isEditingByMe) return
|
const proj = currentProjectRef.current
|
||||||
|
if (!socketRef.current || !proj?.id || !isEditingByMeRef.current) return
|
||||||
const now = Date.now()
|
const now = Date.now()
|
||||||
const emit = () => {
|
const emit = () => {
|
||||||
socketRef.current?.emit('features-updated', {
|
socketRef.current?.emit('features-updated', {
|
||||||
projectId: currentProject!.id,
|
projectId: proj!.id,
|
||||||
features: feats,
|
features: feats,
|
||||||
})
|
})
|
||||||
lastEmitRef.current = Date.now()
|
lastEmitRef.current = Date.now()
|
||||||
}
|
}
|
||||||
// Throttle: emit at most every 1.5 seconds
|
// Throttle: emit at most every 800ms for snappier sync
|
||||||
if (now - lastEmitRef.current > 1500) {
|
if (now - lastEmitRef.current > 800) {
|
||||||
emit()
|
emit()
|
||||||
} else {
|
} else {
|
||||||
if (emitTimerRef.current) clearTimeout(emitTimerRef.current)
|
if (emitTimerRef.current) clearTimeout(emitTimerRef.current)
|
||||||
emitTimerRef.current = setTimeout(emit, 1500 - (now - lastEmitRef.current))
|
emitTimerRef.current = setTimeout(emit, 800 - (now - lastEmitRef.current))
|
||||||
}
|
}
|
||||||
}, [currentProject?.id, isEditingByMe])
|
}, [])
|
||||||
const isEditingByMeRef = useRef(false)
|
const isEditingByMeRef = useRef(false)
|
||||||
|
|
||||||
// Keep ref in sync with state
|
// Keep ref in sync with state
|
||||||
@@ -368,6 +550,7 @@ export default function AppPage() {
|
|||||||
socket.emit('leave-project', prevProjectIdRef.current)
|
socket.emit('leave-project', prevProjectIdRef.current)
|
||||||
}
|
}
|
||||||
socket.emit('join-project', currentProject.id)
|
socket.emit('join-project', currentProject.id)
|
||||||
|
setSocketRoom(currentProject.id)
|
||||||
prevProjectIdRef.current = currentProject.id
|
prevProjectIdRef.current = currentProject.id
|
||||||
|
|
||||||
// Listen for features changes from other clients (only apply if NOT the editor)
|
// Listen for features changes from other clients (only apply if NOT the editor)
|
||||||
@@ -514,11 +697,22 @@ export default function AppPage() {
|
|||||||
const saveTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)
|
const saveTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)
|
||||||
const saveFeaturesToApi = useCallback(async () => {
|
const saveFeaturesToApi = useCallback(async () => {
|
||||||
if (!currentProject?.id) return
|
if (!currentProject?.id) return
|
||||||
|
const url = `/api/projects/${currentProject.id}/features`
|
||||||
|
const body = { features: featuresRef.current }
|
||||||
|
|
||||||
|
// If offline, queue the save for later sync
|
||||||
|
if (!navigator.onLine) {
|
||||||
|
addToSyncQueue(url, 'PUT', body)
|
||||||
|
setSyncQueueCount(getSyncQueue().length)
|
||||||
|
console.log('[Auto-Save] Offline — in Sync-Queue gespeichert')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const res = await fetch(`/api/projects/${currentProject.id}/features`, {
|
const res = await fetch(url, {
|
||||||
method: 'PUT',
|
method: 'PUT',
|
||||||
headers: { 'Content-Type': 'application/json' },
|
headers: { 'Content-Type': 'application/json' },
|
||||||
body: JSON.stringify({ features: featuresRef.current }),
|
body: JSON.stringify(body),
|
||||||
})
|
})
|
||||||
if (res.ok) {
|
if (res.ok) {
|
||||||
console.log('[Auto-Save] Features gespeichert')
|
console.log('[Auto-Save] Features gespeichert')
|
||||||
@@ -530,7 +724,10 @@ export default function AppPage() {
|
|||||||
console.warn('[Auto-Save] Projekt nicht in DB')
|
console.warn('[Auto-Save] Projekt nicht in DB')
|
||||||
}
|
}
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.warn('[Auto-Save] Fehler:', e)
|
// Network error — queue for later
|
||||||
|
addToSyncQueue(url, 'PUT', body)
|
||||||
|
setSyncQueueCount(getSyncQueue().length)
|
||||||
|
console.warn('[Auto-Save] Netzwerkfehler — in Sync-Queue:', e)
|
||||||
}
|
}
|
||||||
}, [currentProject])
|
}, [currentProject])
|
||||||
|
|
||||||
@@ -1001,6 +1198,32 @@ export default function AppPage() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Draw arrowheads for arrow features
|
||||||
|
for (const f of currentFeatures.filter(f => f.type === 'arrow')) {
|
||||||
|
if (f.geometry.type !== 'LineString') continue
|
||||||
|
const lineCoords = f.geometry.coordinates as number[][]
|
||||||
|
if (lineCoords.length < 2) continue
|
||||||
|
const p1 = lineCoords[lineCoords.length - 2]
|
||||||
|
const p2 = lineCoords[lineCoords.length - 1]
|
||||||
|
const px1 = mapInstance.project(p1 as [number, number])
|
||||||
|
const px2 = mapInstance.project(p2 as [number, number])
|
||||||
|
const angle = Math.atan2(px2.y - px1.y, px2.x - px1.x)
|
||||||
|
const color = (f.properties.color as string) || '#000000'
|
||||||
|
const arrowSize = 14 * dpr
|
||||||
|
|
||||||
|
ctx.save()
|
||||||
|
ctx.translate(px2.x * dpr, px2.y * dpr)
|
||||||
|
ctx.rotate(angle + Math.PI / 2)
|
||||||
|
ctx.beginPath()
|
||||||
|
ctx.moveTo(0, -arrowSize)
|
||||||
|
ctx.lineTo(-arrowSize * 0.7, arrowSize * 0.3)
|
||||||
|
ctx.lineTo(arrowSize * 0.7, arrowSize * 0.3)
|
||||||
|
ctx.closePath()
|
||||||
|
ctx.fillStyle = color
|
||||||
|
ctx.fill()
|
||||||
|
ctx.restore()
|
||||||
|
}
|
||||||
|
|
||||||
// Draw line/polygon label markers at midpoints
|
// Draw line/polygon label markers at midpoints
|
||||||
for (const f of currentFeatures.filter(f => f.properties.label && (f.geometry.type === 'LineString' || f.geometry.type === 'Polygon'))) {
|
for (const f of currentFeatures.filter(f => f.properties.label && (f.geometry.type === 'LineString' || f.geometry.type === 'Polygon'))) {
|
||||||
const label = f.properties.label as string
|
const label = f.properties.label as string
|
||||||
@@ -1234,6 +1457,40 @@ export default function AppPage() {
|
|||||||
onLogout={logout}
|
onLogout={logout}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
|
{/* Offline banner */}
|
||||||
|
{isOffline && (
|
||||||
|
<div className="flex items-center justify-center gap-3 px-4 py-2 bg-orange-50 dark:bg-orange-950/40 border-b border-orange-200 dark:border-orange-800 text-sm text-orange-800 dark:text-orange-300">
|
||||||
|
<WifiOff className="w-4 h-4 shrink-0" />
|
||||||
|
<span>
|
||||||
|
<strong>Offline-Modus</strong> — Änderungen werden lokal gespeichert und beim Reconnect synchronisiert.
|
||||||
|
{syncQueueCount > 0 && ` (${syncQueueCount} ausstehend)`}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Email verification banner */}
|
||||||
|
{user && user.emailVerified === false && (
|
||||||
|
<div className="flex items-center justify-center gap-3 px-4 py-2 bg-amber-50 dark:bg-amber-950/40 border-b border-amber-200 dark:border-amber-800 text-sm text-amber-800 dark:text-amber-300">
|
||||||
|
<AlertTriangle className="w-4 h-4 shrink-0" />
|
||||||
|
<span>Ihre E-Mail-Adresse wurde noch nicht bestätigt. Bitte prüfen Sie Ihren Posteingang.</span>
|
||||||
|
<button
|
||||||
|
onClick={async () => {
|
||||||
|
try {
|
||||||
|
const res = await fetch('/api/auth/resend-verification', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({ email: user.email }),
|
||||||
|
})
|
||||||
|
if (res.ok) toast({ title: 'Bestätigungsmail gesendet', description: 'Bitte prüfen Sie Ihren Posteingang.' })
|
||||||
|
else toast({ title: 'Fehler', description: 'Konnte Bestätigungsmail nicht senden.', variant: 'destructive' })
|
||||||
|
} catch { toast({ title: 'Fehler', description: 'Verbindungsfehler.', variant: 'destructive' }) }
|
||||||
|
}}
|
||||||
|
className="shrink-0 text-xs font-semibold underline hover:no-underline text-amber-700 dark:text-amber-400"
|
||||||
|
>
|
||||||
|
Erneut senden
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
{/* Live editing banner */}
|
{/* Live editing banner */}
|
||||||
{currentProject && (
|
{currentProject && (
|
||||||
|
|||||||
@@ -23,6 +23,8 @@ function LoginForm() {
|
|||||||
const [email, setEmail] = useState('')
|
const [email, setEmail] = useState('')
|
||||||
const [password, setPassword] = useState('')
|
const [password, setPassword] = useState('')
|
||||||
const [isLoading, setIsLoading] = useState(false)
|
const [isLoading, setIsLoading] = useState(false)
|
||||||
|
const [resendLoading, setResendLoading] = useState(false)
|
||||||
|
const [resendSuccess, setResendSuccess] = useState(false)
|
||||||
const [tenantLogo, setTenantLogo] = useState<string | null>(null)
|
const [tenantLogo, setTenantLogo] = useState<string | null>(null)
|
||||||
const [tenantName, setTenantName] = useState<string | null>(null)
|
const [tenantName, setTenantName] = useState<string | null>(null)
|
||||||
const { login } = useAuth()
|
const { login } = useAuth()
|
||||||
@@ -110,7 +112,32 @@ function LoginForm() {
|
|||||||
)}
|
)}
|
||||||
{errorParam === 'invalid-token' && (
|
{errorParam === 'invalid-token' && (
|
||||||
<div className="bg-red-50 dark:bg-red-950/30 border border-red-200 dark:border-red-800 rounded-lg p-3 mb-4 text-sm text-red-700 dark:text-red-400 text-center">
|
<div className="bg-red-50 dark:bg-red-950/30 border border-red-200 dark:border-red-800 rounded-lg p-3 mb-4 text-sm text-red-700 dark:text-red-400 text-center">
|
||||||
Ungültiger oder abgelaufener Bestätigungslink.
|
<p>Ungültiger oder abgelaufener Bestätigungslink.</p>
|
||||||
|
<p className="mt-1 text-xs">Geben Sie Ihre E-Mail ein und klicken Sie unten, um einen neuen Link zu erhalten.</p>
|
||||||
|
{resendSuccess ? (
|
||||||
|
<p className="mt-2 text-green-600 dark:text-green-400 font-medium">Neue Bestätigungsmail gesendet!</p>
|
||||||
|
) : (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
disabled={resendLoading || !email}
|
||||||
|
onClick={async () => {
|
||||||
|
setResendLoading(true)
|
||||||
|
try {
|
||||||
|
const res = await fetch('/api/auth/resend-verification', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({ email }),
|
||||||
|
})
|
||||||
|
if (res.ok) setResendSuccess(true)
|
||||||
|
else toast({ title: 'Fehler', description: 'Konnte Bestätigungsmail nicht senden.', variant: 'destructive' })
|
||||||
|
} catch { toast({ title: 'Fehler', description: 'Verbindungsfehler.', variant: 'destructive' }) }
|
||||||
|
setResendLoading(false)
|
||||||
|
}}
|
||||||
|
className="mt-2 text-xs font-medium text-red-600 dark:text-red-400 underline hover:no-underline disabled:opacity-50"
|
||||||
|
>
|
||||||
|
{resendLoading ? 'Wird gesendet...' : 'Bestätigungsmail erneut senden'}
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
'use client'
|
'use client'
|
||||||
|
|
||||||
import { useState, useEffect } from 'react'
|
import { useState, useEffect, use } from 'react'
|
||||||
import { Loader2, FileText, Download, Printer, MapPin, Send, CheckCircle, XCircle } from 'lucide-react'
|
import { Loader2, FileText, Download, Printer, MapPin, Send, CheckCircle, XCircle } from 'lucide-react'
|
||||||
|
|
||||||
interface RapportViewData {
|
interface RapportViewData {
|
||||||
@@ -13,7 +13,8 @@ interface RapportViewData {
|
|||||||
createdBy: { name: string } | null
|
createdBy: { name: string } | null
|
||||||
}
|
}
|
||||||
|
|
||||||
export default function RapportViewerPage({ params }: { params: { token: string } }) {
|
export default function RapportViewerPage({ params }: { params: Promise<{ token: string }> }) {
|
||||||
|
const { token } = use(params)
|
||||||
const [rapport, setRapport] = useState<RapportViewData | null>(null)
|
const [rapport, setRapport] = useState<RapportViewData | null>(null)
|
||||||
const [isLoading, setIsLoading] = useState(true)
|
const [isLoading, setIsLoading] = useState(true)
|
||||||
const [error, setError] = useState('')
|
const [error, setError] = useState('')
|
||||||
@@ -25,7 +26,7 @@ export default function RapportViewerPage({ params }: { params: { token: string
|
|||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
async function load() {
|
async function load() {
|
||||||
try {
|
try {
|
||||||
const res = await fetch(`/api/rapports/${params.token}`)
|
const res = await fetch(`/api/rapports/${token}`)
|
||||||
if (res.ok) {
|
if (res.ok) {
|
||||||
setRapport(await res.json())
|
setRapport(await res.json())
|
||||||
} else {
|
} else {
|
||||||
@@ -38,7 +39,7 @@ export default function RapportViewerPage({ params }: { params: { token: string
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
load()
|
load()
|
||||||
}, [params.token])
|
}, [token])
|
||||||
|
|
||||||
if (isLoading) {
|
if (isLoading) {
|
||||||
return (
|
return (
|
||||||
@@ -64,7 +65,7 @@ export default function RapportViewerPage({ params }: { params: { token: string
|
|||||||
}
|
}
|
||||||
|
|
||||||
const d = rapport.data
|
const d = rapport.data
|
||||||
const pdfUrl = `/api/rapports/${params.token}/pdf`
|
const pdfUrl = `/api/rapports/${token}/pdf`
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="min-h-screen bg-gray-100 py-8">
|
<div className="min-h-screen bg-gray-100 py-8">
|
||||||
@@ -119,7 +120,7 @@ export default function RapportViewerPage({ params }: { params: { token: string
|
|||||||
setEmailSending(true)
|
setEmailSending(true)
|
||||||
setEmailStatus(null)
|
setEmailStatus(null)
|
||||||
try {
|
try {
|
||||||
const res = await fetch(`/api/rapports/${params.token}/send`, {
|
const res = await fetch(`/api/rapports/${token}/send`, {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: { 'Content-Type': 'application/json' },
|
headers: { 'Content-Type': 'application/json' },
|
||||||
body: JSON.stringify({ email: emailTo }),
|
body: JSON.stringify({ email: emailTo }),
|
||||||
|
|||||||
@@ -30,8 +30,8 @@ export default function RegisterPage() {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
if (password.length < 6) {
|
if (password.length < 8) {
|
||||||
toast({ title: 'Passwort muss mindestens 6 Zeichen haben', variant: 'destructive' })
|
toast({ title: 'Passwort muss mindestens 8 Zeichen haben', variant: 'destructive' })
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -163,7 +163,7 @@ export default function RegisterPage() {
|
|||||||
<Input
|
<Input
|
||||||
id="password"
|
id="password"
|
||||||
type="password"
|
type="password"
|
||||||
placeholder="Mindestens 6 Zeichen"
|
placeholder="Mindestens 8 Zeichen"
|
||||||
value={password}
|
value={password}
|
||||||
onChange={(e) => setPassword(e.target.value)}
|
onChange={(e) => setPassword(e.target.value)}
|
||||||
required
|
required
|
||||||
|
|||||||
@@ -32,8 +32,8 @@ function ResetPasswordForm() {
|
|||||||
e.preventDefault()
|
e.preventDefault()
|
||||||
setError('')
|
setError('')
|
||||||
|
|
||||||
if (password.length < 6) {
|
if (password.length < 8) {
|
||||||
setError('Passwort muss mindestens 6 Zeichen lang sein.')
|
setError('Passwort muss mindestens 8 Zeichen lang sein.')
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if (password !== confirmPassword) {
|
if (password !== confirmPassword) {
|
||||||
@@ -108,7 +108,7 @@ function ResetPasswordForm() {
|
|||||||
<Input
|
<Input
|
||||||
id="password"
|
id="password"
|
||||||
type="password"
|
type="password"
|
||||||
placeholder="Min. 6 Zeichen"
|
placeholder="Min. 8 Zeichen"
|
||||||
value={password}
|
value={password}
|
||||||
onChange={(e) => setPassword(e.target.value)}
|
onChange={(e) => setPassword(e.target.value)}
|
||||||
required
|
required
|
||||||
|
|||||||
@@ -1030,8 +1030,8 @@ export function JournalView({ projectId, projectTitle, projectLocation, einsatzl
|
|||||||
if (mapRef?.current) {
|
if (mapRef?.current) {
|
||||||
const canvas = mapRef.current.getCanvas()
|
const canvas = mapRef.current.getCanvas()
|
||||||
if (canvas) {
|
if (canvas) {
|
||||||
// Resize to max 1600px wide and convert to JPEG
|
// Resize to max 2400px wide and convert to JPEG
|
||||||
const maxW = 1600
|
const maxW = 2400
|
||||||
const ratio = Math.min(1, maxW / canvas.width)
|
const ratio = Math.min(1, maxW / canvas.width)
|
||||||
const offscreen = document.createElement('canvas')
|
const offscreen = document.createElement('canvas')
|
||||||
offscreen.width = Math.round(canvas.width * ratio)
|
offscreen.width = Math.round(canvas.width * ratio)
|
||||||
@@ -1039,18 +1039,18 @@ export function JournalView({ projectId, projectTitle, projectLocation, einsatzl
|
|||||||
const ctx = offscreen.getContext('2d')
|
const ctx = offscreen.getContext('2d')
|
||||||
if (ctx) {
|
if (ctx) {
|
||||||
ctx.drawImage(canvas, 0, 0, offscreen.width, offscreen.height)
|
ctx.drawImage(canvas, 0, 0, offscreen.width, offscreen.height)
|
||||||
mapScreenshot = offscreen.toDataURL('image/jpeg', 0.75)
|
mapScreenshot = offscreen.toDataURL('image/jpeg', 0.85)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} catch (e) { console.warn('Map screenshot failed:', e) }
|
} catch (e) { console.warn('Map screenshot failed:', e) }
|
||||||
} else if (rawScreenshot.length > 500000) {
|
} else if (rawScreenshot.length > 800000) {
|
||||||
// Compress pre-captured screenshot if too large
|
// Compress pre-captured screenshot if too large
|
||||||
try {
|
try {
|
||||||
const img = new Image()
|
const img = new Image()
|
||||||
img.src = rawScreenshot
|
img.src = rawScreenshot
|
||||||
await new Promise(r => { img.onload = r; img.onerror = r })
|
await new Promise(r => { img.onload = r; img.onerror = r })
|
||||||
const maxW = 1600
|
const maxW = 2400
|
||||||
const ratio = Math.min(1, maxW / img.naturalWidth)
|
const ratio = Math.min(1, maxW / img.naturalWidth)
|
||||||
const offscreen = document.createElement('canvas')
|
const offscreen = document.createElement('canvas')
|
||||||
offscreen.width = Math.round(img.naturalWidth * ratio)
|
offscreen.width = Math.round(img.naturalWidth * ratio)
|
||||||
@@ -1058,7 +1058,7 @@ export function JournalView({ projectId, projectTitle, projectLocation, einsatzl
|
|||||||
const ctx = offscreen.getContext('2d')
|
const ctx = offscreen.getContext('2d')
|
||||||
if (ctx) {
|
if (ctx) {
|
||||||
ctx.drawImage(img, 0, 0, offscreen.width, offscreen.height)
|
ctx.drawImage(img, 0, 0, offscreen.width, offscreen.height)
|
||||||
mapScreenshot = offscreen.toDataURL('image/jpeg', 0.75)
|
mapScreenshot = offscreen.toDataURL('image/jpeg', 0.85)
|
||||||
}
|
}
|
||||||
} catch { mapScreenshot = rawScreenshot }
|
} catch { mapScreenshot = rawScreenshot }
|
||||||
} else {
|
} else {
|
||||||
|
|||||||
@@ -38,6 +38,7 @@ import {
|
|||||||
Key,
|
Key,
|
||||||
Shield,
|
Shield,
|
||||||
Building2,
|
Building2,
|
||||||
|
MapPin,
|
||||||
} from 'lucide-react'
|
} from 'lucide-react'
|
||||||
import { HoseSettingsDialog } from '@/components/dialogs/hose-settings-dialog'
|
import { HoseSettingsDialog } from '@/components/dialogs/hose-settings-dialog'
|
||||||
import type { Project, DrawFeature } from '@/app/app/page'
|
import type { Project, DrawFeature } from '@/app/app/page'
|
||||||
@@ -90,6 +91,10 @@ export function Topbar({
|
|||||||
const [isLoadDialogOpen, setIsLoadDialogOpen] = useState(false)
|
const [isLoadDialogOpen, setIsLoadDialogOpen] = useState(false)
|
||||||
const [isHoseSettingsOpen, setIsHoseSettingsOpen] = useState(false)
|
const [isHoseSettingsOpen, setIsHoseSettingsOpen] = useState(false)
|
||||||
const [showPasswordDialog, setShowPasswordDialog] = useState(false)
|
const [showPasswordDialog, setShowPasswordDialog] = useState(false)
|
||||||
|
const [showDeleteAccountDialog, setShowDeleteAccountDialog] = useState(false)
|
||||||
|
const [deleteAccountPw, setDeleteAccountPw] = useState('')
|
||||||
|
const [deleteAccountLoading, setDeleteAccountLoading] = useState(false)
|
||||||
|
const [deleteAccountError, setDeleteAccountError] = useState('')
|
||||||
const [pwOld, setPwOld] = useState('')
|
const [pwOld, setPwOld] = useState('')
|
||||||
const [pwNew, setPwNew] = useState('')
|
const [pwNew, setPwNew] = useState('')
|
||||||
const [pwConfirm, setPwConfirm] = useState('')
|
const [pwConfirm, setPwConfirm] = useState('')
|
||||||
@@ -289,6 +294,13 @@ export function Topbar({
|
|||||||
Administration
|
Administration
|
||||||
</DropdownMenuItem>
|
</DropdownMenuItem>
|
||||||
)}
|
)}
|
||||||
|
<DropdownMenuItem
|
||||||
|
onClick={() => { setShowDeleteAccountDialog(true); setDeleteAccountPw(''); setDeleteAccountError('') }}
|
||||||
|
className="text-destructive focus:text-destructive"
|
||||||
|
>
|
||||||
|
<Trash2 className="w-4 h-4 mr-2" />
|
||||||
|
Konto löschen
|
||||||
|
</DropdownMenuItem>
|
||||||
<DropdownMenuItem onClick={onLogout} className="text-destructive focus:text-destructive">
|
<DropdownMenuItem onClick={onLogout} className="text-destructive focus:text-destructive">
|
||||||
<LogOut className="w-4 h-4 mr-2" />
|
<LogOut className="w-4 h-4 mr-2" />
|
||||||
Abmelden
|
Abmelden
|
||||||
@@ -538,6 +550,81 @@ export function Topbar({
|
|||||||
</div>
|
</div>
|
||||||
</DialogContent>
|
</DialogContent>
|
||||||
</Dialog>
|
</Dialog>
|
||||||
|
|
||||||
|
{/* Delete Account Dialog */}
|
||||||
|
<Dialog open={showDeleteAccountDialog} onOpenChange={setShowDeleteAccountDialog}>
|
||||||
|
<DialogContent className="max-w-sm">
|
||||||
|
<DialogHeader>
|
||||||
|
<DialogTitle className="flex items-center gap-2 text-destructive">
|
||||||
|
<AlertTriangle className="w-5 h-5" />
|
||||||
|
Konto löschen
|
||||||
|
</DialogTitle>
|
||||||
|
</DialogHeader>
|
||||||
|
<div className="space-y-4">
|
||||||
|
<p className="text-sm text-muted-foreground">
|
||||||
|
Ihr Konto wird unwiderruflich gelöscht. Ihre Projekte und Daten bleiben der Organisation erhalten,
|
||||||
|
aber Ihr persönlicher Zugang wird entfernt.
|
||||||
|
</p>
|
||||||
|
{userRole === 'TENANT_ADMIN' && (
|
||||||
|
<div className="bg-amber-50 dark:bg-amber-950/30 rounded-lg p-3 text-xs text-amber-800 dark:text-amber-300 border border-amber-200 dark:border-amber-800">
|
||||||
|
<strong>Hinweis:</strong> Als einziger Administrator müssen Sie zuerst die Organisation unter Einstellungen löschen oder die Admin-Rolle übertragen.
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
<div className="space-y-1.5">
|
||||||
|
<label className="text-sm font-medium">Passwort zur Bestätigung</label>
|
||||||
|
<input
|
||||||
|
type="password"
|
||||||
|
value={deleteAccountPw}
|
||||||
|
onChange={(e) => { setDeleteAccountPw(e.target.value); setDeleteAccountError('') }}
|
||||||
|
placeholder="Ihr Passwort"
|
||||||
|
className="w-full rounded-md border border-input bg-background px-3 py-2 text-sm"
|
||||||
|
autoComplete="current-password"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
{deleteAccountError && (
|
||||||
|
<p className="text-sm text-destructive">{deleteAccountError}</p>
|
||||||
|
)}
|
||||||
|
<div className="flex gap-2 justify-end">
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
size="sm"
|
||||||
|
onClick={() => setShowDeleteAccountDialog(false)}
|
||||||
|
disabled={deleteAccountLoading}
|
||||||
|
>
|
||||||
|
Abbrechen
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
variant="destructive"
|
||||||
|
size="sm"
|
||||||
|
disabled={deleteAccountLoading || !deleteAccountPw}
|
||||||
|
onClick={async () => {
|
||||||
|
setDeleteAccountLoading(true)
|
||||||
|
setDeleteAccountError('')
|
||||||
|
try {
|
||||||
|
const res = await fetch('/api/auth/delete-account', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({ password: deleteAccountPw }),
|
||||||
|
})
|
||||||
|
const data = await res.json()
|
||||||
|
if (res.ok) {
|
||||||
|
window.location.href = '/'
|
||||||
|
} else {
|
||||||
|
setDeleteAccountError(data.error || 'Löschung fehlgeschlagen')
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
setDeleteAccountError('Verbindungsfehler')
|
||||||
|
} finally {
|
||||||
|
setDeleteAccountLoading(false)
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{deleteAccountLoading ? 'Wird gelöscht...' : 'Konto endgültig löschen'}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
</header>
|
</header>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -23,6 +23,19 @@ function formatDistance(meters: number): string {
|
|||||||
return `${(meters / 1000).toFixed(2)} km`
|
return `${(meters / 1000).toFixed(2)} km`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Approximate polygon area in m² using the Shoelace formula on spherical coordinates
|
||||||
|
function polygonArea(ring: number[][]): number {
|
||||||
|
const toRad = Math.PI / 180
|
||||||
|
const R = 6371000
|
||||||
|
let area = 0
|
||||||
|
const n = ring.length - 1 // exclude closing duplicate
|
||||||
|
for (let i = 0; i < n; i++) {
|
||||||
|
const j = (i + 1) % n
|
||||||
|
area += (ring[j][0] - ring[i][0]) * toRad * (2 + Math.sin(ring[i][1] * toRad) + Math.sin(ring[j][1] * toRad))
|
||||||
|
}
|
||||||
|
return Math.abs(area * R * R / 2)
|
||||||
|
}
|
||||||
|
|
||||||
// Point-to-segment distance in screen pixels (for click detection on lines)
|
// Point-to-segment distance in screen pixels (for click detection on lines)
|
||||||
function pointToSegmentDist(px: number, py: number, x1: number, y1: number, x2: number, y2: number): number {
|
function pointToSegmentDist(px: number, py: number, x1: number, y1: number, x2: number, y2: number): number {
|
||||||
const dx = x2 - x1, dy = y2 - y1
|
const dx = x2 - x1, dy = y2 - y1
|
||||||
@@ -93,7 +106,7 @@ export function MapView({
|
|||||||
const measureMarkersRef = useRef<maplibregl.Marker[]>([])
|
const measureMarkersRef = useRef<maplibregl.Marker[]>([])
|
||||||
const measureCoordsRef = useRef<number[][]>([])
|
const measureCoordsRef = useRef<number[][]>([])
|
||||||
const [isMapLoaded, setIsMapLoaded] = useState(false)
|
const [isMapLoaded, setIsMapLoaded] = useState(false)
|
||||||
const [isSatellite, setIsSatellite] = useState(false)
|
const [activeBaseLayer, setActiveBaseLayer] = useState<'osm' | 'satellite' | 'swisstopo' | 'swissimage'>('osm')
|
||||||
const [measurePointCount, setMeasurePointCount] = useState(0)
|
const [measurePointCount, setMeasurePointCount] = useState(0)
|
||||||
const [measureFinished, setMeasureFinished] = useState(false)
|
const [measureFinished, setMeasureFinished] = useState(false)
|
||||||
const [drawingPointCount, setDrawingPointCount] = useState(0)
|
const [drawingPointCount, setDrawingPointCount] = useState(0)
|
||||||
@@ -676,6 +689,24 @@ export function MapView({
|
|||||||
attribution: '© Esri, Maxar, Earthstar Geographics',
|
attribution: '© Esri, Maxar, Earthstar Geographics',
|
||||||
maxzoom: 19,
|
maxzoom: 19,
|
||||||
},
|
},
|
||||||
|
'swisstopo': {
|
||||||
|
type: 'raster',
|
||||||
|
tiles: [
|
||||||
|
'https://wmts.geo.admin.ch/1.0.0/ch.swisstopo.pixelkarte-farbe/default/current/3857/{z}/{x}/{y}.jpeg',
|
||||||
|
],
|
||||||
|
tileSize: 256,
|
||||||
|
attribution: '© swisstopo',
|
||||||
|
maxzoom: 18,
|
||||||
|
},
|
||||||
|
'swissimage': {
|
||||||
|
type: 'raster',
|
||||||
|
tiles: [
|
||||||
|
'https://wmts.geo.admin.ch/1.0.0/ch.swisstopo.swissimage/default/current/3857/{z}/{x}/{y}.jpeg',
|
||||||
|
],
|
||||||
|
tileSize: 256,
|
||||||
|
attribution: '© swisstopo SWISSIMAGE',
|
||||||
|
maxzoom: 20,
|
||||||
|
},
|
||||||
},
|
},
|
||||||
layers: [
|
layers: [
|
||||||
{
|
{
|
||||||
@@ -689,6 +720,18 @@ export function MapView({
|
|||||||
source: 'satellite',
|
source: 'satellite',
|
||||||
layout: { visibility: 'none' },
|
layout: { visibility: 'none' },
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
id: 'swisstopo',
|
||||||
|
type: 'raster',
|
||||||
|
source: 'swisstopo',
|
||||||
|
layout: { visibility: 'none' },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'swissimage',
|
||||||
|
type: 'raster',
|
||||||
|
source: 'swissimage',
|
||||||
|
layout: { visibility: 'none' },
|
||||||
|
},
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
center: [initialCenter.lng, initialCenter.lat],
|
center: [initialCenter.lng, initialCenter.lat],
|
||||||
@@ -718,6 +761,9 @@ export function MapView({
|
|||||||
if (!m) return
|
if (!m) return
|
||||||
setIsMapLoaded(true)
|
setIsMapLoaded(true)
|
||||||
|
|
||||||
|
// Guard: skip if sources already exist (React strict mode double-mount)
|
||||||
|
if (m.getSource('draw-features')) return
|
||||||
|
|
||||||
// Drawing features source
|
// Drawing features source
|
||||||
m.addSource('draw-features', {
|
m.addSource('draw-features', {
|
||||||
type: 'geojson',
|
type: 'geojson',
|
||||||
@@ -937,7 +983,7 @@ export function MapView({
|
|||||||
// Eraser mode: click on/near a feature to delete it
|
// Eraser mode: click on/near a feature to delete it
|
||||||
if (mode === 'eraser') {
|
if (mode === 'eraser') {
|
||||||
const pixel = e.point
|
const pixel = e.point
|
||||||
const tolerance = 10 // px
|
const tolerance = 20 // px
|
||||||
const currentFeatures = featuresRef.current
|
const currentFeatures = featuresRef.current
|
||||||
let closestIdx = -1
|
let closestIdx = -1
|
||||||
let closestDist = Infinity
|
let closestDist = Infinity
|
||||||
@@ -946,29 +992,44 @@ export function MapView({
|
|||||||
const f = currentFeatures[i]
|
const f = currentFeatures[i]
|
||||||
const geom = f.geometry
|
const geom = f.geometry
|
||||||
|
|
||||||
// Get all coordinates to check proximity
|
|
||||||
let allCoords: number[][] = []
|
|
||||||
if (geom.type === 'Point') {
|
if (geom.type === 'Point') {
|
||||||
allCoords = [geom.coordinates as number[]]
|
const projected = m.project(geom.coordinates as [number, number])
|
||||||
} else if (geom.type === 'LineString') {
|
|
||||||
allCoords = geom.coordinates as number[][]
|
|
||||||
} else if (geom.type === 'Polygon') {
|
|
||||||
allCoords = (geom.coordinates as number[][][])[0] || []
|
|
||||||
}
|
|
||||||
|
|
||||||
for (const c of allCoords) {
|
|
||||||
const projected = m.project([c[0], c[1]])
|
|
||||||
const dx = projected.x - pixel.x
|
const dx = projected.x - pixel.x
|
||||||
const dy = projected.y - pixel.y
|
const dy = projected.y - pixel.y
|
||||||
const dist = Math.sqrt(dx * dx + dy * dy)
|
const dist = Math.sqrt(dx * dx + dy * dy)
|
||||||
if (dist < closestDist) {
|
if (dist < closestDist) { closestDist = dist; closestIdx = i }
|
||||||
closestDist = dist
|
} else if (geom.type === 'LineString') {
|
||||||
closestIdx = i
|
const lineCoords = geom.coordinates as number[][]
|
||||||
|
for (let j = 0; j < lineCoords.length - 1; j++) {
|
||||||
|
const p1 = m.project(lineCoords[j] as [number, number])
|
||||||
|
const p2 = m.project(lineCoords[j + 1] as [number, number])
|
||||||
|
const dist = pointToSegmentDist(pixel.x, pixel.y, p1.x, p1.y, p2.x, p2.y)
|
||||||
|
if (dist < closestDist) { closestDist = dist; closestIdx = i }
|
||||||
}
|
}
|
||||||
|
} else if (geom.type === 'Polygon') {
|
||||||
|
const ring = (geom.coordinates as number[][][])[0] || []
|
||||||
|
// Check edges
|
||||||
|
for (let j = 0; j < ring.length - 1; j++) {
|
||||||
|
const p1 = m.project(ring[j] as [number, number])
|
||||||
|
const p2 = m.project(ring[j + 1] as [number, number])
|
||||||
|
const dist = pointToSegmentDist(pixel.x, pixel.y, p1.x, p1.y, p2.x, p2.y)
|
||||||
|
if (dist < closestDist) { closestDist = dist; closestIdx = i }
|
||||||
|
}
|
||||||
|
// Point-in-polygon test (screen space)
|
||||||
|
const projected = ring.map(c => m.project(c as [number, number]))
|
||||||
|
let inside = false
|
||||||
|
for (let j = 0, k = projected.length - 1; j < projected.length; k = j++) {
|
||||||
|
const xi = projected[j].x, yi = projected[j].y
|
||||||
|
const xk = projected[k].x, yk = projected[k].y
|
||||||
|
if (((yi > pixel.y) !== (yk > pixel.y)) && (pixel.x < (xk - xi) * (pixel.y - yi) / (yk - yi) + xi)) {
|
||||||
|
inside = !inside
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (inside) { closestDist = 0; closestIdx = i }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (closestIdx >= 0 && closestDist < tolerance * 3) {
|
if (closestIdx >= 0 && closestDist < tolerance) {
|
||||||
const deleted = currentFeatures[closestIdx]
|
const deleted = currentFeatures[closestIdx]
|
||||||
const newFeatures = currentFeatures.filter((_, i) => i !== closestIdx)
|
const newFeatures = currentFeatures.filter((_, i) => i !== closestIdx)
|
||||||
onFeaturesChangeRef.current(newFeatures)
|
onFeaturesChangeRef.current(newFeatures)
|
||||||
@@ -1374,12 +1435,12 @@ export function MapView({
|
|||||||
const lineCoords = f.geometry.coordinates as number[][]
|
const lineCoords = f.geometry.coordinates as number[][]
|
||||||
if (lineCoords.length < 2) return
|
if (lineCoords.length < 2) return
|
||||||
|
|
||||||
// Get last two points to calculate arrow direction
|
// Get last two points to calculate arrow direction using screen-projected coords
|
||||||
const p1 = lineCoords[lineCoords.length - 2]
|
const p1 = lineCoords[lineCoords.length - 2]
|
||||||
const p2 = lineCoords[lineCoords.length - 1]
|
const p2 = lineCoords[lineCoords.length - 1]
|
||||||
const angle = Math.atan2(p2[1] - p1[1], p2[0] - p1[0]) * (180 / Math.PI)
|
const px1 = map.current.project(p1 as [number, number])
|
||||||
// MapLibre uses screen coords where Y is inverted, so negate the angle
|
const px2 = map.current.project(p2 as [number, number])
|
||||||
const screenAngle = -angle + 90
|
const screenAngle = Math.atan2(px2.y - px1.y, px2.x - px1.x) * (180 / Math.PI) + 90
|
||||||
|
|
||||||
const color = (f.properties.color as string) || '#000000'
|
const color = (f.properties.color as string) || '#000000'
|
||||||
const arrowEl = document.createElement('div')
|
const arrowEl = document.createElement('div')
|
||||||
@@ -1393,7 +1454,7 @@ export function MapView({
|
|||||||
pointer-events: none;
|
pointer-events: none;
|
||||||
`
|
`
|
||||||
|
|
||||||
const marker = new maplibregl.Marker({ element: arrowEl, anchor: 'center' })
|
const marker = new maplibregl.Marker({ element: arrowEl, anchor: 'center', rotationAlignment: 'viewport' })
|
||||||
.setLngLat(p2 as [number, number])
|
.setLngLat(p2 as [number, number])
|
||||||
.addTo(map.current)
|
.addTo(map.current)
|
||||||
markersRef.current.push(marker)
|
markersRef.current.push(marker)
|
||||||
@@ -1465,7 +1526,21 @@ export function MapView({
|
|||||||
el.appendChild(labelLine)
|
el.appendChild(labelLine)
|
||||||
el.appendChild(infoLine)
|
el.appendChild(infoLine)
|
||||||
} else {
|
} else {
|
||||||
el.textContent = label
|
// Polygon: show label + area
|
||||||
|
const ring = (f.geometry.coordinates as number[][][])[0]
|
||||||
|
const area = polygonArea(ring)
|
||||||
|
const areaText = area < 10000 ? `${Math.round(area)} m²` : `${(area / 10000).toFixed(2)} ha`
|
||||||
|
|
||||||
|
const labelLine = document.createElement('div')
|
||||||
|
labelLine.textContent = label
|
||||||
|
labelLine.style.cssText = 'font-size:11px;font-weight:600;line-height:1.2;'
|
||||||
|
|
||||||
|
const infoLine = document.createElement('div')
|
||||||
|
infoLine.textContent = areaText
|
||||||
|
infoLine.style.cssText = 'font-size:8px;opacity:0.8;line-height:1.2;font-weight:400;'
|
||||||
|
|
||||||
|
el.appendChild(labelLine)
|
||||||
|
el.appendChild(infoLine)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Double-click to edit label — only in select mode
|
// Double-click to edit label — only in select mode
|
||||||
@@ -1478,7 +1553,7 @@ export function MapView({
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
const marker = new maplibregl.Marker({ element: el, anchor: 'center' })
|
const marker = new maplibregl.Marker({ element: el, anchor: 'center', rotationAlignment: 'viewport' })
|
||||||
.setLngLat(midpoint)
|
.setLngLat(midpoint)
|
||||||
.addTo(map.current)
|
.addTo(map.current)
|
||||||
markersRef.current.push(marker)
|
markersRef.current.push(marker)
|
||||||
@@ -1565,7 +1640,7 @@ export function MapView({
|
|||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const marker = new maplibregl.Marker({ element: wrapper, draggable: canEdit, anchor: 'center' })
|
const marker = new maplibregl.Marker({ element: wrapper, draggable: canEdit, anchor: 'center', rotationAlignment: 'viewport' })
|
||||||
.setLngLat(coords)
|
.setLngLat(coords)
|
||||||
.addTo(map.current)
|
.addTo(map.current)
|
||||||
|
|
||||||
@@ -1631,7 +1706,7 @@ export function MapView({
|
|||||||
el.textContent = (f.properties.text as string) || ''
|
el.textContent = (f.properties.text as string) || ''
|
||||||
wrapper.appendChild(el)
|
wrapper.appendChild(el)
|
||||||
|
|
||||||
const marker = new maplibregl.Marker({ element: wrapper, draggable: canEdit, anchor: 'center' })
|
const marker = new maplibregl.Marker({ element: wrapper, draggable: canEdit, anchor: 'center', rotationAlignment: 'viewport' })
|
||||||
.setLngLat(coords)
|
.setLngLat(coords)
|
||||||
.addTo(map.current)
|
.addTo(map.current)
|
||||||
|
|
||||||
@@ -2028,14 +2103,14 @@ export function MapView({
|
|||||||
const startW = selectedSymbolRef.current.resizeStartWidth || 1
|
const startW = selectedSymbolRef.current.resizeStartWidth || 1
|
||||||
const startScale = selectedSymbolRef.current.resizeStartScale || 1
|
const startScale = selectedSymbolRef.current.resizeStartScale || 1
|
||||||
const ratio = width / startW
|
const ratio = width / startW
|
||||||
selectedSymbolRef.current.scale = Math.max(0.5, Math.min(5, startScale * ratio))
|
selectedSymbolRef.current.scale = Math.max(0.2, Math.min(10, startScale * ratio))
|
||||||
selectedSymbolRef.current.innerEl.style.fontSize = `${baseFontSize * selectedSymbolRef.current.scale}px`
|
selectedSymbolRef.current.innerEl.style.fontSize = `${baseFontSize * selectedSymbolRef.current.scale}px`
|
||||||
} else {
|
} else {
|
||||||
// For symbols: resize wrapper
|
// For symbols: resize wrapper
|
||||||
selectedSymbolRef.current.wrapperEl.style.width = `${width}px`
|
selectedSymbolRef.current.wrapperEl.style.width = `${width}px`
|
||||||
selectedSymbolRef.current.wrapperEl.style.height = `${height}px`
|
selectedSymbolRef.current.wrapperEl.style.height = `${height}px`
|
||||||
const baseSize = 32
|
const baseSize = 32
|
||||||
selectedSymbolRef.current.scale = Math.max(0.3, Math.min(4, width / baseSize))
|
selectedSymbolRef.current.scale = Math.max(0.1, Math.min(10, width / baseSize))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}}
|
}}
|
||||||
@@ -2079,28 +2154,38 @@ export function MapView({
|
|||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{/* Layer toggle: OSM / Satellite */}
|
{/* Layer toggle: cycle through base maps */}
|
||||||
<button
|
<button
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
if (!map.current) return
|
if (!map.current) return
|
||||||
const newSat = !isSatellite
|
const layers: Array<'osm' | 'satellite' | 'swisstopo' | 'swissimage'> = ['osm', 'satellite', 'swisstopo', 'swissimage']
|
||||||
setIsSatellite(newSat)
|
const currentIdx = layers.indexOf(activeBaseLayer)
|
||||||
map.current.setLayoutProperty('osm', 'visibility', newSat ? 'none' : 'visible')
|
const nextLayer = layers[(currentIdx + 1) % layers.length]
|
||||||
map.current.setLayoutProperty('satellite', 'visibility', newSat ? 'visible' : 'none')
|
for (const l of layers) {
|
||||||
|
map.current.setLayoutProperty(l, 'visibility', l === nextLayer ? 'visible' : 'none')
|
||||||
|
}
|
||||||
|
setActiveBaseLayer(nextLayer)
|
||||||
}}
|
}}
|
||||||
className="absolute top-3 right-3 z-10 flex items-center gap-1.5 px-2.5 py-1.5 rounded-lg text-xs font-semibold shadow-lg border transition-colors"
|
className="absolute top-3 right-3 z-10 flex items-center gap-1.5 px-2.5 py-1.5 rounded-lg text-xs font-semibold shadow-lg border transition-colors"
|
||||||
style={{
|
style={{
|
||||||
background: isSatellite ? 'rgba(0,0,0,0.7)' : 'rgba(255,255,255,0.95)',
|
background: activeBaseLayer !== 'osm' ? 'rgba(0,0,0,0.7)' : 'rgba(255,255,255,0.95)',
|
||||||
color: isSatellite ? '#fff' : '#333',
|
color: activeBaseLayer !== 'osm' ? '#fff' : '#333',
|
||||||
borderColor: isSatellite ? 'rgba(255,255,255,0.3)' : 'rgba(0,0,0,0.15)',
|
borderColor: activeBaseLayer !== 'osm' ? 'rgba(255,255,255,0.3)' : 'rgba(0,0,0,0.15)',
|
||||||
}}
|
}}
|
||||||
title={isSatellite ? 'Zur Kartenansicht wechseln' : 'Zur Satellitenansicht wechseln'}
|
title="Kartenstil wechseln"
|
||||||
>
|
>
|
||||||
{isSatellite ? (
|
{activeBaseLayer === 'osm' && (
|
||||||
<><svg className="w-4 h-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M3 7l6-3 6 3 6-3v13l-6 3-6-3-6 3z"/><path d="M9 4v13"/><path d="M15 7v13"/></svg>Karte</>
|
|
||||||
) : (
|
|
||||||
<><svg className="w-4 h-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><circle cx="12" cy="12" r="10"/><path d="M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20"/><path d="M2 12h20"/></svg>Satellit</>
|
<><svg className="w-4 h-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><circle cx="12" cy="12" r="10"/><path d="M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20"/><path d="M2 12h20"/></svg>Satellit</>
|
||||||
)}
|
)}
|
||||||
|
{activeBaseLayer === 'satellite' && (
|
||||||
|
<><svg className="w-4 h-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M3 7l6-3 6 3 6-3v13l-6 3-6-3-6 3z"/><path d="M9 4v13"/><path d="M15 7v13"/></svg>Swisstopo</>
|
||||||
|
)}
|
||||||
|
{activeBaseLayer === 'swisstopo' && (
|
||||||
|
<><svg className="w-4 h-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><circle cx="12" cy="12" r="10"/><path d="M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20"/><path d="M2 12h20"/></svg>Luftbild CH</>
|
||||||
|
)}
|
||||||
|
{activeBaseLayer === 'swissimage' && (
|
||||||
|
<><svg className="w-4 h-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M3 7l6-3 6 3 6-3v13l-6 3-6-3-6 3z"/><path d="M9 4v13"/><path d="M15 7v13"/></svg>OSM</>
|
||||||
|
)}
|
||||||
</button>
|
</button>
|
||||||
|
|
||||||
{/* Zeichnung abschliessen Button (Linie/Polygon/Pfeil) */}
|
{/* Zeichnung abschliessen Button (Linie/Polygon/Pfeil) */}
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ export interface User {
|
|||||||
role: 'SERVER_ADMIN' | 'TENANT_ADMIN' | 'OPERATOR' | 'VIEWER'
|
role: 'SERVER_ADMIN' | 'TENANT_ADMIN' | 'OPERATOR' | 'VIEWER'
|
||||||
tenantId?: string
|
tenantId?: string
|
||||||
tenantSlug?: string
|
tenantSlug?: string
|
||||||
|
emailVerified?: boolean
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface TenantInfo {
|
export interface TenantInfo {
|
||||||
|
|||||||
@@ -18,6 +18,7 @@ export interface UserPayload {
|
|||||||
role: 'SERVER_ADMIN' | 'TENANT_ADMIN' | 'OPERATOR' | 'VIEWER'
|
role: 'SERVER_ADMIN' | 'TENANT_ADMIN' | 'OPERATOR' | 'VIEWER'
|
||||||
tenantId?: string
|
tenantId?: string
|
||||||
tenantSlug?: string
|
tenantSlug?: string
|
||||||
|
emailVerified?: boolean
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function createToken(user: UserPayload): Promise<string> {
|
export async function createToken(user: UserPayload): Promise<string> {
|
||||||
@@ -63,18 +64,16 @@ export async function login(
|
|||||||
}) as any)
|
}) as any)
|
||||||
|
|
||||||
if (!user) {
|
if (!user) {
|
||||||
return { success: false, error: 'Benutzer nicht gefunden' }
|
return { success: false, error: 'E-Mail oder Passwort falsch' }
|
||||||
}
|
}
|
||||||
|
|
||||||
const isValidPassword = await bcrypt.compare(password, user.password)
|
const isValidPassword = await bcrypt.compare(password, user.password)
|
||||||
if (!isValidPassword) {
|
if (!isValidPassword) {
|
||||||
return { success: false, error: 'Ungültiges Passwort' }
|
return { success: false, error: 'E-Mail oder Passwort falsch' }
|
||||||
}
|
}
|
||||||
|
|
||||||
// Check email verification (skip for SERVER_ADMIN and users created before verification was added)
|
// Track email verification status (allow login regardless)
|
||||||
if ((user as any).emailVerified === false && (user.role as string) !== 'SERVER_ADMIN') {
|
const emailVerified = (user as any).emailVerified !== false
|
||||||
return { success: false, error: 'Bitte bestätigen Sie zuerst Ihre E-Mail-Adresse. Prüfen Sie Ihren Posteingang.' }
|
|
||||||
}
|
|
||||||
|
|
||||||
// Get first tenant membership for non-server-admins
|
// Get first tenant membership for non-server-admins
|
||||||
let tenantId: string | undefined
|
let tenantId: string | undefined
|
||||||
@@ -102,6 +101,7 @@ export async function login(
|
|||||||
role: (user.role === 'ADMIN' ? 'SERVER_ADMIN' : user.role) as UserPayload['role'],
|
role: (user.role === 'ADMIN' ? 'SERVER_ADMIN' : user.role) as UserPayload['role'],
|
||||||
tenantId,
|
tenantId,
|
||||||
tenantSlug,
|
tenantSlug,
|
||||||
|
emailVerified,
|
||||||
}
|
}
|
||||||
|
|
||||||
return { success: true, user: userPayload }
|
return { success: true, user: userPayload }
|
||||||
|
|||||||
97
src/lib/offline-sync.ts
Normal file
97
src/lib/offline-sync.ts
Normal file
@@ -0,0 +1,97 @@
|
|||||||
|
// Offline detection and sync queue for saving changes when reconnecting
|
||||||
|
|
||||||
|
const SYNC_QUEUE_KEY = 'lageplan-sync-queue'
|
||||||
|
|
||||||
|
interface SyncQueueItem {
|
||||||
|
id: string
|
||||||
|
url: string
|
||||||
|
method: string
|
||||||
|
body: string
|
||||||
|
timestamp: number
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Get all queued saves */
|
||||||
|
export function getSyncQueue(): SyncQueueItem[] {
|
||||||
|
try {
|
||||||
|
const raw = localStorage.getItem(SYNC_QUEUE_KEY)
|
||||||
|
return raw ? JSON.parse(raw) : []
|
||||||
|
} catch {
|
||||||
|
return []
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Add a save operation to the sync queue (called when offline) */
|
||||||
|
export function addToSyncQueue(url: string, method: string, body: any): void {
|
||||||
|
const queue = getSyncQueue()
|
||||||
|
// Deduplicate: if same URL+method exists, replace it with newer data
|
||||||
|
const existing = queue.findIndex(q => q.url === url && q.method === method)
|
||||||
|
const item: SyncQueueItem = {
|
||||||
|
id: `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,
|
||||||
|
url,
|
||||||
|
method,
|
||||||
|
body: JSON.stringify(body),
|
||||||
|
timestamp: Date.now(),
|
||||||
|
}
|
||||||
|
if (existing >= 0) {
|
||||||
|
queue[existing] = item
|
||||||
|
} else {
|
||||||
|
queue.push(item)
|
||||||
|
}
|
||||||
|
localStorage.setItem(SYNC_QUEUE_KEY, JSON.stringify(queue))
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Flush the sync queue — send all queued requests to the server */
|
||||||
|
export async function flushSyncQueue(): Promise<{ success: number; failed: number }> {
|
||||||
|
const queue = getSyncQueue()
|
||||||
|
if (queue.length === 0) return { success: 0, failed: 0 }
|
||||||
|
|
||||||
|
let success = 0
|
||||||
|
let failed = 0
|
||||||
|
const remaining: SyncQueueItem[] = []
|
||||||
|
|
||||||
|
for (const item of queue) {
|
||||||
|
try {
|
||||||
|
const res = await fetch(item.url, {
|
||||||
|
method: item.method,
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: item.body,
|
||||||
|
})
|
||||||
|
if (res.ok) {
|
||||||
|
success++
|
||||||
|
} else {
|
||||||
|
// Server error — keep in queue for retry
|
||||||
|
remaining.push(item)
|
||||||
|
failed++
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// Still offline — keep in queue
|
||||||
|
remaining.push(item)
|
||||||
|
failed++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
localStorage.setItem(SYNC_QUEUE_KEY, JSON.stringify(remaining))
|
||||||
|
return { success, failed }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Clear the sync queue */
|
||||||
|
export function clearSyncQueue(): void {
|
||||||
|
localStorage.removeItem(SYNC_QUEUE_KEY)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Check if we're online */
|
||||||
|
export function isOnline(): boolean {
|
||||||
|
return navigator.onLine
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Register Background Sync (if supported) */
|
||||||
|
export async function registerBackgroundSync(): Promise<void> {
|
||||||
|
if ('serviceWorker' in navigator && 'SyncManager' in window) {
|
||||||
|
try {
|
||||||
|
const reg = await navigator.serviceWorker.ready
|
||||||
|
await (reg as any).sync.register('sync-saves')
|
||||||
|
} catch {
|
||||||
|
// Background Sync not supported or failed — will use manual flush
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -4,7 +4,7 @@ import { Document, Page, Text, View, StyleSheet, Font, Image } from '@react-pdf/
|
|||||||
// Register default font (Helvetica is built-in)
|
// Register default font (Helvetica is built-in)
|
||||||
const styles = StyleSheet.create({
|
const styles = StyleSheet.create({
|
||||||
page: {
|
page: {
|
||||||
padding: '12mm 15mm 15mm',
|
padding: '12mm 15mm 32mm',
|
||||||
fontFamily: 'Helvetica',
|
fontFamily: 'Helvetica',
|
||||||
fontSize: 10,
|
fontSize: 10,
|
||||||
lineHeight: 1.4,
|
lineHeight: 1.4,
|
||||||
|
|||||||
107
src/lib/rate-limit.ts
Normal file
107
src/lib/rate-limit.ts
Normal file
@@ -0,0 +1,107 @@
|
|||||||
|
// In-memory rate limiter for API endpoints
|
||||||
|
// Tracks request counts per IP within sliding windows
|
||||||
|
|
||||||
|
interface RateLimitEntry {
|
||||||
|
count: number
|
||||||
|
resetAt: number
|
||||||
|
}
|
||||||
|
|
||||||
|
const stores = new Map<string, Map<string, RateLimitEntry>>()
|
||||||
|
|
||||||
|
interface RateLimitConfig {
|
||||||
|
/** Unique identifier for this limiter (e.g. 'login', 'register') */
|
||||||
|
id: string
|
||||||
|
/** Maximum requests allowed within the window */
|
||||||
|
max: number
|
||||||
|
/** Window duration in seconds */
|
||||||
|
windowSeconds: number
|
||||||
|
}
|
||||||
|
|
||||||
|
interface RateLimitResult {
|
||||||
|
success: boolean
|
||||||
|
remaining: number
|
||||||
|
resetAt: number
|
||||||
|
}
|
||||||
|
|
||||||
|
function getStore(id: string): Map<string, RateLimitEntry> {
|
||||||
|
if (!stores.has(id)) {
|
||||||
|
stores.set(id, new Map())
|
||||||
|
}
|
||||||
|
return stores.get(id)!
|
||||||
|
}
|
||||||
|
|
||||||
|
// Periodic cleanup of expired entries (every 5 minutes)
|
||||||
|
setInterval(() => {
|
||||||
|
const now = Date.now()
|
||||||
|
for (const [, store] of stores) {
|
||||||
|
for (const [key, entry] of store) {
|
||||||
|
if (now > entry.resetAt) {
|
||||||
|
store.delete(key)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}, 5 * 60 * 1000)
|
||||||
|
|
||||||
|
export function rateLimit(config: RateLimitConfig) {
|
||||||
|
const store = getStore(config.id)
|
||||||
|
|
||||||
|
return {
|
||||||
|
check(ip: string): RateLimitResult {
|
||||||
|
const now = Date.now()
|
||||||
|
const key = ip
|
||||||
|
const entry = store.get(key)
|
||||||
|
|
||||||
|
// No entry or expired → fresh window
|
||||||
|
if (!entry || now > entry.resetAt) {
|
||||||
|
store.set(key, {
|
||||||
|
count: 1,
|
||||||
|
resetAt: now + config.windowSeconds * 1000,
|
||||||
|
})
|
||||||
|
return { success: true, remaining: config.max - 1, resetAt: now + config.windowSeconds * 1000 }
|
||||||
|
}
|
||||||
|
|
||||||
|
// Within window
|
||||||
|
entry.count++
|
||||||
|
if (entry.count > config.max) {
|
||||||
|
return { success: false, remaining: 0, resetAt: entry.resetAt }
|
||||||
|
}
|
||||||
|
|
||||||
|
return { success: true, remaining: config.max - entry.count, resetAt: entry.resetAt }
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Pre-configured limiters for different endpoints
|
||||||
|
export const loginLimiter = rateLimit({ id: 'login', max: 5, windowSeconds: 60 * 15 }) // 5 attempts per 15 min
|
||||||
|
export const registerLimiter = rateLimit({ id: 'register', max: 3, windowSeconds: 60 * 60 }) // 3 per hour
|
||||||
|
export const forgotPasswordLimiter = rateLimit({ id: 'forgot-pw', max: 3, windowSeconds: 60 * 15 }) // 3 per 15 min
|
||||||
|
export const resendVerificationLimiter = rateLimit({ id: 'resend-verify', max: 3, windowSeconds: 60 * 15 })
|
||||||
|
export const contactLimiter = rateLimit({ id: 'contact', max: 5, windowSeconds: 60 * 60 }) // 5 per hour
|
||||||
|
export const deleteAccountLimiter = rateLimit({ id: 'delete-acct', max: 3, windowSeconds: 60 * 15 })
|
||||||
|
export const resetPasswordLimiter = rateLimit({ id: 'reset-pw', max: 5, windowSeconds: 60 * 15 })
|
||||||
|
|
||||||
|
/** Extract client IP from request headers */
|
||||||
|
export function getClientIp(req: Request): string {
|
||||||
|
const forwarded = req.headers.get('x-forwarded-for')
|
||||||
|
if (forwarded) {
|
||||||
|
return forwarded.split(',')[0].trim()
|
||||||
|
}
|
||||||
|
const realIp = req.headers.get('x-real-ip')
|
||||||
|
if (realIp) return realIp
|
||||||
|
return '127.0.0.1'
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Helper: create a 429 response with retry-after header */
|
||||||
|
export function rateLimitResponse(resetAt: number) {
|
||||||
|
const retryAfter = Math.ceil((resetAt - Date.now()) / 1000)
|
||||||
|
return new Response(
|
||||||
|
JSON.stringify({ error: 'Zu viele Anfragen. Bitte versuchen Sie es später erneut.' }),
|
||||||
|
{
|
||||||
|
status: 429,
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
'Retry-After': String(retryAfter),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -3,23 +3,50 @@
|
|||||||
import { io, Socket } from 'socket.io-client'
|
import { io, Socket } from 'socket.io-client'
|
||||||
|
|
||||||
let socket: Socket | null = null
|
let socket: Socket | null = null
|
||||||
|
let currentRoom: string | null = null
|
||||||
|
|
||||||
export function getSocket(): Socket {
|
export function getSocket(): Socket {
|
||||||
if (!socket) {
|
if (!socket) {
|
||||||
socket = io({
|
socket = io({
|
||||||
path: '/socket.io',
|
path: '/socket.io',
|
||||||
transports: ['polling', 'websocket'],
|
transports: ['websocket', 'polling'],
|
||||||
upgrade: true,
|
upgrade: true,
|
||||||
reconnectionAttempts: 10,
|
reconnection: true,
|
||||||
reconnectionDelay: 2000,
|
reconnectionAttempts: Infinity,
|
||||||
|
reconnectionDelay: 1000,
|
||||||
|
reconnectionDelayMax: 5000,
|
||||||
timeout: 10000,
|
timeout: 10000,
|
||||||
|
forceNew: false,
|
||||||
})
|
})
|
||||||
socket.on('connect', () => {
|
socket.on('connect', () => {
|
||||||
console.log('[Socket.io] Connected:', socket?.id)
|
console.log('[Socket.io] Connected:', socket?.id)
|
||||||
|
// Re-join project room after reconnect
|
||||||
|
if (currentRoom) {
|
||||||
|
console.log('[Socket.io] Re-joining room:', currentRoom)
|
||||||
|
socket?.emit('join-project', currentRoom)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
socket.on('disconnect', (reason) => {
|
||||||
|
console.warn('[Socket.io] Disconnected:', reason)
|
||||||
|
if (reason === 'io server disconnect') {
|
||||||
|
// Server disconnected us, need to manually reconnect
|
||||||
|
socket?.connect()
|
||||||
|
}
|
||||||
})
|
})
|
||||||
socket.on('connect_error', (err) => {
|
socket.on('connect_error', (err) => {
|
||||||
console.warn('[Socket.io] Connection error:', err.message)
|
console.warn('[Socket.io] Connection error:', err.message)
|
||||||
})
|
})
|
||||||
|
socket.io.on('reconnect', (attempt) => {
|
||||||
|
console.log('[Socket.io] Reconnected after', attempt, 'attempts')
|
||||||
|
})
|
||||||
|
socket.io.on('reconnect_attempt', (attempt) => {
|
||||||
|
console.log('[Socket.io] Reconnect attempt', attempt)
|
||||||
|
})
|
||||||
}
|
}
|
||||||
return socket
|
return socket
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Track which room the socket should be in (for auto-rejoin on reconnect) */
|
||||||
|
export function setSocketRoom(projectId: string | null): void {
|
||||||
|
currentRoom = projectId
|
||||||
|
}
|
||||||
|
|||||||
114
src/middleware.ts
Normal file
114
src/middleware.ts
Normal file
@@ -0,0 +1,114 @@
|
|||||||
|
import { NextRequest, NextResponse } from 'next/server'
|
||||||
|
import { jwtVerify } from 'jose'
|
||||||
|
|
||||||
|
const JWT_SECRET = new TextEncoder().encode(
|
||||||
|
process.env.NEXTAUTH_SECRET || 'dev-only-fallback-do-not-use-in-production'
|
||||||
|
)
|
||||||
|
|
||||||
|
// Routes that require authentication
|
||||||
|
const PROTECTED_ROUTES = ['/app', '/settings', '/admin']
|
||||||
|
|
||||||
|
// Routes that should redirect to /app if already logged in
|
||||||
|
const AUTH_ROUTES = ['/login', '/register']
|
||||||
|
|
||||||
|
// API routes that are public (no auth needed)
|
||||||
|
const PUBLIC_API_PREFIXES = [
|
||||||
|
'/api/auth/login',
|
||||||
|
'/api/auth/register',
|
||||||
|
'/api/auth/forgot-password',
|
||||||
|
'/api/auth/reset-password',
|
||||||
|
'/api/auth/verify-email',
|
||||||
|
'/api/auth/resend-verification',
|
||||||
|
'/api/auth/logout',
|
||||||
|
'/api/contact',
|
||||||
|
'/api/demo',
|
||||||
|
'/api/donate',
|
||||||
|
'/api/rapports/',
|
||||||
|
'/api/tenants/by-slug/',
|
||||||
|
]
|
||||||
|
|
||||||
|
export async function middleware(req: NextRequest) {
|
||||||
|
const { pathname } = req.nextUrl
|
||||||
|
const token = req.cookies.get('auth-token')?.value
|
||||||
|
|
||||||
|
// Verify token if present
|
||||||
|
let user: any = null
|
||||||
|
if (token) {
|
||||||
|
try {
|
||||||
|
const { payload } = await jwtVerify(token, JWT_SECRET)
|
||||||
|
user = payload.user
|
||||||
|
} catch {
|
||||||
|
// Invalid/expired token — clear it
|
||||||
|
const response = NextResponse.redirect(new URL('/login', req.url))
|
||||||
|
response.cookies.delete('auth-token')
|
||||||
|
// Only redirect if accessing protected routes
|
||||||
|
if (PROTECTED_ROUTES.some(r => pathname.startsWith(r))) {
|
||||||
|
return response
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Protected routes: redirect to login if not authenticated
|
||||||
|
if (PROTECTED_ROUTES.some(r => pathname.startsWith(r))) {
|
||||||
|
if (!user) {
|
||||||
|
const loginUrl = new URL('/login', req.url)
|
||||||
|
loginUrl.searchParams.set('redirect', pathname)
|
||||||
|
return NextResponse.redirect(loginUrl)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Admin routes: only SERVER_ADMIN and TENANT_ADMIN
|
||||||
|
if (pathname.startsWith('/admin') && user.role !== 'SERVER_ADMIN' && user.role !== 'TENANT_ADMIN') {
|
||||||
|
return NextResponse.redirect(new URL('/app', req.url))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Auth routes: redirect to /app if already logged in
|
||||||
|
if (AUTH_ROUTES.some(r => pathname.startsWith(r))) {
|
||||||
|
if (user) {
|
||||||
|
return NextResponse.redirect(new URL('/app', req.url))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// API routes: check auth for non-public endpoints
|
||||||
|
if (pathname.startsWith('/api/') && !PUBLIC_API_PREFIXES.some(p => pathname.startsWith(p))) {
|
||||||
|
if (!user) {
|
||||||
|
// Allow /api/auth/me to return null (used for auth check)
|
||||||
|
if (pathname === '/api/auth/me') {
|
||||||
|
return NextResponse.next()
|
||||||
|
}
|
||||||
|
// Allow /api/icons GET (public for symbol loading)
|
||||||
|
if (pathname === '/api/icons' && req.method === 'GET') {
|
||||||
|
return NextResponse.next()
|
||||||
|
}
|
||||||
|
return NextResponse.json({ error: 'Nicht autorisiert' }, { status: 401 })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Security: block common attack paths
|
||||||
|
if (
|
||||||
|
pathname.includes('..') ||
|
||||||
|
pathname.includes('.env') ||
|
||||||
|
pathname.includes('wp-admin') ||
|
||||||
|
pathname.includes('wp-login') ||
|
||||||
|
pathname.includes('.php') ||
|
||||||
|
pathname.includes('xmlrpc') ||
|
||||||
|
pathname.match(/\.(sql|bak|config|log|ini)$/i)
|
||||||
|
) {
|
||||||
|
return new NextResponse(null, { status: 404 })
|
||||||
|
}
|
||||||
|
|
||||||
|
return NextResponse.next()
|
||||||
|
}
|
||||||
|
|
||||||
|
export const config = {
|
||||||
|
matcher: [
|
||||||
|
/*
|
||||||
|
* Match all request paths except:
|
||||||
|
* - _next/static (static files)
|
||||||
|
* - _next/image (image optimization)
|
||||||
|
* - favicon.ico, sitemap.xml, robots.txt
|
||||||
|
* - public files (images, sw.js, etc.)
|
||||||
|
*/
|
||||||
|
'/((?!_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt|icons/|sw.js|manifest.json|opengraph-image).*)',
|
||||||
|
],
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user