feat: F014 compare view — side-by-side decision table with AI summary

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
Benjamin Sutter
2026-05-16 14:28:06 +02:00
parent 2cb29a1920
commit 2753d1717c
14 changed files with 884 additions and 350 deletions
+133
View File
@@ -0,0 +1,133 @@
import { useState } from 'react'
import { Alert, Box, Chip, CircularProgress, Collapse, Typography } from '@mui/material'
import { ChevronDown, ChevronUp, Trophy, TrendingDown, ShieldCheck, AlertTriangle, Info, ArrowRight } from 'lucide-react'
import type { ComparisonSummary } from '../../services/aiService'
interface Props {
summary?: ComparisonSummary
isLoading: boolean
}
export function AICompareSummary({ summary, isLoading }: Props) {
const [open, setOpen] = useState(true)
return (
<Box sx={{ mb: 2, border: '1px solid #e2e8f0', borderRadius: 1, overflow: 'hidden' }}>
<Box
onClick={() => setOpen(v => !v)}
sx={{
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
px: 2,
py: 1.25,
bgcolor: '#f8fafc',
cursor: 'pointer',
'&:hover': { bgcolor: '#f1f5f9' },
}}
>
<Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
<Typography variant="subtitle2" sx={{ fontWeight: 700 }}>AI Vergleichs-Zusammenfassung</Typography>
<Chip label="Beta" size="small" sx={{ fontSize: 10, bgcolor: '#ede9fe', color: '#6d28d9' }} />
</Box>
{open ? <ChevronUp size={16} /> : <ChevronDown size={16} />}
</Box>
<Collapse in={open}>
<Box sx={{ p: 2 }}>
{isLoading && (
<Box sx={{ display: 'flex', alignItems: 'center', gap: 1, py: 1 }}>
<CircularProgress size={16} />
<Typography variant="body2" color="text.secondary">Analyse wird erstellt</Typography>
</Box>
)}
{!isLoading && summary && (
<Box sx={{ display: 'flex', flexDirection: 'column', gap: 1.5 }}>
{/* Strongest option */}
<Box sx={{ display: 'flex', gap: 1, alignItems: 'flex-start' }}>
<Trophy size={16} color="#1a7a4a" style={{ flexShrink: 0, marginTop: 2 }} />
<Box>
<Typography variant="caption" sx={{ fontWeight: 600, color: '#64748b', display: 'block' }}>Stärkstes Match</Typography>
<Typography variant="body2" sx={{ fontWeight: 600 }}>{summary.strongestOption.label}</Typography>
<Typography variant="caption" color="text.secondary">{summary.strongestOption.reason}</Typography>
</Box>
</Box>
{/* Best value */}
{summary.bestValue && (
<Box sx={{ display: 'flex', gap: 1, alignItems: 'flex-start' }}>
<TrendingDown size={16} color="#1e3a5f" style={{ flexShrink: 0, marginTop: 2 }} />
<Box>
<Typography variant="caption" sx={{ fontWeight: 600, color: '#64748b', display: 'block' }}>Bestes Preis-Leistungs-Verhältnis</Typography>
<Typography variant="body2" sx={{ fontWeight: 600 }}>{summary.bestValue.label}</Typography>
<Typography variant="caption" color="text.secondary">{summary.bestValue.reason}</Typography>
</Box>
</Box>
)}
{/* Highest confidence */}
<Box sx={{ display: 'flex', gap: 1, alignItems: 'flex-start' }}>
<ShieldCheck size={16} color="#0891b2" style={{ flexShrink: 0, marginTop: 2 }} />
<Box>
<Typography variant="caption" sx={{ fontWeight: 600, color: '#64748b', display: 'block' }}>Höchste Datenkonfidenz</Typography>
<Typography variant="body2" sx={{ fontWeight: 600 }}>
{summary.highestConfidence.label}
<Typography component="span" variant="caption" color="text.secondary" sx={{ ml: 0.5 }}>
({Math.round(summary.highestConfidence.confidenceLevel * 100)}%)
</Typography>
</Typography>
</Box>
</Box>
{/* Tradeoffs */}
{summary.biggestTradeoffs.length > 0 && (
<Box sx={{ display: 'flex', gap: 1, alignItems: 'flex-start' }}>
<AlertTriangle size={16} color="#d97706" style={{ flexShrink: 0, marginTop: 2 }} />
<Box>
<Typography variant="caption" sx={{ fontWeight: 600, color: '#64748b', display: 'block' }}>Wichtigste Abwägungen</Typography>
{summary.biggestTradeoffs.map((t, i) => (
<Typography key={i} variant="caption" color="text.secondary" sx={{ display: 'block' }}>· {t}</Typography>
))}
</Box>
</Box>
)}
{/* Missing data */}
{summary.missingDataWarnings.length > 0 && (
<Box sx={{ display: 'flex', gap: 1, alignItems: 'flex-start' }}>
<Info size={16} color="#c0392b" style={{ flexShrink: 0, marginTop: 2 }} />
<Box>
<Typography variant="caption" sx={{ fontWeight: 600, color: '#64748b', display: 'block' }}>Fehlende Informationen</Typography>
{summary.missingDataWarnings.map((w, i) => (
<Typography key={i} variant="caption" color="error" sx={{ display: 'block' }}>· {w}</Typography>
))}
</Box>
</Box>
)}
{/* Next step */}
<Box sx={{ display: 'flex', gap: 1, alignItems: 'flex-start', pt: 0.5, borderTop: '1px solid #f1f5f9', mt: 0.5 }}>
<ArrowRight size={16} color="#1e3a5f" style={{ flexShrink: 0, marginTop: 2 }} />
<Box>
<Typography variant="caption" sx={{ fontWeight: 600, color: '#64748b', display: 'block' }}>Empfohlener nächster Schritt</Typography>
<Typography variant="body2">{summary.recommendedNextStep}</Typography>
</Box>
</Box>
</Box>
)}
{!isLoading && !summary && (
<Alert severity="info" sx={{ py: 0.5 }}>
Mindestens 2 Ergebnisse auswählen, um die Zusammenfassung zu generieren.
</Alert>
)}
<Typography variant="caption" color="text.secondary" sx={{ display: 'block', mt: 1.5, fontStyle: 'italic' }}>
Diese Zusammenfassung basiert ausschliesslich auf den vorliegenden Daten und trifft keine endgültige Entscheidung.
</Typography>
</Box>
</Collapse>
</Box>
)
}
+48
View File
@@ -0,0 +1,48 @@
import type { ReactNode } from 'react'
import { Box, Tooltip, Typography } from '@mui/material'
import { Info } from 'lucide-react'
export type CellHighlight = 'best' | 'worst' | 'critical' | 'future' | 'none'
interface Props {
highlight?: CellHighlight
icon?: ReactNode
iconTooltip?: string
children: ReactNode
}
const HIGHLIGHT_SX: Record<CellHighlight, object> = {
best: { bgcolor: '#f0fdf4', borderLeft: '3px solid #1a7a4a' },
worst: { bgcolor: '#fef3c7', borderLeft: '3px solid #d97706' },
critical: { bgcolor: '#fef2f2', borderLeft: '3px solid #c0392b' },
future: { bgcolor: '#faf5ff', borderLeft: '3px solid #7c3aed' },
none: {},
}
export function CompareCell({ highlight = 'none', icon, iconTooltip, children }: Props) {
return (
<Box sx={{ display: 'flex', alignItems: 'flex-start', gap: 0.75, ...HIGHLIGHT_SX[highlight] }}>
{icon && (
iconTooltip
? <Tooltip title={iconTooltip}><Box sx={{ flexShrink: 0, display: 'flex', mt: 0.25 }}>{icon}</Box></Tooltip>
: <Box sx={{ flexShrink: 0, display: 'flex', mt: 0.25 }}>{icon}</Box>
)}
<Box sx={{ flex: 1, minWidth: 0 }}>{children}</Box>
</Box>
)
}
export function MissingDataCell({ reason }: { reason?: string }) {
return (
<Box sx={{ display: 'flex', alignItems: 'center', gap: 0.5 }}>
<Tooltip title={reason ?? 'Keine Daten vorhanden — kann Konfidenz beeinflussen'}>
<Box sx={{ display: 'flex', alignItems: 'center' }}>
<Info size={12} color="#94a3b8" />
</Box>
</Tooltip>
<Typography variant="body2" sx={{ color: '#94a3b8', fontStyle: 'italic' }}>
Nicht verfügbar
</Typography>
</Box>
)
}
@@ -0,0 +1,85 @@
import { Box, Chip, IconButton, Tooltip, Typography } from '@mui/material'
import { X, AlertTriangle } from 'lucide-react'
import type { UnifiedMatchResult } from '../../domain/unifiedResult'
const TYPE_META: Record<string, { label: string; color: string }> = {
VERIFIED_PORTFOLIO: { label: 'Verified Portfolio', color: '#1e3a5f' },
EXTERNAL_MARKET: { label: 'Marktinserat', color: '#d97706' },
FUTURE_AVAILABILITY: { label: 'Zukunftssignal', color: '#7c3aed' },
}
const SCORE_COLOR = (s: number) => s >= 78 ? '#1a7a4a' : s >= 52 ? '#d97706' : '#c0392b'
interface Props {
item: UnifiedMatchResult
onRemove: () => void
}
export function CompareColumnHeader({ item, onRemove }: Props) {
const meta = TYPE_META[item.resultType] ?? { label: item.resultType, color: '#64748b' }
const prop = item.resultType !== 'FUTURE_AVAILABILITY' ? (item as any).property : null
const sig = item.resultType === 'FUTURE_AVAILABILITY' ? (item as any).signal : null
const title = prop?.title ?? sig?.companyName ?? sig?.locationHint ?? ''
const subtitle = prop?.location?.city ?? sig?.locationHint ?? ''
const availability = prop?.availabilityDate ?? (sig ? `~${sig.timeHorizonMonths} Monate` : null)
const confidence = Math.round(item.match.confidenceLevel * 100)
const source = prop?.sourceLabel ?? sig?.source?.type ?? ''
return (
<Box sx={{ p: 0.5 }}>
<Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', mb: 1 }}>
<Chip label={meta.label} size="small" sx={{ bgcolor: meta.color, color: 'white', fontWeight: 600, fontSize: 10 }} />
<IconButton size="small" onClick={onRemove} sx={{ p: 0.25, ml: 1 }}>
<X size={14} />
</IconButton>
</Box>
<Typography variant="subtitle2" sx={{ fontWeight: 700, mb: 0.25, lineHeight: 1.3 }}>
{title}
</Typography>
<Typography variant="caption" color="text.secondary" sx={{ display: 'block', mb: 1 }}>
{subtitle}
</Typography>
<Box sx={{ display: 'flex', alignItems: 'baseline', gap: 0.5, mb: 0.5 }}>
<Typography variant="h4" sx={{ fontWeight: 800, color: SCORE_COLOR(item.matchScore), lineHeight: 1 }}>
{item.matchScore}
</Typography>
<Typography variant="caption" color="text.secondary">/100</Typography>
</Box>
<Box sx={{ display: 'flex', flexWrap: 'wrap', gap: 0.5, mt: 0.5 }}>
<Tooltip title="Konfidenz">
<Chip
label={`${confidence}% Konfidenz`}
size="small"
icon={confidence < 60 ? <AlertTriangle size={10} /> : undefined}
sx={{
fontSize: 10,
bgcolor: confidence < 60 ? '#fef3c7' : '#f0fdf4',
color: confidence < 60 ? '#92400e' : '#166534',
}}
/>
</Tooltip>
{source && source !== '' && (
<Chip label={source} size="small" sx={{ fontSize: 10 }} />
)}
{availability && (
<Chip label={availability} size="small" sx={{ fontSize: 10 }} />
)}
</Box>
{item.resultType === 'FUTURE_AVAILABILITY' && sig && (
<Box sx={{ mt: 1, p: 0.75, bgcolor: '#faf5ff', borderRadius: 1, border: '1px solid #e9d5ff' }}>
<Typography variant="caption" sx={{ color: '#7c3aed', fontWeight: 600, display: 'block' }}>
Probabilistisches Signal
</Typography>
<Typography variant="caption" color="text.secondary">
{Math.round(sig.probability * 100)}% Wahrscheinlichkeit
</Typography>
</Box>
)}
</Box>
)
}
@@ -0,0 +1,24 @@
import { Box, Button, Typography } from '@mui/material'
import { Columns2 } from 'lucide-react'
import { useNavigate } from 'react-router'
export function CompareEmptyState() {
const navigate = useNavigate()
return (
<Box sx={{ px: 3, py: 4 }}>
<Box sx={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 2, py: 8 }}>
<Columns2 size={40} color="#94a3b8" />
<Typography variant="h6" color="text.secondary" sx={{ fontWeight: 600 }}>
Keine Ergebnisse zum Vergleich
</Typography>
<Typography variant="body2" color="text.secondary" sx={{ textAlign: 'center', maxWidth: 360 }}>
Fügen Sie 24 Ergebnisse aus dem Feed, Match Detail oder Match Center zum Vergleich hinzu.
</Typography>
<Button variant="contained" size="small" onClick={() => navigate('/demand/results')}
sx={{ bgcolor: '#1e3a5f', '&:hover': { bgcolor: '#162d4a' } }}>
Zu den Suchergebnissen
</Button>
</Box>
</Box>
)
}
+4
View File
@@ -0,0 +1,4 @@
export { CompareEmptyState } from './CompareEmptyState'
export { CompareColumnHeader } from './CompareColumnHeader'
export { CompareCell, MissingDataCell } from './CompareCell'
export { AICompareSummary } from './AICompareSummary'
+47 -16
View File
@@ -1,17 +1,31 @@
import { useEffect } from 'react'
import { useNavigate } from 'react-router'
import { Box, Button, Chip, Typography } from '@mui/material'
import { Box, Button, IconButton, Typography } from '@mui/material'
import { X } from 'lucide-react'
import { useCompareStore } from '../../stores/compareStore'
import { useLayoutStore } from '../../stores/layoutStore'
const TYPE_DOT: Record<string, string> = {
VERIFIED_PORTFOLIO: '#1e3a5f',
EXTERNAL_MARKET: '#d97706',
FUTURE_AVAILABILITY: '#7c3aed',
}
export function CompareTray() {
const { compareTray, removeFromCompare, clearCompare } = useCompareStore()
const { compareItems, removeFromCompare, clearCompare } = useCompareStore()
const { setCompareTrayVisible } = useLayoutStore()
const navigate = useNavigate()
useEffect(() => {
setCompareTrayVisible(compareTray.length > 0)
}, [compareTray.length, setCompareTrayVisible])
setCompareTrayVisible(compareItems.length > 0)
}, [compareItems.length, setCompareTrayVisible])
const getTitle = (item: (typeof compareItems)[number]) => {
if (item.resultType === 'FUTURE_AVAILABILITY') {
return (item as any).signal?.companyName ?? (item as any).signal?.locationHint ?? 'Signal'
}
return (item as any).property?.title ?? `Score ${item.matchScore}`
}
return (
<Box
@@ -27,27 +41,44 @@ export function CompareTray() {
alignItems: 'center',
px: 3,
gap: 2,
transform: compareTray.length > 0 ? 'translateY(0)' : 'translateY(100%)',
transform: compareItems.length > 0 ? 'translateY(0)' : 'translateY(100%)',
transition: 'transform 0.25s ease',
}}
>
<Typography variant="caption" sx={{ color: '#fff', flexShrink: 0 }}>
Vergleich ({compareTray.length}/3)
Vergleich ({compareItems.length}/4)
</Typography>
<Box sx={{ flex: 1, display: 'flex', gap: 1, overflow: 'hidden' }}>
{compareTray.map((id, i) => (
<Chip
key={id}
label={`Objekt ${i + 1}`}
size="small"
onDelete={() => removeFromCompare(id)}
{compareItems.map((item) => (
<Box
key={item.matchId}
sx={{
bgcolor: 'rgba(255,255,255,0.15)',
color: '#fff',
'& .MuiChip-deleteIcon': { color: 'rgba(255,255,255,0.6)' },
display: 'flex',
alignItems: 'center',
gap: 0.75,
bgcolor: 'rgba(255,255,255,0.1)',
borderRadius: 1,
px: 1,
py: 0.25,
flexShrink: 0,
}}
/>
>
<Box sx={{ width: 6, height: 6, borderRadius: '50%', bgcolor: TYPE_DOT[item.resultType] ?? '#64748b', flexShrink: 0 }} />
<Typography variant="caption" sx={{ color: '#fff', maxWidth: 110, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
{getTitle(item)}
</Typography>
<Typography variant="caption" sx={{ color: 'rgba(255,255,255,0.5)', flexShrink: 0 }}>
{item.matchScore}
</Typography>
<IconButton
size="small"
onClick={() => removeFromCompare(item.matchId)}
sx={{ p: 0.25, color: 'rgba(255,255,255,0.5)', '&:hover': { color: '#fff' } }}
>
<X size={12} />
</IconButton>
</Box>
))}
</Box>
@@ -66,7 +66,7 @@ export function MatchBriefingPanel() {
label: 'Vergleichen',
actionType: 'ADD_COMPARE',
variant: 'secondary',
onClick: () => { addToCompare(property.id); navigate('/demand/compare') },
onClick: () => { addToCompare(result); navigate('/demand/compare') },
},
{
id: 'details',
+15 -18
View File
@@ -1,21 +1,18 @@
import { useNavigate } from 'react-router'
import { MatchCardCompact } from '../match-card/MatchCardCompact'
import { buildMatchCardViewModel } from '../../features/matching/matchCardAdapter'
import { useCompareStore } from '../../stores/compareStore'
import type { UnifiedMatchResult } from '../../domain/unifiedResult'
import type { MatchCardAction } from '../match-card/MatchCardViewModel'
interface Props {
result: UnifiedMatchResult
isInCompare: boolean
onCompare: (propertyId: string) => void
}
export function UnifiedResultCard({ result, isInCompare, onCompare }: Props) {
export function UnifiedResultCard({ result }: Props) {
const navigate = useNavigate()
const isFuture = result.resultType === 'FUTURE_AVAILABILITY'
const compareId = !isFuture
? (result as { property: { id: string } }).property.id
: ''
const { addToCompare, removeFromCompare, isInCompare, isFull } = useCompareStore()
const inCompare = isInCompare(result.matchId)
const actions: MatchCardAction[] = [
{
@@ -26,17 +23,17 @@ export function UnifiedResultCard({ result, isInCompare, onCompare }: Props) {
disabled: true,
onClick: () => {},
},
...(!isFuture
? [
{
id: 'compare',
label: 'Vergleichen',
actionType: 'ADD_COMPARE' as const,
variant: (isInCompare ? 'primary' : 'secondary') as 'primary' | 'secondary',
onClick: () => onCompare(compareId),
},
]
: []),
{
id: 'compare',
label: inCompare ? 'Im Vergleich' : 'Vergleichen',
actionType: 'ADD_COMPARE',
variant: inCompare ? 'primary' : 'secondary',
disabled: !inCompare && isFull(),
onClick: () => {
if (inCompare) removeFromCompare(result.matchId)
else addToCompare(result)
},
},
{
id: 'details',
label: 'Details',
+4 -17
View File
@@ -3,27 +3,14 @@ import { UnifiedResultCard } from './UnifiedResultCard'
interface Props {
results: UnifiedMatchResult[]
isInCompare: (id: string) => boolean
onCompare: (propertyId: string) => void
}
export function UnifiedResultFeed({ results, isInCompare, onCompare }: Props) {
export function UnifiedResultFeed({ results }: Props) {
return (
<>
{results.map(result => {
const compareId =
result.resultType !== 'FUTURE_AVAILABILITY'
? (result as { property: { id: string } }).property.id
: ''
return (
<UnifiedResultCard
key={result.matchId}
result={result}
isInCompare={compareId ? isInCompare(compareId) : false}
onCompare={onCompare}
/>
)
})}
{results.map(result => (
<UnifiedResultCard key={result.matchId} result={result} />
))}
</>
)
}
+403 -230
View File
@@ -1,310 +1,483 @@
import type { ReactNode } from 'react'
import {
Alert,
Box,
Button,
Card,
Chip,
Typography,
LinearProgress,
Stack,
Table,
TableBody,
TableCell,
TableHead,
TableRow,
CircularProgress,
Stack,
Typography,
} from '@mui/material'
import { X } from 'lucide-react'
import { useQuery } from '@tanstack/react-query'
import { Trophy, AlertTriangle, AlertOctagon, Zap, CheckCircle2, XCircle } from 'lucide-react'
import { useNavigate } from 'react-router'
import { propertyService } from '../../services/propertyService'
import { useQuery } from '@tanstack/react-query'
import { useCompareStore } from '../../stores/compareStore'
import { EmptyState } from '../../components/ui'
import { ResultType, RiskLevel } from '../../domain/enums'
import type { Property } from '../../domain/property'
import { aiService } from '../../services/aiService'
import {
CompareEmptyState,
CompareColumnHeader,
CompareCell,
MissingDataCell,
AICompareSummary,
} from '../../components/compare'
import type { UnifiedMatchResult } from '../../domain/unifiedResult'
import type { VerifiedPortfolioResult, ExternalMarketResult, FutureAvailabilityResult } from '../../domain/unifiedResult'
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'
}
// ── Helpers ───────────────────────────────────────────────────────────────────
const HARD_CRITERIA = new Set(['area', 'location', 'budget', 'timing'])
const SCORE_COLOR = (s: number) => s >= 78 ? '#1a7a4a' : s >= 52 ? '#d97706' : '#c0392b'
function getProp(item: UnifiedMatchResult) {
return item.resultType !== 'FUTURE_AVAILABILITY'
? (item as VerifiedPortfolioResult | ExternalMarketResult).property
: null
}
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 getSig(item: UnifiedMatchResult) {
return item.resultType === 'FUTURE_AVAILABILITY'
? (item as FutureAvailabilityResult).signal
: null
}
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'
const TYPE_META: Record<string, { label: string; color: string }> = {
VERIFIED_PORTFOLIO: { label: 'Verified Portfolio', color: '#1e3a5f' },
EXTERNAL_MARKET: { label: 'Marktinserat', color: '#d97706' },
FUTURE_AVAILABILITY: { label: 'Zukunftssignal', color: '#7c3aed' },
}
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'
}
const RISK_LEVEL_ORDER: Record<string, number> = { CRITICAL: 0, HIGH: 1, MEDIUM: 2, LOW: 3 }
// ── Row label cell ────────────────────────────────────────────────────────────
const LABEL_SX = {
position: 'sticky' as const,
left: 0,
bgcolor: 'white',
zIndex: 1,
width: 200,
minWidth: 200,
color: '#64748b',
fontSize: 13,
fontWeight: 600,
borderRight: '1px solid #e2e8f0',
verticalAlign: 'top',
py: 1.5,
}
interface CompareRow {
label: string
getValue: (p: Property) => string | number | null
format?: (v: string | number | null, p: Property) => ReactNode
isHigherBetter?: boolean
isLowerBetter?: boolean
const DATA_SX = {
borderLeft: '1px solid #f1f5f9',
minWidth: 220,
verticalAlign: 'top',
py: 1.5,
}
function NumericCell({ value, isBest }: { value: ReactNode; isBest: boolean }) {
return (
<TableCell
sx={{
bgcolor: isBest ? '#f0fdf4' : 'transparent',
fontWeight: isBest ? 700 : 400,
color: isBest ? '#1a7a4a' : 'inherit',
borderLeft: '1px solid #f1f5f9',
}}
>
{value}
</TableCell>
)
}
// ── Main component ────────────────────────────────────────────────────────────
export default function Compare() {
const navigate = useNavigate()
const { compareTray, removeFromCompare, clearCompare } = useCompareStore()
const { compareItems, removeFromCompare, clearCompare } = useCompareStore()
const { data: propResp, isLoading } = useQuery({
queryKey: ['properties'],
queryFn: () => propertyService.getAll(),
const { data: aiSummary, isLoading: aiLoading } = useQuery({
queryKey: ['ai-compare', compareItems.map(i => i.matchId)],
queryFn: () => aiService.summarizeComparison(compareItems),
enabled: compareItems.length >= 2,
select: r => r.data,
staleTime: Infinity,
})
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 !== undefined)
if (isLoading) {
return (
<Box sx={{ display: 'flex', justifyContent: 'center', alignItems: 'center', py: 12 }}>
<CircularProgress />
</Box>
)
}
if (compareTray.length === 0) {
if (compareItems.length === 0) {
return (
<Box>
<Box sx={{ bgcolor: 'white', borderBottom: '1px solid #e2e8f0', px: 3, py: 2 }}>
<Typography variant="h5" sx={{ 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>
<CompareEmptyState />
</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>
// ── Highlight indices ──────────────────────────────────────────────────────
const bestScoreIdx = compareItems.reduce(
(best, item, i) => item.matchScore > compareItems[best].matchScore ? i : best, 0
)
const worstConfIdx = compareItems.reduce(
(worst, item, i) => item.match.confidenceLevel < compareItems[worst].match.confidenceLevel ? i : worst, 0
)
const dqScores = compareItems.map(item => getProp(item)?.dataQuality.score ?? 1)
const worstDQIdx = dqScores.indexOf(Math.min(...dqScores))
const missingCriticalCounts = compareItems.map(
item => item.match.missingData?.filter(m => m.importance === 'CRITICAL').length ?? 0
)
const maxMissingCritical = Math.max(...missingCriticalCounts)
// ── Shared render helpers ─────────────────────────────────────────────────
function row(label: string, cells: ReactNode[]) {
return (
<TableRow hover key={label}>
<TableCell sx={LABEL_SX}>{label}</TableCell>
{cells.map((cell, i) => (
<TableCell key={i} sx={DATA_SX}>{cell}</TableCell>
))}
</TableRow>
)
}
function scoreBar(value: number, label?: string) {
const color = value >= 0.8 ? '#1a7a4a' : value >= 0.6 ? '#d97706' : '#c0392b'
return (
<Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
<Box sx={{ width: 70 }}>
<LinearProgress variant="determinate" value={value * 100}
sx={{ height: 6, borderRadius: 3, '& .MuiLinearProgress-bar': { bgcolor: color } }} />
</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,
},
]
<Typography variant="caption" sx={{ color }}>{label ?? `${Math.round(value * 100)}%`}</Typography>
</Box>
)
}
return (
<Box>
{/* Page Header */}
{/* 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" sx={{ fontWeight: 700 }}>Vergleich</Typography>
<Chip label={`${orderedProperties.length} Objekte`} size="small" />
<Chip label={`${compareItems.length} Ergebnisse`} size="small" />
</Box>
<Button variant="outlined" size="small" color="error" onClick={clearCompare}>
Leeren
Vergleich leeren
</Button>
</Box>
<Box sx={{ px: 3, py: 3 }}>
{/* Mobile notice */}
<Box sx={{ display: { xs: 'block', md: 'none' }, p: 3 }}>
<Alert severity="info">
Die Vergleichsansicht ist für Desktop optimiert. Für beste Erfahrung auf einem grösseren Bildschirm öffnen.
</Alert>
</Box>
{/* Desktop table */}
<Box sx={{ display: { xs: 'none', md: 'block' }, px: 3, py: 3 }}>
{/* AI Summary */}
<AICompareSummary summary={aiSummary} isLoading={aiLoading && compareItems.length >= 2} />
<Card sx={{ overflowX: 'auto' }}>
<Table>
<Table sx={{ tableLayout: 'auto' }}>
{/* Column headers */}
<TableHead>
<TableRow sx={{ bgcolor: '#f8fafc' }}>
<TableCell sx={{ width: 180, fontWeight: 600, color: '#64748b', fontSize: 12 }}>
<TableCell sx={{ ...LABEL_SX, bgcolor: '#f8fafc', zIndex: 2, fontSize: 11, color: '#64748b', fontWeight: 600 }}>
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" sx={{ 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>
{compareItems.map(item => (
<TableCell key={item.matchId} sx={{ ...DATA_SX, bgcolor: '#f8fafc', verticalAlign: 'top' }}>
<CompareColumnHeader item={item} onRemove={() => removeFromCompare(item.matchId)} />
</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
}
}
{/* 1. Result Type */}
{row('1. Result-Typ', compareItems.map(item => {
const m = TYPE_META[item.resultType] ?? { label: item.resultType, color: '#64748b' }
return <Chip label={m.label} size="small" sx={{ bgcolor: m.color, color: 'white', fontWeight: 600, fontSize: 11 }} />
}))}
{/* 2. Source / Provenance */}
{row('2. Quelle / Provenienz', compareItems.map(item => {
const prop = getProp(item)
const sig = getSig(item)
const label = prop?.sourceLabel ?? sig?.source?.type ?? null
return label
? <Typography variant="body2">{label}</Typography>
: <MissingDataCell reason="Quellenangabe fehlt — Datenverlässlichkeit unklar" />
}))}
{/* 3. Match Score */}
{row('3. Match Score', compareItems.map((item, idx) => (
<CompareCell
highlight={idx === bestScoreIdx ? 'best' : 'none'}
icon={idx === bestScoreIdx ? <Trophy size={14} color="#1a7a4a" /> : undefined}
iconTooltip="Höchster Match Score"
>
<Box sx={{ display: 'flex', alignItems: 'baseline', gap: 0.5 }}>
<Typography variant="h5" sx={{ fontWeight: 800, color: SCORE_COLOR(item.matchScore), lineHeight: 1 }}>
{item.matchScore}
</Typography>
<Typography variant="caption" color="text.secondary">/100</Typography>
</Box>
</CompareCell>
)))}
{/* 4. Confidence Score */}
{row('4. Konfidenz', compareItems.map((item, idx) => (
<CompareCell
highlight={idx === worstConfIdx && item.match.confidenceLevel < 0.6 ? 'worst' : 'none'}
icon={idx === worstConfIdx && item.match.confidenceLevel < 0.6 ? <AlertTriangle size={14} color="#d97706" /> : undefined}
iconTooltip="Niedrigste Konfidenz"
>
{scoreBar(item.match.confidenceLevel)}
</CompareCell>
)))}
{/* 5. Data Quality Score */}
{row('5. Datenqualität', compareItems.map((item, idx) => {
const prop = getProp(item)
const dq = prop?.dataQuality.score ?? null
if (dq === null) return <MissingDataCell reason="Keine Datenqualitätsinformation verfügbar" />
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>
<CompareCell
highlight={idx === worstDQIdx && dq < 0.6 ? 'worst' : 'none'}
icon={idx === worstDQIdx && dq < 0.6 ? <AlertTriangle size={14} color="#d97706" /> : undefined}
iconTooltip="Niedrigste Datenqualität"
>
{scoreBar(dq)}
</CompareCell>
)
})}
}))}
{/* 6. Asset Type */}
{row('6. Nutzungstyp', compareItems.map(item => {
const prop = getProp(item)
const label = prop?.assetType ?? null
return label
? <Chip label={label} size="small" variant="outlined" />
: <MissingDataCell />
}))}
{/* 7. Location */}
{row('7. Standort', compareItems.map(item => {
const prop = getProp(item)
const sig = getSig(item)
const city = prop?.location?.city ?? sig?.locationHint ?? null
const district = prop?.location?.district
return city
? <Typography variant="body2">{city}{district ? `, ${district}` : ''}</Typography>
: <MissingDataCell />
}))}
{/* 8. Area */}
{row('8. Fläche', compareItems.map(item => {
const prop = getProp(item)
const sig = getSig(item)
const area = prop?.areaSqm ?? sig?.areaSqmEstimate ?? null
return area !== null
? <Typography variant="body2">{area.toLocaleString('de-CH')} m²{sig ? ' (Schätzung)' : ''}</Typography>
: <MissingDataCell />
}))}
{/* 9. Rent / Budget Fit */}
{row('9. Miete / Budget', compareItems.map(item => {
const prop = getProp(item)
if (!prop) return <MissingDataCell reason="Mietpreis nur für bestätigte Objekte verfügbar" />
return (
<Box>
<Typography variant="body2" sx={{ fontWeight: 600 }}>
CHF {prop.rentPricePerSqm}/m²
</Typography>
{prop.totalRentMonthly && (
<Typography variant="caption" color="text.secondary">
{prop.totalRentMonthly.toLocaleString('de-CH')} CHF/Monat
</Typography>
)}
</Box>
)
}))}
{/* 10. Availability / Time Horizon */}
{row('10. Verfügbarkeit', compareItems.map(item => {
const prop = getProp(item)
const sig = getSig(item)
if (prop) return <Typography variant="body2">{prop.availabilityDate}</Typography>
if (sig) return (
<CompareCell highlight="future" icon={<Zap size={14} color="#7c3aed" />} iconTooltip="Probabilistisches Signal — keine bestätigte Verfügbarkeit">
<Typography variant="body2">~{sig.timeHorizonMonths} Monate</Typography>
<Typography variant="caption" sx={{ color: '#7c3aed' }}>
{Math.round(sig.probability * 100)}% Wahrscheinlichkeit
</Typography>
</CompareCell>
)
return <MissingDataCell />
}))}
{/* 11. Hard Criteria Fit */}
{row('11. Hardkriterien', compareItems.map(item => {
const hardMatches = item.match.positiveFactors.filter(f => HARD_CRITERIA.has(f.criterion))
const total = 4
const count = hardMatches.length
const color = count >= 3 ? '#1a7a4a' : count >= 2 ? '#d97706' : '#c0392b'
return (
<Box>
<Typography variant="body2" sx={{ fontWeight: 700, color }}>
{count}/{total} erfüllt
</Typography>
<Box sx={{ display: 'flex', flexWrap: 'wrap', gap: 0.5, mt: 0.5 }}>
{hardMatches.map(f => (
<Chip key={f.criterion} label={f.criterion} size="small"
icon={<CheckCircle2 size={10} />}
sx={{ fontSize: 10, bgcolor: '#f0fdf4', color: '#166534', '& .MuiChip-icon': { color: '#1a7a4a' } }} />
))}
</Box>
</Box>
)
}))}
{/* 12. Top Soft Factors */}
{row('12. Soft Factors', compareItems.map(item => {
const softFactors = item.match.positiveFactors
.filter(f => !HARD_CRITERIA.has(f.criterion))
.slice(0, 3)
if (softFactors.length === 0) return <MissingDataCell />
return (
<Box sx={{ display: 'flex', flexWrap: 'wrap', gap: 0.5 }}>
{softFactors.map(f => (
<Chip key={f.criterion} label={f.criterion} size="small"
sx={{ fontSize: 10, bgcolor: '#eff6ff', color: '#1e40af' }} />
))}
</Box>
)
}))}
{/* 13. Main Strengths */}
{row('13. Stärken', compareItems.map(item => {
const top = item.match.positiveFactors.slice(0, 2)
if (top.length === 0) return <MissingDataCell />
return (
<Box sx={{ display: 'flex', flexDirection: 'column', gap: 0.5 }}>
{top.map((f, i) => (
<Box key={i} sx={{ display: 'flex', alignItems: 'flex-start', gap: 0.5 }}>
<CheckCircle2 size={13} color="#1a7a4a" style={{ flexShrink: 0, marginTop: 2 }} />
<Typography variant="caption" sx={{ lineHeight: 1.4 }}>{f.explanation}</Typography>
</Box>
))}
</Box>
)
}))}
{/* 14. Main Tradeoffs */}
{row('14. Abwägungen', compareItems.map(item => {
const tradeoffs = item.match.tradeoffs?.slice(0, 2) ?? []
if (tradeoffs.length === 0) return (
<Typography variant="body2" color="text.secondary">Keine signifikanten Abwägungen</Typography>
)
return (
<Box sx={{ display: 'flex', flexDirection: 'column', gap: 0.5 }}>
{tradeoffs.map((t, i) => (
<Box key={i} sx={{ display: 'flex', alignItems: 'flex-start', gap: 0.5 }}>
<AlertTriangle size={13} color="#d97706" style={{ flexShrink: 0, marginTop: 2 }} />
<Typography variant="caption" sx={{ lineHeight: 1.4 }}>{t.criterion}: {t.concern}</Typography>
</Box>
))}
</Box>
)
}))}
{/* 15. Main Risks */}
{row('15. Risiken', compareItems.map(item => {
const risks = [...(item.match.risks ?? [])].sort(
(a, b) => (RISK_LEVEL_ORDER[a.level] ?? 4) - (RISK_LEVEL_ORDER[b.level] ?? 4)
).slice(0, 2)
if (risks.length === 0) return (
<Typography variant="body2" color="text.secondary">Keine identifizierten Risiken</Typography>
)
return (
<Box sx={{ display: 'flex', flexDirection: 'column', gap: 0.5 }}>
{risks.map((r, i) => (
<Box key={i} sx={{ display: 'flex', alignItems: 'flex-start', gap: 0.5 }}>
<XCircle size={13} color={r.level === 'CRITICAL' || r.level === 'HIGH' ? '#c0392b' : '#d97706'} style={{ flexShrink: 0, marginTop: 2 }} />
<Typography variant="caption" sx={{ lineHeight: 1.4 }}>{r.description}</Typography>
</Box>
))}
</Box>
)
}))}
{/* 16. Missing Data */}
{row('16. Fehlende Daten', compareItems.map((item, idx) => {
const total = item.match.missingData?.length ?? 0
const critical = missingCriticalCounts[idx]
if (total === 0) return (
<Box sx={{ display: 'flex', alignItems: 'center', gap: 0.5 }}>
<CheckCircle2 size={14} color="#1a7a4a" />
<Typography variant="body2" sx={{ color: '#1a7a4a' }}>Vollständig</Typography>
</Box>
)
return (
<CompareCell
highlight={critical > 0 && critical === maxMissingCritical ? 'critical' : critical > 0 ? 'worst' : 'none'}
icon={critical > 0 ? <AlertOctagon size={14} color="#c0392b" /> : <AlertTriangle size={14} color="#d97706" />}
iconTooltip={critical > 0 ? 'Kritische Pflichtfelder fehlen' : 'Optionale Felder fehlen'}
>
<Typography variant="body2" sx={{ fontWeight: 600 }}>{total} fehlend</Typography>
{critical > 0 && (
<Typography variant="caption" color="error">{critical} kritisch</Typography>
)}
</CompareCell>
)
}))}
{/* 17. Future Availability Context */}
{row('17. Zukunftskontext', compareItems.map(item => {
const sig = getSig(item)
if (!sig) return (
<Typography variant="body2" color="text.secondary" sx={{ fontStyle: 'italic' }}>Nicht anwendbar</Typography>
)
return (
<CompareCell highlight="future" icon={<Zap size={14} color="#7c3aed" />} iconTooltip="Probabilistisches Zukunftssignal">
<Box sx={{ display: 'flex', flexDirection: 'column', gap: 0.25 }}>
<Typography variant="caption" sx={{ fontWeight: 600, color: '#7c3aed' }}>
{Math.round(sig.probability * 100)}% Wahrscheinlichkeit
</Typography>
<Typography variant="caption" color="text.secondary">
Sensitivität: {sig.sensitivityLevel}
</Typography>
<Typography variant="caption" color="text.secondary" sx={{ fontStyle: 'italic' }}>
{sig.disclaimer}
</Typography>
</Box>
</CompareCell>
)
}))}
{/* 18. Recommended Next Action */}
{row('18. Nächste Aktion', compareItems.map(item => {
const action = item.match.nextBestActions?.[0]
if (!action) return <MissingDataCell />
return (
<Box>
<Typography variant="body2" sx={{ fontWeight: 600 }}>{action.label}</Typography>
{action.description && (
<Typography variant="caption" color="text.secondary">{action.description}</Typography>
)}
</Box>
)
}))}
</TableBody>
</Table>
</Card>
{/* Add more prompt */}
{orderedProperties.length < 3 && (
{compareItems.length < 4 && (
<Card sx={{ p: 2.5, mt: 2, border: '2px dashed #e2e8f0', boxShadow: 'none' }}>
<Stack direction="row" sx={{ alignItems: 'center', justifyContent: 'space-between' }}>
<Box>
<Typography variant="subtitle2" sx={{ fontWeight: 600 }}>Weiteres Objekt hinzufügen</Typography>
<Typography variant="subtitle2" sx={{ fontWeight: 600 }}>Weiteres Ergebnis 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
Bis zu {4 - compareItems.length} weitere{4 - compareItems.length === 1 ? 's' : ''} Ergebnis{4 - compareItems.length === 1 ? '' : 'se'} möglich
</Typography>
</Box>
<Button variant="outlined" size="small" onClick={() => navigate('/demand/results')}>
+20 -2
View File
@@ -42,6 +42,7 @@ export default function MatchDetail() {
const isFuture = match?.resultType === 'FUTURE_AVAILABILITY'
const { data: property = null } = useQuery({
queryKey: ['property', match?.propertyId],
queryFn: () => propertyService.getById(match!.propertyId),
@@ -85,10 +86,27 @@ export default function MatchDetail() {
}
const reasons = buildReasons(match)
const compareId = property?.id ?? ''
const handleCompare = () => {
if (compareId) addToCompare(compareId)
if (match && !isFuture && property) {
addToCompare({
resultType: property.resultType === 'EXTERNAL_MARKET' ? 'EXTERNAL_MARKET' : 'VERIFIED_PORTFOLIO',
matchId: match.id,
needId: match.needId,
matchScore: match.matchScore,
match,
property,
})
} else if (match && isFuture && signal) {
addToCompare({
resultType: 'FUTURE_AVAILABILITY',
matchId: match.id,
needId: match.needId,
matchScore: match.matchScore,
match,
signal,
})
}
navigate('/demand/compare')
}
+2 -51
View File
@@ -1,9 +1,8 @@
import { useState } from 'react'
import { Box, Button, Card, Stack, Typography } from '@mui/material'
import { Box, Button, Card, Typography } from '@mui/material'
import { useNavigate } from 'react-router'
import { useQuery } from '@tanstack/react-query'
import { useUnifiedResults } from '../../hooks/useUnifiedResults'
import { useCompareStore } from '../../stores/compareStore'
import { needService } from '../../services/needService'
import {
FeedEmptyState,
@@ -39,7 +38,6 @@ export default function Results() {
queryKey: ['needs'],
queryFn: () => needService.getAll(),
})
const { addToCompare, removeFromCompare, clearCompare, isInCompare, compareTray } = useCompareStore()
const activeNeed = needResp?.data?.[0]
@@ -52,11 +50,6 @@ export default function Results() {
const externalCount = results.filter(r => r.resultType === 'EXTERNAL_MARKET').length
const futureCount = results.filter(r => r.resultType === 'FUTURE_AVAILABILITY').length
const handleCompare = (propertyId: string) => {
if (isInCompare(propertyId)) removeFromCompare(propertyId)
else addToCompare(propertyId)
}
return (
<Box>
<ResultFeedHeader
@@ -103,51 +96,9 @@ export default function Results() {
) : sorted.length === 0 ? (
<FeedEmptyState filtered={filterSource !== 'ALL'} />
) : (
<UnifiedResultFeed results={sorted} isInCompare={isInCompare} onCompare={handleCompare} />
<UnifiedResultFeed results={sorted} />
)}
</Box>
{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" sx={{ 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>
)
}
+82
View File
@@ -3,6 +3,82 @@ import { ServiceErrorCode } from './types'
import type { CreateNeedInput } from '../domain/need'
import type { AssetType } from '../domain/enums'
import type { ParseNeedResult, ParsedNeedCriteria, FollowUpQuestion } from '../domain/needBuilder'
import type { UnifiedMatchResult } from '../domain/unifiedResult'
// ── Compare Summary ───────────────────────────────────────────────────────────
export interface ComparisonSummary {
strongestOption: { matchId: string; label: string; reason: string }
bestValue: { matchId: string; label: string; reason: string } | null
highestConfidence: { matchId: string; label: string; confidenceLevel: number }
biggestTradeoffs: string[]
missingDataWarnings: string[]
recommendedNextStep: string
}
function buildComparisonSummary(items: UnifiedMatchResult[]): ComparisonSummary {
if (items.length === 0) {
return {
strongestOption: { matchId: '', label: '', reason: 'Keine Ergebnisse' },
bestValue: null,
highestConfidence: { matchId: '', label: '', confidenceLevel: 0 },
biggestTradeoffs: [],
missingDataWarnings: [],
recommendedNextStep: 'Suchergebnisse überprüfen',
}
}
const getTitle = (item: UnifiedMatchResult) =>
item.resultType !== 'FUTURE_AVAILABILITY'
? (item as any).property?.title ?? `Match ${item.matchScore}`
: (item as any).signal?.companyName ?? 'Zukunftssignal'
const strongest = items.reduce((a, b) => a.matchScore > b.matchScore ? a : b)
const propertyItems = items.filter(i => i.resultType !== 'FUTURE_AVAILABILITY')
const bestValue = propertyItems.length > 0
? propertyItems.reduce((a, b) =>
((a as any).property?.rentPricePerSqm ?? Infinity) <= ((b as any).property?.rentPricePerSqm ?? Infinity) ? a : b
)
: null
const highestConf = items.reduce((a, b) =>
a.match.confidenceLevel >= b.match.confidenceLevel ? a : b
)
const tradeoffs = items
.flatMap(i => i.match.tradeoffs?.slice(0, 1).map(t => `${getTitle(i)}: ${t.concern}`) ?? [])
.slice(0, 3)
const missingWarnings = items
.filter(i => (i.match.missingData?.filter(m => m.importance === 'CRITICAL').length ?? 0) > 0)
.map(i => `${getTitle(i)}: fehlende Pflichtfelder`)
const topNextAction = strongest.match.nextBestActions?.[0]?.label ?? 'Objekt besichtigen oder Details prüfen'
return {
strongestOption: {
matchId: strongest.matchId,
label: getTitle(strongest),
reason: `Höchster Match Score (${strongest.matchScore}/100)`,
},
bestValue: bestValue
? {
matchId: bestValue.matchId,
label: getTitle(bestValue),
reason: `Niedrigster Mietpreis (CHF ${(bestValue as any).property?.rentPricePerSqm ?? ''}/m²)`,
}
: null,
highestConfidence: {
matchId: highestConf.matchId,
label: getTitle(highestConf),
confidenceLevel: highestConf.match.confidenceLevel,
},
biggestTradeoffs: tradeoffs,
missingDataWarnings: missingWarnings,
recommendedNextStep: topNextAction,
}
}
// ── Legacy types (kept for backward compatibility) ────────────────────────────
@@ -284,6 +360,12 @@ export const aiService = {
return { data }
},
// F014: Compare summary
async summarizeComparison(items: UnifiedMatchResult[]): Promise<ItemResponse<ComparisonSummary>> {
await new Promise(r => setTimeout(r, 600))
return { data: buildComparisonSummary(items) }
},
// F008 methods
async parseNeed(input: string): Promise<ItemResponse<ParseNeedResult>> {
await new Promise(r => setTimeout(r, 1400))
+16 -15
View File
@@ -1,27 +1,28 @@
import { create } from 'zustand'
import type { UnifiedMatchResult } from '../domain/unifiedResult'
const MAX_COMPARE_ITEMS = 3
const MAX_COMPARE_ITEMS = 4
interface CompareState {
compareTray: string[]
addToCompare: (propertyId: string) => void
removeFromCompare: (propertyId: string) => void
compareItems: UnifiedMatchResult[]
addToCompare: (result: UnifiedMatchResult) => void
removeFromCompare: (matchId: string) => void
clearCompare: () => void
isInCompare: (propertyId: string) => boolean
isInCompare: (matchId: string) => boolean
isFull: () => boolean
}
export const useCompareStore = create<CompareState>((set, get) => ({
compareTray: [],
addToCompare: (propertyId) =>
compareItems: [],
addToCompare: (result) =>
set((state) => {
if (state.compareTray.length >= MAX_COMPARE_ITEMS) return state
if (state.compareTray.includes(propertyId)) return state
return { compareTray: [...state.compareTray, propertyId] }
if (state.compareItems.length >= MAX_COMPARE_ITEMS) return state
if (state.compareItems.some(i => i.matchId === result.matchId)) return state
return { compareItems: [...state.compareItems, result] }
}),
removeFromCompare: (propertyId) =>
set((state) => ({ compareTray: state.compareTray.filter(id => id !== propertyId) })),
clearCompare: () => set({ compareTray: [] }),
isInCompare: (propertyId) => get().compareTray.includes(propertyId),
isFull: () => get().compareTray.length >= MAX_COMPARE_ITEMS,
removeFromCompare: (matchId) =>
set((state) => ({ compareItems: state.compareItems.filter(i => i.matchId !== matchId) })),
clearCompare: () => set({ compareItems: [] }),
isInCompare: (matchId) => get().compareItems.some(i => i.matchId === matchId),
isFull: () => get().compareItems.length >= MAX_COMPARE_ITEMS,
}))