Files
goodgo-platform/apps/web/components/valuation/comparables-map.tsx
Ho Ngoc Hai 0fc6516880
Some checks failed
Security Scanning / Trivy Filesystem Scan (push) Failing after 31s
Security Scanning / Security Gate (push) Failing after 2s
CI / Lint → Typecheck → Test → Build (22) (push) Failing after 13s
Deploy / Build API Image (push) Failing after 36s
Deploy / Build Web Image (push) Failing after 12s
Deploy / Build AI Services Image (push) Failing after 12s
Security Scanning / Trivy Scan — API Image (push) Failing after 1m5s
CI / E2E Tests (push) Has been skipped
CodeQL Analysis / CodeQL (javascript-typescript) (push) Failing after 1m24s
E2E Tests / Playwright E2E (push) Failing after 20s
Security Scanning / Dependency Audit (pnpm) (push) Failing after 3s
Deploy / Deploy to Production (push) Has been cancelled
Deploy / Deploy to Staging (push) Has been cancelled
Deploy / Smoke Test Staging (push) Has been cancelled
Deploy / Rollback Staging (push) Has been cancelled
Deploy / Smoke Test Production (push) Has been cancelled
Deploy / Rollback Production (push) Has been cancelled
Security Scanning / Trivy Scan — AI Services Image (push) Has been cancelled
Security Scanning / Trivy Scan — Web Image (push) Has been cancelled
feat(maps): dark/light Mapbox theme + fix empty Image src & missing keys
Mapbox theming
--------------
- New hook `lib/mapbox-style.ts` returning streets-v12 (light) or
  dark-v11 (dark) from the app's useTheme().
- Six map components now initialise with the themed style and
  `map.setStyle(...)` on theme change: project-map, park-map,
  listing-map, district-heatmap (plus re-adding its heatmap source
  after style.load), neighborhood-poi-map, valuation/comparables-map.
- Marker / popup DOM styles swapped from hard-coded white/#666/#green
  to shadcn CSS tokens (--card, --card-foreground, --muted-foreground,
  --primary, --border). Global Mapbox popup + control + attribution
  skins added in app/globals.css.
- POI filter pills on neighborhood-poi-map were hard-coded `bg-white`
  which rendered same-colour text on white in dark mode — switched to
  `bg-card`/`bg-card/60` for proper contrast.
- Extend the MockMap in comparables-map.spec.tsx with setStyle/on
  so the new theme-sync effect doesn't blow up in tests.

Detail client normaliser (du-an-server)
---------------------------------------
- Project media from the backend is a `string[]` (raw URLs) or richer
  `{url,...}` objects. Handle both shapes and drop entries without
  a URL so we never feed "" to <Image src>.
- Amenities are `string[]` in the DB but the frontend type expects
  `{id,name,icon,category}`; normalise strings into objects so the
  AmenitiesTab has stable keys and a displayable name.

Resolves three classes of runtime warnings on /du-an/<slug>:
"Image is missing required 'src' property", "ReactDOM.preload ...
empty href", and "Each child in a list should have a unique 'key'
prop" (AmenitiesTab).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-19 14:12:28 +07:00

240 lines
7.4 KiB
TypeScript

