Initial commit

This commit is contained in:
Benjamin Sutter
2026-05-15 00:48:18 +02:00
commit 9e827c50f9
72 changed files with 10477 additions and 0 deletions
+43
View File
@@ -0,0 +1,43 @@
import { Container, Typography, Button, Card, CardContent, Chip } from '@mui/material'
import HomeIcon from '@mui/icons-material/Home'
import SearchIcon from '@mui/icons-material/Search'
export default function Home() {
return (
<Container maxWidth="lg" className="py-12">
<div className="mb-8 text-center">
<Typography variant="h3" component="h1" className="font-bold text-gray-800">
Property Match
</Typography>
<Typography variant="subtitle1" className="mt-2 text-gray-500">
Find your ideal property
</Typography>
</div>
<div className="flex items-center gap-4 mb-10 max-w-2xl mx-auto">
<Button variant="contained" size="large" startIcon={<SearchIcon />}>
Search
</Button>
<Button variant="outlined" size="large" startIcon={<HomeIcon />}>
Browse
</Button>
</div>
<div className="grid grid-cols-1 md:grid-cols-3 gap-6">
{(['Buy', 'Rent', 'Invest'] as const).map((category) => (
<Card key={category} elevation={2} className="hover:shadow-lg transition-shadow duration-200">
<CardContent className="p-6">
<Chip label={category} color="primary" size="small" className="mb-3" />
<Typography variant="h6" className="font-semibold mb-2">
{category} a Property
</Typography>
<Typography variant="body2" className="text-gray-500">
Browse listings available for {category.toLowerCase()} in your area.
</Typography>
</CardContent>
</Card>
))}
</div>
</Container>
)
}
+338
View File
@@ -0,0 +1,338 @@
import { useState } from 'react'
import {
Box,
Button,
Card,
Chip,
TextField,
Typography,
CircularProgress,
Alert,
Stack,
Divider,
} from '@mui/material'
import { Sparkles, ArrowRight } from 'lucide-react'
import { useNavigate } from 'react-router'
import { MockupAIServiceProvider, type CriteriaExtractionResult } from '../../services/aiService'
type Step = 'input' | 'extracting' | 'review' | 'done'
const EXAMPLE_QUERIES = [
'Büro Zürich 500-800m²',
'Logistik Basel 2000m²',
'Retail Bern Innenstadt',
]
function ConfidenceColor(score: number): string {
if (score >= 0.8) return '#1a7a4a'
if (score >= 0.6) return '#d97706'
return '#c0392b'
}
export default function AISearch() {
const navigate = useNavigate()
const [step, setStep] = useState<Step>('input')
const [inputText, setInputText] = useState('')
const [extractedCriteria, setExtractedCriteria] = useState<CriteriaExtractionResult | null>(null)
const [followUpAnswers, setFollowUpAnswers] = useState<Record<number, string>>({})
const handleAnalyze = async () => {
setStep('extracting')
await new Promise(r => setTimeout(r, 1500))
const result = await MockupAIServiceProvider.extractCriteria(inputText)
setExtractedCriteria(result)
setStep('review')
}
const handleStartSearch = () => {
navigate('/demand/results', { state: { needId: 'need-001' } })
}
return (
<Box>
{/* Page Header */}
<Box sx={{ bgcolor: 'white', borderBottom: '1px solid #e2e8f0', px: 3, py: 2 }}>
<Typography variant="h5" fontWeight={700} color="text.primary">
AI Bedarfsanalyse
</Typography>
<Typography variant="body2" color="text.secondary">
Beschreiben Sie Ihren Flächenbedarf in natürlicher Sprache
</Typography>
</Box>
<Box sx={{ px: 3, py: 3 }}>
{/* Step 1: Input */}
{step === 'input' && (
<Box>
<Card sx={{ maxWidth: 680, mx: 'auto', p: 3 }}>
<Typography variant="subtitle1" fontWeight={600} mb={2}>
Flächenbedarf beschreiben
</Typography>
<TextField
multiline
rows={5}
fullWidth
placeholder="Beispiel: Wir suchen 8001.000 m² Bürofläche in Zürich-West, verfügbar ab September 2025, Budget max. 45 CHF/m². Wichtig: gute ÖV-Anbindung, moderne Infrastruktur."
value={inputText}
onChange={e => setInputText(e.target.value)}
inputProps={{ maxLength: 2000 }}
sx={{ mb: 1 }}
/>
<Typography variant="caption" color="text.secondary" display="block" textAlign="right" mb={2}>
{inputText.length}/2000
</Typography>
<Button
variant="contained"
fullWidth
disabled={inputText.length < 20}
onClick={handleAnalyze}
endIcon={<Sparkles size={16} />}
sx={{ bgcolor: '#1e3a5f', '&:hover': { bgcolor: '#162d4a' }, mb: 2 }}
>
Analysieren
</Button>
<Typography variant="caption" color="text.secondary" display="block" textAlign="center">
Die KI extrahiert automatisch Kriterien, Standortpräferenzen und Budget aus Ihrer Beschreibung.
</Typography>
</Card>
{/* Example Queries */}
<Box sx={{ maxWidth: 680, mx: 'auto', mt: 2 }}>
<Typography variant="caption" color="text.secondary" display="block" mb={1}>
Beispiele:
</Typography>
<Stack direction="row" spacing={1} flexWrap="wrap" gap={1}>
{EXAMPLE_QUERIES.map(q => (
<Chip
key={q}
label={q}
size="small"
variant="outlined"
clickable
onClick={() => setInputText(q)}
sx={{ cursor: 'pointer' }}
/>
))}
</Stack>
</Box>
</Box>
)}
{/* Step 2: Extracting */}
{step === 'extracting' && (
<Box sx={{ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', py: 12, gap: 3 }}>
<CircularProgress size={48} sx={{ color: '#1e3a5f' }} />
<Typography variant="h6" color="text.secondary">
KI analysiert Ihren Bedarf...
</Typography>
</Box>
)}
{/* Step 3: Review */}
{step === 'review' && extractedCriteria && (
<Box>
<Box className="grid grid-cols-2 gap-4" sx={{ mb: 3 }}>
{/* Left: Extracted Criteria */}
<Card sx={{ p: 3 }}>
<Typography variant="subtitle1" fontWeight={600} mb={2}>
Extrahierte Kriterien
</Typography>
<Stack spacing={2}>
{/* Confidence badge */}
<Box sx={{ display: 'flex', alignItems: 'center', gap: 1, mb: 1 }}>
<Typography variant="caption" color="text.secondary">Gesamtkonfidenz:</Typography>
<Chip
label={`${Math.round(extractedCriteria.confidence * 100)}%`}
size="small"
sx={{
bgcolor: ConfidenceColor(extractedCriteria.confidence),
color: 'white',
fontWeight: 700,
}}
/>
</Box>
<Divider />
{/* Criteria items */}
{extractedCriteria.extractedCriteria.requiredArea && (
<Box>
<Typography
variant="caption"
fontWeight={600}
sx={{ color: ConfidenceColor(extractedCriteria.confidence) }}
>
Flächenbedarf
</Typography>
<Typography variant="body2">
{extractedCriteria.extractedCriteria.requiredArea.min}
{extractedCriteria.extractedCriteria.requiredArea.max} m²
</Typography>
</Box>
)}
{extractedCriteria.extractedCriteria.budgetRange && (
<Box>
<Typography
variant="caption"
fontWeight={600}
sx={{ color: ConfidenceColor(extractedCriteria.confidence) }}
>
Budget
</Typography>
<Typography variant="body2">
max. {extractedCriteria.extractedCriteria.budgetRange.maxPerSqm}{' '}
{extractedCriteria.extractedCriteria.budgetRange.currency}/m²
</Typography>
</Box>
)}
{extractedCriteria.extractedCriteria.companyName && (
<Box>
<Typography
variant="caption"
fontWeight={600}
sx={{ color: ConfidenceColor(0.5) }}
>
Unternehmen
</Typography>
<Typography variant="body2">
{extractedCriteria.extractedCriteria.companyName}
</Typography>
</Box>
)}
{extractedCriteria.extractedCriteria.preferredLocations && extractedCriteria.extractedCriteria.preferredLocations.length > 0 && (
<Box>
<Typography
variant="caption"
fontWeight={600}
sx={{ color: ConfidenceColor(0.85) }}
>
Standort
</Typography>
<Typography variant="body2">
{extractedCriteria.extractedCriteria.preferredLocations.join(', ')}
</Typography>
</Box>
)}
{extractedCriteria.extractedCriteria.timing && (
<Box>
<Typography
variant="caption"
fontWeight={600}
sx={{ color: ConfidenceColor(0.85) }}
>
Verfügbarkeit
</Typography>
<Typography variant="body2">
ab {extractedCriteria.extractedCriteria.timing.earliestMoveIn}
</Typography>
</Box>
)}
{extractedCriteria.extractedCriteria.assetType && (
<Box>
<Typography
variant="caption"
fontWeight={600}
sx={{ color: ConfidenceColor(0.85) }}
>
Objekttyp
</Typography>
<Typography variant="body2">
{extractedCriteria.extractedCriteria.assetType}
</Typography>
</Box>
)}
</Stack>
{/* Assumptions */}
{extractedCriteria.assumptions.length > 0 && (
<Box mt={3}>
<Typography variant="caption" fontWeight={600} color="text.secondary" display="block" mb={1}>
Annahmen der KI
</Typography>
<Stack spacing={0.5}>
{extractedCriteria.assumptions.map((a, i) => (
<Alert key={i} severity="warning" sx={{ py: 0, px: 1, '& .MuiAlert-message': { fontSize: 12 } }}>
{a}
</Alert>
))}
</Stack>
</Box>
)}
{/* Missing Fields */}
{extractedCriteria.missingFields.length > 0 && (
<Box mt={2}>
<Typography variant="caption" fontWeight={600} color="text.secondary" display="block" mb={1}>
Fehlende Informationen
</Typography>
<Stack direction="row" spacing={0.5} flexWrap="wrap" gap={0.5}>
{extractedCriteria.missingFields.map(f => (
<Chip
key={f}
label={f}
size="small"
color="warning"
variant="outlined"
/>
))}
</Stack>
</Box>
)}
</Card>
{/* Right: Follow-up Questions */}
<Card sx={{ p: 3 }}>
<Typography variant="subtitle1" fontWeight={600} mb={0.5}>
Rückfragen der KI
</Typography>
<Typography variant="caption" color="text.secondary" display="block" mb={2}>
Diese Fragen sind optional verbessern jedoch die Trefferqualität.
</Typography>
<Stack spacing={3}>
{extractedCriteria.followUpQuestions.map((q, i) => (
<Box key={i}>
<Typography variant="body2" fontWeight={500} mb={1}>
{i + 1}. {q}
</Typography>
<TextField
size="small"
fullWidth
placeholder="Ihre Antwort (optional)"
value={followUpAnswers[i] ?? ''}
onChange={e =>
setFollowUpAnswers(prev => ({ ...prev, [i]: e.target.value }))
}
/>
</Box>
))}
</Stack>
</Card>
</Box>
{/* Footer Actions */}
<Box sx={{ display: 'flex', justifyContent: 'flex-end', gap: 2 }}>
<Button variant="outlined" onClick={() => setStep('input')}>
Zurück
</Button>
<Button
variant="contained"
onClick={handleStartSearch}
endIcon={<ArrowRight size={16} />}
sx={{ bgcolor: '#1e3a5f', '&:hover': { bgcolor: '#162d4a' } }}
>
Suche starten
</Button>
</Box>
</Box>
)}
</Box>
</Box>
)
}
+320
View File
@@ -0,0 +1,320 @@
import {
Box,
Button,
Card,
Chip,
Typography,
LinearProgress,
Table,
TableBody,
TableCell,
TableHead,
TableRow,
CircularProgress,
Stack,
} from '@mui/material'
import { X } from 'lucide-react'
import { useQuery } from '@tanstack/react-query'
import { useNavigate } from 'react-router'
import { propertyService } from '../../services/propertyService'
import { useCompareStore } from '../../stores/compareStore'
import { EmptyState } from '../../components/ui'
import { ResultType, RiskLevel } from '../../domain/enums'
import type { Property } from '../../domain/property'
function getResultTypeLabel(type: ResultType): string {
switch (type) {
case ResultType.VERIFIED_PORTFOLIO: return 'Verified Portfolio'
case ResultType.EXTERNAL_MARKET: return 'Marktinserat'
case ResultType.FUTURE_AVAILABILITY: return 'Zukunftssignal'
}
}
function getResultTypeColor(type: ResultType): string {
switch (type) {
case ResultType.VERIFIED_PORTFOLIO: return '#1e3a5f'
case ResultType.EXTERNAL_MARKET: return '#d97706'
case ResultType.FUTURE_AVAILABILITY: return '#7c3aed'
}
}
function getRiskColor(risk?: RiskLevel): 'success' | 'warning' | 'error' | 'default' {
if (!risk) return 'default'
if (risk === RiskLevel.LOW) return 'success'
if (risk === RiskLevel.MEDIUM) return 'warning'
return 'error'
}
function getRiskLabel(risk?: RiskLevel): string {
if (!risk) return ''
switch (risk) {
case RiskLevel.LOW: return 'Niedrig'
case RiskLevel.MEDIUM: return 'Mittel'
case RiskLevel.HIGH: return 'Hoch'
case RiskLevel.CRITICAL: return 'Kritisch'
}
}
interface CompareRow {
label: string
getValue: (p: Property) => string | number | null
format?: (v: string | number | null, p: Property) => React.ReactNode
isHigherBetter?: boolean
isLowerBetter?: boolean
}
function NumericCell({ value, isBest }: { value: React.ReactNode; isBest: boolean }) {
return (
<TableCell
sx={{
bgcolor: isBest ? '#f0fdf4' : 'transparent',
fontWeight: isBest ? 700 : 400,
color: isBest ? '#1a7a4a' : 'inherit',
borderLeft: '1px solid #f1f5f9',
}}
>
{value}
</TableCell>
)
}
export default function Compare() {
const navigate = useNavigate()
const { compareTray, removeFromCompare, clearCompare } = useCompareStore()
const { data: propResp, isLoading } = useQuery({
queryKey: ['properties'],
queryFn: () => propertyService.getAll(),
})
const properties = propResp?.data ?? []
const compareProperties = properties.filter(p => compareTray.includes(p.id))
// Keep ordering same as tray
const orderedProperties = compareTray
.map(id => compareProperties.find(p => p.id === id))
.filter((p): p is Property => p !== null)
if (isLoading) {
return (
<Box sx={{ display: 'flex', justifyContent: 'center', alignItems: 'center', py: 12 }}>
<CircularProgress />
</Box>
)
}
if (compareTray.length === 0) {
return (
<Box>
<Box sx={{ bgcolor: 'white', borderBottom: '1px solid #e2e8f0', px: 3, py: 2 }}>
<Typography variant="h5" fontWeight={700}>Vergleich</Typography>
</Box>
<Box sx={{ px: 3, py: 3 }}>
<EmptyState
title="Keine Objekte zum Vergleich"
description="Fügen Sie Objekte aus den Suchergebnissen zum Vergleich hinzu."
action={{ label: 'Zur Suche', onClick: () => navigate('/demand/results') }}
/>
</Box>
</Box>
)
}
const rows: CompareRow[] = [
{
label: 'Fläche (m²)',
getValue: p => p.areaSqm,
isHigherBetter: false,
},
{
label: 'Miete/m² (CHF)',
getValue: p => p.rentPricePerSqm,
isLowerBetter: true,
},
{
label: 'Gesamtmiete/Monat (CHF)',
getValue: p => p.totalRentMonthly ?? null,
format: (v) => v != null ? `${Number(v).toLocaleString('de-CH')} CHF` : <em style={{ color: '#94a3b8' }}></em>,
isLowerBetter: true,
},
{
label: 'Verfügbarkeit',
getValue: p => p.availabilityDate,
format: (v) => v ?? <em style={{ color: '#94a3b8' }}></em>,
},
{
label: 'Standort',
getValue: p => `${p.location.city}${p.location.district ? ', ' + p.location.district : ''}`,
},
{
label: 'Datenqualität',
getValue: p => p.dataQuality.score,
format: (v, p) => (
<Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
<Box sx={{ width: 80 }}>
<LinearProgress
variant="determinate"
value={p.dataQuality.score * 100}
sx={{ height: 6, borderRadius: 3 }}
color={p.dataQuality.score >= 0.8 ? 'success' : p.dataQuality.score >= 0.6 ? 'warning' : 'error'}
/>
</Box>
<Typography variant="caption">{Math.round(p.dataQuality.score * 100)}%</Typography>
</Box>
),
isHigherBetter: true,
},
{
label: 'Konfidenz',
getValue: p => p.confidenceScore,
format: (v) => v != null ? `${Math.round(Number(v) * 100)}%` : <em style={{ color: '#94a3b8' }}></em>,
isHigherBetter: true,
},
{
label: 'Risiko',
getValue: p => p.riskLevel ?? null,
format: (v, p) => (
<Chip
label={getRiskLabel(p.riskLevel)}
size="small"
color={getRiskColor(p.riskLevel)}
variant="outlined"
/>
),
},
{
label: 'Prestige',
getValue: p => p.softFactors?.prestige ?? null,
format: (v) => v != null ? String(v) : <em style={{ color: '#94a3b8' }}></em>,
isHigherBetter: true,
},
{
label: 'Erreichbarkeit',
getValue: p => p.softFactors?.accessibility ?? null,
format: (v) => v != null ? String(v) : <em style={{ color: '#94a3b8' }}></em>,
isHigherBetter: true,
},
{
label: 'ÖV-Minuten',
getValue: p => p.softFactors?.publicTransportMinutes ?? null,
format: (v) => v != null ? `${v} Min.` : <em style={{ color: '#94a3b8' }}></em>,
isLowerBetter: true,
},
{
label: 'Fehlende Pflichtfelder',
getValue: p => p.dataQuality.missingCriticalFields.length,
format: (v) => v != null ? String(v) : <em style={{ color: '#94a3b8' }}></em>,
isLowerBetter: true,
},
]
return (
<Box>
{/* Page Header */}
<Box sx={{ bgcolor: 'white', borderBottom: '1px solid #e2e8f0', px: 3, py: 2, display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
<Box sx={{ display: 'flex', alignItems: 'center', gap: 2 }}>
<Typography variant="h5" fontWeight={700}>Vergleich</Typography>
<Chip label={`${orderedProperties.length} Objekte`} size="small" />
</Box>
<Button variant="outlined" size="small" color="error" onClick={clearCompare}>
Leeren
</Button>
</Box>
<Box sx={{ px: 3, py: 3 }}>
<Card sx={{ overflowX: 'auto' }}>
<Table>
<TableHead>
<TableRow sx={{ bgcolor: '#f8fafc' }}>
<TableCell sx={{ width: 180, fontWeight: 600, color: '#64748b', fontSize: 12 }}>
Kriterium
</TableCell>
{orderedProperties.map(p => (
<TableCell key={p.id} sx={{ borderLeft: '1px solid #f1f5f9', minWidth: 220 }}>
<Box sx={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 1 }}>
<Box>
<Typography variant="body2" fontWeight={600}>{p.title}</Typography>
<Chip
label={getResultTypeLabel(p.resultType)}
size="small"
sx={{
bgcolor: getResultTypeColor(p.resultType),
color: 'white',
fontSize: 10,
mt: 0.5,
}}
/>
</Box>
<Button
size="small"
sx={{ minWidth: 'auto', p: 0.5 }}
onClick={() => removeFromCompare(p.id)}
>
<X size={14} />
</Button>
</Box>
</TableCell>
))}
</TableRow>
</TableHead>
<TableBody>
{rows.map(row => {
const values = orderedProperties.map(p => row.getValue(p))
const numericValues = values
.map((v, i) => ({ v, i }))
.filter(x => x.v != null && typeof x.v === 'number') as { v: number; i: number }[]
let bestIdx = -1
if (numericValues.length > 1) {
if (row.isHigherBetter) {
bestIdx = numericValues.reduce((best, cur) => cur.v > best.v ? cur : best).i
} else if (row.isLowerBetter) {
bestIdx = numericValues.reduce((best, cur) => cur.v < best.v ? cur : best).i
}
}
return (
<TableRow key={row.label} hover>
<TableCell sx={{ color: '#64748b', fontSize: 13, fontWeight: 500 }}>
{row.label}
</TableCell>
{orderedProperties.map((p, idx) => {
const raw = row.getValue(p)
const displayValue = row.format
? row.format(raw, p)
: raw != null
? String(raw)
: <em style={{ color: '#94a3b8' }}></em>
const isBest = bestIdx === idx
return (
<NumericCell key={p.id} value={displayValue} isBest={isBest} />
)
})}
</TableRow>
)
})}
</TableBody>
</Table>
</Card>
{/* Add more prompt */}
{orderedProperties.length < 3 && (
<Card sx={{ p: 2.5, mt: 2, border: '2px dashed #e2e8f0', boxShadow: 'none' }}>
<Stack direction="row" alignItems="center" justifyContent="space-between">
<Box>
<Typography variant="subtitle2" fontWeight={600}>Weiteres Objekt hinzufügen</Typography>
<Typography variant="caption" color="text.secondary">
Bis zu {3 - orderedProperties.length} weitere{orderedProperties.length < 2 ? 's' : ''} Objekt{orderedProperties.length < 2 ? '' : 'e'} möglich
</Typography>
</Box>
<Button variant="outlined" size="small" onClick={() => navigate('/demand/results')}>
Zur Suche
</Button>
</Stack>
</Card>
)}
</Box>
</Box>
)
}
+476
View File
@@ -0,0 +1,476 @@
import { useState } from 'react'
import {
Box,
Button,
Card,
Chip,
Typography,
LinearProgress,
Stack,
Alert,
CircularProgress,
Divider,
} from '@mui/material'
import {
MapPin,
Maximize2,
Banknote,
Calendar,
Bookmark,
Columns2,
} from 'lucide-react'
import { useQuery } from '@tanstack/react-query'
import { useNavigate, useLocation } from 'react-router'
import { propertyService } from '../../services/propertyService'
import { matchService } from '../../services/matchService'
import { needService } from '../../services/needService'
import { ResultType, MatchStrength, RiskLevel } from '../../domain/enums'
import type { Property } from '../../domain/property'
import type { Match } from '../../domain/match'
import { useCompareStore } from '../../stores/compareStore'
import { EmptyState } from '../../components/ui'
type FilterSource = ResultType | 'ALL'
type SortBy = 'score' | 'rent' | 'area'
function getResultTypeLabel(type: ResultType): string {
switch (type) {
case ResultType.VERIFIED_PORTFOLIO: return 'Verified Portfolio'
case ResultType.EXTERNAL_MARKET: return 'Marktinserat'
case ResultType.FUTURE_AVAILABILITY: return 'Zukunftssignal'
}
}
function getResultTypeColor(type: ResultType): string {
switch (type) {
case ResultType.VERIFIED_PORTFOLIO: return '#1e3a5f'
case ResultType.EXTERNAL_MARKET: return '#d97706'
case ResultType.FUTURE_AVAILABILITY: return '#7c3aed'
}
}
function getMatchStrengthColor(strength: MatchStrength): string {
switch (strength) {
case MatchStrength.STRONG: return '#1a7a4a'
case MatchStrength.MODERATE: return '#d97706'
case MatchStrength.WEAK: return '#c0392b'
}
}
function getRiskChipColor(risk: RiskLevel): 'success' | 'warning' | 'error' {
if (risk === RiskLevel.LOW) return 'success'
if (risk === RiskLevel.MEDIUM) return 'warning'
return 'error'
}
function getRiskLabel(risk: RiskLevel): string {
switch (risk) {
case RiskLevel.LOW: return 'Niedriges Risiko'
case RiskLevel.MEDIUM: return 'Mittleres Risiko'
case RiskLevel.HIGH: return 'Hohes Risiko'
case RiskLevel.CRITICAL: return 'Kritisches Risiko'
}
}
interface ResultCardProps {
property: Property
match: Match
onCompare: (id: string) => void
isInCompare: boolean
}
function ResultCard({ property, match, onCompare, isInCompare }: ResultCardProps) {
const scoreColor = getMatchStrengthColor(match.matchStrength)
return (
<Card sx={{ p: 2.5, mb: 1.5 }}>
{/* Future signal warning */}
{property.resultType === ResultType.FUTURE_AVAILABILITY && (
<Alert severity="warning" sx={{ mb: 1.5, py: 0.5 }}>
Probabilistisches Signal kein bestätigtes Objekt
</Alert>
)}
{/* Header row */}
<Box sx={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', mb: 1.5 }}>
<Box sx={{ display: 'flex', alignItems: 'center', gap: 1.5 }}>
<Chip
label={getResultTypeLabel(property.resultType)}
size="small"
sx={{
bgcolor: getResultTypeColor(property.resultType),
color: 'white',
fontWeight: 600,
fontSize: 11,
}}
/>
<Typography variant="h6" fontWeight={600}>
{property.title}
</Typography>
</Box>
<Box sx={{ display: 'flex', alignItems: 'baseline', gap: 0.5 }}>
<Typography variant="h4" fontWeight={800} sx={{ color: scoreColor }}>
{match.matchScore}
</Typography>
<Typography variant="body2" color="text.secondary">/100</Typography>
</Box>
</Box>
{/* Property details row */}
<Stack direction="row" spacing={2.5} sx={{ mb: 1.5 }} flexWrap="wrap">
<Box sx={{ display: 'flex', alignItems: 'center', gap: 0.5 }}>
<MapPin size={14} color="#64748b" />
<Typography variant="body2" color="text.secondary">
{property.location.city}
{property.location.district ? `, ${property.location.district}` : ''}
</Typography>
</Box>
<Box sx={{ display: 'flex', alignItems: 'center', gap: 0.5 }}>
<Maximize2 size={14} color="#64748b" />
<Typography variant="body2" color="text.secondary">
{property.areaSqm} m²
</Typography>
</Box>
<Box sx={{ display: 'flex', alignItems: 'center', gap: 0.5 }}>
<Banknote size={14} color="#64748b" />
<Typography variant="body2" color="text.secondary">
CHF {property.rentPricePerSqm}/m²
</Typography>
</Box>
<Box sx={{ display: 'flex', alignItems: 'center', gap: 0.5 }}>
<Calendar size={14} color="#64748b" />
<Typography variant="body2" color="text.secondary">
{property.availabilityDate}
</Typography>
</Box>
</Stack>
{/* Match factors section */}
<Divider sx={{ mb: 1.5 }} />
{match.positiveFactors.length > 0 && (
<Box sx={{ mb: 1 }}>
<Typography variant="caption" fontWeight={600} color="text.secondary" display="block" mb={0.5}>
Positive Faktoren
</Typography>
<Stack direction="row" spacing={0.5} flexWrap="wrap" gap={0.5}>
{match.positiveFactors.slice(0, 3).map((f, i) => (
<Chip
key={i}
label={f.criterion}
size="small"
sx={{ bgcolor: '#f0fdf4', color: '#1a7a4a', border: '1px solid #bbf7d0', fontSize: 11 }}
/>
))}
</Stack>
</Box>
)}
{match.tradeoffs.length > 0 && (
<Alert severity="warning" sx={{ py: 0.5, px: 1.5, mb: 1, '& .MuiAlert-message': { fontSize: 12 } }}>
<Typography variant="caption" fontWeight={600} display="block" mb={0.5}>Abwägungen</Typography>
{match.tradeoffs.slice(0, 2).map((t, i) => (
<Typography key={i} variant="caption" display="block">
{t.criterion}: {t.concern}
</Typography>
))}
</Alert>
)}
{/* Confidence + Quality row */}
<Stack direction="row" spacing={2.5} alignItems="center" sx={{ mb: 1.5 }} flexWrap="wrap">
<Typography variant="caption">
<span style={{ color: '#64748b' }}>Konfidenz </span>
<strong style={{ color: match.confidenceLevel >= 0.8 ? '#1a7a4a' : match.confidenceLevel >= 0.6 ? '#d97706' : '#c0392b' }}>
{Math.round(match.confidenceLevel * 100)}%
</strong>
</Typography>
<Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
<Typography variant="caption" color="text.secondary">Datenqualität</Typography>
<Box sx={{ width: 80 }}>
<LinearProgress
variant="determinate"
value={property.dataQuality.score * 100}
sx={{ height: 6, borderRadius: 3 }}
color={
property.dataQuality.score >= 0.8 ? 'success' :
property.dataQuality.score >= 0.6 ? 'warning' : 'error'
}
/>
</Box>
<Typography variant="caption" color="text.secondary">
{Math.round(property.dataQuality.score * 100)}%
</Typography>
</Box>
{property.riskLevel && (
<Chip
label={getRiskLabel(property.riskLevel)}
size="small"
color={getRiskChipColor(property.riskLevel)}
variant="outlined"
/>
)}
</Stack>
{/* Actions row */}
<Box sx={{ display: 'flex', justifyContent: 'flex-end', gap: 1 }}>
<Button
variant="outlined"
size="small"
startIcon={<Bookmark size={14} />}
disabled
>
Shortlist
</Button>
<Button
variant={isInCompare ? 'contained' : 'outlined'}
size="small"
startIcon={<Columns2 size={14} />}
onClick={() => onCompare(property.id)}
sx={isInCompare ? { bgcolor: '#1e3a5f' } : {}}
>
Vergleichen
</Button>
<Button
variant="contained"
size="small"
disabled
sx={{ bgcolor: '#1e3a5f', '&:hover': { bgcolor: '#162d4a' } }}
>
Details
</Button>
</Box>
</Card>
)
}
export default function Results() {
const navigate = useNavigate()
const location = useLocation()
const _needId = (location.state as { needId?: string } | null)?.needId ?? 'need-001'
const [filterSource, setFilterSource] = useState<FilterSource>('ALL')
const [sortBy, setSortBy] = useState<SortBy>('score')
const { data: propResp, isLoading: propLoading } = useQuery({
queryKey: ['properties'],
queryFn: () => propertyService.getAll(),
})
const { data: matchResp, isLoading: matchLoading } = useQuery({
queryKey: ['matches'],
queryFn: () => matchService.getAll(),
})
const { data: needResp, isLoading: needLoading } = useQuery({
queryKey: ['needs'],
queryFn: () => needService.getAll(),
})
const { addToCompare, removeFromCompare, clearCompare, isInCompare, compareTray } = useCompareStore()
const properties = propResp?.data ?? []
const matches = matchResp?.data ?? []
const needs = needResp?.data ?? []
const activeNeed = needs[0]
const isLoading = propLoading || matchLoading || needLoading
// Join matches with properties
const resultItems = matches
.map(match => {
const property = properties.find(p => p.id === match.propertyId)
return property ? { match, property } : null
})
.filter((item): item is { match: Match; property: Property } => item !== null)
// Filter by source
const filtered = filterSource === 'ALL'
? resultItems
: resultItems.filter(item => item.property.resultType === filterSource)
// Sort
const sorted = [...filtered].sort((a, b) => {
if (sortBy === 'score') return b.match.matchScore - a.match.matchScore
if (sortBy === 'rent') return a.property.rentPricePerSqm - b.property.rentPricePerSqm
if (sortBy === 'area') return b.property.areaSqm - a.property.areaSqm
return 0
})
const verifiedCount = resultItems.filter(i => i.property.resultType === ResultType.VERIFIED_PORTFOLIO).length
const externalCount = resultItems.filter(i => i.property.resultType === ResultType.EXTERNAL_MARKET).length
const futureCount = resultItems.filter(i => i.property.resultType === ResultType.FUTURE_AVAILABILITY).length
const handleToggleCompare = (id: string) => {
if (isInCompare(id)) {
removeFromCompare(id)
} else {
addToCompare(id)
}
}
if (isLoading) {
return (
<Box sx={{ display: 'flex', justifyContent: 'center', alignItems: 'center', py: 12 }}>
<CircularProgress />
</Box>
)
}
return (
<Box>
{/* Page Header */}
<Box sx={{ bgcolor: 'white', borderBottom: '1px solid #e2e8f0', px: 3, py: 2, display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
<Box>
<Typography variant="h5" fontWeight={700} color="text.primary">
{sorted.length} Treffer gefunden
</Typography>
<Typography variant="body2" color="text.secondary">
{verifiedCount} Verified · {externalCount} Extern · {futureCount} Signale
</Typography>
</Box>
</Box>
<Box sx={{ px: 3, py: 3 }}>
{/* Active Need Banner */}
{activeNeed && (
<Card sx={{ bgcolor: '#eff6ff', p: 2, mb: 2, border: '1px solid #bfdbfe' }}>
<Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
<Box>
<Typography variant="subtitle2" fontWeight={600} color="#1e3a5f">
Aktive Suche: {activeNeed.companyName}
</Typography>
<Typography variant="caption" color="text.secondary">
{activeNeed.assetType} · {activeNeed.requiredArea.min}{activeNeed.requiredArea.max} m² ·{' '}
{activeNeed.preferredLocations.join(', ')}
</Typography>
</Box>
<Button
size="small"
variant="text"
onClick={() => navigate('/demand/ai-search')}
sx={{ color: '#1e3a5f' }}
>
Suche ändern
</Button>
</Box>
</Card>
)}
{/* Filter/Sort bar */}
<Card sx={{ p: 1.5, mb: 2 }}>
<Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', flexWrap: 'wrap', gap: 1 }}>
<Stack direction="row" spacing={0.5} flexWrap="wrap" gap={0.5}>
{(['ALL', ResultType.VERIFIED_PORTFOLIO, ResultType.EXTERNAL_MARKET, ResultType.FUTURE_AVAILABILITY] as FilterSource[]).map(source => {
const labels: Record<FilterSource, string> = {
ALL: 'Alle',
[ResultType.VERIFIED_PORTFOLIO]: 'Verified Portfolio',
[ResultType.EXTERNAL_MARKET]: 'Marktinserate',
[ResultType.FUTURE_AVAILABILITY]: 'Zukunftssignale',
}
const colors: Partial<Record<FilterSource, string>> = {
[ResultType.VERIFIED_PORTFOLIO]: '#1e3a5f',
[ResultType.EXTERNAL_MARKET]: '#d97706',
[ResultType.FUTURE_AVAILABILITY]: '#7c3aed',
}
const isActive = filterSource === source
return (
<Chip
key={source}
label={labels[source]}
size="small"
clickable
onClick={() => setFilterSource(source)}
sx={{
bgcolor: isActive ? (colors[source] ?? '#1e3a5f') : 'transparent',
color: isActive ? 'white' : 'text.secondary',
border: `1px solid ${isActive ? (colors[source] ?? '#1e3a5f') : '#e2e8f0'}`,
fontWeight: isActive ? 600 : 400,
}}
/>
)
})}
</Stack>
<Stack direction="row" spacing={0.5} alignItems="center">
<Typography variant="caption" color="text.secondary">Sortierung:</Typography>
{([['score', 'Relevanz'], ['area', 'Fläche'], ['rent', 'Mietpreis']] as [SortBy, string][]).map(([val, label]) => (
<Chip
key={val}
label={label}
size="small"
clickable
onClick={() => setSortBy(val)}
sx={{
bgcolor: sortBy === val ? '#1e3a5f' : 'transparent',
color: sortBy === val ? 'white' : 'text.secondary',
border: `1px solid ${sortBy === val ? '#1e3a5f' : '#e2e8f0'}`,
}}
/>
))}
</Stack>
</Box>
</Card>
{/* Results */}
{sorted.length === 0 ? (
<EmptyState
title="Keine Treffer gefunden"
description="Passen Sie die Suchkriterien an oder wechseln Sie den Filter."
/>
) : (
sorted.map(({ match, property }) => (
<ResultCard
key={match.id}
property={property}
match={match}
onCompare={handleToggleCompare}
isInCompare={isInCompare(property.id)}
/>
))
)}
</Box>
{/* Compare Tray */}
{compareTray.length > 0 && (
<Box
sx={{
position: 'fixed',
bottom: 0,
left: 0,
right: 0,
bgcolor: '#1e3a5f',
color: 'white',
py: 1.5,
px: 3,
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
zIndex: 1200,
boxShadow: '0 -4px 12px rgba(0,0,0,0.15)',
}}
>
<Typography variant="body2" fontWeight={600}>
{compareTray.length} Objekte zum Vergleich ausgewählt
</Typography>
<Stack direction="row" spacing={1}>
<Button
size="small"
variant="outlined"
sx={{ color: 'white', borderColor: 'rgba(255,255,255,0.5)' }}
onClick={clearCompare}
>
Leeren
</Button>
<Button
size="small"
variant="contained"
sx={{ bgcolor: 'white', color: '#1e3a5f', '&:hover': { bgcolor: '#f1f5f9' } }}
onClick={() => navigate('/demand/compare')}
>
Vergleich starten
</Button>
</Stack>
</Box>
)}
</Box>
)
}
+174
View File
@@ -0,0 +1,174 @@
import {
Box,
Button,
Card,
Chip,
Typography,
Stack,
Divider,
List,
ListItem,
ListItemText,
} from '@mui/material'
import { Bookmark } from 'lucide-react'
interface MockShortlist {
id: string
title: string
company: string
assetType: string
objectCount: number
createdAt: string
updatedAt: string
properties: string[]
}
const MOCK_SHORTLISTS: MockShortlist[] = [
{
id: 'sl-001',
title: 'Bürosuche Innovatech AG',
company: 'Innovatech AG',
assetType: 'Büro',
objectCount: 2,
createdAt: '01.05.2025',
updatedAt: '08.05.2025',
properties: ['Bürofläche Zollstrasse 12', 'Gemischte Gewerbeeinheit Europaallee'],
},
{
id: 'sl-002',
title: 'Logistik Basel — Schweizer Logistik',
company: 'Schweizer Logistik GmbH',
assetType: 'Logistik',
objectCount: 1,
createdAt: '03.05.2025',
updatedAt: '03.05.2025',
properties: ['Lagerfläche Hardstrasse 44'],
},
]
export default function Shortlists() {
return (
<Box>
{/* Page Header */}
<Box
sx={{
bgcolor: 'white',
borderBottom: '1px solid #e2e8f0',
px: 3,
py: 2,
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
}}
>
<Box>
<Typography variant="h5" fontWeight={700} color="text.primary">
Shortlists
</Typography>
<Typography variant="body2" color="text.secondary">
Gespeicherte Objektlisten und Entscheidungsvorlagen
</Typography>
</Box>
<Button
variant="contained"
size="small"
startIcon={<Bookmark size={14} />}
disabled
sx={{ bgcolor: '#1e3a5f' }}
>
Neue Shortlist
</Button>
</Box>
<Box sx={{ px: 3, py: 3 }}>
<Stack spacing={2}>
{MOCK_SHORTLISTS.map(sl => (
<Card key={sl.id} sx={{ p: 2.5 }}>
{/* Card header */}
<Box
sx={{
display: 'flex',
alignItems: 'flex-start',
justifyContent: 'space-between',
mb: 1.5,
}}
>
<Box>
<Typography variant="subtitle1" fontWeight={700}>
{sl.title}
</Typography>
<Typography variant="body2" color="text.secondary">
{sl.company} · {sl.assetType}
</Typography>
</Box>
<Chip
label={`${sl.objectCount} Objekte`}
size="small"
sx={{ bgcolor: '#eff6ff', color: '#1e3a5f', fontWeight: 600 }}
/>
</Box>
{/* Dates */}
<Stack direction="row" spacing={2} sx={{ mb: 1.5 }}>
<Typography variant="caption" color="text.secondary">
Erstellt: {sl.createdAt}
</Typography>
<Typography variant="caption" color="text.secondary">
Zuletzt aktualisiert: {sl.updatedAt}
</Typography>
</Stack>
<Divider sx={{ mb: 1.5 }} />
{/* Property list */}
<List dense disablePadding sx={{ mb: 1.5 }}>
{sl.properties.map((prop, i) => (
<ListItem key={i} disableGutters sx={{ py: 0.25 }}>
<Box
sx={{
width: 6,
height: 6,
borderRadius: '50%',
bgcolor: '#1e3a5f',
mr: 1.5,
flexShrink: 0,
}}
/>
<ListItemText
primary={prop}
primaryTypographyProps={{ variant: 'body2' }}
/>
</ListItem>
))}
</List>
{/* Actions */}
<Box sx={{ display: 'flex', justifyContent: 'flex-end', gap: 1 }}>
<Button variant="outlined" size="small" disabled>
Teilen
</Button>
<Button variant="outlined" size="small" disabled>
Öffnen
</Button>
</Box>
</Card>
))}
{/* Empty shortlist prompt */}
<Card
sx={{
p: 2,
border: '2px dashed #e2e8f0',
boxShadow: 'none',
bgcolor: '#fafafa',
}}
>
<Typography variant="body2" color="text.secondary" textAlign="center">
Objekte aus den Suchergebnissen zur Shortlist hinzufügen
</Typography>
</Card>
</Stack>
</Box>
</Box>
)
}
+280
View File
@@ -0,0 +1,280 @@
import {
Box,
Card,
Chip,
Typography,
LinearProgress,
Stack,
Table,
TableBody,
TableCell,
TableHead,
TableRow,
Alert,
CircularProgress,
} from '@mui/material'
import { useQuery } from '@tanstack/react-query'
import { propertyService } from '../../services/propertyService'
interface MetricCard {
label: string
value: string
color: string
note: string
}
const HEALTH_METRICS: MetricCard[] = [
{ label: 'Extraktionsgenauigkeit', value: '94%', color: '#1a7a4a', note: 'Ø letzte 30 Tage' },
{ label: 'Konfidenz-Ø', value: '73%', color: '#d97706', note: 'Alle Objekte' },
{ label: 'Validierungsrate', value: '88%', color: '#1a7a4a', note: 'Menschliche Bestätigung' },
{ label: 'Fehlerrate', value: '2.1%', color: '#1a7a4a', note: 'Kritische Fehler' },
]
interface AIDecision {
timestamp: string
type: string
confidence: string
result: string
impact: string
}
const RECENT_DECISIONS: AIDecision[] = [
{
timestamp: '15.05.2025 14:32',
type: 'Bedarfsextraktion',
confidence: '91%',
result: 'Kriterien extrahiert',
impact: 'Suche ausgelöst',
},
{
timestamp: '15.05.2025 11:15',
type: 'Match-Scoring',
confidence: '88%',
result: '3 Matches berechnet',
impact: 'Review ausgelöst',
},
{
timestamp: '14.05.2025 16:40',
type: 'Signal-Erkennung',
confidence: '72%',
result: 'Expansion erkannt',
impact: 'Signal erstellt',
},
{
timestamp: '14.05.2025 09:00',
type: 'Datenqualitätsprüfung',
confidence: '95%',
result: '2 Warnungen erkannt',
impact: 'Meldung erstellt',
},
{
timestamp: '13.05.2025 15:22',
type: 'Match-Scoring',
confidence: '84%',
result: '2 Matches berechnet',
impact: 'Review ausgelöst',
},
{
timestamp: '12.05.2025 10:11',
type: 'Signal-Erkennung',
confidence: '65%',
result: 'Möglicher Auszug erkannt',
impact: 'Signal erstellt',
},
]
function getConfidenceBadge(pct: string) {
const n = parseInt(pct)
const color = n >= 85 ? '#1a7a4a' : n >= 70 ? '#d97706' : '#c0392b'
return (
<Chip
label={pct}
size="small"
sx={{ bgcolor: color, color: 'white', fontWeight: 700, fontSize: 11 }}
/>
)
}
export default function AIMonitoring() {
const { data: propResp, isLoading } = useQuery({
queryKey: ['properties'],
queryFn: () => propertyService.getAll(),
})
const properties = propResp?.data ?? []
const highConf = properties.filter(p => p.confidenceScore > 0.85).length
const midConf = properties.filter(p => p.confidenceScore >= 0.65 && p.confidenceScore <= 0.85).length
const lowConf = properties.filter(p => p.confidenceScore < 0.65).length
const total = properties.length || 1
return (
<Box>
{/* Page Header */}
<Box
sx={{
bgcolor: 'white',
borderBottom: '1px solid #e2e8f0',
px: 3,
py: 2,
display: 'flex',
alignItems: 'center',
gap: 2,
}}
>
<Box sx={{ flex: 1 }}>
<Box sx={{ display: 'flex', alignItems: 'center', gap: 1.5 }}>
<Typography variant="h5" fontWeight={700} color="text.primary">
AI Monitoring
</Typography>
<Chip
label="Live"
size="small"
sx={{
bgcolor: '#1a7a4a',
color: 'white',
fontWeight: 700,
fontSize: 11,
animation: 'pulse 2s ease-in-out infinite',
'@keyframes pulse': {
'0%, 100%': { opacity: 1 },
'50%': { opacity: 0.6 },
},
}}
/>
</Box>
<Typography variant="body2" color="text.secondary">
AI-Layer Gesundheit und Entscheidungsqualität
</Typography>
</Box>
</Box>
<Box sx={{ px: 3, py: 3 }}>
{/* Health Metrics */}
<Box className="grid grid-cols-4 gap-4" sx={{ mb: 3 }}>
{HEALTH_METRICS.map(m => (
<Card key={m.label} sx={{ p: 2.5 }}>
<Typography variant="overline" color="text.secondary" lineHeight={1.4} display="block">
{m.label}
</Typography>
<Typography variant="h3" fontWeight={800} sx={{ color: m.color }}>
{m.value}
</Typography>
<Typography variant="caption" color="text.secondary">
{m.note}
</Typography>
</Card>
))}
</Box>
<Box className="grid grid-cols-2 gap-4" sx={{ mb: 3 }}>
{/* Confidence Distribution */}
<Card sx={{ p: 2.5 }}>
<Typography variant="subtitle1" fontWeight={600} mb={2}>
Konfidenzverteilung
</Typography>
{isLoading ? (
<Box sx={{ display: 'flex', justifyContent: 'center', py: 4 }}>
<CircularProgress size={32} />
</Box>
) : (
<Stack spacing={2}>
<Box>
<Box sx={{ display: 'flex', justifyContent: 'space-between', mb: 0.5 }}>
<Typography variant="body2" fontWeight={500}>Hoch (&gt;85%)</Typography>
<Typography variant="body2" color="text.secondary">{highConf} Objekte</Typography>
</Box>
<LinearProgress
variant="determinate"
value={(highConf / total) * 100}
color="success"
sx={{ height: 10, borderRadius: 5 }}
/>
</Box>
<Box>
<Box sx={{ display: 'flex', justifyContent: 'space-between', mb: 0.5 }}>
<Typography variant="body2" fontWeight={500}>Mittel (6585%)</Typography>
<Typography variant="body2" color="text.secondary">{midConf} Objekte</Typography>
</Box>
<LinearProgress
variant="determinate"
value={(midConf / total) * 100}
color="warning"
sx={{ height: 10, borderRadius: 5 }}
/>
</Box>
<Box>
<Box sx={{ display: 'flex', justifyContent: 'space-between', mb: 0.5 }}>
<Typography variant="body2" fontWeight={500}>Niedrig (&lt;65%)</Typography>
<Typography variant="body2" color="text.secondary">{lowConf} Objekte</Typography>
</Box>
<LinearProgress
variant="determinate"
value={(lowConf / total) * 100}
color="error"
sx={{ height: 10, borderRadius: 5 }}
/>
</Box>
</Stack>
)}
</Card>
{/* Anomaly Alerts */}
<Card sx={{ p: 2.5 }}>
<Typography variant="subtitle1" fontWeight={600} mb={2}>
Anomalien
</Typography>
<Stack spacing={1.5}>
<Alert severity="warning">
Mietpreisangaben für prop-004 weichen von Marktdurchschnitt ab (±31%). Manuelle Prüfung empfohlen.
</Alert>
<Alert severity="success">
Keine kritischen Anomalien erkannt. System läuft stabil.
</Alert>
</Stack>
</Card>
</Box>
{/* Recent AI Decisions */}
<Card>
<Box sx={{ px: 2.5, py: 2, borderBottom: '1px solid #f1f5f9' }}>
<Typography variant="subtitle1" fontWeight={600}>
Letzte KI-Entscheidungen
</Typography>
</Box>
<Table>
<TableHead>
<TableRow sx={{ bgcolor: '#f8fafc' }}>
<TableCell sx={{ fontSize: 12, fontWeight: 600, color: '#64748b' }}>Zeitpunkt</TableCell>
<TableCell sx={{ fontSize: 12, fontWeight: 600, color: '#64748b' }}>Entscheidungstyp</TableCell>
<TableCell sx={{ fontSize: 12, fontWeight: 600, color: '#64748b' }}>Konfidenz</TableCell>
<TableCell sx={{ fontSize: 12, fontWeight: 600, color: '#64748b' }}>Ergebnis</TableCell>
<TableCell sx={{ fontSize: 12, fontWeight: 600, color: '#64748b' }}>Einfluss</TableCell>
</TableRow>
</TableHead>
<TableBody>
{RECENT_DECISIONS.map((d, i) => (
<TableRow key={i} hover>
<TableCell>
<Typography variant="caption" color="text.secondary">{d.timestamp}</Typography>
</TableCell>
<TableCell>
<Typography variant="body2" fontWeight={500}>{d.type}</Typography>
</TableCell>
<TableCell>{getConfidenceBadge(d.confidence)}</TableCell>
<TableCell>
<Typography variant="body2">{d.result}</Typography>
</TableCell>
<TableCell>
<Typography variant="body2" color="text.secondary">{d.impact}</Typography>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</Card>
</Box>
</Box>
)
}
+311
View File
@@ -0,0 +1,311 @@
import { useState } from 'react'
import {
Box,
Button,
Card,
Chip,
Typography,
Stack,
CircularProgress,
} from '@mui/material'
import {
Building2,
Edit,
CheckCircle,
XCircle,
TrendingUp,
Search,
ClipboardList,
} from 'lucide-react'
import { useQuery } from '@tanstack/react-query'
import { governanceService, type ActivityEventType, type ActivityEvent } from '../../services/governanceService'
import { EmptyState } from '../../components/ui'
function getEventLabel(type: ActivityEventType): string {
switch (type) {
case 'PROPERTY_CREATED': return 'Objekt erstellt'
case 'PROPERTY_UPDATED': return 'Objekt aktualisiert'
case 'MATCH_APPROVED': return 'Match genehmigt'
case 'MATCH_REJECTED': return 'Match abgelehnt'
case 'SIGNAL_VERIFIED': return 'Signal verifiziert'
case 'NEED_CREATED': return 'Bedarf erstellt'
case 'REVIEW_REQUESTED': return 'Überprüfung angefordert'
}
}
function getEventDescription(event: ActivityEvent): string {
const actor = event.performedBy
const action = getEventLabel(event.type)
const entity = `${event.entityType} ${event.entityId}`
return `${actor} hat ${entity}${action}`
}
function getEventColor(type: ActivityEventType): string {
switch (type) {
case 'PROPERTY_CREATED': return '#1e3a5f'
case 'PROPERTY_UPDATED': return '#1e3a5f'
case 'MATCH_APPROVED': return '#1a7a4a'
case 'MATCH_REJECTED': return '#c0392b'
case 'SIGNAL_VERIFIED': return '#7c3aed'
case 'NEED_CREATED': return '#0891b2'
case 'REVIEW_REQUESTED': return '#d97706'
}
}
function getEventIcon(type: ActivityEventType) {
const size = 14
switch (type) {
case 'PROPERTY_CREATED': return <Building2 size={size} color="white" />
case 'PROPERTY_UPDATED': return <Edit size={size} color="white" />
case 'MATCH_APPROVED': return <CheckCircle size={size} color="white" />
case 'MATCH_REJECTED': return <XCircle size={size} color="white" />
case 'SIGNAL_VERIFIED': return <TrendingUp size={size} color="white" />
case 'NEED_CREATED': return <Search size={size} color="white" />
case 'REVIEW_REQUESTED': return <ClipboardList size={size} color="white" />
}
}
const ALL_EVENT_TYPES: ActivityEventType[] = [
'PROPERTY_CREATED',
'PROPERTY_UPDATED',
'MATCH_APPROVED',
'MATCH_REJECTED',
'SIGNAL_VERIFIED',
'NEED_CREATED',
'REVIEW_REQUESTED',
]
function formatDateTime(dateStr: string): string {
const d = new Date(dateStr)
return d.toLocaleDateString('de-CH', {
day: '2-digit',
month: '2-digit',
year: 'numeric',
}) + ', ' + d.toLocaleTimeString('de-CH', { hour: '2-digit', minute: '2-digit' })
}
function isToday(dateStr: string): boolean {
const d = new Date(dateStr)
const now = new Date()
return d.getFullYear() === now.getFullYear() &&
d.getMonth() === now.getMonth() &&
d.getDate() === now.getDate()
}
export default function Governance() {
const [filterType, setFilterType] = useState<ActivityEventType | 'ALL'>('ALL')
const { data: activityResp, isLoading, error } = useQuery({
queryKey: ['activity', 'org-wincasa'],
queryFn: () => governanceService.getActivityLog('org-wincasa'),
})
const events = activityResp?.data ?? []
const presentTypes = [...new Set(events.map(e => e.type))]
const todayCount = events.filter(e => isToday(e.createdAt)).length
const uniqueUsers = new Set(events.map(e => e.performedBy)).size
const filtered = filterType === 'ALL'
? events
: events.filter(e => e.type === filterType)
if (isLoading) {
return (
<Box sx={{ display: 'flex', justifyContent: 'center', alignItems: 'center', py: 12 }}>
<CircularProgress />
</Box>
)
}
if (error) {
return (
<Box sx={{ px: 3, py: 4 }}>
<Typography color="error">Fehler beim Laden des Aktivitätslogs.</Typography>
</Box>
)
}
return (
<Box>
{/* Page Header */}
<Box
sx={{
bgcolor: 'white',
borderBottom: '1px solid #e2e8f0',
px: 3,
py: 2,
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
}}
>
<Box>
<Typography variant="h5" fontWeight={700} color="text.primary">
Governance & Aktivitätslog
</Typography>
<Typography variant="body2" color="text.secondary">
Vollständiger Audit-Trail aller Plattformaktionen
</Typography>
</Box>
<Button variant="outlined" size="small" disabled>
Exportieren
</Button>
</Box>
<Box sx={{ px: 3, py: 3 }}>
{/* Stats row */}
<Box className="grid grid-cols-3 gap-4" sx={{ mb: 3 }}>
<Card sx={{ p: 2.5 }}>
<Typography variant="overline" color="text.secondary" lineHeight={1.4} display="block">
Ereignisse gesamt
</Typography>
<Typography variant="h3" fontWeight={700}>
{events.length}
</Typography>
<Typography variant="caption" color="text.secondary">Alle Aktivitäten</Typography>
</Card>
<Card sx={{ p: 2.5 }}>
<Typography variant="overline" color="text.secondary" lineHeight={1.4} display="block">
Ereignisse heute
</Typography>
<Typography variant="h3" fontWeight={700}>
{todayCount}
</Typography>
<Typography variant="caption" color="text.secondary">Heutige Aktivitäten</Typography>
</Card>
<Card sx={{ p: 2.5 }}>
<Typography variant="overline" color="text.secondary" lineHeight={1.4} display="block">
Aktive Benutzer
</Typography>
<Typography variant="h3" fontWeight={700}>
{uniqueUsers}
</Typography>
<Typography variant="caption" color="text.secondary">Unterschiedliche Nutzer</Typography>
</Card>
</Box>
{/* Filter chips */}
<Stack direction="row" spacing={0.5} flexWrap="wrap" gap={0.5} sx={{ mb: 2 }}>
<Chip
label="Alle"
size="small"
clickable
onClick={() => setFilterType('ALL')}
sx={{
bgcolor: filterType === 'ALL' ? '#1e3a5f' : 'transparent',
color: filterType === 'ALL' ? 'white' : 'text.secondary',
border: `1px solid ${filterType === 'ALL' ? '#1e3a5f' : '#e2e8f0'}`,
fontWeight: filterType === 'ALL' ? 600 : 400,
}}
/>
{ALL_EVENT_TYPES.filter(t => presentTypes.includes(t)).map(t => (
<Chip
key={t}
label={getEventLabel(t)}
size="small"
clickable
onClick={() => setFilterType(t)}
sx={{
bgcolor: filterType === t ? getEventColor(t) : 'transparent',
color: filterType === t ? 'white' : 'text.secondary',
border: `1px solid ${filterType === t ? getEventColor(t) : '#e2e8f0'}`,
fontWeight: filterType === t ? 600 : 400,
}}
/>
))}
</Stack>
{/* Activity Timeline */}
<Card sx={{ p: 2.5 }}>
<Typography variant="subtitle1" fontWeight={600} mb={2}>
Aktivitätslog
</Typography>
{filtered.length === 0 ? (
<EmptyState
title="Keine Ereignisse"
description="Für diesen Filter wurden keine Aktivitäten gefunden."
/>
) : (
<Box sx={{ position: 'relative' }}>
{/* Vertical line */}
<Box
sx={{
position: 'absolute',
left: 15,
top: 16,
bottom: 16,
width: 2,
bgcolor: '#e2e8f0',
zIndex: 0,
}}
/>
<Stack spacing={0}>
{filtered.map((event, idx) => (
<Box
key={event.id}
sx={{
display: 'flex',
gap: 2,
py: 1.5,
borderBottom: idx < filtered.length - 1 ? '1px solid #f8fafc' : 'none',
position: 'relative',
}}
>
{/* Icon dot */}
<Box
sx={{
width: 32,
height: 32,
borderRadius: '50%',
bgcolor: getEventColor(event.type),
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
flexShrink: 0,
zIndex: 1,
boxShadow: '0 0 0 3px white',
}}
>
{getEventIcon(event.type)}
</Box>
{/* Content */}
<Box sx={{ flex: 1, minWidth: 0, pt: 0.5 }}>
<Typography variant="body2">
{getEventDescription(event)}
</Typography>
{event.notes && (
<Typography variant="caption" color="text.secondary" display="block" mt={0.25}>
{event.notes}
</Typography>
)}
<Box sx={{ display: 'flex', alignItems: 'center', gap: 1, mt: 0.5 }}>
<Chip
label={event.organizationId}
size="small"
sx={{ fontSize: 10, height: 18, bgcolor: '#f1f5f9', color: '#475569' }}
/>
</Box>
</Box>
{/* Timestamp */}
<Typography
variant="caption"
color="text.secondary"
sx={{ flexShrink: 0, pt: 0.5, textAlign: 'right', minWidth: 110 }}
>
{formatDateTime(event.createdAt)}
</Typography>
</Box>
))}
</Stack>
</Box>
)}
</Card>
</Box>
</Box>
)
}
+380
View File
@@ -0,0 +1,380 @@
import { useState } from 'react'
import {
Box,
Button,
Card,
Chip,
Typography,
TextField,
Stack,
CircularProgress,
Divider,
Alert,
} from '@mui/material'
import { Target, TrendingUp } from 'lucide-react'
import { useQuery, useQueryClient } from '@tanstack/react-query'
import { matchService } from '../../services/matchService'
import { futureSignalService } from '../../services/futureSignalService'
import { RiskLevel } from '../../domain/enums'
import { EmptyState } from '../../components/ui'
type ReviewItemType = 'MATCH' | 'SIGNAL'
interface ReviewItem {
id: string
type: ReviewItemType
title: string
confidence: number
risk?: RiskLevel
summary?: string
probability?: number
}
function getPriorityLabel(confidence: number): string {
return confidence > 0.8 ? 'Kritisch' : 'Normal'
}
function getPriorityColor(confidence: number): 'error' | 'primary' {
return confidence > 0.8 ? 'error' : 'primary'
}
function getRiskLabel(risk?: RiskLevel): string {
if (!risk) return ''
switch (risk) {
case RiskLevel.LOW: return 'Niedrig'
case RiskLevel.MEDIUM: return 'Mittel'
case RiskLevel.HIGH: return 'Hoch'
case RiskLevel.CRITICAL: return 'Kritisch'
}
}
function getRiskColor(risk?: RiskLevel): 'success' | 'warning' | 'error' | 'default' {
if (!risk) return 'default'
if (risk === RiskLevel.LOW) return 'success'
if (risk === RiskLevel.MEDIUM) return 'warning'
return 'error'
}
export default function ReviewQueue() {
const queryClient = useQueryClient()
const [activeItem, setActiveItem] = useState<string | null>(null)
const [reviewNotes, setReviewNotes] = useState('')
const [approvedIds, setApprovedIds] = useState<Set<string>>(new Set())
const [rejectedIds, setRejectedIds] = useState<Set<string>>(new Set())
const { data: matchResp, isLoading: matchLoading } = useQuery({
queryKey: ['matches'],
queryFn: () => matchService.getAll(),
})
const { data: signalResp, isLoading: signalLoading } = useQuery({
queryKey: ['futureSignals'],
queryFn: () => futureSignalService.getAll(),
})
const matches = matchResp?.data ?? []
const signals = signalResp?.data ?? []
// Review items = matches NOT approved + future signals NOT verified
const matchItems: ReviewItem[] = matches
.filter(m => !m.isApproved && !approvedIds.has(m.id) && !rejectedIds.has(m.id))
.map(m => ({
id: m.id,
type: 'MATCH' as ReviewItemType,
title: `Match: ${m.propertyId} / ${m.needId}`,
confidence: m.confidenceLevel,
risk: m.riskLevel,
summary: m.explainabilitySummary,
}))
const signalItems: ReviewItem[] = signals
.filter(s => !s.isVerified && !approvedIds.has(s.id) && !rejectedIds.has(s.id))
.map(s => ({
id: s.id,
type: 'SIGNAL' as ReviewItemType,
title: `${s.signalType}: ${s.locationHint}`,
confidence: s.confidenceScore,
risk: s.riskLevel,
probability: s.probability,
summary: s.disclaimer,
}))
const allItems = [...matchItems, ...signalItems]
const selectedItem = allItems.find(i => i.id === activeItem)
const isLoading = matchLoading || signalLoading
const handleApprove = async () => {
if (!activeItem) return
const item = allItems.find(i => i.id === activeItem)
if (item?.type === 'MATCH') {
await matchService.approve(activeItem, 'admin@ideal-sharing.ch')
await queryClient.invalidateQueries({ queryKey: ['matches'] })
} else if (item?.type === 'SIGNAL') {
await futureSignalService.verify(activeItem, 'admin@ideal-sharing.ch')
await queryClient.invalidateQueries({ queryKey: ['futureSignals'] })
}
setApprovedIds(prev => new Set([...prev, activeItem]))
setActiveItem(null)
setReviewNotes('')
}
const handleReject = () => {
if (!activeItem) return
setRejectedIds(prev => new Set([...prev, activeItem]))
setActiveItem(null)
setReviewNotes('')
}
if (isLoading) {
return (
<Box sx={{ display: 'flex', justifyContent: 'center', alignItems: 'center', py: 12 }}>
<CircularProgress />
</Box>
)
}
const totalPending = matchItems.length + signalItems.length
return (
<Box>
{/* Page Header */}
<Box sx={{ bgcolor: 'white', borderBottom: '1px solid #e2e8f0', px: 3, py: 2, display: 'flex', alignItems: 'center', gap: 2 }}>
<Box>
<Box sx={{ display: 'flex', alignItems: 'center', gap: 1.5 }}>
<Typography variant="h5" fontWeight={700} color="text.primary">
Review Queue
</Typography>
{totalPending > 0 && (
<Chip
label={totalPending}
size="small"
sx={{ bgcolor: '#d97706', color: 'white', fontWeight: 700 }}
/>
)}
</Box>
<Typography variant="body2" color="text.secondary">
Human-in-the-loop Prüfung
</Typography>
</Box>
</Box>
<Box sx={{ px: 3, py: 3 }}>
{/* Stats row */}
<Box className="grid grid-cols-2 gap-4" sx={{ mb: 3 }}>
<Card sx={{ p: 2.5 }}>
<Typography variant="overline" color="text.secondary" lineHeight={1.4} display="block">
Offene Reviews
</Typography>
<Typography variant="h3" fontWeight={700} sx={{ color: totalPending > 0 ? 'warning.main' : 'text.primary' }}>
{totalPending}
</Typography>
<Typography variant="caption" color="text.secondary">
Ausstehende Prüfungen
</Typography>
</Card>
<Card sx={{ p: 2.5 }}>
<Typography variant="overline" color="text.secondary" lineHeight={1.4} display="block">
Signale zur Prüfung
</Typography>
<Typography variant="h3" fontWeight={700} sx={{ color: signalItems.length > 0 ? 'warning.main' : 'text.primary' }}>
{signalItems.length}
</Typography>
<Typography variant="caption" color="text.secondary">
Unverifizierte Signale
</Typography>
</Card>
</Box>
{/* Two-column layout */}
<Box className="grid grid-cols-2 gap-4" sx={{ alignItems: 'start' }}>
{/* Left: Item List */}
<Card sx={{ p: 0, overflow: 'hidden' }}>
<Box sx={{ px: 2, py: 1.5, borderBottom: '1px solid #f1f5f9' }}>
<Typography variant="subtitle2" fontWeight={600}>
Ausstehende Elemente
</Typography>
</Box>
{allItems.length === 0 ? (
<EmptyState
title="Keine ausstehenden Reviews"
description="Alle Elemente wurden geprüft."
/>
) : (
<Box>
{allItems.map(item => (
<Box
key={item.id}
onClick={() => {
setActiveItem(item.id)
setReviewNotes('')
}}
sx={{
px: 2,
py: 1.5,
cursor: 'pointer',
borderBottom: '1px solid #f8fafc',
bgcolor: activeItem === item.id ? '#eff6ff' : 'white',
'&:hover': { bgcolor: activeItem === item.id ? '#eff6ff' : '#fafafa' },
display: 'flex',
alignItems: 'flex-start',
gap: 1.5,
}}
>
<Box
sx={{
width: 32,
height: 32,
borderRadius: '50%',
bgcolor: item.type === 'MATCH' ? '#eff6ff' : '#faf5ff',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
flexShrink: 0,
mt: 0.25,
}}
>
{item.type === 'MATCH'
? <Target size={16} color="#1e3a5f" />
: <TrendingUp size={16} color="#7c3aed" />
}
</Box>
<Box sx={{ flex: 1, minWidth: 0 }}>
<Typography variant="body2" fontWeight={500} noWrap>
{item.title}
</Typography>
<Stack direction="row" spacing={0.5} mt={0.5} flexWrap="wrap">
<Chip
label={getPriorityLabel(item.confidence)}
size="small"
color={getPriorityColor(item.confidence)}
variant="outlined"
sx={{ fontSize: 10 }}
/>
<Chip
label="Ausstehend"
size="small"
sx={{ bgcolor: '#fef3c7', color: '#92400e', fontSize: 10 }}
/>
</Stack>
</Box>
</Box>
))}
</Box>
)}
</Card>
{/* Right: Review Panel */}
<Card sx={{ p: 0, overflow: 'hidden' }}>
{!selectedItem ? (
<EmptyState
title="Wählen Sie ein Element zur Prüfung"
description="Klicken Sie auf ein Element in der Liste, um es zu prüfen."
/>
) : (
<Box>
<Box sx={{ px: 2.5, py: 2, borderBottom: '1px solid #f1f5f9' }}>
<Box sx={{ display: 'flex', alignItems: 'center', gap: 1, mb: 0.5 }}>
<Chip
label={selectedItem.type === 'MATCH' ? 'Match' : 'Signal'}
size="small"
sx={{
bgcolor: selectedItem.type === 'MATCH' ? '#eff6ff' : '#faf5ff',
color: selectedItem.type === 'MATCH' ? '#1e3a5f' : '#7c3aed',
fontWeight: 600,
}}
/>
<Typography variant="subtitle2" fontWeight={600}>
{selectedItem.title}
</Typography>
</Box>
</Box>
<Box sx={{ px: 2.5, py: 2 }}>
{/* Key facts */}
<Stack spacing={1} sx={{ mb: 2 }}>
<Box sx={{ display: 'flex', gap: 3 }}>
<Box>
<Typography variant="caption" color="text.secondary" display="block">Konfidenz</Typography>
<Typography variant="body2" fontWeight={600}>
{Math.round(selectedItem.confidence * 100)}%
</Typography>
</Box>
{selectedItem.probability != null && (
<Box>
<Typography variant="caption" color="text.secondary" display="block">Wahrscheinlichkeit</Typography>
<Typography variant="body2" fontWeight={600}>
{Math.round(selectedItem.probability * 100)}%
</Typography>
</Box>
)}
<Box>
<Typography variant="caption" color="text.secondary" display="block">Risiko</Typography>
<Chip
label={getRiskLabel(selectedItem.risk)}
size="small"
color={getRiskColor(selectedItem.risk)}
variant="outlined"
/>
</Box>
</Box>
</Stack>
{selectedItem.summary && (
<Alert severity="info" sx={{ mb: 2, '& .MuiAlert-message': { fontSize: 13 } }}>
{selectedItem.summary}
</Alert>
)}
<Divider sx={{ mb: 2 }} />
{/* Notes */}
<Typography variant="caption" fontWeight={600} color="text.secondary" display="block" mb={1}>
Notizen
</Typography>
<TextField
multiline
rows={3}
fullWidth
placeholder="Optionale Anmerkungen zur Entscheidung..."
value={reviewNotes}
onChange={e => setReviewNotes(e.target.value)}
size="small"
sx={{ mb: 2 }}
/>
{/* Decision buttons */}
<Stack spacing={1}>
<Button
variant="contained"
fullWidth
onClick={handleApprove}
sx={{ bgcolor: '#1a7a4a', '&:hover': { bgcolor: '#155f3a' } }}
>
Genehmigen
</Button>
<Button
variant="outlined"
fullWidth
color="error"
onClick={handleReject}
>
Ablehnen
</Button>
<Button
variant="outlined"
fullWidth
sx={{ color: '#64748b', borderColor: '#e2e8f0' }}
>
Weiterleiten
</Button>
</Stack>
</Box>
</Box>
)}
</Card>
</Box>
</Box>
</Box>
)
}
+309
View File
@@ -0,0 +1,309 @@
import {
Alert,
Box,
Card,
Chip,
LinearProgress,
Table,
TableBody,
TableCell,
TableHead,
TableRow,
Typography,
} from '@mui/material'
import { useQuery } from '@tanstack/react-query'
import { ErrorState, LoadingPage, SectionContainer } from '../../components/ui'
import { propertyService } from '../../services/propertyService'
import { DataFreshness, ResultType } from '../../domain/enums'
function getResultTypeLabel(type: ResultType): string {
switch (type) {
case ResultType.VERIFIED_PORTFOLIO: return 'Verified Portfolio'
case ResultType.EXTERNAL_MARKET: return 'Marktinserat'
case ResultType.FUTURE_AVAILABILITY: return 'Zukunftssignal'
}
}
function getQualityColor(score: number): 'success' | 'warning' | 'error' {
if (score >= 0.8) return 'success'
if (score >= 0.6) return 'warning'
return 'error'
}
function getFreshnessLabel(freshness: DataFreshness): string {
switch (freshness) {
case DataFreshness.FRESH: return 'Aktuell'
case DataFreshness.STALE: return 'Veraltet'
case DataFreshness.OUTDATED: return 'Abgelaufen'
}
}
function getFreshnessColor(freshness: DataFreshness): 'success' | 'warning' | 'error' {
switch (freshness) {
case DataFreshness.FRESH: return 'success'
case DataFreshness.STALE: return 'warning'
case DataFreshness.OUTDATED: return 'error'
}
}
export default function DataQuality() {
const { data: resp, isLoading, error } = useQuery({
queryKey: ['properties'],
queryFn: () => propertyService.getAll(),
})
if (isLoading) return <LoadingPage />
if (error) return <ErrorState />
const properties = resp?.data ?? []
const avgScore = properties.length
? properties.reduce((sum, p) => sum + p.dataQuality.score, 0) / properties.length
: 0
const criticalIssues = properties.filter(p => p.dataQuality.missingCriticalFields.length > 0)
const staleData = properties.filter(
p => p.dataQuality.freshness === DataFreshness.STALE || p.dataQuality.freshness === DataFreshness.OUTDATED
)
const highQuality = properties.filter(p => p.dataQuality.score >= 0.8)
const medQuality = properties.filter(p => p.dataQuality.score >= 0.6 && p.dataQuality.score < 0.8)
const lowQuality = properties.filter(p => p.dataQuality.score < 0.6)
// Sort by score ascending (worst first)
const sortedProperties = [...properties].sort((a, b) => a.dataQuality.score - b.dataQuality.score)
return (
<Box>
{/* Page Header */}
<Box sx={{ bgcolor: 'white', borderBottom: '1px solid', borderColor: 'divider', px: 3, py: 2 }}>
<Typography variant="h5" fontWeight={700} color="text.primary">Datenqualität</Typography>
<Typography variant="body2" color="text.secondary">Vollständigkeit und Aktualität der Objektdaten</Typography>
</Box>
{/* Content */}
<Box sx={{ px: 3, py: 3 }} className="flex flex-col gap-4">
{/* Summary Stats Row */}
<Box className="grid grid-cols-3 gap-4">
{/* Avg Quality Score */}
<Card sx={{ elevation: 1, p: 2.5 }}>
<Typography variant="overline" color="text.secondary" display="block">Ø Qualitätsscore</Typography>
<Typography variant="h4" fontWeight={700} sx={{ color: avgScore >= 0.8 ? '#1a7a4a' : avgScore >= 0.6 ? '#d97706' : '#c0392b' }}>
{Math.round(avgScore * 100)}%
</Typography>
<Box sx={{ mt: 1 }}>
<LinearProgress
variant="determinate"
value={avgScore * 100}
color={getQualityColor(avgScore)}
sx={{ height: 8, borderRadius: 4 }}
/>
</Box>
</Card>
{/* Critical Issues */}
<Card sx={{ elevation: 1, p: 2.5 }}>
<Typography variant="overline" color="text.secondary" display="block">Kritische Felder fehlen</Typography>
<Typography
variant="h4"
fontWeight={700}
sx={{ color: criticalIssues.length > 2 ? '#c0392b' : criticalIssues.length > 0 ? '#d97706' : '#1a7a4a' }}
>
{criticalIssues.length}
</Typography>
<Typography variant="caption" color="text.secondary">
von {properties.length} Objekten
</Typography>
</Card>
{/* Stale Data */}
<Card sx={{ elevation: 1, p: 2.5 }}>
<Typography variant="overline" color="text.secondary" display="block">Veraltete Daten</Typography>
<Typography
variant="h4"
fontWeight={700}
sx={{ color: staleData.length > 2 ? '#c0392b' : staleData.length > 0 ? '#d97706' : '#1a7a4a' }}
>
{staleData.length}
</Typography>
<Typography variant="caption" color="text.secondary">
von {properties.length} Objekten
</Typography>
</Card>
</Box>
{/* Quality Distribution */}
<SectionContainer title="Qualitätsverteilung">
<Card sx={{ elevation: 1, p: 2.5 }}>
<Box className="flex flex-col gap-3">
{/* High */}
<Box className="flex items-center gap-3">
<Typography variant="body2" sx={{ width: 120, flexShrink: 0 }}>Hoch (80%)</Typography>
<Chip label={highQuality.length} size="small" color="success" />
<Box className="flex-1">
<LinearProgress
variant="determinate"
value={properties.length > 0 ? (highQuality.length / properties.length) * 100 : 0}
color="success"
sx={{ height: 10, borderRadius: 5 }}
/>
</Box>
<Typography variant="caption" color="text.secondary" sx={{ width: 40, textAlign: 'right' }}>
{properties.length > 0 ? Math.round((highQuality.length / properties.length) * 100) : 0}%
</Typography>
</Box>
{/* Medium */}
<Box className="flex items-center gap-3">
<Typography variant="body2" sx={{ width: 120, flexShrink: 0 }}>Mittel (6079%)</Typography>
<Chip label={medQuality.length} size="small" color="warning" />
<Box className="flex-1">
<LinearProgress
variant="determinate"
value={properties.length > 0 ? (medQuality.length / properties.length) * 100 : 0}
color="warning"
sx={{ height: 10, borderRadius: 5 }}
/>
</Box>
<Typography variant="caption" color="text.secondary" sx={{ width: 40, textAlign: 'right' }}>
{properties.length > 0 ? Math.round((medQuality.length / properties.length) * 100) : 0}%
</Typography>
</Box>
{/* Low */}
<Box className="flex items-center gap-3">
<Typography variant="body2" sx={{ width: 120, flexShrink: 0 }}>Niedrig ({'<'}60%)</Typography>
<Chip label={lowQuality.length} size="small" color="error" />
<Box className="flex-1">
<LinearProgress
variant="determinate"
value={properties.length > 0 ? (lowQuality.length / properties.length) * 100 : 0}
color="error"
sx={{ height: 10, borderRadius: 5 }}
/>
</Box>
<Typography variant="caption" color="text.secondary" sx={{ width: 40, textAlign: 'right' }}>
{properties.length > 0 ? Math.round((lowQuality.length / properties.length) * 100) : 0}%
</Typography>
</Box>
</Box>
</Card>
</SectionContainer>
{/* Properties Quality Table */}
<SectionContainer title="Objektübersicht Datenqualität">
<Card sx={{ elevation: 1 }}>
<Table size="small">
<TableHead>
<TableRow sx={{ bgcolor: 'grey.50' }}>
<TableCell><Typography variant="caption" fontWeight={600}>Objekt</Typography></TableCell>
<TableCell><Typography variant="caption" fontWeight={600}>Quelle</Typography></TableCell>
<TableCell><Typography variant="caption" fontWeight={600}>Score</Typography></TableCell>
<TableCell><Typography variant="caption" fontWeight={600}>Kritische Felder</Typography></TableCell>
<TableCell><Typography variant="caption" fontWeight={600}>Optionale Felder</Typography></TableCell>
<TableCell><Typography variant="caption" fontWeight={600}>Aktualität</Typography></TableCell>
<TableCell><Typography variant="caption" fontWeight={600}>Warnungen</Typography></TableCell>
</TableRow>
</TableHead>
<TableBody>
{sortedProperties.map(property => {
const hasCritical = property.dataQuality.missingCriticalFields.length > 0
const missingCritical = property.dataQuality.missingCriticalFields
const missingOptional = property.dataQuality.missingOptionalFields
const score = property.dataQuality.score
return (
<TableRow
key={property.id}
hover
sx={hasCritical ? { bgcolor: 'rgba(192,57,43,0.04)' } : {}}
>
{/* Objekt */}
<TableCell>
<Typography variant="body2" fontWeight={500}>{property.title}</Typography>
</TableCell>
{/* Quelle */}
<TableCell>
<Typography variant="caption" color="text.secondary">
{getResultTypeLabel(property.resultType)}
</Typography>
</TableCell>
{/* Score */}
<TableCell>
<Box sx={{ width: 100 }}>
<Box className="flex items-center justify-between mb-1">
<Typography variant="caption" fontWeight={700} sx={{ color: score >= 0.8 ? '#1a7a4a' : score >= 0.6 ? '#d97706' : '#c0392b' }}>
{Math.round(score * 100)}%
</Typography>
</Box>
<LinearProgress
variant="determinate"
value={score * 100}
color={getQualityColor(score)}
sx={{ height: 5, borderRadius: 2 }}
/>
</Box>
</TableCell>
{/* Kritische Felder */}
<TableCell>
{missingCritical.length === 0 ? (
<Chip label="Vollständig" color="success" size="small" />
) : (
<Box className="flex flex-wrap gap-1 items-center">
{missingCritical.slice(0, 2).map(f => (
<Chip key={f} label={f} color="error" size="small" variant="outlined" />
))}
{missingCritical.length > 2 && (
<Typography variant="caption" color="error.main" fontWeight={600}>
+{missingCritical.length - 2} weitere
</Typography>
)}
</Box>
)}
</TableCell>
{/* Optionale Felder */}
<TableCell>
{missingOptional.length === 0 ? (
<Typography variant="caption" color="text.secondary"></Typography>
) : (
<Typography variant="caption" color="text.secondary">
{missingOptional.length} fehlen
</Typography>
)}
</TableCell>
{/* Aktualität */}
<TableCell>
<Chip
label={getFreshnessLabel(property.dataQuality.freshness)}
color={getFreshnessColor(property.dataQuality.freshness)}
size="small"
/>
</TableCell>
{/* Warnungen */}
<TableCell>
{property.dataQuality.warnings.length > 0 ? (
<Alert severity="warning" sx={{ py: 0, px: 1, fontSize: 11 }}>
{property.dataQuality.warnings[0]}
</Alert>
) : (
<Typography variant="caption" color="text.secondary"></Typography>
)}
</TableCell>
</TableRow>
)
})}
</TableBody>
</Table>
</Card>
</SectionContainer>
</Box>
</Box>
)
}
+237
View File
@@ -0,0 +1,237 @@
import {
Box,
Button,
Card,
Chip,
Divider,
LinearProgress,
Typography,
} from '@mui/material'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { EmptyState, ErrorState, LoadingPage } from '../../components/ui'
import { futureSignalService } from '../../services/futureSignalService'
import { SignalType } from '../../domain/enums'
function getSignalTypeLabel(type: SignalType): string {
switch (type) {
case SignalType.EXPANSION: return 'Expansion'
case SignalType.POSSIBLE_MOVE_OUT: return 'Möglicher Auszug'
case SignalType.CONSTRUCTION_PROJECT: return 'Bauprojekt'
case SignalType.RESTRUCTURING: return 'Restrukturierung'
case SignalType.PROJECT_DEVELOPMENT: return 'Projektentwicklung'
case SignalType.SPACE_CONSOLIDATION: return 'Flächenkonsolidierung'
}
}
function getSignalTypeColor(type: SignalType): string {
switch (type) {
case SignalType.EXPANSION: return '#1a7a4a'
case SignalType.POSSIBLE_MOVE_OUT: return '#d97706'
case SignalType.CONSTRUCTION_PROJECT: return '#1e3a5f'
case SignalType.RESTRUCTURING: return '#ea580c'
case SignalType.PROJECT_DEVELOPMENT: return '#7c3aed'
case SignalType.SPACE_CONSOLIDATION: return '#6b7280'
}
}
function getProbabilityColor(prob: number): 'success' | 'warning' | 'error' {
if (prob > 0.7) return 'success'
if (prob >= 0.5) return 'warning'
return 'error'
}
function formatDate(dateStr?: string): string {
if (!dateStr) return ''
return new Date(dateStr).toLocaleDateString('de-CH', { day: '2-digit', month: '2-digit', year: 'numeric' })
}
function getSourceTypeLabel(type: string): string {
switch (type) {
case 'PRESS': return 'Pressebericht'
case 'CONSTRUCTION_PERMIT': return 'Baubewilligung'
case 'JOB_POSTING': return 'Stelleninserat'
case 'COMPANY_REPORT': return 'Geschäftsbericht'
case 'MARKET_DATA': return 'Marktdaten'
case 'MANUAL': return 'Manuell'
default: return type
}
}
export default function FutureAvailability() {
const queryClient = useQueryClient()
const { data: resp, isLoading, error } = useQuery({
queryKey: ['futureSignals'],
queryFn: () => futureSignalService.getAll(),
})
const verifyMutation = useMutation({
mutationFn: (signalId: string) => futureSignalService.verify(signalId, 'admin@ideal-sharing.ch'),
onSuccess: () => queryClient.invalidateQueries({ queryKey: ['futureSignals'] }),
})
if (isLoading) return <LoadingPage />
if (error) return <ErrorState />
const signals = resp?.data ?? []
const totalCount = signals.length
const verifiedCount = signals.filter(s => s.isVerified).length
const highProbCount = signals.filter(s => s.probability > 0.7).length
const avgProbability = signals.length
? signals.reduce((sum, s) => sum + s.probability, 0) / signals.length
: 0
return (
<Box>
{/* Page Header */}
<Box sx={{ bgcolor: 'white', borderBottom: '1px solid', borderColor: 'divider', px: 3, py: 2 }} className="flex items-center gap-3">
<Box className="flex-1">
<Box className="flex items-center gap-2">
<Typography variant="h5" fontWeight={700} color="text.primary">Marktchancen</Typography>
<Chip
label="Shadow Intelligence Layer"
size="small"
sx={{ bgcolor: '#7c3aed', color: 'white', fontWeight: 600 }}
/>
</Box>
<Typography variant="body2" color="text.secondary">KI-generierte Verfügbarkeitssignale</Typography>
</Box>
</Box>
{/* Content */}
<Box sx={{ px: 3, py: 3 }} className="flex flex-col gap-4">
{/* Stats Row */}
<Box className="grid grid-cols-4 gap-4">
<Card sx={{ elevation: 1, p: 2.5 }}>
<Typography variant="overline" color="text.secondary" display="block">Signale gesamt</Typography>
<Typography variant="h4" fontWeight={700}>{totalCount}</Typography>
</Card>
<Card sx={{ elevation: 1, p: 2.5 }}>
<Typography variant="overline" color="text.secondary" display="block">Verifiziert</Typography>
<Typography variant="h4" fontWeight={700} sx={{ color: '#1a7a4a' }}>{verifiedCount}</Typography>
</Card>
<Card sx={{ elevation: 1, p: 2.5 }}>
<Typography variant="overline" color="text.secondary" display="block">Hohe Wahrscheinlichkeit</Typography>
<Typography variant="h4" fontWeight={700} sx={{ color: '#1e3a5f' }}>{highProbCount}</Typography>
</Card>
<Card sx={{ elevation: 1, p: 2.5 }}>
<Typography variant="overline" color="text.secondary" display="block">Ø Wahrscheinlichkeit</Typography>
<Typography variant="h4" fontWeight={700} sx={{ color: getProbabilityColor(avgProbability) === 'success' ? '#1a7a4a' : getProbabilityColor(avgProbability) === 'warning' ? '#d97706' : '#c0392b' }}>
{Math.round(avgProbability * 100)}%
</Typography>
</Card>
</Box>
{/* Signal Cards Grid */}
{signals.length === 0 ? (
<EmptyState title="Keine Signale gefunden" description="Es sind noch keine Zukunftssignale vorhanden." />
) : (
<Box className="flex flex-wrap gap-4">
{signals.map(signal => (
<Card key={signal.id} sx={{ elevation: 1, p: 2, flex: '1 1 calc(50% - 16px)', minWidth: 320 }}>
{/* Card Header */}
<Box className="flex items-center justify-between mb-2">
<Chip
label={getSignalTypeLabel(signal.signalType)}
size="small"
sx={{ bgcolor: getSignalTypeColor(signal.signalType), color: 'white', fontWeight: 600 }}
/>
<Chip
label={signal.sensitivityLevel === 'PUBLIC' ? 'Öffentlich' : signal.sensitivityLevel === 'CONFIDENTIAL' ? 'Vertraulich' : 'Intern'}
size="small"
variant="outlined"
color={signal.sensitivityLevel === 'CONFIDENTIAL' ? 'error' : 'default'}
/>
</Box>
{/* Location */}
<Box className="mb-2">
<Typography variant="body1" fontWeight={500}>{signal.locationHint}</Typography>
{signal.companyName && (
<Typography variant="body2" color="text.secondary">{signal.companyName}</Typography>
)}
</Box>
{/* Probability */}
<Box className="mb-2">
<Box className="flex items-center justify-between mb-1">
<Typography variant="caption" color="text.secondary">Wahrscheinlichkeit</Typography>
<Typography variant="body2" fontWeight={700} sx={{ color: signal.probability > 0.7 ? '#1a7a4a' : signal.probability >= 0.5 ? '#d97706' : '#c0392b' }}>
{Math.round(signal.probability * 100)}%
</Typography>
</Box>
<LinearProgress
variant="determinate"
value={signal.probability * 100}
color={getProbabilityColor(signal.probability)}
sx={{ height: 6, borderRadius: 3 }}
/>
</Box>
{/* Details */}
<Box className="flex flex-wrap gap-2 mb-2">
{signal.areaSqmEstimate && (
<Typography variant="caption" color="text.secondary">
Fläche: ca. {signal.areaSqmEstimate.toLocaleString('de-CH')} m²
</Typography>
)}
<Typography variant="caption" color="text.secondary">
Zeithorizont: {signal.timeHorizonMonths} Monate
</Typography>
{signal.expiresAt && (
<Typography variant="caption" color="text.secondary">
Verfügbar ab: {formatDate(signal.expiresAt)}
</Typography>
)}
</Box>
{/* Source */}
<Box className="mb-2">
<Typography variant="caption" color="text.secondary">
Quelle: {getSourceTypeLabel(signal.source.type)} Glaubwürdigkeit:{' '}
<span style={{ color: signal.source.credibility === 'HIGH' ? '#1a7a4a' : signal.source.credibility === 'MEDIUM' ? '#d97706' : '#c0392b', fontWeight: 600 }}>
{signal.source.credibility === 'HIGH' ? 'Hoch' : signal.source.credibility === 'MEDIUM' ? 'Mittel' : 'Niedrig'}
</span>
</Typography>
</Box>
{/* Verification Status */}
<Box className="mb-2">
{signal.isVerified ? (
<Box className="flex items-center gap-2">
<Chip label="Verifiziert" color="success" size="small" />
<Typography variant="caption" color="text.secondary">{formatDate(signal.verifiedAt)}</Typography>
</Box>
) : (
<Chip label="Nicht verifiziert" color="warning" size="small" variant="outlined" />
)}
</Box>
<Divider sx={{ my: 1 }} />
{/* Footer buttons */}
<Box className="flex items-center gap-2">
{!signal.isVerified && (
<Button
variant="outlined"
size="small"
onClick={() => verifyMutation.mutate(signal.id)}
disabled={verifyMutation.isPending}
>
Verifizieren
</Button>
)}
<Button variant="outlined" size="small" disabled>
Zu Shortlist
</Button>
</Box>
</Card>
))}
</Box>
)}
</Box>
</Box>
)
}
+283
View File
@@ -0,0 +1,283 @@
import {
Box,
Button,
Card,
Chip,
Divider,
LinearProgress,
Typography,
} from '@mui/material'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { Building2 } from 'lucide-react'
import { useState } from 'react'
import { EmptyState, ErrorState, LoadingPage } from '../../components/ui'
import { matchService } from '../../services/matchService'
import { propertyService } from '../../services/propertyService'
import { needService } from '../../services/needService'
import { MatchStrength, RiskLevel } from '../../domain/enums'
function getMatchStrengthLabel(strength: MatchStrength): string {
switch (strength) {
case MatchStrength.STRONG: return 'Stark'
case MatchStrength.MODERATE: return 'Mittel'
case MatchStrength.WEAK: return 'Schwach'
}
}
function getMatchStrengthColor(strength: MatchStrength): 'success' | 'warning' | 'error' {
switch (strength) {
case MatchStrength.STRONG: return 'success'
case MatchStrength.MODERATE: return 'warning'
case MatchStrength.WEAK: return 'error'
}
}
function getScoreColor(strength: MatchStrength): string {
switch (strength) {
case MatchStrength.STRONG: return '#1a7a4a'
case MatchStrength.MODERATE: return '#d97706'
case MatchStrength.WEAK: return '#c0392b'
}
}
function getConfidenceColor(score: number): 'success' | 'primary' | 'warning' {
if (score >= 0.85) return 'success'
if (score >= 0.65) return 'primary'
return 'warning'
}
function getConfidenceLabel(score: number): string {
if (score >= 0.85) return 'Hoch'
if (score >= 0.65) return 'Mittel'
return 'Niedrig'
}
function getRiskLabel(level: RiskLevel): string {
switch (level) {
case RiskLevel.LOW: return 'Niedriges Risiko'
case RiskLevel.MEDIUM: return 'Mittleres Risiko'
case RiskLevel.HIGH: return 'Hohes Risiko'
case RiskLevel.CRITICAL: return 'Kritisches Risiko'
}
}
function getRiskColor(level: RiskLevel): 'success' | 'warning' | 'error' {
switch (level) {
case RiskLevel.LOW: return 'success'
case RiskLevel.MEDIUM: return 'warning'
case RiskLevel.HIGH: return 'error'
case RiskLevel.CRITICAL: return 'error'
}
}
export default function MatchCenter() {
const [filterStrength, setFilterStrength] = useState<MatchStrength | 'ALL'>('ALL')
const queryClient = useQueryClient()
const { data: matchResp, isLoading: matchLoading, error: matchError } = useQuery({
queryKey: ['matches'],
queryFn: () => matchService.getAll(),
})
const { data: propResp, isLoading: propLoading, error: propError } = useQuery({
queryKey: ['properties'],
queryFn: () => propertyService.getAll(),
})
const { data: needResp, isLoading: needLoading, error: needError } = useQuery({
queryKey: ['needs'],
queryFn: () => needService.getAll(),
})
const approveMutation = useMutation({
mutationFn: (matchId: string) => matchService.approve(matchId, 'admin@ideal-sharing.ch'),
onSuccess: () => queryClient.invalidateQueries({ queryKey: ['matches'] }),
})
if (matchLoading || propLoading || needLoading) return <LoadingPage />
if (matchError || propError || needError) return <ErrorState />
const matches = matchResp?.data ?? []
const properties = propResp?.data ?? []
const needs = needResp?.data ?? []
const filtered = filterStrength === 'ALL'
? matches
: matches.filter(m => m.matchStrength === filterStrength)
const sortedFiltered = [...filtered].sort((a, b) => b.matchScore - a.matchScore)
const strengthFilters: { value: MatchStrength | 'ALL'; label: string }[] = [
{ value: 'ALL', label: 'Alle' },
{ value: MatchStrength.STRONG, label: 'Stark' },
{ value: MatchStrength.MODERATE, label: 'Mittel' },
{ value: MatchStrength.WEAK, label: 'Schwach' },
]
return (
<Box>
{/* Page Header */}
<Box sx={{ bgcolor: 'white', borderBottom: '1px solid', borderColor: 'divider', px: 3, py: 2 }} className="flex items-center justify-between">
<Box>
<Box className="flex items-center gap-2">
<Typography variant="h5" fontWeight={700} color="text.primary">Match Center</Typography>
<Chip label={`${matches.length} Matches`} size="small" sx={{ bgcolor: '#1e3a5f', color: 'white', fontWeight: 700 }} />
</Box>
<Typography variant="body2" color="text.secondary">KI-gestützte Objekt-Bedarfs-Analyse</Typography>
</Box>
</Box>
{/* Content */}
<Box sx={{ px: 3, py: 3 }} className="flex flex-col gap-3">
{/* Filter Chips */}
<Box className="flex items-center gap-2">
{strengthFilters.map(f => (
<Chip
key={f.value}
label={f.label}
variant={filterStrength === f.value ? 'filled' : 'outlined'}
size="small"
onClick={() => setFilterStrength(f.value)}
color={
f.value === MatchStrength.STRONG ? 'success'
: f.value === MatchStrength.MODERATE ? 'warning'
: f.value === MatchStrength.WEAK ? 'error'
: 'default'
}
sx={{ cursor: 'pointer', fontWeight: filterStrength === f.value ? 700 : 400 }}
/>
))}
</Box>
{/* Match Cards */}
{sortedFiltered.length === 0 ? (
<EmptyState title="Keine Matches gefunden" description="Passen Sie den Filter an." />
) : (
<Box className="flex flex-col gap-4">
{sortedFiltered.map(match => {
const property = properties.find(p => p.id === match.propertyId)
const need = needs.find(n => n.id === match.needId)
return (
<Card key={match.id} sx={{ elevation: 1, p: 2.5 }}>
<Box className="flex gap-4">
{/* Left column: score */}
<Box sx={{ width: 80, flexShrink: 0, textAlign: 'center' }} className="flex flex-col items-center gap-1">
<Typography variant="h3" fontWeight={700} sx={{ color: getScoreColor(match.matchStrength) }}>
{match.matchScore}
</Typography>
<Typography variant="caption" color="text.secondary">/ 100</Typography>
<Chip
label={getMatchStrengthLabel(match.matchStrength)}
color={getMatchStrengthColor(match.matchStrength)}
size="small"
/>
</Box>
{/* Center column: details */}
<Box className="flex-1 flex flex-col gap-2">
{/* Property info */}
<Box className="flex items-center gap-1">
<Building2 size={16} color="#1e3a5f" />
<Typography variant="h6" fontWeight={600}>
{property?.title ?? match.propertyId}
</Typography>
</Box>
{need && (
<Typography variant="body2" color="text.secondary">
{need.companyName} {need.assetType}
</Typography>
)}
<Divider />
{/* Positive factors */}
<Box className="flex flex-col gap-1">
{match.positiveFactors.slice(0, 3).map((f, i) => (
<Box key={i} className="flex items-center gap-2">
<Typography variant="caption" sx={{ color: '#1a7a4a', fontWeight: 600 }}>
{f.criterion}: {Math.round(f.score)}%
</Typography>
<Box sx={{ width: 60 }}>
<LinearProgress
variant="determinate"
value={f.score}
color="success"
sx={{ height: 4, borderRadius: 2 }}
/>
</Box>
</Box>
))}
</Box>
{/* Negative factors */}
{match.negativeFactors.slice(0, 2).map((f, i) => (
<Typography key={i} variant="caption" sx={{ color: '#c0392b' }}>
{f.criterion}
</Typography>
))}
{/* Tradeoffs */}
{match.tradeoffs.length > 0 && (
<Box>
{match.tradeoffs.slice(0, 2).map((t, i) => (
<Typography key={i} variant="caption" sx={{ color: '#d97706' }}>
{t.concern}
</Typography>
))}
</Box>
)}
</Box>
{/* Right column: actions */}
<Box sx={{ width: 160, flexShrink: 0, textAlign: 'right' }} className="flex flex-col gap-2 items-end">
<Chip
label={`Konfidenz: ${getConfidenceLabel(match.confidenceLevel)}`}
color={getConfidenceColor(match.confidenceLevel)}
size="small"
/>
<Chip
label={getRiskLabel(match.riskLevel)}
color={getRiskColor(match.riskLevel)}
size="small"
variant="outlined"
/>
<Button
variant="outlined"
size="small"
fullWidth
disabled
>
Details
</Button>
{match.isApproved ? (
<Chip
label="✓ Genehmigt"
color="success"
size="small"
sx={{ width: '100%', justifyContent: 'center' }}
/>
) : (
<Button
variant="contained"
size="small"
fullWidth
color="primary"
sx={{ bgcolor: '#1e3a5f' }}
onClick={() => approveMutation.mutate(match.id)}
disabled={approveMutation.isPending}
>
Genehmigen
</Button>
)}
</Box>
</Box>
</Card>
)
})}
</Box>
)}
</Box>
</Box>
)
}
+374
View File
@@ -0,0 +1,374 @@
import {
Box,
Card,
Chip,
IconButton,
LinearProgress,
MenuItem,
Select,
Table,
TableBody,
TableCell,
TableHead,
TableRow,
TextField,
Tooltip,
Typography,
} from '@mui/material'
import { useQuery } from '@tanstack/react-query'
import { Eye, MoreHorizontal, Plus } from 'lucide-react'
import { useState } from 'react'
import { EmptyState, ErrorState, LoadingPage } from '../../components/ui'
import { propertyService } from '../../services/propertyService'
import { AssetType, AvailabilityStatus, ResultType } from '../../domain/enums'
function getAssetTypeLabel(type: AssetType): string {
switch (type) {
case AssetType.OFFICE: return 'Büro'
case AssetType.LOGISTICS: return 'Logistik'
case AssetType.RETAIL: return 'Retail'
case AssetType.GASTRO: return 'Gastro'
case AssetType.PRODUCTION: return 'Produktion'
case AssetType.MIXED: return 'Gemischt'
}
}
function getAssetTypeColor(type: AssetType): string {
switch (type) {
case AssetType.OFFICE: return '#1e3a5f'
case AssetType.LOGISTICS: return '#d97706'
case AssetType.RETAIL: return '#7c3aed'
case AssetType.GASTRO: return '#0d9488'
case AssetType.PRODUCTION: return '#92400e'
case AssetType.MIXED: return '#6b7280'
}
}
function getAvailabilityLabel(status: AvailabilityStatus): string {
switch (status) {
case AvailabilityStatus.AVAILABLE_NOW: return 'Verfügbar'
case AvailabilityStatus.AVAILABLE_SOON: return 'Bald verfügbar'
case AvailabilityStatus.FUTURE_SIGNAL: return 'Zukunftssignal'
case AvailabilityStatus.OCCUPIED: return 'Belegt'
case AvailabilityStatus.UNKNOWN: return 'Unbekannt'
}
}
function getAvailabilityColor(status: AvailabilityStatus): 'success' | 'warning' | 'secondary' | 'error' | 'default' {
switch (status) {
case AvailabilityStatus.AVAILABLE_NOW: return 'success'
case AvailabilityStatus.AVAILABLE_SOON: return 'warning'
case AvailabilityStatus.FUTURE_SIGNAL: return 'secondary'
case AvailabilityStatus.OCCUPIED: return 'error'
case AvailabilityStatus.UNKNOWN: return 'default'
}
}
function getResultTypeLabel(type: ResultType): string {
switch (type) {
case ResultType.VERIFIED_PORTFOLIO: return 'Verified Portfolio'
case ResultType.EXTERNAL_MARKET: return 'Marktinserat'
case ResultType.FUTURE_AVAILABILITY: return 'Zukunftssignal'
}
}
function getResultTypeColor(type: ResultType): string {
switch (type) {
case ResultType.VERIFIED_PORTFOLIO: return '#1e3a5f'
case ResultType.EXTERNAL_MARKET: return '#d97706'
case ResultType.FUTURE_AVAILABILITY: return '#7c3aed'
}
}
function getConfidenceColor(score: number): string {
if (score >= 0.85) return '#1a7a4a'
if (score >= 0.65) return '#1e3a5f'
return '#d97706'
}
function getQualityColor(score: number): 'success' | 'warning' | 'error' {
if (score >= 0.8) return 'success'
if (score >= 0.6) return 'warning'
return 'error'
}
export default function Properties() {
const [selectedResultType, setSelectedResultType] = useState<ResultType | 'ALL'>('ALL')
const [selectedAssetType, setSelectedAssetType] = useState<AssetType | 'ALL'>('ALL')
const [searchQuery, setSearchQuery] = useState('')
const { data: resp, isLoading, error } = useQuery({
queryKey: ['properties'],
queryFn: () => propertyService.getAll(),
})
if (isLoading) return <LoadingPage />
if (error) return <ErrorState />
const properties = resp?.data ?? []
const filtered = properties.filter(p => {
if (selectedResultType !== 'ALL' && p.resultType !== selectedResultType) return false
if (selectedAssetType !== 'ALL' && p.assetType !== selectedAssetType) return false
if (searchQuery) {
const q = searchQuery.toLowerCase()
const matchesTitle = p.title.toLowerCase().includes(q)
const matchesCity = p.location.city.toLowerCase().includes(q)
const matchesStreet = p.address.street.toLowerCase().includes(q)
if (!matchesTitle && !matchesCity && !matchesStreet) return false
}
return true
})
const sourceTypeFilters: { value: ResultType | 'ALL'; label: string; color: string }[] = [
{ value: 'ALL', label: 'Alle', color: '#6b7280' },
{ value: ResultType.VERIFIED_PORTFOLIO, label: 'Verified Portfolio', color: '#1e3a5f' },
{ value: ResultType.EXTERNAL_MARKET, label: 'Marktinserate', color: '#d97706' },
{ value: ResultType.FUTURE_AVAILABILITY, label: 'Zukunftssignale', color: '#7c3aed' },
]
return (
<Box>
{/* Page Header */}
<Box sx={{ bgcolor: 'white', borderBottom: '1px solid', borderColor: 'divider', px: 3, py: 2 }} className="flex items-center justify-between">
<Box className="flex items-center gap-2">
<Typography variant="h5" fontWeight={700} color="text.primary">Objekte</Typography>
<Chip label={properties.length} size="small" sx={{ bgcolor: '#1e3a5f', color: 'white', fontWeight: 700 }} />
</Box>
<Tooltip title="In Entwicklung">
<span>
<button
disabled
style={{
display: 'flex',
alignItems: 'center',
gap: 6,
padding: '6px 16px',
border: 'none',
borderRadius: 4,
background: '#1e3a5f',
color: 'white',
cursor: 'not-allowed',
opacity: 0.5,
fontSize: 14,
fontWeight: 500,
}}
>
<Plus size={16} />
Neues Objekt
</button>
</span>
</Tooltip>
</Box>
{/* Content */}
<Box sx={{ px: 3, py: 3 }} className="flex flex-col gap-3">
{/* Filter Bar */}
<Card sx={{ elevation: 1, p: 1.5 }}>
<Box className="flex flex-col gap-2">
{/* Row 1: Source type chips */}
<Box className="flex items-center gap-2 flex-wrap">
{sourceTypeFilters.map(f => (
<Chip
key={f.value}
label={f.label}
variant={selectedResultType === f.value ? 'filled' : 'outlined'}
size="small"
onClick={() => setSelectedResultType(f.value)}
sx={
selectedResultType === f.value
? { bgcolor: f.color, color: 'white', borderColor: f.color, fontWeight: 600, cursor: 'pointer' }
: { borderColor: f.color, color: f.color, cursor: 'pointer' }
}
/>
))}
</Box>
{/* Row 2: Asset type select + search */}
<Box className="flex items-center gap-2">
<Select
value={selectedAssetType}
onChange={e => setSelectedAssetType(e.target.value as AssetType | 'ALL')}
size="small"
sx={{ minWidth: 160 }}
>
<MenuItem value="ALL">Alle Typen</MenuItem>
{Object.values(AssetType).map(t => (
<MenuItem key={t} value={t}>{getAssetTypeLabel(t)}</MenuItem>
))}
</Select>
<TextField
value={searchQuery}
onChange={e => setSearchQuery(e.target.value)}
placeholder="Suche nach Titel, Stadt, Strasse…"
size="small"
sx={{ ml: 'auto', minWidth: 260 }}
/>
</Box>
</Box>
</Card>
{/* Properties Table */}
{filtered.length === 0 ? (
<EmptyState title="Keine Objekte gefunden" description="Passen Sie die Filter an, um Ergebnisse anzuzeigen." />
) : (
<Card sx={{ elevation: 1 }}>
<Table stickyHeader size="small">
<TableHead>
<TableRow sx={{ bgcolor: 'grey.50' }}>
<TableCell><Typography variant="caption" fontWeight={600}>Objekt</Typography></TableCell>
<TableCell><Typography variant="caption" fontWeight={600}>Typ</Typography></TableCell>
<TableCell><Typography variant="caption" fontWeight={600}>Standort</Typography></TableCell>
<TableCell><Typography variant="caption" fontWeight={600}>Fläche</Typography></TableCell>
<TableCell><Typography variant="caption" fontWeight={600}>Miete/m²</Typography></TableCell>
<TableCell><Typography variant="caption" fontWeight={600}>Quelle</Typography></TableCell>
<TableCell><Typography variant="caption" fontWeight={600}>Konfidenz</Typography></TableCell>
<TableCell><Typography variant="caption" fontWeight={600}>Datenqualität</Typography></TableCell>
<TableCell><Typography variant="caption" fontWeight={600}>Verfügbarkeit</Typography></TableCell>
<TableCell><Typography variant="caption" fontWeight={600}>Aktionen</Typography></TableCell>
</TableRow>
</TableHead>
<TableBody>
{filtered.map(property => {
const hasCritical = property.dataQuality.missingCriticalFields.length > 0
return (
<TableRow
key={property.id}
hover
sx={hasCritical ? { bgcolor: 'rgba(192,57,43,0.04)' } : {}}
>
{/* Objekt */}
<TableCell>
<Typography variant="body2" fontWeight={500}>{property.title}</Typography>
<Typography variant="caption" color="text.secondary">
{property.address.street} {property.address.houseNumber}, {property.address.city}
</Typography>
</TableCell>
{/* Typ */}
<TableCell>
<Chip
label={getAssetTypeLabel(property.assetType)}
size="small"
sx={{ bgcolor: getAssetTypeColor(property.assetType), color: 'white', fontSize: 11 }}
/>
</TableCell>
{/* Standort */}
<TableCell>
<Typography variant="body2">{property.location.city}</Typography>
{property.location.canton && (
<Typography variant="caption" color="text.secondary">{property.location.canton}</Typography>
)}
</TableCell>
{/* Fläche */}
<TableCell>
<Typography variant="body2">{property.areaSqm.toLocaleString('de-CH')} m²</Typography>
</TableCell>
{/* Miete/m² */}
<TableCell>
<Typography variant="body2">CHF {property.rentPricePerSqm}</Typography>
</TableCell>
{/* Quelle */}
<TableCell>
<Chip
label={getResultTypeLabel(property.resultType)}
size="small"
sx={{ bgcolor: getResultTypeColor(property.resultType), color: 'white', fontSize: 11 }}
/>
</TableCell>
{/* Konfidenz */}
<TableCell>
<Typography
variant="body2"
fontWeight={600}
sx={{ color: getConfidenceColor(property.confidenceScore) }}
>
{Math.round(property.confidenceScore * 100)}%
</Typography>
</TableCell>
{/* Datenqualität */}
<TableCell>
<Tooltip
title={
<Box>
{property.dataQuality.missingCriticalFields.length > 0 && (
<Box>
<Typography variant="caption" fontWeight={600}>Kritische Felder fehlen:</Typography>
{property.dataQuality.missingCriticalFields.map(f => (
<Typography key={f} variant="caption" display="block"> {f}</Typography>
))}
</Box>
)}
{property.dataQuality.warnings.length > 0 && (
<Box mt={0.5}>
<Typography variant="caption" fontWeight={600}>Warnungen:</Typography>
{property.dataQuality.warnings.map((w, i) => (
<Typography key={i} variant="caption" display="block"> {w}</Typography>
))}
</Box>
)}
{property.dataQuality.missingCriticalFields.length === 0 && property.dataQuality.warnings.length === 0 && (
<Typography variant="caption">Keine Probleme</Typography>
)}
</Box>
}
>
<Box sx={{ width: 80 }}>
<LinearProgress
variant="determinate"
value={property.dataQuality.score * 100}
color={getQualityColor(property.dataQuality.score)}
sx={{ height: 6, borderRadius: 3 }}
/>
<Typography variant="caption" color="text.secondary">
{Math.round(property.dataQuality.score * 100)}%
</Typography>
</Box>
</Tooltip>
</TableCell>
{/* Verfügbarkeit */}
<TableCell>
<Chip
label={getAvailabilityLabel(property.availabilityStatus)}
color={getAvailabilityColor(property.availabilityStatus)}
size="small"
/>
</TableCell>
{/* Aktionen */}
<TableCell>
<Box className="flex items-center gap-1">
<Tooltip title="Details (in Entwicklung)">
<span>
<IconButton size="small" disabled>
<Eye size={16} />
</IconButton>
</span>
</Tooltip>
<Tooltip title="Mehr Aktionen (in Entwicklung)">
<span>
<IconButton size="small" disabled>
<MoreHorizontal size={16} />
</IconButton>
</span>
</Tooltip>
</Box>
</TableCell>
</TableRow>
)
})}
</TableBody>
</Table>
</Card>
)}
</Box>
</Box>
)
}
+283
View File
@@ -0,0 +1,283 @@
import { Box, Card, Chip, LinearProgress, Table, TableBody, TableCell, TableHead, TableRow, Tooltip, Typography } from '@mui/material'
import { useQuery } from '@tanstack/react-query'
import { AlertTriangle, BarChart2, Building2, Target } from 'lucide-react'
import { SectionContainer, LoadingPage, ErrorState } from '../../components/ui'
import { propertyService } from '../../services/propertyService'
import { matchService } from '../../services/matchService'
import { governanceService } from '../../services/governanceService'
import { ResultType, MatchStrength } from '../../domain/enums'
import type { ActivityEventType } from '../../services/governanceService'
function getMatchStrengthColor(strength: MatchStrength): 'success' | 'warning' | 'error' {
if (strength === MatchStrength.STRONG) return 'success'
if (strength === MatchStrength.MODERATE) return 'warning'
return 'error'
}
function getMatchStrengthLabel(strength: MatchStrength): string {
if (strength === MatchStrength.STRONG) return 'Stark'
if (strength === MatchStrength.MODERATE) return 'Mittel'
return 'Schwach'
}
function getEventDescription(type: ActivityEventType): string {
switch (type) {
case 'PROPERTY_CREATED': return 'hat ein Objekt erstellt'
case 'PROPERTY_UPDATED': return 'hat ein Objekt aktualisiert'
case 'MATCH_APPROVED': return 'hat einen Match genehmigt'
case 'MATCH_REJECTED': return 'hat einen Match abgelehnt'
case 'SIGNAL_VERIFIED': return 'hat ein Signal verifiziert'
case 'NEED_CREATED': return 'hat einen Bedarf erstellt'
case 'REVIEW_REQUESTED': return 'hat eine Überprüfung angefordert'
}
}
function getEventColor(type: ActivityEventType): string {
switch (type) {
case 'PROPERTY_CREATED': return '#1e3a5f'
case 'PROPERTY_UPDATED': return '#1e3a5f'
case 'MATCH_APPROVED': return '#1a7a4a'
case 'MATCH_REJECTED': return '#c0392b'
case 'SIGNAL_VERIFIED': return '#7c3aed'
case 'NEED_CREATED': return '#d97706'
case 'REVIEW_REQUESTED': return '#d97706'
}
}
function formatTimeAgo(dateStr: string): string {
const diff = Date.now() - new Date(dateStr).getTime()
const hours = Math.floor(diff / 3600000)
const days = Math.floor(hours / 24)
if (hours < 1) return 'vor weniger als 1 Stunde'
if (hours < 24) return `vor ${hours} Stunde${hours > 1 ? 'n' : ''}`
return `vor ${days} Tag${days > 1 ? 'en' : ''}`
}
export default function SupplyDashboard() {
const { data: propResp, isLoading: propLoading, error: propError } = useQuery({
queryKey: ['properties'],
queryFn: () => propertyService.getAll(),
})
const { data: matchResp, isLoading: matchLoading, error: matchError } = useQuery({
queryKey: ['matches'],
queryFn: () => matchService.getAll(),
})
const { data: activityResp, isLoading: activityLoading, error: activityError } = useQuery({
queryKey: ['activity', 'org-wincasa'],
queryFn: () => governanceService.getActivityLog('org-wincasa'),
})
if (propLoading || matchLoading || activityLoading) return <LoadingPage />
if (propError || matchError || activityError) return <ErrorState />
const properties = propResp?.data ?? []
const matches = matchResp?.data ?? []
const activities = activityResp?.data ?? []
const avgQuality = properties.length
? properties.reduce((sum, p) => sum + p.dataQuality.score, 0) / properties.length
: 0
const pendingReview = properties.filter(p => p.dataQuality.missingCriticalFields.length > 0).length
const avgQualityColor = avgQuality >= 0.8 ? 'success.main' : avgQuality >= 0.6 ? 'warning.main' : 'error.main'
const verifiedCount = properties.filter(p => p.resultType === ResultType.VERIFIED_PORTFOLIO).length
const marketCount = properties.filter(p => p.resultType === ResultType.EXTERNAL_MARKET).length
const futureCount = properties.filter(p => p.resultType === ResultType.FUTURE_AVAILABILITY).length
const topMatches = [...matches].sort((a, b) => b.matchScore - a.matchScore).slice(0, 3)
return (
<Box>
{/* Page Header */}
<Box sx={{ bgcolor: 'white', borderBottom: '1px solid', borderColor: 'divider', px: 3, py: 2 }}>
<Typography variant="h5" fontWeight={700} color="text.primary">Supply Dashboard</Typography>
<Typography variant="body2" color="text.secondary">Portfolioübersicht und aktuelle Kennzahlen</Typography>
</Box>
{/* Content */}
<Box sx={{ px: 3, py: 3 }} className="flex flex-col gap-4">
{/* Section 1 - KPI Cards */}
<Box className="grid grid-cols-4 gap-4">
{/* Objekte */}
<Card sx={{ elevation: 1, p: 2.5 }}>
<Box className="flex flex-col gap-1">
<Box className="flex items-center justify-between">
<Typography variant="overline" color="text.secondary" lineHeight={1.4}>Objekte</Typography>
<Building2 size={20} color="#1e3a5f" />
</Box>
<Typography variant="h3" fontWeight={700} color="text.primary">{properties.length}</Typography>
<Typography variant="caption" color="text.secondary">Gesamtportfolio</Typography>
</Box>
</Card>
{/* Aktive Matches */}
<Card sx={{ elevation: 1, p: 2.5 }}>
<Box className="flex flex-col gap-1">
<Box className="flex items-center justify-between">
<Typography variant="overline" color="text.secondary" lineHeight={1.4}>Aktive Matches</Typography>
<Target size={20} color="#1a7a4a" />
</Box>
<Typography variant="h3" fontWeight={700} color="text.primary">{matches.length}</Typography>
<Typography variant="caption" color="text.secondary">KI-generierte Matches</Typography>
</Box>
</Card>
{/* Ø Datenqualität */}
<Card sx={{ elevation: 1, p: 2.5 }}>
<Box className="flex flex-col gap-1">
<Box className="flex items-center justify-between">
<Typography variant="overline" color="text.secondary" lineHeight={1.4}>Ø Datenqualität</Typography>
<BarChart2 size={20} color={avgQuality >= 0.8 ? '#1a7a4a' : avgQuality >= 0.6 ? '#d97706' : '#c0392b'} />
</Box>
<Typography variant="h3" fontWeight={700} sx={{ color: avgQualityColor }}>
{Math.round(avgQuality * 100)}%
</Typography>
<Typography variant="caption" color="text.secondary">Durchschnittlicher Score</Typography>
</Box>
</Card>
{/* Prüfungen ausstehend */}
<Card sx={{ elevation: 1, p: 2.5 }}>
<Box className="flex flex-col gap-1">
<Box className="flex items-center justify-between">
<Typography variant="overline" color="text.secondary" lineHeight={1.4}>Prüfungen ausstehend</Typography>
<AlertTriangle size={20} color="#d97706" />
</Box>
<Typography variant="h3" fontWeight={700} sx={{ color: pendingReview > 0 ? 'warning.main' : 'text.primary' }}>
{pendingReview}
</Typography>
<Typography variant="caption" color="text.secondary">Kritische Felder fehlen</Typography>
</Box>
</Card>
</Box>
{/* Section 2 - Portfolio Overview */}
<Box className="grid grid-cols-3 gap-4">
<Card sx={{ elevation: 1, borderTop: '4px solid #1e3a5f', p: 2.5 }}>
<Typography variant="h4" fontWeight={700} color="text.primary">{verifiedCount}</Typography>
<Typography variant="body2" color="text.secondary">Verified Portfolio</Typography>
</Card>
<Card sx={{ elevation: 1, borderTop: '4px solid #d97706', p: 2.5 }}>
<Typography variant="h4" fontWeight={700} color="text.primary">{marketCount}</Typography>
<Typography variant="body2" color="text.secondary">Marktinserate</Typography>
</Card>
<Card sx={{ elevation: 1, borderTop: '4px solid #7c3aed', p: 2.5 }}>
<Typography variant="h4" fontWeight={700} color="text.primary">{futureCount}</Typography>
<Typography variant="body2" color="text.secondary">Zukunftssignale</Typography>
</Card>
</Box>
{/* Section 3 - Recent Matches */}
<SectionContainer title="Aktuelle Matches">
<Card sx={{ elevation: 1 }}>
<Table>
<TableHead>
<TableRow sx={{ bgcolor: 'grey.50' }}>
<TableCell><Typography variant="caption" fontWeight={600}>Objekt</Typography></TableCell>
<TableCell><Typography variant="caption" fontWeight={600}>Unternehmen</Typography></TableCell>
<TableCell><Typography variant="caption" fontWeight={600}>Score</Typography></TableCell>
<TableCell><Typography variant="caption" fontWeight={600}>Stärke</Typography></TableCell>
<TableCell><Typography variant="caption" fontWeight={600}>Aktion</Typography></TableCell>
</TableRow>
</TableHead>
<TableBody>
{topMatches.map(match => {
const property = properties.find(p => p.id === match.propertyId)
return (
<TableRow key={match.id} hover>
<TableCell>
<Typography variant="body2" fontWeight={500}>{property?.title ?? match.propertyId}</Typography>
</TableCell>
<TableCell>
<Typography variant="body2" color="text.secondary">{match.needId}</Typography>
</TableCell>
<TableCell>
<Box className="flex items-center gap-2">
<Typography variant="body2" fontWeight={700}>{match.matchScore}</Typography>
<Box sx={{ width: 80 }}>
<LinearProgress
variant="determinate"
value={match.matchScore}
color={match.matchStrength === MatchStrength.STRONG ? 'success' : match.matchStrength === MatchStrength.MODERATE ? 'warning' : 'error'}
/>
</Box>
</Box>
</TableCell>
<TableCell>
<Chip
label={getMatchStrengthLabel(match.matchStrength)}
color={getMatchStrengthColor(match.matchStrength)}
size="small"
/>
</TableCell>
<TableCell>
<Tooltip title="Details-Seite in Entwicklung">
<span>
<button
disabled
style={{
padding: '4px 12px',
border: '1px solid rgba(0,0,0,0.23)',
borderRadius: 4,
background: 'transparent',
cursor: 'not-allowed',
opacity: 0.5,
fontSize: 13,
}}
>
Details
</button>
</span>
</Tooltip>
</TableCell>
</TableRow>
)
})}
</TableBody>
</Table>
</Card>
</SectionContainer>
{/* Section 4 - Activity Log */}
<SectionContainer title="Aktivitäten">
<Card sx={{ elevation: 1, p: 2 }}>
<Box className="flex flex-col gap-3">
{activities.slice(0, 5).map(event => (
<Box key={event.id} className="flex items-center gap-3">
<Box
sx={{
width: 32,
height: 32,
borderRadius: '50%',
bgcolor: getEventColor(event.type),
flexShrink: 0,
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
}}
>
<Building2 size={14} color="white" />
</Box>
<Box className="flex-1">
<Typography variant="body2">
<strong>{event.performedBy}</strong> {getEventDescription(event.type)}
</Typography>
{event.notes && (
<Typography variant="caption" color="text.secondary">{event.notes}</Typography>
)}
</Box>
<Typography variant="caption" color="text.secondary" sx={{ flexShrink: 0 }}>
{formatTimeAgo(event.createdAt)}
</Typography>
</Box>
))}
</Box>
</Card>
</SectionContainer>
</Box>
</Box>
)
}