129 lines
4.8 KiB
TypeScript
129 lines
4.8 KiB
TypeScript
import { NextResponse } from 'next/server'
|
||
import { getServerSession } from 'next-auth'
|
||
import { authOptions } from '@/lib/auth'
|
||
import * as statusColors from '@/lib/statusColors'
|
||
|
||
export async function GET(request: Request) {
|
||
try {
|
||
const session = await getServerSession(authOptions)
|
||
if (!session?.accessToken) {
|
||
return NextResponse.json({ success: false, error: 'Unauthorized' }, { status: 401 })
|
||
}
|
||
|
||
const backendUrl = process.env.BACKEND_URL
|
||
|
||
// Получаем zone_id из query параметров
|
||
const { searchParams } = new URL(request.url)
|
||
const zoneId = searchParams.get('zone_id')
|
||
|
||
// Формируем URL для бэкенда с zone_id если он есть
|
||
const detectorsUrl = zoneId
|
||
? `${backendUrl}/account/get-detectors/?zone_id=${zoneId}`
|
||
: `${backendUrl}/account/get-detectors/`
|
||
|
||
console.log('[get-detectors] Fetching from backend:', detectorsUrl)
|
||
|
||
const [detectorsRes, objectsRes] = await Promise.all([
|
||
fetch(detectorsUrl, {
|
||
headers: {
|
||
'Content-Type': 'application/json',
|
||
Authorization: `Bearer ${session.accessToken}`,
|
||
},
|
||
cache: 'no-store',
|
||
}),
|
||
fetch(`${backendUrl}/account/get-objects/`, {
|
||
headers: {
|
||
'Content-Type': 'application/json',
|
||
Authorization: `Bearer ${session.accessToken}`,
|
||
},
|
||
cache: 'no-store',
|
||
}),
|
||
])
|
||
|
||
if (!detectorsRes.ok) {
|
||
const err = await detectorsRes.text()
|
||
return NextResponse.json({ success: false, error: `Backend detectors error: ${err}` }, { status: detectorsRes.status })
|
||
}
|
||
if (!objectsRes.ok) {
|
||
const err = await objectsRes.text()
|
||
return NextResponse.json({ success: false, error: `Backend objects error: ${err}` }, { status: objectsRes.status })
|
||
}
|
||
|
||
const detectorsPayload = await detectorsRes.json()
|
||
const objectsPayload = await objectsRes.json()
|
||
|
||
const titleToIdMap: Record<string, string> = {}
|
||
if (Array.isArray(objectsPayload)) {
|
||
for (const obj of objectsPayload) {
|
||
if (obj && typeof obj.title === 'string' && typeof obj.id === 'number') {
|
||
titleToIdMap[obj.title] = `object_${obj.id}`
|
||
}
|
||
}
|
||
}
|
||
|
||
const statusToColor: Record<string, string> = {
|
||
critical: statusColors.STATUS_COLOR_CRITICAL,
|
||
warning: statusColors.STATUS_COLOR_WARNING,
|
||
normal: statusColors.STATUS_COLOR_NORMAL,
|
||
}
|
||
|
||
const transformedDetectors: Record<string, any> = {}
|
||
const detectorsObj = detectorsPayload?.detectors ?? {}
|
||
for (const [key, sensor] of Object.entries<any>(detectorsObj)) {
|
||
const color = statusToColor[sensor.status] ?? statusColors.STATUS_COLOR_NORMAL
|
||
const objectId = titleToIdMap[sensor.object] || sensor.object
|
||
transformedDetectors[key] = {
|
||
...sensor,
|
||
status: color,
|
||
object: objectId,
|
||
checked: sensor.checked ?? false,
|
||
location: sensor.zone ?? '',
|
||
serial_number: sensor.serial_number ?? sensor.name ?? '',
|
||
detector_type: sensor.detector_type ?? '',
|
||
notifications: Array.isArray(sensor.notifications) ? sensor.notifications.map((n: any) => {
|
||
const severity = String(n?.severity || n?.type || '').toLowerCase()
|
||
|
||
// Логируем оригинальные данные для отладки
|
||
if (sensor.serial_number === 'GLE-1') {
|
||
console.log('[get-detectors] Original notification for GLE-1:', { severity: n?.severity, type: n?.type, message: n?.message })
|
||
}
|
||
|
||
// Добавляем поддержку русских названий
|
||
let type = 'info'
|
||
if (severity === 'critical' || severity === 'критический' || severity === 'критичный') {
|
||
type = 'critical'
|
||
} else if (severity === 'warning' || severity === 'предупреждение') {
|
||
type = 'warning'
|
||
}
|
||
|
||
const priority = type === 'critical' ? 'high' : type === 'warning' ? 'medium' : 'low'
|
||
return {
|
||
id: n.id,
|
||
type,
|
||
message: n.message,
|
||
timestamp: n.timestamp || n.created_at,
|
||
acknowledged: typeof n.acknowledged === 'boolean' ? n.acknowledged : !!n.resolved,
|
||
priority,
|
||
}
|
||
}) : []
|
||
}
|
||
}
|
||
|
||
return NextResponse.json({
|
||
success: true,
|
||
data: { detectors: transformedDetectors },
|
||
objectsCount: Array.isArray(objectsPayload) ? objectsPayload.length : 0,
|
||
detectorsCount: Object.keys(transformedDetectors).length,
|
||
})
|
||
} catch (error) {
|
||
console.error('Error fetching detectors data:', error)
|
||
return NextResponse.json(
|
||
{
|
||
success: false,
|
||
error: 'Failed to fetch detectors data',
|
||
},
|
||
{ status: 500 }
|
||
)
|
||
}
|
||
}
|