New api and zone management; highligh occlusion and highlighAll functionality; improved search in reports and alerts history + autofill; refactored alert panel

This commit is contained in:
iv_vuytsik
2025-12-25 03:10:21 +03:00
parent 31030f2997
commit ce7e39debf
36 changed files with 1562 additions and 472 deletions

View File

@@ -1,6 +1,33 @@
import React, { useState, useEffect, useCallback } from 'react';
import React, { useEffect, useCallback } from 'react';
import Image from 'next/image';
import useNavigationStore from '@/app/store/navigationStore';
import type { Zone } from '@/app/types';
// Безопасный резолвер src изображения, чтобы избежать ошибок Invalid URL в next/image
const resolveImageSrc = (src?: string | null): string => {
if (!src || typeof src !== 'string') return '/images/test_image.png';
let s = src.trim();
if (!s) return '/images/test_image.png';
s = s.replace(/\\/g, '/');
const lower = s.toLowerCase();
// Явный плейсхолдер test_image.png маппим на наш статический ресурс
if (lower === 'test_image.png' || lower.endsWith('/test_image.png') || lower.includes('/public/images/test_image.png')) {
return '/images/test_image.png';
}
// Если путь содержит public/images (даже абсолютный путь ФС), переводим в относительный путь сайта
if (/\/public\/images\//i.test(s)) {
const parts = s.split(/\/public\/images\//i);
const rel = parts[1] || '';
return `/images/${rel}`;
}
// Абсолютные URL и пути, относительные к сайту
if (s.startsWith('http://') || s.startsWith('https://')) return s;
if (s.startsWith('/')) return s;
// Нормализуем относительные имена ресурсов до путей сайта под /images
// Убираем ведущий 'public/', если он присутствует
s = s.replace(/^public\//i, '');
return s.startsWith('images/') ? `/${s}` : `/images/${s}`;
}
interface MonitoringProps {
onClose?: () => void;
@@ -8,49 +35,25 @@ interface MonitoringProps {
}
const Monitoring: React.FC<MonitoringProps> = ({ onClose, onSelectModel }) => {
const [models, setModels] = useState<{ title: string; path: string }[]>([]);
const [loadError, setLoadError] = useState<string | null>(null);
const PREFERRED_MODEL = useNavigationStore((state) => state.PREFERRED_MODEL);
const { currentObject, currentZones, zonesLoading, zonesError, loadZones } = useNavigationStore();
const handleSelectModel = useCallback((modelPath: string) => {
console.log(`[NavigationPage] Model selected: ${modelPath}`);
onSelectModel?.(modelPath);
}, [onSelectModel]);
useEffect(() => {
const fetchModels = async () => {
try {
setLoadError(null);
const res = await fetch('/api/big-models/list');
if (!res.ok) {
const text = await res.text();
throw new Error(text || 'Failed to fetch models list');
}
const data = await res.json();
const items: { name: string; path: string }[] = Array.isArray(data?.models) ? data.models : [];
const objId = currentObject?.id;
if (!objId) return;
loadZones(objId);
}, [currentObject?.id, loadZones]);
const preferredModelName = PREFERRED_MODEL.split('/').pop()?.split('.').slice(0, -1).join('.') || '';
const formatted = items
.map((it) => ({ title: it.name, path: it.path }))
.sort((a, b) => {
const aName = a.path.split('/').pop()?.split('.').slice(0, -1).join('.') || '';
const bName = b.path.split('/').pop()?.split('.').slice(0, -1).join('.') || '';
if (aName === preferredModelName) return -1;
if (bName === preferredModelName) return 1;
return a.title.localeCompare(b.title);
});
setModels(formatted);
} catch (error) {
console.error('[Monitoring] Error loading models list:', error);
setLoadError(error instanceof Error ? error.message : String(error));
setModels([]);
}
};
fetchModels();
}, [PREFERRED_MODEL]);
const sortedZones: Zone[] = (currentZones || []).slice().sort((a: Zone, b: Zone) => {
const oa = typeof a.order === 'number' ? a.order : 0;
const ob = typeof b.order === 'number' ? b.order : 0;
if (oa !== ob) return oa - ob;
return (a.name || '').localeCompare(b.name || '');
});
return (
<div className="w-full">
@@ -68,85 +71,86 @@ const Monitoring: React.FC<MonitoringProps> = ({ onClose, onSelectModel }) => {
</button>
)}
</div>
{loadError && (
{/* UI зон */}
{zonesError && (
<div className="rounded-lg bg-red-600/20 border border-red-600/40 text-red-200 text-xs px-3 py-2">
Ошибка загрузки списка моделей: {loadError}
Ошибка загрузки зон: {zonesError}
</div>
)}
{models.length > 0 && (
{zonesLoading && (
<div className="rounded-lg bg-gray-200 text-gray-700 text-xs px-3 py-2 border border-gray-300">
Загрузка зон...
</div>
)}
{sortedZones.length > 0 && (
<>
{/* Большая панорамная карточка для приоритетной модели */}
{models[0] && (
{sortedZones[0] && (
<button
key={`${models[0].path}-panorama`}
key={`zone-${sortedZones[0].id}-panorama`}
type="button"
onClick={() => handleSelectModel(models[0].path)}
onClick={() => sortedZones[0].model_path ? handleSelectModel(sortedZones[0].model_path) : null}
className="w-full bg-gray-300 rounded-lg h-[200px] flex items-center justify-center hover:bg-gray-400 transition-colors mb-4"
title={`Загрузить модель: ${models[0].title}`}
title={sortedZones[0].model_path ? `Открыть 3D модель зоны: ${sortedZones[0].name}` : 'Модель зоны отсутствует'}
disabled={!sortedZones[0].model_path}
>
<div className="w-full h-full bg-gray-200 rounded flex flex-col items-center justify-center relative">
{/* Всегда рендерим с разрешённой заглушкой */}
<Image
src="/images/test_image.png"
alt={models[0].title}
src={resolveImageSrc(sortedZones[0].image_path)}
alt={sortedZones[0].name || 'Зона'}
width={200}
height={200}
className="max-w-full max-h-full object-contain opacity-50"
style={{ height: 'auto' }}
onError={(e) => {
const target = e.target as HTMLImageElement;
target.style.display = 'none';
target.src = '/images/test_image.png';
}}
/>
<div className="absolute bottom-2 left-2 right-2 text-sm text-gray-700 bg-white/80 rounded px-3 py-1 truncate">
{models[0].title}
{sortedZones[0].name}
</div>
</div>
</button>
)}
{/* Сетка маленьких карточек для остальных моделей */}
{models.length > 1 && (
{sortedZones.length > 1 && (
<div className="grid grid-cols-2 gap-3">
{models.slice(1).map((model, idx) => (
{sortedZones.slice(1).map((zone: Zone, idx: number) => (
<button
key={`${model.path}-${idx}`}
key={`zone-${zone.id}-${idx}`}
type="button"
onClick={() => handleSelectModel(model.path)}
className="relative flex-1 bg-gray-300 rounded-lg h-[120px] flex items-center justify-center hover:bg-gray-400 transition-colors"
title={`Загрузить модель: ${model.title}`}
>
onClick={() => zone.model_path ? handleSelectModel(zone.model_path) : null}
className="relative flex-1 bg-gray-300 rounded-lg h-[120px] flex items-center justify-center hover:bg-gray-400 transition-colors"
title={zone.model_path ? `Открыть 3D модель зоны: ${zone.name}` : 'Модель зоны отсутствует'}
disabled={!zone.model_path}
>
<div className="w-full h-full bg-gray-200 rounded flex flex-col items-center justify-center relative">
<Image
src="/images/test_image.png"
alt={model.title}
src={resolveImageSrc(zone.image_path)}
alt={zone.name || 'Зона'}
width={120}
height={120}
className="max-w-full max-h-full object-contain opacity-50"
style={{ height: 'auto' }}
onError={(e) => {
const target = e.target as HTMLImageElement;
target.style.display = 'none';
target.src = '/images/test_image.png';
}}
/>
<div className="absolute bottom-1 left-1 right-1 text-[10px] text-gray-700 bg-white/70 rounded px-2 py-0.5 truncate">
{model.title}
{zone.name}
</div>
</div>
</button>
))}
</div>
)}
</>
)}
{models.length === 0 && !loadError && (
{sortedZones.length === 0 && !zonesError && !zonesLoading && (
<div className="col-span-2">
<div className="rounded-lg bg-gray-200 text-gray-700 text-xs px-3 py-2 border border-gray-300">
Список моделей пуст. Добавьте файлы в assets/big-models или проверьте API /api/big-models/list.
Зоны не найдены для выбранного объекта. Проверьте параметр objectId в API /api/get-zones.
</div>
</div>
)}