Compare commits
14 Commits
c11565aaf8
...
v1.2.0
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1583ef2a17 | ||
|
|
d893373bd9 | ||
|
|
cb575f9a82 | ||
|
|
6b96f1ffb1 | ||
|
|
0784553017 | ||
|
|
e4c3c92cab | ||
|
|
0abc1c6b02 | ||
|
|
5bf4106db2 | ||
|
|
2432e9a17f | ||
|
|
e3f8f14f6a | ||
|
|
0376e71066 | ||
|
|
8ef2cbe68e | ||
|
|
b75bf9bb30 | ||
|
|
25d3d553ff |
@@ -31,15 +31,27 @@ const nextConfig = {
|
||||
key: 'Cross-Origin-Opener-Policy',
|
||||
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',
|
||||
value: [
|
||||
"default-src 'self'",
|
||||
"script-src 'self' 'unsafe-inline' 'unsafe-eval' blob:",
|
||||
"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://*.geo.admin.ch http://localhost:9000 http://minio:9000",
|
||||
"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://*.geo.admin.ch",
|
||||
"frame-ancestors 'self'",
|
||||
"base-uri 'self'",
|
||||
"form-action 'self'",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "lageplan",
|
||||
"version": "1.0.2",
|
||||
"version": "1.2.0",
|
||||
"description": "Feuerwehr Lageplan - Krokier-App für Einsatzdokumentation",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
|
||||
@@ -214,6 +214,23 @@ async function migrate() {
|
||||
console.log(' Privacy consent columns skipped:', e.message)
|
||||
}
|
||||
|
||||
// ─── Step 12: Create tenant_symbols table ───
|
||||
console.log(' [12] Creating tenant_symbols table...')
|
||||
try {
|
||||
await prisma.$executeRawUnsafe(`
|
||||
CREATE TABLE IF NOT EXISTS tenant_symbols (
|
||||
id TEXT PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
"isActive" BOOLEAN NOT NULL DEFAULT true,
|
||||
"tenantId" TEXT NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
|
||||
"iconId" TEXT NOT NULL REFERENCES icon_assets(id) ON DELETE CASCADE,
|
||||
UNIQUE("tenantId", "iconId")
|
||||
)
|
||||
`)
|
||||
console.log(' tenant_symbols table created (or already exists)')
|
||||
} catch (e) {
|
||||
console.log(' tenant_symbols table skipped:', e.message)
|
||||
}
|
||||
|
||||
console.log('✅ Database migrations complete')
|
||||
}
|
||||
|
||||
|
||||
@@ -89,6 +89,7 @@ model Tenant {
|
||||
checkTemplates JournalCheckTemplate[]
|
||||
iconCategories IconCategory[]
|
||||
iconAssets IconAsset[]
|
||||
tenantSymbols TenantSymbol[]
|
||||
upgradeRequests UpgradeRequest[]
|
||||
dictionaryEntries DictionaryEntry[]
|
||||
rapports Rapport[]
|
||||
@@ -236,6 +237,8 @@ model IconAsset {
|
||||
tenantId String?
|
||||
tenant Tenant? @relation(fields: [tenantId], references: [id], onDelete: SetNull)
|
||||
|
||||
tenantSymbols TenantSymbol[]
|
||||
|
||||
@@map("icon_assets")
|
||||
}
|
||||
|
||||
@@ -375,6 +378,22 @@ model UpgradeRequest {
|
||||
@@map("upgrade_requests")
|
||||
}
|
||||
|
||||
// ─── Tenant Symbol Visibility ─────────────────────────────
|
||||
|
||||
model TenantSymbol {
|
||||
id String @id @default(uuid())
|
||||
isActive Boolean @default(true)
|
||||
|
||||
tenantId String
|
||||
tenant Tenant @relation(fields: [tenantId], references: [id], onDelete: Cascade)
|
||||
|
||||
iconId String
|
||||
icon IconAsset @relation(fields: [iconId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@unique([tenantId, iconId])
|
||||
@@map("tenant_symbols")
|
||||
}
|
||||
|
||||
// ─── Dictionary (Global + Tenant word library) ────────────
|
||||
|
||||
model DictionaryEntry {
|
||||
|
||||
@@ -252,32 +252,8 @@ async function main() {
|
||||
console.log('✅ Hose types created:', hoseTypes.length)
|
||||
|
||||
// ─── Journal Check Templates (SOMA) ─────────────────────
|
||||
const somaTemplates = [
|
||||
{ label: 'Stopp Zutritt / Ex-Gefahr', sortOrder: 1 },
|
||||
{ label: 'Alarmierung Gesamt-Fw', sortOrder: 2 },
|
||||
{ label: 'Alarmierung Ofw Wohlen', sortOrder: 3 },
|
||||
{ label: 'Alarmierung Stp Baden', sortOrder: 4 },
|
||||
{ label: 'Alarmierung Ambulanz', sortOrder: 5 },
|
||||
{ label: 'Alarmierung BWL', sortOrder: 6 },
|
||||
{ label: 'Alarmierung BL/Meister', sortOrder: 7 },
|
||||
{ label: 'Brunnenchef Villmergen', sortOrder: 8 },
|
||||
{ label: 'Berieselung Tank / Anl', sortOrder: 9 },
|
||||
{ label: 'Druckerhöhung', sortOrder: 10 },
|
||||
]
|
||||
|
||||
for (const tpl of somaTemplates) {
|
||||
await prisma.journalCheckTemplate.upsert({
|
||||
where: { id: tpl.label.replace(/[^a-zA-Z0-9]/g, '-').toLowerCase() },
|
||||
update: { label: tpl.label, sortOrder: tpl.sortOrder },
|
||||
create: {
|
||||
id: tpl.label.replace(/[^a-zA-Z0-9]/g, '-').toLowerCase(),
|
||||
label: tpl.label,
|
||||
sortOrder: tpl.sortOrder,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
console.log('✅ SOMA templates created:', somaTemplates.length)
|
||||
// No default SOMA templates — each tenant defines their own via Admin → SOMA tab
|
||||
console.log('ℹ️ SOMA templates: keine Standard-Vorgaben (Tenants konfigurieren eigene)')
|
||||
console.log('🎉 Seed completed successfully!')
|
||||
}
|
||||
|
||||
|
||||
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",
|
||||
"sizes": "192x192",
|
||||
"type": "image/png",
|
||||
"purpose": "any maskable"
|
||||
"purpose": "any"
|
||||
},
|
||||
{
|
||||
"src": "/logo-icon-maskable.png",
|
||||
"sizes": "192x192",
|
||||
"type": "image/png",
|
||||
"purpose": "maskable"
|
||||
}
|
||||
],
|
||||
"screenshots": [],
|
||||
|
||||
121
public/sw.js
121
public/sw.js
@@ -1,6 +1,10 @@
|
||||
const TILE_CACHE = 'lageplan-tiles-v2'
|
||||
const STATIC_CACHE = 'lageplan-static-v2'
|
||||
const APP_CACHE = 'lageplan-app-v2'
|
||||
const TILE_CACHE = 'lageplan-tiles-v3'
|
||||
const STATIC_CACHE = 'lageplan-static-v3'
|
||||
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
|
||||
self.addEventListener('install', (event) => {
|
||||
@@ -8,6 +12,8 @@ self.addEventListener('install', (event) => {
|
||||
caches.open(APP_CACHE).then((cache) =>
|
||||
cache.addAll([
|
||||
'/app',
|
||||
'/login',
|
||||
'/',
|
||||
'/logo.svg',
|
||||
'/logo-icon.png',
|
||||
'/manifest.json',
|
||||
@@ -17,7 +23,6 @@ self.addEventListener('install', (event) => {
|
||||
self.skipWaiting()
|
||||
})
|
||||
|
||||
// Cache strategy: Network First for API, Cache First for tiles, Stale While Revalidate for static assets
|
||||
self.addEventListener('fetch', (event) => {
|
||||
const url = event.request.url
|
||||
const { pathname } = new URL(url)
|
||||
@@ -25,19 +30,71 @@ self.addEventListener('fetch', (event) => {
|
||||
// Skip non-GET requests
|
||||
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
|
||||
|
||||
// Cache map tiles from OpenStreetMap (Cache First)
|
||||
if (url.includes('tile.openstreetmap.org') || url.includes('api.maptiler.com')) {
|
||||
// Cache map tiles from OSM / MapTiler / ArcGIS / Swisstopo (Cache First — tiles don't change)
|
||||
if (url.includes('tile.openstreetmap.org') || url.includes('api.maptiler.com') || url.includes('server.arcgisonline.com') || url.includes('geo.admin.ch')) {
|
||||
event.respondWith(
|
||||
caches.open(TILE_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())
|
||||
}
|
||||
if (response.ok) cache.put(event.request, response.clone())
|
||||
return response
|
||||
}).catch(() => new Response('', { status: 503 }))
|
||||
})
|
||||
@@ -46,7 +103,23 @@ self.addEventListener('fetch', (event) => {
|
||||
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?)$/)) {
|
||||
event.respondWith(
|
||||
caches.open(STATIC_CACHE).then((cache) =>
|
||||
@@ -62,8 +135,8 @@ self.addEventListener('fetch', (event) => {
|
||||
return
|
||||
}
|
||||
|
||||
// App pages: Network First with cache fallback
|
||||
if (pathname === '/app' || pathname === '/' || pathname.startsWith('/app')) {
|
||||
// App pages / navigation: Network First with cache fallback
|
||||
if (event.request.mode === 'navigate' || pathname === '/app' || pathname === '/' || pathname.startsWith('/app')) {
|
||||
event.respondWith(
|
||||
fetch(event.request).then((response) => {
|
||||
if (response.ok) {
|
||||
@@ -81,7 +154,7 @@ self.addEventListener('fetch', (event) => {
|
||||
|
||||
// Clean old caches on activation
|
||||
self.addEventListener('activate', (event) => {
|
||||
const currentCaches = [TILE_CACHE, STATIC_CACHE, APP_CACHE]
|
||||
const currentCaches = [TILE_CACHE, STATIC_CACHE, APP_CACHE, API_CACHE]
|
||||
event.waitUntil(
|
||||
caches.keys().then((keys) =>
|
||||
Promise.all(
|
||||
@@ -92,3 +165,23 @@ self.addEventListener('activate', (event) => {
|
||||
).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)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -55,9 +55,13 @@ import {
|
||||
X,
|
||||
BookOpen,
|
||||
Download,
|
||||
AlertTriangle,
|
||||
GripVertical,
|
||||
LayoutGrid,
|
||||
} from 'lucide-react'
|
||||
import Link from 'next/link'
|
||||
import { TenantDetailDialog } from '@/components/admin/tenant-detail-dialog'
|
||||
import { HoseSettingsDialog } from '@/components/dialogs/hose-settings-dialog'
|
||||
|
||||
// --- Types ---
|
||||
interface IconCategory {
|
||||
@@ -214,6 +218,27 @@ export default function AdminPage() {
|
||||
const [symbolScaleLoading, setSymbolScaleLoading] = useState(false)
|
||||
const [symbolScaleStatus, setSymbolScaleStatus] = useState<string | null>(null)
|
||||
|
||||
// Admin Projects (SERVER_ADMIN)
|
||||
const [adminProjects, setAdminProjects] = useState<any[]>([])
|
||||
const [adminProjectsLoading, setAdminProjectsLoading] = useState(false)
|
||||
const [adminProjectTenantFilter, setAdminProjectTenantFilter] = useState<string>('all')
|
||||
|
||||
// Hose Settings (Tenant Admin)
|
||||
const [isHoseSettingsOpen, setIsHoseSettingsOpen] = useState(false)
|
||||
|
||||
// SOMA Templates (Tenant Admin)
|
||||
const [somaTemplates, setSomaTemplates] = useState<{ id: string; label: string; sortOrder: number; isActive: boolean }[]>([])
|
||||
const [newSomaLabel, setNewSomaLabel] = useState('')
|
||||
const [somaLoading, setSomaLoading] = useState(false)
|
||||
|
||||
// Symbol Management (Tenant Admin)
|
||||
const [tenantSymbols, setTenantSymbols] = useState<{ id: string; name: string; fileKey: string; mimeType: string; iconType: string; categoryId: string | null; categoryName: string; isActive: boolean }[]>([])
|
||||
const [symbolSearch, setSymbolSearch] = useState('')
|
||||
const [symbolCatFilter, setSymbolCatFilter] = useState('all')
|
||||
const [symbolViewTab, setSymbolViewTab] = useState<'library' | 'active'>('library')
|
||||
const [selectedSymbolIds, setSelectedSymbolIds] = useState<Set<string>>(new Set())
|
||||
const [symbolsLoading, setSymbolsLoading] = useState(false)
|
||||
|
||||
// Redirect to login if not authenticated, or to app if not admin
|
||||
useEffect(() => {
|
||||
if (authLoading) return
|
||||
@@ -237,6 +262,38 @@ export default function AdminPage() {
|
||||
.catch(() => {})
|
||||
}, [tenant?.id])
|
||||
|
||||
// Load SOMA templates (TENANT_ADMIN)
|
||||
const fetchSomaTemplates = async () => {
|
||||
setSomaLoading(true)
|
||||
try {
|
||||
const res = await fetch('/api/tenant/soma-templates')
|
||||
if (res.ok) {
|
||||
const data = await res.json()
|
||||
setSomaTemplates(data.templates || [])
|
||||
}
|
||||
} catch {}
|
||||
setSomaLoading(false)
|
||||
}
|
||||
useEffect(() => {
|
||||
if (user?.role === 'TENANT_ADMIN') fetchSomaTemplates()
|
||||
}, [user?.role])
|
||||
|
||||
// Load tenant symbols (TENANT_ADMIN)
|
||||
const fetchTenantSymbols = async () => {
|
||||
setSymbolsLoading(true)
|
||||
try {
|
||||
const res = await fetch('/api/tenant/symbols')
|
||||
if (res.ok) {
|
||||
const data = await res.json()
|
||||
setTenantSymbols(data.symbols || [])
|
||||
}
|
||||
} catch {}
|
||||
setSymbolsLoading(false)
|
||||
}
|
||||
useEffect(() => {
|
||||
if (user?.role === 'TENANT_ADMIN') fetchTenantSymbols()
|
||||
}, [user?.role])
|
||||
|
||||
// Load global dictionary (SERVER_ADMIN)
|
||||
const fetchGlobalDict = async () => {
|
||||
try {
|
||||
@@ -251,6 +308,25 @@ export default function AdminPage() {
|
||||
if (user?.role === 'SERVER_ADMIN') fetchGlobalDict()
|
||||
}, [user?.role])
|
||||
|
||||
// Fetch admin projects (SERVER_ADMIN)
|
||||
const fetchAdminProjects = async (tenantFilter?: string) => {
|
||||
setAdminProjectsLoading(true)
|
||||
try {
|
||||
const url = tenantFilter && tenantFilter !== 'all'
|
||||
? `/api/admin/projects?tenantId=${tenantFilter}`
|
||||
: '/api/admin/projects'
|
||||
const res = await fetch(url)
|
||||
if (res.ok) {
|
||||
const data = await res.json()
|
||||
setAdminProjects(data.projects || [])
|
||||
}
|
||||
} catch {}
|
||||
setAdminProjectsLoading(false)
|
||||
}
|
||||
useEffect(() => {
|
||||
if (user?.role === 'SERVER_ADMIN') fetchAdminProjects()
|
||||
}, [user?.role])
|
||||
|
||||
const fetchData = async () => {
|
||||
setIsLoading(true)
|
||||
try {
|
||||
@@ -683,11 +759,15 @@ export default function AdminPage() {
|
||||
<div className="container mx-auto py-6 px-4 max-w-7xl">
|
||||
<Tabs value={activeTab} onValueChange={setActiveTab} className="space-y-6">
|
||||
{user?.role === 'SERVER_ADMIN' ? (
|
||||
<TabsList className="grid w-full grid-cols-6 max-w-3xl">
|
||||
<TabsList className="grid w-full grid-cols-7 max-w-4xl">
|
||||
<TabsTrigger value="tenants" className="gap-2">
|
||||
<Shield className="w-4 h-4" />
|
||||
Mandanten
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="projects" className="gap-2">
|
||||
<Map className="w-4 h-4" />
|
||||
Einsätze
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="icons" className="gap-2">
|
||||
<Image className="w-4 h-4" />
|
||||
Symbole
|
||||
@@ -710,7 +790,7 @@ export default function AdminPage() {
|
||||
</TabsTrigger>
|
||||
</TabsList>
|
||||
) : user?.role === 'TENANT_ADMIN' ? (
|
||||
<TabsList className="grid w-full grid-cols-5 max-w-2xl">
|
||||
<TabsList className="grid w-full grid-cols-7 max-w-4xl">
|
||||
<TabsTrigger value="users" className="gap-2">
|
||||
<Users className="w-4 h-4" />
|
||||
Benutzer
|
||||
@@ -719,6 +799,10 @@ export default function AdminPage() {
|
||||
<ClipboardList className="w-4 h-4" />
|
||||
Wörterliste
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="hose-types" className="gap-2">
|
||||
<Settings className="w-4 h-4" />
|
||||
Schläuche
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="donate" className="gap-2">
|
||||
<Heart className="w-4 h-4" />
|
||||
Spenden
|
||||
@@ -731,66 +815,225 @@ export default function AdminPage() {
|
||||
<Layers className="w-4 h-4" />
|
||||
Kategorien
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="soma" className="gap-2">
|
||||
<AlertTriangle className="w-4 h-4" />
|
||||
SOMA
|
||||
</TabsTrigger>
|
||||
</TabsList>
|
||||
) : null}
|
||||
|
||||
{/* ===== ICONS TAB ===== */}
|
||||
<TabsContent value="icons" className="space-y-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-4">
|
||||
<Select value={selectedCategory} onValueChange={setSelectedCategory}>
|
||||
<SelectTrigger className="w-[200px]">
|
||||
<SelectValue placeholder="Kategorie filtern" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="all">Alle Kategorien</SelectItem>
|
||||
{categories.map(cat => (
|
||||
<SelectItem key={cat.id} value={cat.id}>{cat.name}</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<span className="text-sm text-muted-foreground">{filteredIcons.length} Symbol(e)</span>
|
||||
</div>
|
||||
<Button onClick={() => setIsUploadDialogOpen(true)}>
|
||||
<Upload className="w-4 h-4 mr-2" />
|
||||
Icons hochladen
|
||||
</Button>
|
||||
</div>
|
||||
{user?.role === 'TENANT_ADMIN' ? (() => {
|
||||
// --- Tenant Symbol Management UI ---
|
||||
const symbolCategories = [...new Set(tenantSymbols.map(s => s.categoryName))].sort()
|
||||
const viewSymbols = tenantSymbols
|
||||
.filter(s => symbolViewTab === 'active' ? s.isActive : true)
|
||||
.filter(s => symbolCatFilter === 'all' || s.categoryName === symbolCatFilter)
|
||||
.filter(s => !symbolSearch || s.name.toLowerCase().includes(symbolSearch.toLowerCase()))
|
||||
const grouped = viewSymbols.reduce<Record<string, typeof viewSymbols>>((acc, s) => {
|
||||
const key = s.categoryName
|
||||
if (!acc[key]) acc[key] = []
|
||||
acc[key].push(s)
|
||||
return acc
|
||||
}, {})
|
||||
const toggleSelect = (id: string) => {
|
||||
setSelectedSymbolIds(prev => {
|
||||
const next = new Set(prev)
|
||||
next.has(id) ? next.delete(id) : next.add(id)
|
||||
return next
|
||||
})
|
||||
}
|
||||
const bulkUpdate = async (ids: string[], isActive: boolean) => {
|
||||
try {
|
||||
await fetch('/api/tenant/symbols', {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ updates: ids.map(iconId => ({ iconId, isActive })) }),
|
||||
})
|
||||
setSelectedSymbolIds(new Set())
|
||||
fetchTenantSymbols()
|
||||
toast({ title: isActive ? 'Symbole aktiviert' : 'Symbole deaktiviert' })
|
||||
} catch {}
|
||||
}
|
||||
|
||||
{filteredIcons.length === 0 ? (
|
||||
<div className="border-2 border-dashed rounded-lg p-12 text-center">
|
||||
<Image className="w-12 h-12 mx-auto text-muted-foreground mb-4" />
|
||||
<h3 className="font-medium text-lg mb-2">Keine Symbole vorhanden</h3>
|
||||
<p className="text-muted-foreground mb-4">Laden Sie eigene Symbole hoch (PNG, SVG, JPEG)</p>
|
||||
<Button onClick={() => setIsUploadDialogOpen(true)}>
|
||||
<Upload className="w-4 h-4 mr-2" />
|
||||
Jetzt hochladen
|
||||
</Button>
|
||||
</div>
|
||||
) : (
|
||||
<div className="grid grid-cols-2 md:grid-cols-4 lg:grid-cols-6 xl:grid-cols-8 gap-4">
|
||||
{filteredIcons.map(icon => (
|
||||
<div key={icon.id} className={`relative group border rounded-lg p-3 transition-all hover:shadow-md ${!icon.isActive ? 'opacity-50' : ''}`}>
|
||||
<div className="aspect-square flex items-center justify-center mb-2 bg-muted rounded">
|
||||
<img src={`/api/icons/${icon.id}/image`} alt={icon.name} className="w-12 h-12 object-contain" />
|
||||
</div>
|
||||
<p className="text-xs text-center truncate font-medium" title={icon.name}>{icon.name}</p>
|
||||
<p className="text-[10px] text-center text-muted-foreground truncate">{icon.category.name}</p>
|
||||
{icon.isSystem && <p className="text-[10px] text-center text-blue-500">System</p>}
|
||||
<div className="absolute inset-0 bg-background/80 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center gap-1 rounded-lg">
|
||||
<Button variant="ghost" size="icon" className="h-8 w-8" onClick={() => handleEditIcon(icon)}>
|
||||
<Pencil className="w-4 h-4" />
|
||||
</Button>
|
||||
<Button variant="ghost" size="icon" className="h-8 w-8" onClick={() => handleToggleIconActive(icon)}>
|
||||
{icon.isActive ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
|
||||
</Button>
|
||||
<Button variant="ghost" size="icon" className="h-8 w-8 text-destructive" onClick={() => handleDeleteIcon(icon.id)}>
|
||||
<Trash2 className="w-4 h-4" />
|
||||
</Button>
|
||||
return (
|
||||
<>
|
||||
{/* Header: View tabs + search + filter */}
|
||||
<div className="flex flex-wrap items-center gap-3">
|
||||
<div className="flex rounded-lg border overflow-hidden">
|
||||
<button
|
||||
className={`px-3 py-1.5 text-sm font-medium transition-colors ${symbolViewTab === 'library' ? 'bg-primary text-primary-foreground' : 'hover:bg-muted'}`}
|
||||
onClick={() => { setSymbolViewTab('library'); setSelectedSymbolIds(new Set()) }}
|
||||
>
|
||||
<LayoutGrid className="w-3.5 h-3.5 inline mr-1.5" />Bibliothek
|
||||
</button>
|
||||
<button
|
||||
className={`px-3 py-1.5 text-sm font-medium transition-colors ${symbolViewTab === 'active' ? 'bg-primary text-primary-foreground' : 'hover:bg-muted'}`}
|
||||
onClick={() => { setSymbolViewTab('active'); setSelectedSymbolIds(new Set()) }}
|
||||
>
|
||||
<Eye className="w-3.5 h-3.5 inline mr-1.5" />Aktive
|
||||
</button>
|
||||
</div>
|
||||
<Input
|
||||
placeholder="Symbole suchen..."
|
||||
value={symbolSearch}
|
||||
onChange={e => setSymbolSearch(e.target.value)}
|
||||
className="w-48"
|
||||
/>
|
||||
<Select value={symbolCatFilter} onValueChange={setSymbolCatFilter}>
|
||||
<SelectTrigger className="w-[180px]">
|
||||
<SelectValue placeholder="Kategorie" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="all">Alle Kategorien</SelectItem>
|
||||
{symbolCategories.map(cat => (
|
||||
<SelectItem key={cat} value={cat}>{cat}</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<span className="text-sm text-muted-foreground ml-auto">
|
||||
{tenantSymbols.filter(s => s.isActive).length} aktiv / {tenantSymbols.length} gesamt
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* Bulk category action */}
|
||||
{symbolCatFilter !== 'all' && (
|
||||
<div className="flex gap-2">
|
||||
<Button size="sm" variant="outline" onClick={() => {
|
||||
const ids = tenantSymbols.filter(s => s.categoryName === symbolCatFilter).map(s => s.id)
|
||||
bulkUpdate(ids, true)
|
||||
}}>
|
||||
<Eye className="w-3.5 h-3.5 mr-1" /> Alle «{symbolCatFilter}» aktivieren
|
||||
</Button>
|
||||
<Button size="sm" variant="outline" onClick={() => {
|
||||
const ids = tenantSymbols.filter(s => s.categoryName === symbolCatFilter).map(s => s.id)
|
||||
bulkUpdate(ids, false)
|
||||
}}>
|
||||
<EyeOff className="w-3.5 h-3.5 mr-1" /> Alle «{symbolCatFilter}» deaktivieren
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Selection action bar */}
|
||||
{selectedSymbolIds.size > 0 && (
|
||||
<div className="flex items-center gap-3 bg-foreground text-background px-4 py-2.5 rounded-lg">
|
||||
<span className="text-sm font-medium">{selectedSymbolIds.size} ausgewählt</span>
|
||||
<Button size="sm" variant="secondary" onClick={() => bulkUpdate([...selectedSymbolIds], true)}>
|
||||
<Eye className="w-3.5 h-3.5 mr-1" /> Aktivieren
|
||||
</Button>
|
||||
<Button size="sm" variant="secondary" onClick={() => bulkUpdate([...selectedSymbolIds], false)}>
|
||||
<EyeOff className="w-3.5 h-3.5 mr-1" /> Deaktivieren
|
||||
</Button>
|
||||
<button className="ml-auto text-sm opacity-70 hover:opacity-100" onClick={() => setSelectedSymbolIds(new Set())}>
|
||||
<X className="w-4 h-4" />
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Symbol grid grouped by category */}
|
||||
{symbolsLoading ? (
|
||||
<div className="flex items-center gap-2 py-8 justify-center text-muted-foreground">
|
||||
<Loader2 className="w-5 h-5 animate-spin" /> Symbole laden...
|
||||
</div>
|
||||
) : viewSymbols.length === 0 ? (
|
||||
<div className="border-2 border-dashed rounded-lg p-12 text-center text-muted-foreground">
|
||||
{symbolViewTab === 'active' ? 'Keine aktiven Symbole.' : 'Keine Symbole gefunden.'}
|
||||
</div>
|
||||
) : (
|
||||
Object.entries(grouped).sort(([a], [b]) => a.localeCompare(b)).map(([catName, syms]) => (
|
||||
<div key={catName}>
|
||||
<h4 className="font-semibold text-sm mb-2 flex items-center gap-2">
|
||||
{catName}
|
||||
<span className="text-xs text-muted-foreground font-normal">({syms.length})</span>
|
||||
</h4>
|
||||
<div className="grid grid-cols-3 sm:grid-cols-4 md:grid-cols-6 lg:grid-cols-8 xl:grid-cols-10 gap-2 mb-4">
|
||||
{syms.map(sym => {
|
||||
const selected = selectedSymbolIds.has(sym.id)
|
||||
return (
|
||||
<div
|
||||
key={sym.id}
|
||||
onClick={() => toggleSelect(sym.id)}
|
||||
className={`relative cursor-pointer border-2 rounded-lg p-2 transition-all hover:shadow-sm ${
|
||||
selected ? 'border-blue-500 bg-blue-50 dark:bg-blue-950/30' :
|
||||
sym.isActive ? 'border-transparent hover:border-border' : 'border-transparent opacity-40'
|
||||
}`}
|
||||
>
|
||||
<div className="aspect-square flex items-center justify-center mb-1 bg-muted/50 rounded">
|
||||
<img src={`/api/icons/${sym.id}/image`} alt={sym.name} className="w-10 h-10 object-contain" />
|
||||
</div>
|
||||
<p className="text-[10px] text-center truncate" title={sym.name}>{sym.name}</p>
|
||||
{/* Status dot */}
|
||||
<div className={`absolute top-1.5 right-1.5 w-2 h-2 rounded-full ${sym.isActive ? 'bg-green-500' : 'bg-gray-300'}`} />
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
</>
|
||||
)
|
||||
})() : (
|
||||
/* --- SERVER_ADMIN: existing icon management --- */
|
||||
<>
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-4">
|
||||
<Select value={selectedCategory} onValueChange={setSelectedCategory}>
|
||||
<SelectTrigger className="w-[200px]">
|
||||
<SelectValue placeholder="Kategorie filtern" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="all">Alle Kategorien</SelectItem>
|
||||
{categories.map(cat => (
|
||||
<SelectItem key={cat.id} value={cat.id}>{cat.name}</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<span className="text-sm text-muted-foreground">{filteredIcons.length} Symbol(e)</span>
|
||||
</div>
|
||||
<Button onClick={() => setIsUploadDialogOpen(true)}>
|
||||
<Upload className="w-4 h-4 mr-2" />
|
||||
Icons hochladen
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{filteredIcons.length === 0 ? (
|
||||
<div className="border-2 border-dashed rounded-lg p-12 text-center">
|
||||
<Image className="w-12 h-12 mx-auto text-muted-foreground mb-4" />
|
||||
<h3 className="font-medium text-lg mb-2">Keine Symbole vorhanden</h3>
|
||||
<p className="text-muted-foreground mb-4">Laden Sie eigene Symbole hoch (PNG, SVG, JPEG)</p>
|
||||
<Button onClick={() => setIsUploadDialogOpen(true)}>
|
||||
<Upload className="w-4 h-4 mr-2" />
|
||||
Jetzt hochladen
|
||||
</Button>
|
||||
</div>
|
||||
) : (
|
||||
<div className="grid grid-cols-2 md:grid-cols-4 lg:grid-cols-6 xl:grid-cols-8 gap-4">
|
||||
{filteredIcons.map(icon => (
|
||||
<div key={icon.id} className={`relative group border rounded-lg p-3 transition-all hover:shadow-md ${!icon.isActive ? 'opacity-50' : ''}`}>
|
||||
<div className="aspect-square flex items-center justify-center mb-2 bg-muted rounded">
|
||||
<img src={`/api/icons/${icon.id}/image`} alt={icon.name} className="w-12 h-12 object-contain" />
|
||||
</div>
|
||||
<p className="text-xs text-center truncate font-medium" title={icon.name}>{icon.name}</p>
|
||||
<p className="text-[10px] text-center text-muted-foreground truncate">{icon.category.name}</p>
|
||||
{icon.isSystem && <p className="text-[10px] text-center text-blue-500">System</p>}
|
||||
<div className="absolute inset-0 bg-background/80 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center gap-1 rounded-lg">
|
||||
<Button variant="ghost" size="icon" className="h-8 w-8" onClick={() => handleEditIcon(icon)}>
|
||||
<Pencil className="w-4 h-4" />
|
||||
</Button>
|
||||
<Button variant="ghost" size="icon" className="h-8 w-8" onClick={() => handleToggleIconActive(icon)}>
|
||||
{icon.isActive ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
|
||||
</Button>
|
||||
<Button variant="ghost" size="icon" className="h-8 w-8 text-destructive" onClick={() => handleDeleteIcon(icon.id)}>
|
||||
<Trash2 className="w-4 h-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</TabsContent>
|
||||
|
||||
@@ -960,6 +1203,97 @@ export default function AdminPage() {
|
||||
</TabsContent>
|
||||
)}
|
||||
|
||||
{/* ===== PROJECTS TAB (SERVER_ADMIN — Einsätze verwalten) ===== */}
|
||||
{user?.role === 'SERVER_ADMIN' && (
|
||||
<TabsContent value="projects" className="space-y-4">
|
||||
<div className="flex items-center justify-between gap-4 flex-wrap">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{adminProjects.length} Einsatz/Einsätze
|
||||
</p>
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-sm text-muted-foreground">Feuerwehr:</span>
|
||||
<Select value={adminProjectTenantFilter} onValueChange={(val) => { setAdminProjectTenantFilter(val); fetchAdminProjects(val) }}>
|
||||
<SelectTrigger className="w-[220px]">
|
||||
<SelectValue placeholder="Alle Mandanten" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="all">Alle Mandanten</SelectItem>
|
||||
{tenants.map(t => (
|
||||
<SelectItem key={t.id} value={t.id}>{t.name}</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{adminProjectsLoading ? (
|
||||
<div className="flex items-center justify-center py-12">
|
||||
<Loader2 className="w-6 h-6 animate-spin text-muted-foreground" />
|
||||
</div>
|
||||
) : adminProjects.length === 0 ? (
|
||||
<p className="text-center text-muted-foreground py-8">Keine Einsätze gefunden.</p>
|
||||
) : (
|
||||
<div className="border rounded-lg overflow-hidden">
|
||||
<table className="w-full text-sm">
|
||||
<thead className="bg-muted/50">
|
||||
<tr>
|
||||
<th className="text-left px-4 py-2.5 font-medium">Einsatz-Nr</th>
|
||||
<th className="text-left px-4 py-2.5 font-medium">Titel</th>
|
||||
<th className="text-left px-4 py-2.5 font-medium">Ort</th>
|
||||
<th className="text-left px-4 py-2.5 font-medium">Erstellt von</th>
|
||||
<th className="text-left px-4 py-2.5 font-medium">Feuerwehr</th>
|
||||
<th className="text-left px-4 py-2.5 font-medium">Elemente</th>
|
||||
<th className="text-left px-4 py-2.5 font-medium">Geändert</th>
|
||||
<th className="text-left px-4 py-2.5 font-medium">Aktion</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y">
|
||||
{adminProjects.map((p: any) => (
|
||||
<tr key={p.id} className="hover:bg-muted/30">
|
||||
<td className="px-4 py-2.5 font-mono text-xs">{p.einsatzNr || '—'}</td>
|
||||
<td className="px-4 py-2.5 font-semibold">{p.title}</td>
|
||||
<td className="px-4 py-2.5 text-muted-foreground truncate max-w-[200px]">{p.location || '—'}</td>
|
||||
<td className="px-4 py-2.5">
|
||||
<span className="text-xs">{p.owner?.name || p.owner?.email || '—'}</span>
|
||||
</td>
|
||||
<td className="px-4 py-2.5">
|
||||
<span className="text-xs bg-primary/10 text-primary px-1.5 py-0.5 rounded">{p.tenant?.name || '—'}</span>
|
||||
</td>
|
||||
<td className="px-4 py-2.5 text-center">{p._count?.features || 0}</td>
|
||||
<td className="px-4 py-2.5 text-xs text-muted-foreground">{new Date(p.updatedAt).toLocaleString('de-CH')}</td>
|
||||
<td className="px-4 py-2.5">
|
||||
<Button size="sm" variant="outline" className="h-7 text-xs" onClick={() => window.open(`/app?project=${p.id}`, '_blank')}>
|
||||
<Eye className="w-3 h-3 mr-1" />
|
||||
Öffnen
|
||||
</Button>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
</TabsContent>
|
||||
)}
|
||||
|
||||
{/* ===== HOSE TYPES TAB (Schlauchtypen) ===== */}
|
||||
<TabsContent value="hose-types" className="space-y-4">
|
||||
<div className="border rounded-lg p-6">
|
||||
<h3 className="font-semibold text-lg mb-2 flex items-center gap-2">
|
||||
<Settings className="w-5 h-5" />
|
||||
Schlauchtypen verwalten
|
||||
</h3>
|
||||
<p className="text-sm text-muted-foreground mb-4">
|
||||
Konfiguriere die Schlauchtypen für die Druckberechnung im Messwerkzeug. Der Standard-Schlauch wird automatisch für neue Berechnungen verwendet.
|
||||
</p>
|
||||
<Button variant="outline" onClick={() => setIsHoseSettingsOpen(true)}>
|
||||
<Settings className="w-4 h-4 mr-2" />
|
||||
Schlauchtypen bearbeiten
|
||||
</Button>
|
||||
</div>
|
||||
<HoseSettingsDialog open={isHoseSettingsOpen} onOpenChange={setIsHoseSettingsOpen} />
|
||||
</TabsContent>
|
||||
|
||||
{/* ===== SUGGESTIONS TAB (Word Library) ===== */}
|
||||
<TabsContent value="suggestions" className="space-y-4">
|
||||
<div className="border rounded-lg p-6">
|
||||
@@ -1496,6 +1830,14 @@ export default function AdminPage() {
|
||||
Zur Spendenseite
|
||||
</a>
|
||||
</Button>
|
||||
<div className="mt-6 pt-4 border-t">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
mit ♥ von Pepe —{' '}
|
||||
<a href="/" target="_blank" rel="noopener noreferrer" className="text-primary hover:underline">
|
||||
Über mich & Lageplan
|
||||
</a>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="border rounded-lg p-6">
|
||||
<h3 className="font-semibold text-lg mb-4">Dein Mandant</h3>
|
||||
@@ -1517,6 +1859,130 @@ export default function AdminPage() {
|
||||
</TabsContent>
|
||||
)}
|
||||
|
||||
{/* ===== SOMA TAB (TENANT_ADMIN) ===== */}
|
||||
{user?.role === 'TENANT_ADMIN' && (
|
||||
<TabsContent value="soma" className="space-y-6">
|
||||
<div className="border rounded-lg p-6">
|
||||
<h3 className="font-semibold text-lg mb-2 flex items-center gap-2">
|
||||
<AlertTriangle className="w-5 h-5 text-red-600" />
|
||||
SOMA-Checkliste verwalten
|
||||
</h3>
|
||||
<p className="text-sm text-muted-foreground mb-4">
|
||||
Definiere die Sofortmassnahmen (SOMA), die bei jedem neuen Einsatz als Checkliste erscheinen.
|
||||
Bestehende Einsätze werden nicht verändert.
|
||||
</p>
|
||||
|
||||
{somaLoading ? (
|
||||
<div className="flex items-center gap-2 py-4 text-muted-foreground">
|
||||
<Loader2 className="w-4 h-4 animate-spin" /> Laden...
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
{/* Template list */}
|
||||
<div className="border rounded-lg divide-y">
|
||||
{somaTemplates.length === 0 ? (
|
||||
<div className="px-4 py-6 text-center text-muted-foreground text-sm">
|
||||
Keine SOMA-Vorlagen definiert. Neue Einsätze starten ohne Checkliste.
|
||||
</div>
|
||||
) : somaTemplates.map((tpl, idx) => (
|
||||
<div key={tpl.id} className={`flex items-center gap-3 px-4 py-2.5 ${!tpl.isActive ? 'opacity-50' : ''}`}>
|
||||
<GripVertical className="w-4 h-4 text-muted-foreground/40 shrink-0" />
|
||||
<span className="text-sm font-medium flex-1">{tpl.label}</span>
|
||||
<span className="text-xs text-muted-foreground">#{idx + 1}</span>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-7 px-2"
|
||||
onClick={async () => {
|
||||
try {
|
||||
await fetch('/api/tenant/soma-templates', {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ updates: [{ id: tpl.id, isActive: !tpl.isActive }] }),
|
||||
})
|
||||
fetchSomaTemplates()
|
||||
} catch {}
|
||||
}}
|
||||
>
|
||||
{tpl.isActive ? <Eye className="w-3.5 h-3.5" /> : <EyeOff className="w-3.5 h-3.5" />}
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-7 px-2 text-destructive hover:text-destructive"
|
||||
onClick={async () => {
|
||||
if (!confirm(`"${tpl.label}" wirklich löschen?`)) return
|
||||
try {
|
||||
await fetch('/api/tenant/soma-templates', {
|
||||
method: 'DELETE',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ id: tpl.id }),
|
||||
})
|
||||
fetchSomaTemplates()
|
||||
toast({ title: 'SOMA-Vorlage gelöscht' })
|
||||
} catch {}
|
||||
}}
|
||||
>
|
||||
<Trash2 className="w-3.5 h-3.5" />
|
||||
</Button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* Add new */}
|
||||
<div className="flex gap-2 mt-4">
|
||||
<Input
|
||||
placeholder="Neue Sofortmassnahme..."
|
||||
value={newSomaLabel}
|
||||
onChange={e => setNewSomaLabel(e.target.value)}
|
||||
onKeyDown={e => {
|
||||
if (e.key === 'Enter' && newSomaLabel.trim()) {
|
||||
e.preventDefault()
|
||||
;(async () => {
|
||||
try {
|
||||
await fetch('/api/tenant/soma-templates', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ label: newSomaLabel.trim(), sortOrder: somaTemplates.length }),
|
||||
})
|
||||
setNewSomaLabel('')
|
||||
fetchSomaTemplates()
|
||||
toast({ title: 'SOMA-Vorlage hinzugefügt' })
|
||||
} catch {}
|
||||
})()
|
||||
}
|
||||
}}
|
||||
className="flex-1"
|
||||
/>
|
||||
<Button
|
||||
disabled={!newSomaLabel.trim()}
|
||||
onClick={async () => {
|
||||
try {
|
||||
await fetch('/api/tenant/soma-templates', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ label: newSomaLabel.trim(), sortOrder: somaTemplates.length }),
|
||||
})
|
||||
setNewSomaLabel('')
|
||||
fetchSomaTemplates()
|
||||
toast({ title: 'SOMA-Vorlage hinzugefügt' })
|
||||
} catch {}
|
||||
}}
|
||||
>
|
||||
<Plus className="w-4 h-4 mr-1" /> Hinzufügen
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<p className="text-xs text-muted-foreground mt-3">
|
||||
{somaTemplates.filter(t => t.isActive).length} aktiv / {somaTemplates.length} gesamt —
|
||||
Nur aktive Vorlagen erscheinen bei neuen Einsätzen.
|
||||
</p>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</TabsContent>
|
||||
)}
|
||||
|
||||
{/* Upgrades tab removed — plan management simplified */}
|
||||
</Tabs>
|
||||
</div>
|
||||
|
||||
39
src/app/api/admin/projects/route.ts
Normal file
39
src/app/api/admin/projects/route.ts
Normal file
@@ -0,0 +1,39 @@
|
||||
import { NextRequest, NextResponse } from 'next/server'
|
||||
import { getSession } from '@/lib/auth'
|
||||
import { prisma } from '@/lib/db'
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
try {
|
||||
const user = await getSession()
|
||||
if (!user || user.role !== 'SERVER_ADMIN') {
|
||||
return NextResponse.json({ error: 'Nicht autorisiert' }, { status: 401 })
|
||||
}
|
||||
|
||||
const { searchParams } = new URL(request.url)
|
||||
const tenantId = searchParams.get('tenantId')
|
||||
|
||||
const where: any = {}
|
||||
if (tenantId) where.tenantId = tenantId
|
||||
|
||||
const projects = await (prisma as any).project.findMany({
|
||||
where,
|
||||
orderBy: { updatedAt: 'desc' },
|
||||
include: {
|
||||
owner: {
|
||||
select: { id: true, name: true, email: true },
|
||||
},
|
||||
tenant: {
|
||||
select: { id: true, name: true },
|
||||
},
|
||||
_count: {
|
||||
select: { features: true },
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
return NextResponse.json({ projects })
|
||||
} catch (error) {
|
||||
console.error('Error fetching admin projects:', error)
|
||||
return NextResponse.json({ error: 'Serverfehler' }, { status: 500 })
|
||||
}
|
||||
}
|
||||
@@ -2,9 +2,16 @@ import { NextRequest, NextResponse } from 'next/server'
|
||||
import { getSession } from '@/lib/auth'
|
||||
import { prisma } from '@/lib/db'
|
||||
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) {
|
||||
try {
|
||||
const ip = getClientIp(req)
|
||||
const rl = changePwLimiter.check(ip)
|
||||
if (!rl.success) return rateLimitResponse(rl.resetAt)
|
||||
|
||||
const user = await getSession()
|
||||
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 })
|
||||
}
|
||||
|
||||
if (newPassword.length < 6) {
|
||||
return NextResponse.json({ error: 'Neues Kennwort muss mindestens 6 Zeichen lang sein' }, { status: 400 })
|
||||
if (newPassword.length < 8) {
|
||||
return NextResponse.json({ error: 'Neues Kennwort muss mindestens 8 Zeichen lang sein' }, { status: 400 })
|
||||
}
|
||||
|
||||
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 { randomBytes } from 'crypto'
|
||||
import { sendEmail, getSmtpConfig } from '@/lib/email'
|
||||
import { forgotPasswordLimiter, getClientIp, rateLimitResponse } from '@/lib/rate-limit'
|
||||
|
||||
export async function POST(req: NextRequest) {
|
||||
try {
|
||||
const ip = getClientIp(req)
|
||||
const rl = forgotPasswordLimiter.check(ip)
|
||||
if (!rl.success) return rateLimitResponse(rl.resetAt)
|
||||
|
||||
const { email } = await req.json()
|
||||
if (!email) {
|
||||
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 { loginSchema } from '@/lib/validations'
|
||||
import { prisma } from '@/lib/db'
|
||||
import { loginLimiter, getClientIp, rateLimitResponse } from '@/lib/rate-limit'
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
try {
|
||||
const ip = getClientIp(request)
|
||||
const rl = loginLimiter.check(ip)
|
||||
if (!rl.success) return rateLimitResponse(rl.resetAt)
|
||||
|
||||
const body = await request.json()
|
||||
|
||||
const validated = loginSchema.safeParse(body)
|
||||
@@ -17,11 +22,16 @@ export async function POST(request: NextRequest) {
|
||||
}
|
||||
|
||||
const { email, password } = validated.data
|
||||
const rememberMe = body.rememberMe === true
|
||||
const result = await login(email, password)
|
||||
|
||||
if (!result.success || !result.user) {
|
||||
const remaining = rl.remaining
|
||||
const warningText = remaining <= 3 && remaining > 0
|
||||
? ` (Noch ${remaining} Versuch${remaining === 1 ? '' : 'e'})`
|
||||
: ''
|
||||
return NextResponse.json(
|
||||
{ error: result.error || 'Login fehlgeschlagen' },
|
||||
{ error: (result.error || 'Login fehlgeschlagen') + warningText, remaining },
|
||||
{ status: 401 }
|
||||
)
|
||||
}
|
||||
@@ -34,13 +44,13 @@ export async function POST(request: NextRequest) {
|
||||
})
|
||||
} catch {}
|
||||
|
||||
const token = await createToken(result.user)
|
||||
const token = await createToken(result.user, rememberMe)
|
||||
|
||||
;(await cookies()).set('auth-token', token, {
|
||||
httpOnly: true,
|
||||
secure: process.env.NODE_ENV === 'production',
|
||||
sameSite: 'lax',
|
||||
maxAge: 60 * 60 * 24, // 24 hours
|
||||
maxAge: rememberMe ? 60 * 60 * 24 * 30 : 60 * 60 * 24, // 30 days or 24 hours
|
||||
path: '/',
|
||||
})
|
||||
|
||||
|
||||
@@ -4,16 +4,21 @@ import { hashPassword } from '@/lib/auth'
|
||||
import { sendEmail } from '@/lib/email'
|
||||
import { randomBytes } from 'crypto'
|
||||
import { z } from 'zod'
|
||||
import { registerLimiter, getClientIp, rateLimitResponse } from '@/lib/rate-limit'
|
||||
|
||||
const registerSchema = z.object({
|
||||
organizationName: z.string().min(2, 'Organisationsname zu kurz').max(200),
|
||||
name: z.string().min(2, 'Name zu kurz').max(200),
|
||||
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) {
|
||||
try {
|
||||
const ip = getClientIp(req)
|
||||
const rl = registerLimiter.check(ip)
|
||||
if (!rl.success) return rateLimitResponse(rl.resetAt)
|
||||
|
||||
const body = await req.json()
|
||||
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 { prisma } from '@/lib/db'
|
||||
import { hashPassword } from '@/lib/auth'
|
||||
import { resetPasswordLimiter, getClientIp, rateLimitResponse } from '@/lib/rate-limit'
|
||||
|
||||
export async function POST(req: NextRequest) {
|
||||
try {
|
||||
const ip = getClientIp(req)
|
||||
const rl = resetPasswordLimiter.check(ip)
|
||||
if (!rl.success) return rateLimitResponse(rl.resetAt)
|
||||
|
||||
const { token, password } = await req.json()
|
||||
if (!token || !password) {
|
||||
return NextResponse.json({ error: 'Token und Passwort erforderlich' }, { status: 400 })
|
||||
}
|
||||
|
||||
if (password.length < 6) {
|
||||
return NextResponse.json({ error: 'Passwort muss mindestens 6 Zeichen lang sein' }, { status: 400 })
|
||||
if (password.length < 8) {
|
||||
return NextResponse.json({ error: 'Passwort muss mindestens 8 Zeichen lang sein' }, { status: 400 })
|
||||
}
|
||||
|
||||
const user = await (prisma as any).user.findFirst({
|
||||
|
||||
@@ -2,6 +2,7 @@ import { NextRequest, NextResponse } from 'next/server'
|
||||
import { prisma } from '@/lib/db'
|
||||
import { sendEmail, getSmtpConfig } from '@/lib/email'
|
||||
import { z } from 'zod'
|
||||
import { contactLimiter, getClientIp, rateLimitResponse } from '@/lib/rate-limit'
|
||||
|
||||
const contactSchema = z.object({
|
||||
name: z.string().min(1).max(200),
|
||||
@@ -23,6 +24,10 @@ async function getContactEmail(): Promise<string> {
|
||||
|
||||
export async function POST(req: NextRequest) {
|
||||
try {
|
||||
const ip = getClientIp(req)
|
||||
const rl = contactLimiter.check(ip)
|
||||
if (!rl.success) return rateLimitResponse(rl.resetAt)
|
||||
|
||||
const body = await req.json()
|
||||
const data = contactSchema.parse(body)
|
||||
|
||||
|
||||
@@ -21,7 +21,6 @@ export async function POST(req: NextRequest) {
|
||||
const origin = req.headers.get('origin') || req.nextUrl.origin
|
||||
|
||||
const session = await stripe.checkout.sessions.create({
|
||||
payment_method_types: ['card', 'twint'],
|
||||
mode: 'payment',
|
||||
line_items: [
|
||||
{
|
||||
|
||||
@@ -38,20 +38,28 @@ export async function GET() {
|
||||
},
|
||||
})
|
||||
|
||||
// Get tenant's hidden icon IDs
|
||||
// Get tenant's hidden icon IDs (legacy) + TenantSymbol overrides
|
||||
let hiddenIconIds: string[] = []
|
||||
let deactivatedIconIds = new Set<string>()
|
||||
if (user?.tenantId) {
|
||||
const tenant = await (prisma as any).tenant.findUnique({
|
||||
where: { id: user.tenantId },
|
||||
select: { hiddenIconIds: true },
|
||||
})
|
||||
const [tenant, tenantSymbols] = await Promise.all([
|
||||
(prisma as any).tenant.findUnique({
|
||||
where: { id: user.tenantId },
|
||||
select: { hiddenIconIds: true },
|
||||
}),
|
||||
(prisma as any).tenantSymbol.findMany({
|
||||
where: { tenantId: user.tenantId, isActive: false },
|
||||
select: { iconId: true },
|
||||
}),
|
||||
])
|
||||
hiddenIconIds = tenant?.hiddenIconIds || []
|
||||
deactivatedIconIds = new Set(tenantSymbols.map((ts: any) => ts.iconId))
|
||||
}
|
||||
|
||||
const categoriesWithUrls = categories.map((cat: any) => ({
|
||||
...cat,
|
||||
icons: cat.icons
|
||||
.filter((icon: any) => !hiddenIconIds.includes(icon.id))
|
||||
.filter((icon: any) => !hiddenIconIds.includes(icon.id) && !deactivatedIconIds.has(icon.id))
|
||||
.map((icon: any) => ({
|
||||
...icon,
|
||||
url: `/api/icons/${icon.id}/image`,
|
||||
|
||||
@@ -113,7 +113,19 @@ export async function PUT(
|
||||
}
|
||||
|
||||
const body = await request.json()
|
||||
const { features } = body as { features: Array<{ id?: string; type: string; geometry: object; properties?: object }> }
|
||||
const { features, mapCenter, mapZoom } = body as {
|
||||
features: Array<{ id?: string; type: string; geometry: object; properties?: object }>
|
||||
mapCenter?: { lng: number; lat: number }
|
||||
mapZoom?: number
|
||||
}
|
||||
|
||||
// Persist map viewport alongside features (if provided)
|
||||
if (mapCenter && mapZoom !== undefined) {
|
||||
await (prisma as any).project.update({
|
||||
where: { id },
|
||||
data: { mapCenter, mapZoom },
|
||||
})
|
||||
}
|
||||
|
||||
await (prisma as any).feature.deleteMany({
|
||||
where: { projectId: id },
|
||||
|
||||
@@ -24,10 +24,17 @@ export async function POST(req: NextRequest, { params }: { params: Promise<{ id:
|
||||
if (existing.length > 0) {
|
||||
return NextResponse.json(existing)
|
||||
}
|
||||
const templates = await (prisma as any).journalCheckTemplate.findMany({
|
||||
where: { isActive: true },
|
||||
// Prefer tenant-specific templates; fall back to global (tenantId=null) if none exist
|
||||
let templates = await (prisma as any).journalCheckTemplate.findMany({
|
||||
where: { isActive: true, tenantId: user.tenantId || null },
|
||||
orderBy: { sortOrder: 'asc' },
|
||||
})
|
||||
if (templates.length === 0 && user.tenantId) {
|
||||
templates = await (prisma as any).journalCheckTemplate.findMany({
|
||||
where: { isActive: true, tenantId: null },
|
||||
orderBy: { sortOrder: 'asc' },
|
||||
})
|
||||
}
|
||||
const items = await Promise.all(
|
||||
templates.map((tpl: any, i: number) =>
|
||||
(prisma as any).journalCheckItem.create({
|
||||
|
||||
108
src/app/api/tenant/soma-templates/route.ts
Normal file
108
src/app/api/tenant/soma-templates/route.ts
Normal file
@@ -0,0 +1,108 @@
|
||||
import { NextRequest, NextResponse } from 'next/server'
|
||||
import { prisma } from '@/lib/db'
|
||||
import { getSession } from '@/lib/auth'
|
||||
|
||||
// GET: List SOMA templates for the current tenant
|
||||
export async function GET() {
|
||||
try {
|
||||
const user = await getSession()
|
||||
if (!user) return NextResponse.json({ error: 'Nicht autorisiert' }, { status: 401 })
|
||||
if (user.role !== 'TENANT_ADMIN' && user.role !== 'SERVER_ADMIN') {
|
||||
return NextResponse.json({ error: 'Keine Berechtigung' }, { status: 403 })
|
||||
}
|
||||
|
||||
const templates = await (prisma as any).journalCheckTemplate.findMany({
|
||||
where: { tenantId: user.tenantId || null },
|
||||
orderBy: { sortOrder: 'asc' },
|
||||
})
|
||||
|
||||
return NextResponse.json({ templates })
|
||||
} catch (error) {
|
||||
console.error('Error fetching SOMA templates:', error)
|
||||
return NextResponse.json({ error: 'Interner Fehler' }, { status: 500 })
|
||||
}
|
||||
}
|
||||
|
||||
// POST: Create a new SOMA template for the current tenant
|
||||
export async function POST(req: NextRequest) {
|
||||
try {
|
||||
const user = await getSession()
|
||||
if (!user) return NextResponse.json({ error: 'Nicht autorisiert' }, { status: 401 })
|
||||
if (user.role !== 'TENANT_ADMIN' && user.role !== 'SERVER_ADMIN') {
|
||||
return NextResponse.json({ error: 'Keine Berechtigung' }, { status: 403 })
|
||||
}
|
||||
|
||||
const { label, sortOrder } = await req.json()
|
||||
if (!label?.trim()) {
|
||||
return NextResponse.json({ error: 'Label ist erforderlich' }, { status: 400 })
|
||||
}
|
||||
|
||||
const template = await (prisma as any).journalCheckTemplate.create({
|
||||
data: {
|
||||
label: label.trim(),
|
||||
sortOrder: sortOrder ?? 0,
|
||||
tenantId: user.tenantId || null,
|
||||
isActive: true,
|
||||
},
|
||||
})
|
||||
|
||||
return NextResponse.json({ template }, { status: 201 })
|
||||
} catch (error) {
|
||||
console.error('Error creating SOMA template:', error)
|
||||
return NextResponse.json({ error: 'Interner Fehler' }, { status: 500 })
|
||||
}
|
||||
}
|
||||
|
||||
// PATCH: Update multiple templates (bulk reorder/toggle)
|
||||
export async function PATCH(req: NextRequest) {
|
||||
try {
|
||||
const user = await getSession()
|
||||
if (!user) return NextResponse.json({ error: 'Nicht autorisiert' }, { status: 401 })
|
||||
if (user.role !== 'TENANT_ADMIN' && user.role !== 'SERVER_ADMIN') {
|
||||
return NextResponse.json({ error: 'Keine Berechtigung' }, { status: 403 })
|
||||
}
|
||||
|
||||
const { updates } = await req.json()
|
||||
if (!Array.isArray(updates)) {
|
||||
return NextResponse.json({ error: 'updates Array erforderlich' }, { status: 400 })
|
||||
}
|
||||
|
||||
await Promise.all(
|
||||
updates.map((u: { id: string; label?: string; sortOrder?: number; isActive?: boolean }) =>
|
||||
(prisma as any).journalCheckTemplate.update({
|
||||
where: { id: u.id },
|
||||
data: {
|
||||
...(u.label !== undefined && { label: u.label }),
|
||||
...(u.sortOrder !== undefined && { sortOrder: u.sortOrder }),
|
||||
...(u.isActive !== undefined && { isActive: u.isActive }),
|
||||
},
|
||||
})
|
||||
)
|
||||
)
|
||||
|
||||
return NextResponse.json({ success: true })
|
||||
} catch (error) {
|
||||
console.error('Error updating SOMA templates:', error)
|
||||
return NextResponse.json({ error: 'Interner Fehler' }, { status: 500 })
|
||||
}
|
||||
}
|
||||
|
||||
// DELETE: Delete a SOMA template
|
||||
export async function DELETE(req: NextRequest) {
|
||||
try {
|
||||
const user = await getSession()
|
||||
if (!user) return NextResponse.json({ error: 'Nicht autorisiert' }, { status: 401 })
|
||||
if (user.role !== 'TENANT_ADMIN' && user.role !== 'SERVER_ADMIN') {
|
||||
return NextResponse.json({ error: 'Keine Berechtigung' }, { status: 403 })
|
||||
}
|
||||
|
||||
const { id } = await req.json()
|
||||
if (!id) return NextResponse.json({ error: 'ID erforderlich' }, { status: 400 })
|
||||
|
||||
await (prisma as any).journalCheckTemplate.delete({ where: { id } })
|
||||
return NextResponse.json({ success: true })
|
||||
} catch (error) {
|
||||
console.error('Error deleting SOMA template:', error)
|
||||
return NextResponse.json({ error: 'Interner Fehler' }, { status: 500 })
|
||||
}
|
||||
}
|
||||
83
src/app/api/tenant/symbols/route.ts
Normal file
83
src/app/api/tenant/symbols/route.ts
Normal file
@@ -0,0 +1,83 @@
|
||||
import { NextRequest, NextResponse } from 'next/server'
|
||||
import { prisma } from '@/lib/db'
|
||||
import { getSession } from '@/lib/auth'
|
||||
|
||||
// GET: List all icons with their tenant-specific active status
|
||||
export async function GET() {
|
||||
try {
|
||||
const user = await getSession()
|
||||
if (!user) return NextResponse.json({ error: 'Nicht autorisiert' }, { status: 401 })
|
||||
if (user.role !== 'TENANT_ADMIN' && user.role !== 'SERVER_ADMIN') {
|
||||
return NextResponse.json({ error: 'Keine Berechtigung' }, { status: 403 })
|
||||
}
|
||||
|
||||
const tenantId = user.tenantId
|
||||
if (!tenantId) return NextResponse.json({ error: 'Kein Mandant zugeordnet' }, { status: 400 })
|
||||
|
||||
// Get all system icons (active ones)
|
||||
const icons = await (prisma as any).iconAsset.findMany({
|
||||
where: { isActive: true },
|
||||
include: { category: { select: { id: true, name: true } } },
|
||||
orderBy: [{ category: { sortOrder: 'asc' } }, { name: 'asc' }],
|
||||
})
|
||||
|
||||
// Get tenant-specific overrides
|
||||
const overrides = await (prisma as any).tenantSymbol.findMany({
|
||||
where: { tenantId },
|
||||
})
|
||||
|
||||
const overrideMap = new Map(overrides.map((o: any) => [o.iconId, o.isActive]))
|
||||
|
||||
// Merge: default is active (true) unless override says otherwise
|
||||
const symbols = icons.map((icon: any) => ({
|
||||
id: icon.id,
|
||||
name: icon.name,
|
||||
fileKey: icon.fileKey,
|
||||
mimeType: icon.mimeType,
|
||||
iconType: icon.iconType,
|
||||
categoryId: icon.categoryId,
|
||||
categoryName: icon.category?.name || 'Ohne Kategorie',
|
||||
isActive: overrideMap.has(icon.id) ? overrideMap.get(icon.id) : true,
|
||||
}))
|
||||
|
||||
return NextResponse.json({ symbols })
|
||||
} catch (error) {
|
||||
console.error('Error fetching tenant symbols:', error)
|
||||
return NextResponse.json({ error: 'Interner Fehler' }, { status: 500 })
|
||||
}
|
||||
}
|
||||
|
||||
// PATCH: Update symbol visibility for the tenant (bulk)
|
||||
export async function PATCH(req: NextRequest) {
|
||||
try {
|
||||
const user = await getSession()
|
||||
if (!user) return NextResponse.json({ error: 'Nicht autorisiert' }, { status: 401 })
|
||||
if (user.role !== 'TENANT_ADMIN' && user.role !== 'SERVER_ADMIN') {
|
||||
return NextResponse.json({ error: 'Keine Berechtigung' }, { status: 403 })
|
||||
}
|
||||
|
||||
const tenantId = user.tenantId
|
||||
if (!tenantId) return NextResponse.json({ error: 'Kein Mandant zugeordnet' }, { status: 400 })
|
||||
|
||||
const { updates } = await req.json()
|
||||
if (!Array.isArray(updates)) {
|
||||
return NextResponse.json({ error: 'updates Array erforderlich' }, { status: 400 })
|
||||
}
|
||||
|
||||
// Upsert each symbol override
|
||||
await Promise.all(
|
||||
updates.map((u: { iconId: string; isActive: boolean }) =>
|
||||
(prisma as any).tenantSymbol.upsert({
|
||||
where: { tenantId_iconId: { tenantId, iconId: u.iconId } },
|
||||
update: { isActive: u.isActive },
|
||||
create: { tenantId, iconId: u.iconId, isActive: u.isActive },
|
||||
})
|
||||
)
|
||||
)
|
||||
|
||||
return NextResponse.json({ success: true })
|
||||
} catch (error) {
|
||||
console.error('Error updating tenant symbols:', error)
|
||||
return NextResponse.json({ error: 'Interner Fehler' }, { status: 500 })
|
||||
}
|
||||
}
|
||||
@@ -19,9 +19,11 @@ import { Button } from '@/components/ui/button'
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog'
|
||||
import { JournalView } from '@/components/journal/journal-view'
|
||||
import { jsPDF } from 'jspdf'
|
||||
import { Lock, Unlock, Eye } from 'lucide-react'
|
||||
import { getSocket } from '@/lib/socket'
|
||||
import { Lock, Unlock, Eye, AlertTriangle, WifiOff } from 'lucide-react'
|
||||
import { getSocket, setSocketRoom } from '@/lib/socket'
|
||||
import { CustomDragLayer } from '@/components/map/custom-drag-layer'
|
||||
import { OnboardingTour, resetOnboardingTour } from '@/components/onboarding/onboarding-tour'
|
||||
import { addToSyncQueue, flushSyncQueue, getSyncQueue, isOnline as checkOnline } from '@/lib/offline-sync'
|
||||
|
||||
export interface Project {
|
||||
id: string
|
||||
@@ -91,6 +93,9 @@ export default function AppPage() {
|
||||
const [lastMapScreenshot, setLastMapScreenshot] = useState<string>('')
|
||||
const [defaultSymbolScale, setDefaultSymbolScale] = useState(1.5)
|
||||
|
||||
// Onboarding tour
|
||||
const [showTour, setShowTour] = useState(false)
|
||||
|
||||
// Live editing lock state
|
||||
const [editingBy, setEditingBy] = useState<{ id: string; name: string; since: string } | null>(null)
|
||||
const [isEditingByMe, setIsEditingByMe] = useState(false)
|
||||
@@ -366,6 +371,54 @@ export default function AppPage() {
|
||||
// Ref to access the map for export
|
||||
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
|
||||
const undoStackRef = useRef<DrawFeature[][]>([])
|
||||
const redoStackRef = useRef<DrawFeature[][]>([])
|
||||
@@ -458,27 +511,31 @@ export default function AppPage() {
|
||||
const socketRef = useRef<any>(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 emitTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)
|
||||
const currentProjectRef = useRef(currentProject)
|
||||
useEffect(() => { currentProjectRef.current = currentProject }, [currentProject])
|
||||
|
||||
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 emit = () => {
|
||||
socketRef.current?.emit('features-updated', {
|
||||
projectId: currentProject!.id,
|
||||
projectId: proj!.id,
|
||||
features: feats,
|
||||
})
|
||||
lastEmitRef.current = Date.now()
|
||||
}
|
||||
// Throttle: emit at most every 1.5 seconds
|
||||
if (now - lastEmitRef.current > 1500) {
|
||||
// Throttle: emit at most every 800ms for snappier sync
|
||||
if (now - lastEmitRef.current > 800) {
|
||||
emit()
|
||||
} else {
|
||||
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)
|
||||
|
||||
// Keep ref in sync with state
|
||||
@@ -497,6 +554,7 @@ export default function AppPage() {
|
||||
socket.emit('leave-project', prevProjectIdRef.current)
|
||||
}
|
||||
socket.emit('join-project', currentProject.id)
|
||||
setSocketRoom(currentProject.id)
|
||||
prevProjectIdRef.current = currentProject.id
|
||||
|
||||
// Listen for features changes from other clients (only apply if NOT the editor)
|
||||
@@ -643,11 +701,28 @@ export default function AppPage() {
|
||||
const saveTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)
|
||||
const saveFeaturesToApi = useCallback(async () => {
|
||||
if (!currentProject?.id) return
|
||||
const url = `/api/projects/${currentProject.id}/features`
|
||||
const mapInstance = mapRef.current
|
||||
const body: any = { features: featuresRef.current }
|
||||
if (mapInstance) {
|
||||
const c = mapInstance.getCenter()
|
||||
body.mapCenter = { lng: c.lng, lat: c.lat }
|
||||
body.mapZoom = mapInstance.getZoom()
|
||||
}
|
||||
|
||||
// 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 {
|
||||
const res = await fetch(`/api/projects/${currentProject.id}/features`, {
|
||||
const res = await fetch(url, {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ features: featuresRef.current }),
|
||||
body: JSON.stringify(body),
|
||||
})
|
||||
if (res.ok) {
|
||||
console.log('[Auto-Save] Features gespeichert')
|
||||
@@ -659,7 +734,10 @@ export default function AppPage() {
|
||||
console.warn('[Auto-Save] Projekt nicht in DB')
|
||||
}
|
||||
} 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])
|
||||
|
||||
@@ -817,10 +895,16 @@ export default function AppPage() {
|
||||
|
||||
setIsSaving(true)
|
||||
try {
|
||||
const saveBody: any = { features }
|
||||
if (mapRef.current) {
|
||||
const c = mapRef.current.getCenter()
|
||||
saveBody.mapCenter = { lng: c.lng, lat: c.lat }
|
||||
saveBody.mapZoom = mapRef.current.getZoom()
|
||||
}
|
||||
let res = await fetch(`/api/projects/${currentProject.id}/features`, {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ features }),
|
||||
body: JSON.stringify(saveBody),
|
||||
})
|
||||
|
||||
// If project doesn't exist in DB (404), re-create it first then retry
|
||||
@@ -980,6 +1064,59 @@ export default function AppPage() {
|
||||
}
|
||||
}, [])
|
||||
|
||||
// Keyboard shortcuts for tools
|
||||
const [isShortcutHelpOpen, setIsShortcutHelpOpen] = useState(false)
|
||||
useEffect(() => {
|
||||
const handleKeyDown = (e: KeyboardEvent) => {
|
||||
// Ignore when typing in inputs/textareas
|
||||
const tag = (e.target as HTMLElement)?.tagName
|
||||
if (tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT' || (e.target as HTMLElement)?.isContentEditable) return
|
||||
|
||||
// ? or F1 → help
|
||||
if (e.key === '?' || e.key === 'F1') { e.preventDefault(); setIsShortcutHelpOpen(true); return }
|
||||
|
||||
// DEL / Backspace → delete selected feature(s)
|
||||
if (e.key === 'Delete' || e.key === 'Backspace') {
|
||||
e.preventDefault()
|
||||
// Remove all selected features
|
||||
const current = featuresRef.current
|
||||
const selected = current.filter(f => f.properties?._selected)
|
||||
if (selected.length > 0) {
|
||||
handleFeaturesChange(current.filter(f => !f.properties?._selected))
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// Ctrl/Cmd shortcuts (CH keyboard: Z and Y are swapped)
|
||||
if (e.ctrlKey || e.metaKey) {
|
||||
if (e.key === 'z') { e.preventDefault(); handleRedo(); return }
|
||||
if (e.key === 'y') { e.preventDefault(); handleUndo(); return }
|
||||
if (e.key === 's') { e.preventDefault(); handleSaveProject(); return }
|
||||
return
|
||||
}
|
||||
|
||||
// Tool shortcuts (single key, no modifier)
|
||||
const shortcuts: Record<string, DrawMode> = {
|
||||
'v': 'select', 's': 'select',
|
||||
'p': 'point',
|
||||
'l': 'linestring',
|
||||
'g': 'polygon',
|
||||
'r': 'rectangle',
|
||||
'c': 'circle',
|
||||
'f': 'freehand',
|
||||
'a': 'arrow',
|
||||
't': 'text',
|
||||
'e': 'eraser',
|
||||
'm': 'measure',
|
||||
'd': 'dangerzone',
|
||||
}
|
||||
const mode = shortcuts[e.key.toLowerCase()]
|
||||
if (mode) { e.preventDefault(); setDrawMode(mode); return }
|
||||
}
|
||||
window.addEventListener('keydown', handleKeyDown)
|
||||
return () => window.removeEventListener('keydown', handleKeyDown)
|
||||
}, [handleUndo, handleRedo, handleSaveProject, setDrawMode, handleFeaturesChange])
|
||||
|
||||
const handlePlanUpload = useCallback(() => {
|
||||
if (!currentProject) return
|
||||
const input = document.createElement('input')
|
||||
@@ -1130,6 +1267,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
|
||||
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
|
||||
@@ -1361,8 +1524,43 @@ export default function AppPage() {
|
||||
userName={user?.name}
|
||||
userRole={user?.role}
|
||||
onLogout={logout}
|
||||
onStartTour={() => { resetOnboardingTour(); setShowTour(true) }}
|
||||
/>
|
||||
|
||||
{/* 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 */}
|
||||
{currentProject && (
|
||||
@@ -1402,7 +1600,7 @@ export default function AppPage() {
|
||||
|
||||
<div className="flex-1 flex overflow-hidden">
|
||||
{/* Map view — always mounted, hidden via CSS to preserve state */}
|
||||
<div className={`contents ${activeTab !== 'map' ? 'hidden' : ''}`}>
|
||||
<div data-tour="toolbar" className={`contents ${activeTab !== 'map' ? 'hidden' : ''}`}>
|
||||
<LeftToolbar
|
||||
drawMode={drawMode}
|
||||
onDrawModeChange={setDrawMode}
|
||||
@@ -1455,6 +1653,7 @@ export default function AppPage() {
|
||||
|
||||
{/* Right sidebar — always visible, contains Karte/Journal tabs */}
|
||||
<RightSidebar
|
||||
data-tour="sidebar"
|
||||
onSymbolDrop={handleSymbolDrop}
|
||||
canEdit={canEdit}
|
||||
isOpen={isSidebarOpen}
|
||||
@@ -1488,6 +1687,39 @@ export default function AppPage() {
|
||||
lineType={(pendingLineFeature?.type as any) || 'linestring'}
|
||||
/>
|
||||
|
||||
{/* Keyboard Shortcuts Help Dialog */}
|
||||
<Dialog open={isShortcutHelpOpen} onOpenChange={setIsShortcutHelpOpen}>
|
||||
<DialogContent className="max-w-md">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Tastenkürzel</DialogTitle>
|
||||
</DialogHeader>
|
||||
<div className="grid grid-cols-2 gap-x-6 gap-y-1.5 text-sm mt-2">
|
||||
<div className="font-semibold text-muted-foreground col-span-2 mt-1 mb-0.5">Werkzeuge</div>
|
||||
{[
|
||||
['V', 'Auswählen'], ['P', 'Punkt'], ['L', 'Linie'], ['G', 'Polygon'],
|
||||
['R', 'Rechteck'], ['C', 'Kreis'], ['F', 'Freihand'], ['A', 'Pfeil / Route'],
|
||||
['T', 'Text'], ['E', 'Radiergummi'], ['M', 'Messen'], ['D', 'Gefahrenzone'],
|
||||
].map(([key, label]) => (
|
||||
<div key={key} className="flex items-center justify-between">
|
||||
<span>{label}</span>
|
||||
<kbd className="ml-2 px-1.5 py-0.5 bg-muted rounded border border-border font-mono text-xs">{key}</kbd>
|
||||
</div>
|
||||
))}
|
||||
<div className="font-semibold text-muted-foreground col-span-2 mt-3 mb-0.5">Aktionen</div>
|
||||
{[
|
||||
['Ctrl+Y', 'Rückgängig'], ['Ctrl+Z', 'Wiederholen'],
|
||||
['Ctrl+S', 'Speichern'], ['Del', 'Auswahl löschen'],
|
||||
['Esc', 'Abbrechen'], ['?', 'Diese Hilfe'],
|
||||
].map(([key, label]) => (
|
||||
<div key={key} className="flex items-center justify-between">
|
||||
<span>{label}</span>
|
||||
<kbd className="ml-2 px-1.5 py-0.5 bg-muted rounded border border-border font-mono text-xs">{key}</kbd>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
{/* Delete All Confirmation Dialog */}
|
||||
<Dialog open={isDeleteAllConfirmOpen} onOpenChange={setIsDeleteAllConfirmOpen}>
|
||||
<DialogContent className="max-w-sm">
|
||||
@@ -1507,6 +1739,12 @@ export default function AppPage() {
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
{/* Onboarding Tour */}
|
||||
<OnboardingTour
|
||||
forceShow={showTour}
|
||||
onComplete={() => setShowTour(false)}
|
||||
/>
|
||||
</div>
|
||||
</DndProvider>
|
||||
)
|
||||
|
||||
@@ -4,25 +4,26 @@
|
||||
|
||||
@layer base {
|
||||
:root {
|
||||
--background: 0 0% 100%;
|
||||
--foreground: 222.2 84% 4.9%;
|
||||
--card: 0 0% 100%;
|
||||
--card-foreground: 222.2 84% 4.9%;
|
||||
/* Light Mode — optimiert für Einsatz-Kontext (WCAG 2.1 AA) */
|
||||
--background: 210 33% 99%; /* #fafbfc — leicht abgesetzt, kein reines Weiss */
|
||||
--foreground: 217.2 32.6% 17.5%; /* Slate-800 #1e293b — Primärtext, 12.6:1 Kontrast */
|
||||
--card: 0 0% 100%; /* Weisse Karten/Panels */
|
||||
--card-foreground: 217.2 32.6% 17.5%;
|
||||
--popover: 0 0% 100%;
|
||||
--popover-foreground: 222.2 84% 4.9%;
|
||||
--primary: 222.2 47.4% 11.2%;
|
||||
--popover-foreground: 217.2 32.6% 17.5%;
|
||||
--primary: 222.2 47.4% 11.2%; /* Slate-900 — Buttons, aktive Elemente */
|
||||
--primary-foreground: 210 40% 98%;
|
||||
--secondary: 210 40% 96.1%;
|
||||
--secondary-foreground: 222.2 47.4% 11.2%;
|
||||
--muted: 210 40% 96.1%;
|
||||
--muted-foreground: 215.4 16.3% 46.9%;
|
||||
--secondary: 210 40% 96.1%; /* Slate-100 */
|
||||
--secondary-foreground: 217.2 32.6% 17.5%;
|
||||
--muted: 210 40% 96.1%; /* Slate-100 — Hover, dezente Flächen */
|
||||
--muted-foreground: 215.3 19.4% 34.5%; /* Slate-600 #475569 — Sekundärtext, 7.1:1 Kontrast */
|
||||
--accent: 210 40% 96.1%;
|
||||
--accent-foreground: 222.2 47.4% 11.2%;
|
||||
--destructive: 0 84.2% 60.2%;
|
||||
--destructive-foreground: 210 40% 98%;
|
||||
--border: 214.3 31.8% 91.4%;
|
||||
--input: 214.3 31.8% 91.4%;
|
||||
--ring: 222.2 84% 4.9%;
|
||||
--accent-foreground: 217.2 32.6% 17.5%;
|
||||
--destructive: 0 72.2% 50.6%; /* Feuerwehr-Rot #dc2626 */
|
||||
--destructive-foreground: 0 0% 100%;
|
||||
--border: 214.3 31.8% 91.4%; /* Slate-200 #e2e8f0 */
|
||||
--input: 212.7 26.8% 83.9%; /* Slate-300 #cbd5e1 — stärkere Input-Borders */
|
||||
--ring: 217.2 91.2% 59.8%; /* Blau #3b82f6 — Focus-Ring */
|
||||
--radius: 0.5rem;
|
||||
}
|
||||
|
||||
@@ -56,6 +57,9 @@
|
||||
}
|
||||
body {
|
||||
@apply bg-background text-foreground;
|
||||
font-size: 15px;
|
||||
line-height: 1.6;
|
||||
letter-spacing: 0.01em;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
import type { Metadata, Viewport } from 'next'
|
||||
import { Inter } from 'next/font/google'
|
||||
import { Barlow } from 'next/font/google'
|
||||
import './globals.css'
|
||||
import { Toaster } from '@/components/ui/toaster'
|
||||
import { AuthProvider } from '@/components/providers/auth-provider'
|
||||
import { ServiceWorkerRegister } from '@/components/providers/sw-register'
|
||||
import { CookieConsent } from '@/components/ui/cookie-consent'
|
||||
|
||||
const inter = Inter({
|
||||
const barlow = Barlow({
|
||||
subsets: ['latin'],
|
||||
weight: ['400', '500', '600', '700'],
|
||||
display: 'swap',
|
||||
@@ -105,7 +105,7 @@ export default function RootLayout({
|
||||
<meta name="mobile-web-app-capable" content="yes" />
|
||||
<meta name="theme-color" content="#dc2626" />
|
||||
</head>
|
||||
<body className={`${inter.className} antialiased`} style={{ fontFeatureSettings: '"tnum", "cv01"' }}>
|
||||
<body className={`${barlow.className} antialiased`} style={{ fontFeatureSettings: '"tnum"' }}>
|
||||
<AuthProvider>
|
||||
<ServiceWorkerRegister />
|
||||
{children}
|
||||
|
||||
@@ -22,7 +22,10 @@ export default function LoginPage() {
|
||||
function LoginForm() {
|
||||
const [email, setEmail] = useState('')
|
||||
const [password, setPassword] = useState('')
|
||||
const [rememberMe, setRememberMe] = useState(true)
|
||||
const [isLoading, setIsLoading] = useState(false)
|
||||
const [resendLoading, setResendLoading] = useState(false)
|
||||
const [resendSuccess, setResendSuccess] = useState(false)
|
||||
const [tenantLogo, setTenantLogo] = useState<string | null>(null)
|
||||
const [tenantName, setTenantName] = useState<string | null>(null)
|
||||
const { login } = useAuth()
|
||||
@@ -53,7 +56,7 @@ function LoginForm() {
|
||||
e.preventDefault()
|
||||
setIsLoading(true)
|
||||
|
||||
const result = await login(email, password)
|
||||
const result = await login(email, password, rememberMe)
|
||||
|
||||
if (result.success) {
|
||||
toast({
|
||||
@@ -110,7 +113,32 @@ function LoginForm() {
|
||||
)}
|
||||
{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">
|
||||
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>
|
||||
)}
|
||||
|
||||
@@ -146,6 +174,16 @@ function LoginForm() {
|
||||
/>
|
||||
</div>
|
||||
|
||||
<label className="flex items-center gap-2 cursor-pointer select-none">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={rememberMe}
|
||||
onChange={(e) => setRememberMe(e.target.checked)}
|
||||
className="w-4 h-4 rounded border-gray-300 text-red-600 focus:ring-red-500"
|
||||
/>
|
||||
<span className="text-sm text-muted-foreground">Angemeldet bleiben</span>
|
||||
</label>
|
||||
|
||||
<Button
|
||||
type="submit"
|
||||
className="w-full bg-red-600 hover:bg-red-700"
|
||||
|
||||
@@ -526,10 +526,10 @@ function SupportSection() {
|
||||
{/* Tier preview */}
|
||||
<div className="grid grid-cols-2 sm:grid-cols-4 gap-3 mb-8">
|
||||
{[
|
||||
{ emoji: '\u2615', label: 'Kaffee', amount: 'CHF 5' },
|
||||
{ emoji: '\uD83C\uDF55', label: 'Pizza', amount: 'CHF 10' },
|
||||
{ emoji: '\uD83D\uDDA5\uFE0F', label: 'Server', amount: 'CHF 25' },
|
||||
{ emoji: '\uD83D\uDDA5\uFE0F', label: 'Server', amount: 'CHF 20' },
|
||||
{ emoji: '\uD83D\uDE80', label: 'Feature', amount: 'CHF 50' },
|
||||
{ emoji: '\u2764\uFE0F', label: 'Freibetrag', amount: 'Frei' },
|
||||
].map(tier => (
|
||||
<div key={tier.label} className="rounded-xl p-4 border border-gray-100 bg-gray-50">
|
||||
<span className="text-2xl block mb-1">{tier.emoji}</span>
|
||||
@@ -540,7 +540,7 @@ function SupportSection() {
|
||||
</div>
|
||||
|
||||
<p className="text-gray-500 mb-6">
|
||||
Wähle einen Betrag auf unserer Spendenseite — Zahlung sicher via Stripe (Kreditkarte, Twint).
|
||||
Wähle einen Betrag auf unserer Spendenseite — Zahlung sicher via Stripe (Kreditkarte, Twint, Apple Pay, Google Pay).
|
||||
</p>
|
||||
|
||||
<Link href="/spenden">
|
||||
|
||||
@@ -72,7 +72,7 @@ export default function RapportViewerPage({ params }: { params: Promise<{ token:
|
||||
{/* Action bar */}
|
||||
<div className="max-w-[210mm] mx-auto mb-4 flex justify-between items-center px-4">
|
||||
<div className="flex items-center gap-2">
|
||||
<MapPin className="w-5 h-5 text-red-500" />
|
||||
<img src="/logo.svg" alt="Lageplan" className="w-5 h-5 object-contain" />
|
||||
<span className="font-semibold text-sm">Lageplan — Einsatzrapport</span>
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
@@ -168,8 +168,7 @@ export default function RapportViewerPage({ params }: { params: Promise<{ token:
|
||||
<Field label="Alarmzeit" value={d.alarmzeit} mono />
|
||||
<Field label="Priorität" value={d.prioritaet} last />
|
||||
<Field label="Einsatzort / Adresse" value={d.einsatzort} span={2} />
|
||||
<Field label="Koordinaten" value={d.koordinaten} mono />
|
||||
<Field label="Objekt / Gebäude" value={d.objekt} last />
|
||||
<Field label="Objekt / Gebäude" value={d.objekt} span={2} last />
|
||||
<Field label="Alarmierungsart" value={d.alarmierungsart} span={2} />
|
||||
<Field label="Stichwort / Meldebild" value={d.stichwort} span={2} last />
|
||||
</div>
|
||||
@@ -177,15 +176,9 @@ export default function RapportViewerPage({ params }: { params: Promise<{ token:
|
||||
|
||||
{/* 2. Zeitverlauf */}
|
||||
<Section num="2" title="Zeitverlauf">
|
||||
<div className="grid grid-cols-4 border rounded">
|
||||
<div className="grid grid-cols-2 border rounded">
|
||||
<Field label="Alarmierung" value={d.zeitAlarm} mono highlight />
|
||||
<Field label="Ausrücken" value={d.zeitAusruecken} mono highlight />
|
||||
<Field label="Eintreffen" value={d.zeitEintreffen} mono highlight />
|
||||
<Field label="Einsatzbereit" value={d.zeitBereit} mono highlight last />
|
||||
<Field label="Feuer unter Kontrolle" value={d.zeitKontrolle} mono highlight />
|
||||
<Field label="Feuer aus" value={d.zeitAus} mono highlight />
|
||||
<Field label="Einrücken" value={d.zeitEinruecken} mono highlight />
|
||||
<Field label="Einsatzende" value={d.zeitEnde} mono highlight last />
|
||||
<Field label="Eintreffen" value={d.zeitEintreffen} mono highlight last />
|
||||
</div>
|
||||
</Section>
|
||||
|
||||
|
||||
@@ -30,8 +30,8 @@ export default function RegisterPage() {
|
||||
return
|
||||
}
|
||||
|
||||
if (password.length < 6) {
|
||||
toast({ title: 'Passwort muss mindestens 6 Zeichen haben', variant: 'destructive' })
|
||||
if (password.length < 8) {
|
||||
toast({ title: 'Passwort muss mindestens 8 Zeichen haben', variant: 'destructive' })
|
||||
return
|
||||
}
|
||||
|
||||
@@ -163,7 +163,7 @@ export default function RegisterPage() {
|
||||
<Input
|
||||
id="password"
|
||||
type="password"
|
||||
placeholder="Mindestens 6 Zeichen"
|
||||
placeholder="Mindestens 8 Zeichen"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
required
|
||||
|
||||
@@ -32,8 +32,8 @@ function ResetPasswordForm() {
|
||||
e.preventDefault()
|
||||
setError('')
|
||||
|
||||
if (password.length < 6) {
|
||||
setError('Passwort muss mindestens 6 Zeichen lang sein.')
|
||||
if (password.length < 8) {
|
||||
setError('Passwort muss mindestens 8 Zeichen lang sein.')
|
||||
return
|
||||
}
|
||||
if (password !== confirmPassword) {
|
||||
@@ -108,7 +108,7 @@ function ResetPasswordForm() {
|
||||
<Input
|
||||
id="password"
|
||||
type="password"
|
||||
placeholder="Min. 6 Zeichen"
|
||||
placeholder="Min. 8 Zeichen"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
required
|
||||
|
||||
@@ -10,14 +10,15 @@ import {
|
||||
import { Logo } from '@/components/ui/logo'
|
||||
|
||||
const tiers = [
|
||||
{ value: 5, label: 'Kaffee', emoji: '\u2615', desc: 'Ein Kaffee für die nächste Coding-Session' },
|
||||
{ value: 10, label: 'Pizza', emoji: '\uD83C\uDF55', desc: 'Pizza-Abend nach einem langen Entwicklungstag' },
|
||||
{ value: 25, label: 'Server', emoji: '\uD83D\uDDA5\uFE0F', desc: 'Hilft die monatlichen Serverkosten zu decken' },
|
||||
{ value: 10, label: 'Pizza', emoji: '\uD83C\uDF55', desc: 'Eine Pizza für die nächste Coding-Session' },
|
||||
{ value: 20, label: 'Server', emoji: '\uD83D\uDDA5\uFE0F', desc: 'Hilft die monatlichen Serverkosten zu decken' },
|
||||
{ value: 50, label: 'Feature', emoji: '\uD83D\uDE80', desc: 'Finanziert die Entwicklung eines neuen Features' },
|
||||
]
|
||||
|
||||
export default function SpendenPage() {
|
||||
const [amount, setAmount] = useState(10)
|
||||
const [amount, setAmount] = useState(20)
|
||||
const [customAmount, setCustomAmount] = useState('')
|
||||
const [isCustom, setIsCustom] = useState(false)
|
||||
const [name, setName] = useState('')
|
||||
const [message, setMessage] = useState('')
|
||||
const [isLoading, setIsLoading] = useState(false)
|
||||
@@ -112,9 +113,9 @@ export default function SpendenPage() {
|
||||
{tiers.map(tier => (
|
||||
<button
|
||||
key={tier.value}
|
||||
onClick={() => setAmount(tier.value)}
|
||||
onClick={() => { setAmount(tier.value); setIsCustom(false); setCustomAmount('') }}
|
||||
className={`rounded-xl p-4 text-center transition-all border-2 ${
|
||||
amount === tier.value
|
||||
!isCustom && amount === tier.value
|
||||
? 'border-red-500 bg-red-50 shadow-md'
|
||||
: 'border-gray-100 hover:border-gray-200 hover:bg-gray-50'
|
||||
}`}
|
||||
@@ -124,34 +125,52 @@ export default function SpendenPage() {
|
||||
<span className="text-xs text-gray-500 block mt-0.5">{tier.label}</span>
|
||||
</button>
|
||||
))}
|
||||
<button
|
||||
onClick={() => setIsCustom(true)}
|
||||
className={`rounded-xl p-4 text-center transition-all border-2 ${
|
||||
isCustom
|
||||
? 'border-red-500 bg-red-50 shadow-md'
|
||||
: 'border-gray-100 hover:border-gray-200 hover:bg-gray-50'
|
||||
}`}
|
||||
>
|
||||
<span className="text-2xl block mb-1">{"\u2764\uFE0F"}</span>
|
||||
<span className="text-lg font-bold text-gray-900">Frei</span>
|
||||
<span className="text-xs text-gray-500 block mt-0.5">Eigener Betrag</span>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Slider */}
|
||||
<div className="mb-6">
|
||||
<div className="flex justify-between items-center mb-2">
|
||||
<span className="text-sm text-gray-500">Oder wähle einen eigenen Betrag:</span>
|
||||
<span className="text-xl font-bold text-red-600">CHF {amount}</span>
|
||||
{/* Custom amount input */}
|
||||
{isCustom && (
|
||||
<div className="mb-8">
|
||||
<label className="block text-sm font-medium text-gray-700 mb-2">Eigener Betrag in CHF</label>
|
||||
<div className="relative">
|
||||
<span className="absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 font-medium">CHF</span>
|
||||
<input
|
||||
type="number"
|
||||
min="1"
|
||||
max="1000"
|
||||
step="1"
|
||||
value={customAmount}
|
||||
onChange={e => {
|
||||
setCustomAmount(e.target.value)
|
||||
const val = parseInt(e.target.value)
|
||||
if (val > 0) setAmount(val)
|
||||
}}
|
||||
placeholder="Betrag eingeben..."
|
||||
className="w-full rounded-lg border border-gray-300 pl-14 pr-4 py-3 text-lg font-bold focus:outline-none focus:ring-2 focus:ring-red-500 focus:border-transparent"
|
||||
autoFocus
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<input
|
||||
type="range"
|
||||
min="5"
|
||||
max="200"
|
||||
step="5"
|
||||
value={amount}
|
||||
onChange={e => setAmount(parseInt(e.target.value))}
|
||||
className="w-full h-2 bg-gray-200 rounded-lg appearance-none cursor-pointer accent-red-600"
|
||||
/>
|
||||
<div className="flex justify-between text-xs text-gray-400 mt-1">
|
||||
<span>CHF 5</span>
|
||||
<span>CHF 200</span>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Current tier description */}
|
||||
<div className="bg-gray-50 rounded-xl p-4 mb-6 text-center">
|
||||
<span className="text-3xl">{activeTier.emoji}</span>
|
||||
<p className="text-sm text-gray-600 mt-2">{activeTier.desc}</p>
|
||||
</div>
|
||||
{!isCustom && (
|
||||
<div className="bg-gray-50 rounded-xl p-4 mb-6 text-center">
|
||||
<span className="text-3xl">{activeTier.emoji}</span>
|
||||
<p className="text-sm text-gray-600 mt-2">{activeTier.desc}</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Optional name & message */}
|
||||
<div className="space-y-4 mb-6">
|
||||
@@ -203,14 +222,32 @@ export default function SpendenPage() {
|
||||
</Button>
|
||||
)}
|
||||
|
||||
<div className="mt-4 flex flex-wrap items-center justify-center gap-4 text-xs text-gray-400">
|
||||
<div className="mt-4 flex flex-wrap items-center justify-center gap-3 text-xs text-gray-400">
|
||||
<span className="flex items-center gap-1"><Shield className="w-3.5 h-3.5" /> Sichere Zahlung via Stripe</span>
|
||||
<span className="flex items-center gap-1"><Check className="w-3.5 h-3.5" /> Kreditkarte & Twint</span>
|
||||
<span className="flex items-center gap-1"><Check className="w-3.5 h-3.5" /> Kreditkarte</span>
|
||||
<span className="flex items-center gap-1"><Check className="w-3.5 h-3.5" /> Twint</span>
|
||||
<span className="flex items-center gap-1"><Check className="w-3.5 h-3.5" /> Apple Pay</span>
|
||||
<span className="flex items-center gap-1"><Check className="w-3.5 h-3.5" /> Google Pay</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Story */}
|
||||
<div className="mt-10 bg-gray-50 rounded-2xl p-6 md:p-8 border border-gray-100">
|
||||
<h3 className="font-bold text-gray-900 mb-3">Die Geschichte hinter Lageplan</h3>
|
||||
<p className="text-sm text-gray-600 leading-relaxed">
|
||||
Lageplan wird seit über 2 Jahren von einem aktiven Feuerwehrmann in seiner Freizeit entwickelt.
|
||||
Die App ist und bleibt <strong>kostenlos</strong> — weil jede Feuerwehr Zugang zu guten Werkzeugen haben soll,
|
||||
unabhängig vom Budget. Es gibt zwar kommerzielle Alternativen, aber die Idee war immer:
|
||||
Ein Werkzeug <em>von der Feuerwehr, für die Feuerwehr</em>.
|
||||
</p>
|
||||
<p className="text-sm text-gray-600 leading-relaxed mt-3">
|
||||
Mit deiner Spende hilfst du, dass das so bleibt. Jeder Franken fliesst direkt in
|
||||
Serverkosten und Weiterentwicklung. Danke für deine Unterstützung!
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Trust */}
|
||||
<div className="mt-10 text-center">
|
||||
<div className="mt-8 text-center">
|
||||
<p className="text-sm text-gray-500">
|
||||
100% deiner Spende fliesst direkt in Serverkosten und Weiterentwicklung.
|
||||
<br />Kein Unternehmen, keine Investoren — nur ein Feuerwehrmann mit einer Idee.
|
||||
|
||||
@@ -948,10 +948,6 @@ export function JournalView({ projectId, projectTitle, projectLocation, einsatzl
|
||||
</div>
|
||||
</div>
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<div>
|
||||
<label className="text-xs font-semibold text-gray-500 uppercase">Koordinaten</label>
|
||||
<Input value={rapportForm.koordinaten || ''} onChange={e => setRapportForm(f => ({ ...f, koordinaten: e.target.value }))} />
|
||||
</div>
|
||||
<div>
|
||||
<label className="text-xs font-semibold text-gray-500 uppercase">Alarmierungsart</label>
|
||||
<Input value={rapportForm.alarmierungsart || ''} onChange={e => setRapportForm(f => ({ ...f, alarmierungsart: e.target.value }))} />
|
||||
@@ -964,22 +960,15 @@ export function JournalView({ projectId, projectTitle, projectLocation, einsatzl
|
||||
{/* Zeitverlauf */}
|
||||
<div>
|
||||
<label className="text-xs font-semibold text-gray-500 uppercase mb-1 block">Zeitverlauf</label>
|
||||
<div className="grid grid-cols-4 gap-2">
|
||||
{[
|
||||
['zeitAlarm', 'Alarm'],
|
||||
['zeitAusruecken', 'Ausrücken'],
|
||||
['zeitEintreffen', 'Eintreffen'],
|
||||
['zeitBereit', 'Bereit'],
|
||||
['zeitKontrolle', 'F. u. Kontrolle'],
|
||||
['zeitAus', 'F. aus'],
|
||||
['zeitEinruecken', 'Einrücken'],
|
||||
['zeitEnde', 'Ende'],
|
||||
].map(([key, label]) => (
|
||||
<div key={key}>
|
||||
<label className="text-[10px] text-gray-400">{label}</label>
|
||||
<Input className="text-sm h-8" value={rapportForm[key] || ''} onChange={e => setRapportForm(f => ({ ...f, [key]: e.target.value }))} placeholder="HH:MM" />
|
||||
</div>
|
||||
))}
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<div>
|
||||
<label className="text-[10px] text-gray-400">Alarm</label>
|
||||
<Input type="time" className="text-sm h-8" value={rapportForm.zeitAlarm || ''} onChange={e => setRapportForm(f => ({ ...f, zeitAlarm: e.target.value }))} />
|
||||
</div>
|
||||
<div>
|
||||
<label className="text-[10px] text-gray-400">Eintreffen</label>
|
||||
<Input type="time" className="text-sm h-8" value={rapportForm.zeitEintreffen || ''} onChange={e => setRapportForm(f => ({ ...f, zeitEintreffen: e.target.value }))} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{/* Lagebild */}
|
||||
@@ -1030,8 +1019,8 @@ export function JournalView({ projectId, projectTitle, projectLocation, einsatzl
|
||||
if (mapRef?.current) {
|
||||
const canvas = mapRef.current.getCanvas()
|
||||
if (canvas) {
|
||||
// Resize to max 1600px wide and convert to JPEG
|
||||
const maxW = 1600
|
||||
// Resize to max 2400px wide and convert to JPEG
|
||||
const maxW = 2400
|
||||
const ratio = Math.min(1, maxW / canvas.width)
|
||||
const offscreen = document.createElement('canvas')
|
||||
offscreen.width = Math.round(canvas.width * ratio)
|
||||
@@ -1039,18 +1028,18 @@ export function JournalView({ projectId, projectTitle, projectLocation, einsatzl
|
||||
const ctx = offscreen.getContext('2d')
|
||||
if (ctx) {
|
||||
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) }
|
||||
} else if (rawScreenshot.length > 500000) {
|
||||
} else if (rawScreenshot.length > 800000) {
|
||||
// Compress pre-captured screenshot if too large
|
||||
try {
|
||||
const img = new Image()
|
||||
img.src = rawScreenshot
|
||||
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 offscreen = document.createElement('canvas')
|
||||
offscreen.width = Math.round(img.naturalWidth * ratio)
|
||||
@@ -1058,7 +1047,7 @@ export function JournalView({ projectId, projectTitle, projectLocation, einsatzl
|
||||
const ctx = offscreen.getContext('2d')
|
||||
if (ctx) {
|
||||
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 }
|
||||
} else {
|
||||
|
||||
@@ -48,18 +48,18 @@ const colors = [
|
||||
{ value: '#ffffff', name: 'Weiss' },
|
||||
]
|
||||
|
||||
const drawTools: { mode: DrawMode; icon: typeof MousePointer2; label: string }[] = [
|
||||
{ mode: 'select', icon: MousePointer2, label: 'Auswählen' },
|
||||
{ mode: 'point', icon: CircleDot, label: 'Punkt' },
|
||||
{ mode: 'linestring', icon: Minus, label: 'Linie' },
|
||||
{ mode: 'polygon', icon: Pentagon, label: 'Polygon' },
|
||||
{ mode: 'rectangle', icon: Square, label: 'Rechteck' },
|
||||
{ mode: 'circle', icon: Circle, label: 'Kreis' },
|
||||
{ mode: 'freehand', icon: Pencil, label: 'Freihand' },
|
||||
{ mode: 'arrow', icon: MoveRight, label: 'Pfeil / Route' },
|
||||
{ mode: 'text', icon: Type, label: 'Text' },
|
||||
{ mode: 'eraser', icon: Eraser, label: 'Radiergummi' },
|
||||
{ mode: 'measure', icon: Ruler, label: 'Messen' },
|
||||
const drawTools: { mode: DrawMode; icon: typeof MousePointer2; label: string; shortcut: string }[] = [
|
||||
{ mode: 'select', icon: MousePointer2, label: 'Auswählen', shortcut: 'V' },
|
||||
{ mode: 'point', icon: CircleDot, label: 'Punkt', shortcut: 'P' },
|
||||
{ mode: 'linestring', icon: Minus, label: 'Linie', shortcut: 'L' },
|
||||
{ mode: 'polygon', icon: Pentagon, label: 'Polygon', shortcut: 'G' },
|
||||
{ mode: 'rectangle', icon: Square, label: 'Rechteck', shortcut: 'R' },
|
||||
{ mode: 'circle', icon: Circle, label: 'Kreis', shortcut: 'C' },
|
||||
{ mode: 'freehand', icon: Pencil, label: 'Freihand', shortcut: 'F' },
|
||||
{ mode: 'arrow', icon: MoveRight, label: 'Pfeil / Route', shortcut: 'A' },
|
||||
{ mode: 'text', icon: Type, label: 'Text', shortcut: 'T' },
|
||||
{ mode: 'eraser', icon: Eraser, label: 'Radiergummi', shortcut: 'E' },
|
||||
{ mode: 'measure', icon: Ruler, label: 'Messen', shortcut: 'M' },
|
||||
]
|
||||
|
||||
export function LeftToolbar({
|
||||
@@ -92,7 +92,7 @@ export function LeftToolbar({
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent side="right">
|
||||
<p>{tool.label}</p>
|
||||
<p>{tool.label} <kbd className="ml-1.5 text-[10px] px-1 py-0.5 bg-muted rounded border border-border font-mono">{tool.shortcut}</kbd></p>
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
))}
|
||||
|
||||
@@ -39,6 +39,7 @@ import {
|
||||
Shield,
|
||||
Building2,
|
||||
MapPin,
|
||||
HelpCircle,
|
||||
} from 'lucide-react'
|
||||
import { HoseSettingsDialog } from '@/components/dialogs/hose-settings-dialog'
|
||||
import type { Project, DrawFeature } from '@/app/app/page'
|
||||
@@ -65,6 +66,7 @@ interface TopbarProps {
|
||||
userName?: string
|
||||
userRole?: string
|
||||
onLogout?: () => void
|
||||
onStartTour?: () => void
|
||||
}
|
||||
|
||||
export function Topbar({
|
||||
@@ -87,10 +89,15 @@ export function Topbar({
|
||||
userName,
|
||||
userRole,
|
||||
onLogout,
|
||||
onStartTour,
|
||||
}: TopbarProps) {
|
||||
const [isLoadDialogOpen, setIsLoadDialogOpen] = useState(false)
|
||||
const [isHoseSettingsOpen, setIsHoseSettingsOpen] = 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 [pwNew, setPwNew] = useState('')
|
||||
const [pwConfirm, setPwConfirm] = useState('')
|
||||
@@ -155,6 +162,7 @@ export function Topbar({
|
||||
|
||||
<div className="flex items-center gap-1 md:gap-2">
|
||||
<Button
|
||||
data-tour="save"
|
||||
variant="outline"
|
||||
className="h-9 md:h-10 px-2 md:px-4 text-sm"
|
||||
onClick={onSaveProject}
|
||||
@@ -173,7 +181,7 @@ export function Topbar({
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="start" className="w-52">
|
||||
<DropdownMenuItem onClick={onNewProject} className="py-2.5 px-3">
|
||||
<DropdownMenuItem data-tour="new-project" onClick={onNewProject} className="py-2.5 px-3">
|
||||
<Plus className="w-4 h-4 mr-2" />
|
||||
Neuer Einsatz
|
||||
</DropdownMenuItem>
|
||||
@@ -290,6 +298,19 @@ export function Topbar({
|
||||
Administration
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
{onStartTour && (
|
||||
<DropdownMenuItem onClick={onStartTour}>
|
||||
<HelpCircle className="w-4 h-4 mr-2" />
|
||||
Tour starten
|
||||
</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">
|
||||
<LogOut className="w-4 h-4 mr-2" />
|
||||
Abmelden
|
||||
@@ -403,6 +424,9 @@ export function Topbar({
|
||||
</p>
|
||||
)}
|
||||
<p className="text-xs text-muted-foreground mt-1">
|
||||
{(p as any).owner?.name && (
|
||||
<><span className="font-medium text-foreground/70">{(p as any).owner.name}</span> · </>
|
||||
)}
|
||||
Erstellt: {formatDateTime(p.createdAt)} | Geändert: {formatDateTime(p.updatedAt)}
|
||||
</p>
|
||||
</button>
|
||||
@@ -539,6 +563,81 @@ export function Topbar({
|
||||
</div>
|
||||
</DialogContent>
|
||||
</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>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -23,6 +23,19 @@ function formatDistance(meters: number): string {
|
||||
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)
|
||||
function pointToSegmentDist(px: number, py: number, x1: number, y1: number, x2: number, y2: number): number {
|
||||
const dx = x2 - x1, dy = y2 - y1
|
||||
@@ -93,7 +106,8 @@ export function MapView({
|
||||
const measureMarkersRef = useRef<maplibregl.Marker[]>([])
|
||||
const measureCoordsRef = useRef<number[][]>([])
|
||||
const [isMapLoaded, setIsMapLoaded] = useState(false)
|
||||
const [isSatellite, setIsSatellite] = useState(false)
|
||||
const [activeBaseLayer, setActiveBaseLayer] = useState<'osm' | 'satellite' | 'swisstopo'>('osm')
|
||||
const [layerDropdownOpen, setLayerDropdownOpen] = useState(false)
|
||||
const [measurePointCount, setMeasurePointCount] = useState(0)
|
||||
const [measureFinished, setMeasureFinished] = useState(false)
|
||||
const [drawingPointCount, setDrawingPointCount] = useState(0)
|
||||
@@ -676,6 +690,15 @@ export function MapView({
|
||||
attribution: '© Esri, Maxar, Earthstar Geographics',
|
||||
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: 17,
|
||||
},
|
||||
},
|
||||
layers: [
|
||||
{
|
||||
@@ -689,6 +712,12 @@ export function MapView({
|
||||
source: 'satellite',
|
||||
layout: { visibility: 'none' },
|
||||
},
|
||||
{
|
||||
id: 'swisstopo',
|
||||
type: 'raster',
|
||||
source: 'swisstopo',
|
||||
layout: { visibility: 'none' },
|
||||
},
|
||||
],
|
||||
},
|
||||
center: [initialCenter.lng, initialCenter.lat],
|
||||
@@ -940,7 +969,7 @@ export function MapView({
|
||||
// Eraser mode: click on/near a feature to delete it
|
||||
if (mode === 'eraser') {
|
||||
const pixel = e.point
|
||||
const tolerance = 10 // px
|
||||
const tolerance = 20 // px
|
||||
const currentFeatures = featuresRef.current
|
||||
let closestIdx = -1
|
||||
let closestDist = Infinity
|
||||
@@ -949,29 +978,44 @@ export function MapView({
|
||||
const f = currentFeatures[i]
|
||||
const geom = f.geometry
|
||||
|
||||
// Get all coordinates to check proximity
|
||||
let allCoords: number[][] = []
|
||||
if (geom.type === 'Point') {
|
||||
allCoords = [geom.coordinates as 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 projected = m.project(geom.coordinates as [number, number])
|
||||
const dx = projected.x - pixel.x
|
||||
const dy = projected.y - pixel.y
|
||||
const dist = Math.sqrt(dx * dx + dy * dy)
|
||||
if (dist < closestDist) {
|
||||
closestDist = dist
|
||||
closestIdx = i
|
||||
if (dist < closestDist) { closestDist = dist; closestIdx = i }
|
||||
} else if (geom.type === 'LineString') {
|
||||
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 newFeatures = currentFeatures.filter((_, i) => i !== closestIdx)
|
||||
onFeaturesChangeRef.current(newFeatures)
|
||||
@@ -1377,12 +1421,12 @@ export function MapView({
|
||||
const lineCoords = f.geometry.coordinates as number[][]
|
||||
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 p2 = lineCoords[lineCoords.length - 1]
|
||||
const angle = Math.atan2(p2[1] - p1[1], p2[0] - p1[0]) * (180 / Math.PI)
|
||||
// MapLibre uses screen coords where Y is inverted, so negate the angle
|
||||
const screenAngle = -angle + 90
|
||||
const px1 = map.current.project(p1 as [number, number])
|
||||
const px2 = map.current.project(p2 as [number, number])
|
||||
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 arrowEl = document.createElement('div')
|
||||
@@ -1396,7 +1440,7 @@ export function MapView({
|
||||
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])
|
||||
.addTo(map.current)
|
||||
markersRef.current.push(marker)
|
||||
@@ -1468,7 +1512,21 @@ export function MapView({
|
||||
el.appendChild(labelLine)
|
||||
el.appendChild(infoLine)
|
||||
} 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
|
||||
@@ -1481,7 +1539,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)
|
||||
.addTo(map.current)
|
||||
markersRef.current.push(marker)
|
||||
@@ -1568,7 +1626,7 @@ export function MapView({
|
||||
}
|
||||
|
||||
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)
|
||||
.addTo(map.current)
|
||||
|
||||
@@ -1634,7 +1692,7 @@ export function MapView({
|
||||
el.textContent = (f.properties.text as string) || ''
|
||||
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)
|
||||
.addTo(map.current)
|
||||
|
||||
@@ -2034,11 +2092,12 @@ export function MapView({
|
||||
selectedSymbolRef.current.scale = Math.max(0.2, Math.min(10, startScale * ratio))
|
||||
selectedSymbolRef.current.innerEl.style.fontSize = `${baseFontSize * selectedSymbolRef.current.scale}px`
|
||||
} else {
|
||||
// For symbols: resize wrapper
|
||||
// For symbols: resize wrapper, use ratio from start to preserve zoom-aware scale
|
||||
selectedSymbolRef.current.wrapperEl.style.width = `${width}px`
|
||||
selectedSymbolRef.current.wrapperEl.style.height = `${height}px`
|
||||
const baseSize = 32
|
||||
selectedSymbolRef.current.scale = Math.max(0.1, Math.min(10, width / baseSize))
|
||||
const startW = selectedSymbolRef.current.resizeStartWidth || 1
|
||||
const startScale = selectedSymbolRef.current.resizeStartScale || 1
|
||||
selectedSymbolRef.current.scale = Math.max(0.1, Math.min(10, startScale * (width / startW)))
|
||||
}
|
||||
}
|
||||
}}
|
||||
@@ -2082,29 +2141,52 @@ export function MapView({
|
||||
</>
|
||||
)}
|
||||
|
||||
{/* Layer toggle: OSM / Satellite */}
|
||||
<button
|
||||
onClick={() => {
|
||||
if (!map.current) return
|
||||
const newSat = !isSatellite
|
||||
setIsSatellite(newSat)
|
||||
map.current.setLayoutProperty('osm', 'visibility', newSat ? 'none' : 'visible')
|
||||
map.current.setLayoutProperty('satellite', 'visibility', newSat ? 'visible' : 'none')
|
||||
}}
|
||||
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={{
|
||||
background: isSatellite ? 'rgba(0,0,0,0.7)' : 'rgba(255,255,255,0.95)',
|
||||
color: isSatellite ? '#fff' : '#333',
|
||||
borderColor: isSatellite ? 'rgba(255,255,255,0.3)' : 'rgba(0,0,0,0.15)',
|
||||
}}
|
||||
title={isSatellite ? 'Zur Kartenansicht wechseln' : 'Zur Satellitenansicht wechseln'}
|
||||
>
|
||||
{isSatellite ? (
|
||||
<><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</>
|
||||
{/* Layer selector dropdown */}
|
||||
<div className="absolute top-3 right-3 z-10">
|
||||
<button
|
||||
onClick={() => setLayerDropdownOpen(v => !v)}
|
||||
className="flex items-center gap-1.5 px-2.5 py-1.5 rounded-lg text-[11px] font-medium shadow-md border backdrop-blur-sm transition-all"
|
||||
style={{
|
||||
background: activeBaseLayer !== 'osm' ? 'rgba(0,0,0,0.7)' : 'rgba(255,255,255,0.92)',
|
||||
color: activeBaseLayer !== 'osm' ? '#fff' : '#1f2937',
|
||||
borderColor: activeBaseLayer !== 'osm' ? 'rgba(255,255,255,0.2)' : 'rgba(0,0,0,0.1)',
|
||||
}}
|
||||
>
|
||||
<svg className="w-3.5 h-3.5 opacity-70" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M12 2L2 7l10 5 10-5-10-5z"/><path d="M2 17l10 5 10-5"/><path d="M2 12l10 5 10-5"/></svg>
|
||||
{{ osm: 'OpenStreetMap', satellite: 'Satellit', swisstopo: 'Swisstopo' }[activeBaseLayer]}
|
||||
<svg className={`w-3 h-3 opacity-50 transition-transform ${layerDropdownOpen ? 'rotate-180' : ''}`} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M6 9l6 6 6-6"/></svg>
|
||||
</button>
|
||||
{layerDropdownOpen && (
|
||||
<>
|
||||
<div className="fixed inset-0 z-10" onClick={() => setLayerDropdownOpen(false)} />
|
||||
<div className="absolute right-0 mt-1 z-20 min-w-[160px] rounded-lg shadow-xl border overflow-hidden backdrop-blur-md"
|
||||
style={{ background: 'rgba(255,255,255,0.95)', borderColor: 'rgba(0,0,0,0.08)' }}>
|
||||
{([
|
||||
{ key: 'osm', label: 'OpenStreetMap' },
|
||||
{ key: 'satellite', label: 'Satellit (Esri)' },
|
||||
{ key: 'swisstopo', label: 'Swisstopo Karte' },
|
||||
] as const).map(({ key, label }) => (
|
||||
<button
|
||||
key={key}
|
||||
onClick={() => {
|
||||
if (!map.current) return
|
||||
const allLayers: Array<'osm' | 'satellite' | 'swisstopo'> = ['osm', 'satellite', 'swisstopo']
|
||||
for (const l of allLayers) {
|
||||
map.current.setLayoutProperty(l, 'visibility', l === key ? 'visible' : 'none')
|
||||
}
|
||||
setActiveBaseLayer(key)
|
||||
setLayerDropdownOpen(false)
|
||||
}}
|
||||
className={`w-full text-left px-3 py-2 text-[11px] font-medium transition-colors ${activeBaseLayer === key ? 'bg-blue-50 text-blue-700' : 'text-gray-700 hover:bg-gray-50'}`}
|
||||
>
|
||||
{activeBaseLayer === key && <span className="inline-block w-1.5 h-1.5 rounded-full bg-blue-500 mr-2 align-middle" />}
|
||||
{label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Zeichnung abschliessen Button (Linie/Polygon/Pfeil) */}
|
||||
{(drawMode === 'linestring' || drawMode === 'polygon' || drawMode === 'arrow' || drawMode === 'dangerzone') && drawingPointCount >= 2 && (
|
||||
|
||||
270
src/components/onboarding/onboarding-tour.tsx
Normal file
270
src/components/onboarding/onboarding-tour.tsx
Normal file
@@ -0,0 +1,270 @@
|
||||
'use client'
|
||||
|
||||
import { useState, useEffect, useCallback } from 'react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import {
|
||||
X, ChevronRight, ChevronLeft, SkipForward,
|
||||
MapPin, Pencil, LayoutGrid, Save, Ruler, Users, Keyboard, Rocket,
|
||||
} from 'lucide-react'
|
||||
|
||||
const TOUR_STORAGE_KEY = 'lageplan-onboarding-completed'
|
||||
|
||||
interface TourStep {
|
||||
title: string
|
||||
description: string
|
||||
icon?: React.ReactNode
|
||||
targetSelector?: string
|
||||
position?: 'top' | 'bottom' | 'left' | 'right'
|
||||
}
|
||||
|
||||
const TOUR_STEPS: TourStep[] = [
|
||||
{
|
||||
title: 'Willkommen bei Lageplan!',
|
||||
icon: <Rocket className="w-5 h-5 text-red-500" />,
|
||||
description: 'Lageplan ist deine taktische Lageskizzen-App für den Feuerwehr-Einsatz. Diese kurze Tour zeigt dir die wichtigsten Funktionen. Du kannst sie jederzeit überspringen oder später im Benutzermenü erneut starten.',
|
||||
},
|
||||
{
|
||||
title: 'Einsatz erstellen',
|
||||
icon: <MapPin className="w-5 h-5 text-red-500" />,
|
||||
description: 'Erstelle über «Neuer Einsatz» ein neues Projekt. Gib eine Adresse ein — die Karte fliegt automatisch dorthin. Jeder Einsatz wird separat gespeichert und kann als PDF oder PNG exportiert werden.',
|
||||
targetSelector: '[data-tour="new-project"]',
|
||||
position: 'bottom',
|
||||
},
|
||||
{
|
||||
title: 'Zeichenwerkzeuge',
|
||||
icon: <Pencil className="w-5 h-5 text-blue-500" />,
|
||||
description: 'Die Werkzeugleiste links enthält alle Zeichentools: Punkte, Linien, Polygone, Freihand, Pfeile, Text, Radiergummi und mehr. Jedes Tool hat ein Tastenkürzel — drücke «?» für eine Übersicht.',
|
||||
targetSelector: '[data-tour="toolbar"]',
|
||||
position: 'right',
|
||||
},
|
||||
{
|
||||
title: 'Symbole & Sidebar',
|
||||
icon: <LayoutGrid className="w-5 h-5 text-orange-500" />,
|
||||
description: 'Rechts findest du über 100 taktische Feuerwehr-Symbole, sortiert nach Kategorien (Wasser, Feuer, Fahrzeuge usw.). Ziehe sie per Drag & Drop auf die Karte. Wechsle zwischen Symbolen und dem Einsatz-Journal.',
|
||||
targetSelector: '[data-tour="sidebar"]',
|
||||
position: 'left',
|
||||
},
|
||||
{
|
||||
title: 'Speichern & Export',
|
||||
icon: <Save className="w-5 h-5 text-green-500" />,
|
||||
description: 'Speichere deinen Einsatz mit Ctrl+S oder dem Speichern-Button. Exportiere als PNG (Bild) oder als druckfertiges PDF. Die letzte Kartenansicht wird automatisch gespeichert.',
|
||||
targetSelector: '[data-tour="save"]',
|
||||
position: 'bottom',
|
||||
},
|
||||
{
|
||||
title: 'Messen & Schlauch-Rechner',
|
||||
icon: <Ruler className="w-5 h-5 text-purple-500" />,
|
||||
description: 'Mit dem Messwerkzeug (Taste «M») misst du Distanzen direkt auf der Karte. Der Schlauch-Rechner im Admin-Bereich berechnet die benötigten Schlauchlängen und -typen für deinen Einsatz.',
|
||||
},
|
||||
{
|
||||
title: 'Live-Zusammenarbeit',
|
||||
icon: <Users className="w-5 h-5 text-cyan-500" />,
|
||||
description: 'Mehrere Benutzer können gleichzeitig am selben Einsatz arbeiten. Änderungen werden in Echtzeit synchronisiert — ideal für die Einsatzleitung mit mehreren Operateuren.',
|
||||
},
|
||||
{
|
||||
title: 'Tastenkürzel (CH)',
|
||||
icon: <Keyboard className="w-5 h-5 text-slate-500" />,
|
||||
description: 'Optimiert für Schweizer Tastaturen: Ctrl+Y = Rückgängig, Ctrl+Z = Wiederholen, Del = Löschen, Ctrl+S = Speichern. Drücke «?» oder F1 für die komplette Übersicht aller Kürzel.',
|
||||
},
|
||||
{
|
||||
title: 'Bereit für den Einsatz!',
|
||||
icon: <Rocket className="w-5 h-5 text-red-500" />,
|
||||
description: 'Du bist startklar! Diese Tour kannst du jederzeit über dein Benutzermenü (oben rechts → «Tour starten») erneut aufrufen. Viel Erfolg im Einsatz — Feuer frei!',
|
||||
},
|
||||
]
|
||||
|
||||
interface OnboardingTourProps {
|
||||
forceShow?: boolean
|
||||
onComplete?: () => void
|
||||
}
|
||||
|
||||
export function OnboardingTour({ forceShow = false, onComplete }: OnboardingTourProps) {
|
||||
const [isVisible, setIsVisible] = useState(false)
|
||||
const [currentStep, setCurrentStep] = useState(0)
|
||||
const [highlightRect, setHighlightRect] = useState<DOMRect | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
if (forceShow) {
|
||||
setIsVisible(true)
|
||||
setCurrentStep(0)
|
||||
return
|
||||
}
|
||||
const completed = localStorage.getItem(TOUR_STORAGE_KEY)
|
||||
if (!completed) {
|
||||
// Small delay so the app renders first
|
||||
const timer = setTimeout(() => setIsVisible(true), 1500)
|
||||
return () => clearTimeout(timer)
|
||||
}
|
||||
}, [forceShow])
|
||||
|
||||
const updateHighlight = useCallback(() => {
|
||||
const step = TOUR_STEPS[currentStep]
|
||||
if (step.targetSelector) {
|
||||
const el = document.querySelector(step.targetSelector)
|
||||
if (el) {
|
||||
setHighlightRect(el.getBoundingClientRect())
|
||||
return
|
||||
}
|
||||
}
|
||||
setHighlightRect(null)
|
||||
}, [currentStep])
|
||||
|
||||
useEffect(() => {
|
||||
if (!isVisible) return
|
||||
updateHighlight()
|
||||
window.addEventListener('resize', updateHighlight)
|
||||
return () => window.removeEventListener('resize', updateHighlight)
|
||||
}, [isVisible, currentStep, updateHighlight])
|
||||
|
||||
const completeTour = useCallback(() => {
|
||||
localStorage.setItem(TOUR_STORAGE_KEY, 'true')
|
||||
setIsVisible(false)
|
||||
onComplete?.()
|
||||
}, [onComplete])
|
||||
|
||||
const nextStep = () => {
|
||||
if (currentStep < TOUR_STEPS.length - 1) {
|
||||
setCurrentStep(currentStep + 1)
|
||||
} else {
|
||||
completeTour()
|
||||
}
|
||||
}
|
||||
|
||||
const prevStep = () => {
|
||||
if (currentStep > 0) setCurrentStep(currentStep - 1)
|
||||
}
|
||||
|
||||
if (!isVisible) return null
|
||||
|
||||
const step = TOUR_STEPS[currentStep]
|
||||
const isFirst = currentStep === 0
|
||||
const isLast = currentStep === TOUR_STEPS.length - 1
|
||||
|
||||
// Calculate tooltip position based on highlight
|
||||
const getTooltipStyle = (): React.CSSProperties => {
|
||||
if (!highlightRect) {
|
||||
// Center on screen
|
||||
return {
|
||||
position: 'fixed',
|
||||
top: '50%',
|
||||
left: '50%',
|
||||
transform: 'translate(-50%, -50%)',
|
||||
}
|
||||
}
|
||||
const pos = step.position || 'bottom'
|
||||
const gap = 12
|
||||
switch (pos) {
|
||||
case 'bottom':
|
||||
return {
|
||||
position: 'fixed',
|
||||
top: highlightRect.bottom + gap,
|
||||
left: Math.max(16, Math.min(highlightRect.left, window.innerWidth - 360)),
|
||||
}
|
||||
case 'top':
|
||||
return {
|
||||
position: 'fixed',
|
||||
bottom: window.innerHeight - highlightRect.top + gap,
|
||||
left: Math.max(16, Math.min(highlightRect.left, window.innerWidth - 360)),
|
||||
}
|
||||
case 'right':
|
||||
return {
|
||||
position: 'fixed',
|
||||
top: Math.max(16, highlightRect.top),
|
||||
left: highlightRect.right + gap,
|
||||
}
|
||||
case 'left':
|
||||
return {
|
||||
position: 'fixed',
|
||||
top: Math.max(16, highlightRect.top),
|
||||
right: window.innerWidth - highlightRect.left + gap,
|
||||
}
|
||||
default:
|
||||
return { position: 'fixed', top: '50%', left: '50%', transform: 'translate(-50%, -50%)' }
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
{/* Backdrop overlay */}
|
||||
<div
|
||||
className="fixed inset-0 z-[99998]"
|
||||
style={{ background: 'rgba(0,0,0,0.5)' }}
|
||||
onClick={completeTour}
|
||||
/>
|
||||
|
||||
{/* Highlight cutout */}
|
||||
{highlightRect && (
|
||||
<div
|
||||
className="fixed z-[99999] pointer-events-none rounded-lg"
|
||||
style={{
|
||||
top: highlightRect.top - 4,
|
||||
left: highlightRect.left - 4,
|
||||
width: highlightRect.width + 8,
|
||||
height: highlightRect.height + 8,
|
||||
boxShadow: '0 0 0 9999px rgba(0,0,0,0.5)',
|
||||
border: '2px solid rgba(59,130,246,0.7)',
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* Tooltip card */}
|
||||
<div
|
||||
className="z-[100000] w-[340px] bg-card border border-border rounded-xl shadow-2xl p-5"
|
||||
style={getTooltipStyle()}
|
||||
>
|
||||
<div className="flex items-start justify-between mb-2">
|
||||
<div className="flex items-center gap-2">
|
||||
{step.icon}
|
||||
<h3 className="font-semibold text-base">{step.title}</h3>
|
||||
</div>
|
||||
<button
|
||||
onClick={completeTour}
|
||||
className="text-muted-foreground hover:text-foreground -mt-1 -mr-1 p-1"
|
||||
>
|
||||
<X className="w-4 h-4" />
|
||||
</button>
|
||||
</div>
|
||||
<p className="text-sm text-muted-foreground leading-relaxed mb-4">
|
||||
{step.description}
|
||||
</p>
|
||||
|
||||
{/* Progress dots */}
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex gap-1">
|
||||
{TOUR_STEPS.map((_, i) => (
|
||||
<div
|
||||
key={i}
|
||||
className={`w-1.5 h-1.5 rounded-full transition-colors ${
|
||||
i === currentStep ? 'bg-primary' : i < currentStep ? 'bg-primary/40' : 'bg-muted-foreground/20'
|
||||
}`}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-1.5">
|
||||
{!isFirst && (
|
||||
<Button variant="ghost" size="sm" className="h-8 px-2" onClick={prevStep}>
|
||||
<ChevronLeft className="w-4 h-4" />
|
||||
</Button>
|
||||
)}
|
||||
{isFirst && (
|
||||
<Button variant="ghost" size="sm" className="h-8 text-xs text-muted-foreground" onClick={completeTour}>
|
||||
<SkipForward className="w-3 h-3 mr-1" />
|
||||
Überspringen
|
||||
</Button>
|
||||
)}
|
||||
<Button size="sm" className="h-8 px-3" onClick={nextStep}>
|
||||
{isLast ? 'Fertig' : 'Weiter'}
|
||||
{!isLast && <ChevronRight className="w-4 h-4 ml-0.5" />}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
/** Reset the onboarding tour so it shows again next time */
|
||||
export function resetOnboardingTour() {
|
||||
localStorage.removeItem(TOUR_STORAGE_KEY)
|
||||
}
|
||||
@@ -9,6 +9,7 @@ export interface User {
|
||||
role: 'SERVER_ADMIN' | 'TENANT_ADMIN' | 'OPERATOR' | 'VIEWER'
|
||||
tenantId?: string
|
||||
tenantSlug?: string
|
||||
emailVerified?: boolean
|
||||
}
|
||||
|
||||
export interface TenantInfo {
|
||||
@@ -28,7 +29,7 @@ interface AuthContextType {
|
||||
user: User | null
|
||||
tenant: TenantInfo | null
|
||||
loading: boolean
|
||||
login: (email: string, password: string) => Promise<{ success: boolean; error?: string }>
|
||||
login: (email: string, password: string, rememberMe?: boolean) => Promise<{ success: boolean; error?: string }>
|
||||
logout: () => Promise<void>
|
||||
canEdit: () => boolean
|
||||
isAdmin: () => boolean
|
||||
@@ -61,12 +62,12 @@ export function AuthProvider({ children }: { children: ReactNode }) {
|
||||
}
|
||||
}
|
||||
|
||||
const login = async (email: string, password: string) => {
|
||||
const login = async (email: string, password: string, rememberMe = false) => {
|
||||
try {
|
||||
const res = await fetch('/api/auth/login', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ email, password }),
|
||||
body: JSON.stringify({ email, password, rememberMe }),
|
||||
})
|
||||
|
||||
const data = await res.json()
|
||||
|
||||
@@ -18,13 +18,14 @@ export interface UserPayload {
|
||||
role: 'SERVER_ADMIN' | 'TENANT_ADMIN' | 'OPERATOR' | 'VIEWER'
|
||||
tenantId?: string
|
||||
tenantSlug?: string
|
||||
emailVerified?: boolean
|
||||
}
|
||||
|
||||
export async function createToken(user: UserPayload): Promise<string> {
|
||||
export async function createToken(user: UserPayload, rememberMe = false): Promise<string> {
|
||||
return await new SignJWT({ user })
|
||||
.setProtectedHeader({ alg: 'HS256' })
|
||||
.setIssuedAt()
|
||||
.setExpirationTime('24h')
|
||||
.setExpirationTime(rememberMe ? '30d' : '24h')
|
||||
.sign(JWT_SECRET)
|
||||
}
|
||||
|
||||
@@ -63,18 +64,16 @@ export async function login(
|
||||
}) as any)
|
||||
|
||||
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)
|
||||
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)
|
||||
if ((user as any).emailVerified === false && (user.role as string) !== 'SERVER_ADMIN') {
|
||||
return { success: false, error: 'Bitte bestätigen Sie zuerst Ihre E-Mail-Adresse. Prüfen Sie Ihren Posteingang.' }
|
||||
}
|
||||
// Track email verification status (allow login regardless)
|
||||
const emailVerified = (user as any).emailVerified !== false
|
||||
|
||||
// Get first tenant membership for non-server-admins
|
||||
let tenantId: string | undefined
|
||||
@@ -102,6 +101,7 @@ export async function login(
|
||||
role: (user.role === 'ADMIN' ? 'SERVER_ADMIN' : user.role) as UserPayload['role'],
|
||||
tenantId,
|
||||
tenantSlug,
|
||||
emailVerified,
|
||||
}
|
||||
|
||||
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)
|
||||
const styles = StyleSheet.create({
|
||||
page: {
|
||||
padding: '12mm 15mm 15mm',
|
||||
padding: '12mm 15mm 32mm',
|
||||
fontFamily: 'Helvetica',
|
||||
fontSize: 10,
|
||||
lineHeight: 1.4,
|
||||
@@ -166,8 +166,7 @@ export function RapportDocument({ data }: { data: RapportData }) {
|
||||
</View>
|
||||
<View style={styles.fieldRow}>
|
||||
<FieldCell label="Einsatzort / Adresse" value={data.einsatzort} width="50%" />
|
||||
<FieldCell label="Koordinaten" value={data.koordinaten} mono width="25%" />
|
||||
<FieldCell label="Objekt / Gebäude" value={data.objekt} width="25%" />
|
||||
<FieldCell label="Objekt / Gebäude" value={data.objekt} width="50%" />
|
||||
</View>
|
||||
<View style={styles.fieldRow}>
|
||||
<FieldCell label="Alarmierungsart" value={data.alarmierungsart} width="50%" />
|
||||
@@ -185,16 +184,8 @@ export function RapportDocument({ data }: { data: RapportData }) {
|
||||
</View>
|
||||
<View style={styles.fieldGrid}>
|
||||
<View style={styles.fieldRow}>
|
||||
<FieldCell label="Alarmierung" value={data.zeitAlarm} mono highlight width="25%" />
|
||||
<FieldCell label="Ausrücken" value={data.zeitAusruecken} mono highlight width="25%" />
|
||||
<FieldCell label="Eintreffen" value={data.zeitEintreffen} mono highlight width="25%" />
|
||||
<FieldCell label="Einsatzbereit" value={data.zeitBereit} mono highlight width="25%" />
|
||||
</View>
|
||||
<View style={styles.fieldRow}>
|
||||
<FieldCell label="Feuer unter Kontrolle" value={data.zeitKontrolle} mono highlight width="25%" />
|
||||
<FieldCell label="Feuer aus" value={data.zeitAus} mono highlight width="25%" />
|
||||
<FieldCell label="Einrücken" value={data.zeitEinruecken} mono highlight width="25%" />
|
||||
<FieldCell label="Einsatzende" value={data.zeitEnde} mono highlight width="25%" />
|
||||
<FieldCell label="Alarmierung" value={data.zeitAlarm} mono highlight width="50%" />
|
||||
<FieldCell label="Eintreffen" value={data.zeitEintreffen} mono highlight width="50%" />
|
||||
</View>
|
||||
</View>
|
||||
</View>
|
||||
|
||||
111
src/lib/rate-limit.ts
Normal file
111
src/lib/rate-limit.ts
Normal file
@@ -0,0 +1,111 @@
|
||||
// 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: 10, windowSeconds: 60 * 5 }) // 10 attempts per 5 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)
|
||||
const minutes = Math.ceil(retryAfter / 60)
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
error: `Zu viele Versuche. Bitte warten Sie ${minutes > 1 ? `${minutes} Minuten` : `${retryAfter} Sekunden`} und versuchen es erneut.`,
|
||||
retryAfter,
|
||||
}),
|
||||
{
|
||||
status: 429,
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Retry-After': String(retryAfter),
|
||||
},
|
||||
}
|
||||
)
|
||||
}
|
||||
@@ -3,23 +3,50 @@
|
||||
import { io, Socket } from 'socket.io-client'
|
||||
|
||||
let socket: Socket | null = null
|
||||
let currentRoom: string | null = null
|
||||
|
||||
export function getSocket(): Socket {
|
||||
if (!socket) {
|
||||
socket = io({
|
||||
path: '/socket.io',
|
||||
transports: ['polling', 'websocket'],
|
||||
transports: ['websocket', 'polling'],
|
||||
upgrade: true,
|
||||
reconnectionAttempts: 10,
|
||||
reconnectionDelay: 2000,
|
||||
reconnection: true,
|
||||
reconnectionAttempts: Infinity,
|
||||
reconnectionDelay: 1000,
|
||||
reconnectionDelayMax: 5000,
|
||||
timeout: 10000,
|
||||
forceNew: false,
|
||||
})
|
||||
socket.on('connect', () => {
|
||||
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) => {
|
||||
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
|
||||
}
|
||||
|
||||
/** 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