'use client';
/* eslint-disable import-x/no-named-as-default-member */
import mapboxgl from 'mapbox-gl';
import * as React from 'react';
import 'mapbox-gl/dist/mapbox-gl.css';
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from '@/components/ui/card';
import { formatPrice, formatPricePerM2 } from '@/lib/currency';
import { useMapboxStyle } from '@/lib/mapbox-style';
import type { ValuationComparable } from '@/lib/valuation-api';
interface ComparablesMapProps {
comparables: ValuationComparable[];
subjectLatitude?: number;
subjectLongitude?: number;
className?: string;
}
const DEFAULT_CENTER: [number, number] = [106.6297, 10.8231];
const DEFAULT_ZOOM = 11;
function similarityColor(sim: number): string {
if (sim >= 0.85) return '#16a34a';
if (sim >= 0.7) return '#eab308';
return '#dc2626';
}
function escapeHtml(str: string): string {
return str
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&#39;');
}
export function ComparablesMap({
comparables,
subjectLatitude,
subjectLongitude,
className,
}: ComparablesMapProps) {
const mapContainerRef = React.useRef<HTMLDivElement>(null);
const mapRef = React.useRef<mapboxgl.Map | null>(null);
const markersRef = React.useRef<mapboxgl.Marker[]>([]);
const mapStyle = useMapboxStyle();
const geoComparables = React.useMemo(
() =>
comparables.filter(
(c) => c.latitude != null && c.longitude != null,
),
[comparables],
);
React.useEffect(() => {
if (!mapContainerRef.current) return;
const token = process.env['NEXT_PUBLIC_MAPBOX_TOKEN'];
if (!token) return;
mapboxgl.accessToken = token;
const map = new mapboxgl.Map({
container: mapContainerRef.current,
style: mapStyle,
center: DEFAULT_CENTER,
zoom: DEFAULT_ZOOM,
attributionControl: false,
});
map.addControl(new mapboxgl.NavigationControl(), 'top-right');
map.addControl(
new mapboxgl.AttributionControl({ compact: true }),
'bottom-right',
);
mapRef.current = map;
return () => {
map.remove();
mapRef.current = null;
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
React.useEffect(() => {
const map = mapRef.current;
if (!map) return;
map.setStyle(mapStyle);
}, [mapStyle]);
React.useEffect(() => {
const map = mapRef.current;
if (!map) return;
markersRef.current.forEach((m) => m.remove());
markersRef.current = [];
const bounds = new mapboxgl.LngLatBounds();
let extended = false;
if (subjectLatitude != null && subjectLongitude != null) {
const subjectEl = document.createElement('div');
subjectEl.setAttribute('data-testid', 'comparables-map-subject');
subjectEl.style.cssText = `
width: 22px;
height: 22px;
border-radius: 50%;
background: hsl(221.2, 83.2%, 53.3%);
border: 3px solid white;
box-shadow: 0 0 0 2px hsl(221.2, 83.2%, 53.3%), 0 2px 6px rgba(0,0,0,0.3);
`;
const marker = new mapboxgl.Marker({ element: subjectEl })
.setLngLat([subjectLongitude, subjectLatitude])
.addTo(map);
markersRef.current.push(marker);
bounds.extend([subjectLongitude, subjectLatitude]);
extended = true;
}
geoComparables.forEach((comp) => {
const color = similarityColor(comp.similarity);
const el = document.createElement('div');
el.setAttribute('data-testid', 'comparables-map-marker');
el.style.cssText = `
background: white;
border-radius: 8px;
padding: 4px 8px;
font-size: 11px;
font-weight: 600;
box-shadow: 0 2px 6px rgba(0,0,0,0.15);
white-space: nowrap;
cursor: pointer;
border-left: 3px solid ${color};
transition: transform 0.15s;
max-width: 180px;
overflow: hidden;
text-overflow: ellipsis;
`;
el.textContent = formatPrice(comp.priceVND);
el.addEventListener('mouseenter', () => {
el.style.transform = 'scale(1.08)';
});
el.addEventListener('mouseleave', () => {
el.style.transform = 'scale(1)';
});
const popup = new mapboxgl.Popup({
offset: 15,
maxWidth: '280px',
closeButton: false,
}).setHTML(
`<div style="font-family:system-ui,sans-serif;padding:4px 0;">
<p style="font-weight:600;font-size:13px;margin:0 0 4px;">${escapeHtml(comp.title)}</p>
<p style="font-size:12px;color:#666;margin:0 0 4px;">${escapeHtml(comp.address)}</p>
<p style="font-size:12px;margin:0 0 2px;">
<span style="font-weight:600;color:hsl(221.2,83.2%,53.3%);">${formatPrice(comp.priceVND)} VNĐ</span>
<span style="color:#666;margin-left:6px;">${formatPricePerM2(comp.pricePerM2)}</span>
</p>
<p style="font-size:12px;color:#666;margin:0;">
${comp.areaM2} m² · Tương đồng ${Math.round(comp.similarity * 100)}%
</p>
</div>`,
);
const marker = new mapboxgl.Marker({ element: el, anchor: 'left' })
.setLngLat([comp.longitude!, comp.latitude!])
.setPopup(popup)
.addTo(map);
markersRef.current.push(marker);
bounds.extend([comp.longitude!, comp.latitude!]);
extended = true;
});
if (!extended) return;
if (!bounds.isEmpty() && markersRef.current.length > 1) {
map.fitBounds(bounds, { padding: 60, maxZoom: 14 });
} else if (markersRef.current.length === 1) {
const first = geoComparables[0] ?? {
latitude: subjectLatitude,
longitude: subjectLongitude,
};
if (first.latitude != null && first.longitude != null) {
map.flyTo({ center: [first.longitude, first.latitude], zoom: 14 });
}
}
}, [geoComparables, subjectLatitude, subjectLongitude]);
const hasToken =
typeof process !== 'undefined' &&
Boolean(process.env['NEXT_PUBLIC_MAPBOX_TOKEN']);
const hasAnyGeo =
geoComparables.length > 0 ||
(subjectLatitude != null && subjectLongitude != null);
return (
<Card>
<CardHeader>
<CardTitle className="text-lg">Bản đ so sánh</CardTitle>
<CardDescription>
Vị trí các bất đng sản tương tự đưc sử dụng trong hình AVM
</CardDescription>
</CardHeader>
<CardContent>
<div
className={`relative overflow-hidden rounded-lg border ${className || 'h-[360px] md:h-[420px]'}`}
>
<div ref={mapContainerRef} className="h-full w-full" />
{!hasToken && (
<div className="absolute inset-0 flex items-center justify-center bg-gradient-to-b from-blue-50 to-green-50 text-center text-sm text-muted-foreground">
Thiết lập NEXT_PUBLIC_MAPBOX_TOKEN đ hiển thị bản đ
</div>
)}
{hasToken && !hasAnyGeo && (
<div className="absolute inset-0 flex items-center justify-center bg-muted/40 text-center text-sm text-muted-foreground">
Không toạ đ cho các BĐS so sánh
</div>
)}
<div className="absolute bottom-3 left-3 rounded bg-white/90 px-2 py-1 text-xs text-muted-foreground shadow">
{geoComparables.length} BĐS so sánh
</div>
</div>
</CardContent>
</Card>
);
}