import { NextRequest, NextResponse } from 'next/server'; import { postgresClient } from '@/lib/services/postgres-client'; async function getExcludedCompanyIds(): Promise { try { const result = await postgresClient.query( `SELECT setting_value FROM kiosk_settings WHERE setting_key = 'excluded_company_ids'` ); const value = result.rows[0]?.setting_value || ''; return value ? value.split(',').map((id: string) => parseInt(id.trim())).filter((id: number) => !isNaN(id)) : []; } catch (error) { console.error('Error fetching excluded company IDs:', error); return []; } } async function getExcludedClassifications(): Promise { try { const result = await postgresClient.query( `SELECT setting_value FROM kiosk_settings WHERE setting_key = 'excluded_classifications'` ); const value = result.rows[0]?.setting_value || ''; return value ? value.split(',').map((c: string) => c.trim()).filter(Boolean) : []; } catch (error) { console.error('Error fetching excluded classifications:', error); return []; } } export async function GET(request: NextRequest) { try { // Get excluded company IDs (co-managed clients) and classifications const excludedCompanyIds = await getExcludedCompanyIds(); const excludedClassifications = await getExcludedClassifications(); // Build company exclusion filter let excludeCompanyFilter = ''; if (excludedCompanyIds.length > 0 || excludedClassifications.length > 0) { const conditions = []; if (excludedCompanyIds.length > 0) { conditions.push(`t.company_id NOT IN (${excludedCompanyIds.join(',')})`); } if (excludedClassifications.length > 0) { const classificationList = excludedClassifications.map(c => `'${c.replace(/'/g, "''")}'`).join(','); conditions.push(`t.company_id NOT IN (SELECT id FROM companies WHERE classification IN (${classificationList}))`); } excludeCompanyFilter = `AND (${conditions.join(' AND ')})`; } // Get recent ticket activity for ticker feed - exclude RMM alerts (source = 8), co-managed clients, and excluded classifications const activityResult = await postgresClient.query( `SELECT t.ticket_number, t.title, t.priority, t.status, t.create_date, t.last_activity_date, c.company_name, s.label as status_label FROM tickets t LEFT JOIN companies c ON t.company_id = c.id LEFT JOIN statuses s ON t.status = s.value WHERE t.completed_date IS NULL AND t.is_deleted = false AND (t.source IS NULL OR t.source != 8) ${excludeCompanyFilter} ORDER BY t.last_activity_date DESC NULLS LAST LIMIT 50` ); const activities = activityResult.rows.map((row: any) => ({ ticketNumber: row.ticket_number, title: row.title, priority: row.priority, status: row.status, statusLabel: row.status_label, companyName: row.company_name, createDate: row.create_date, lastActivityDate: row.last_activity_date, })); return NextResponse.json({ activities }); } catch (error) { console.error('Error fetching kiosk activity:', error); return NextResponse.json( { error: 'Failed to fetch kiosk activity' }, { status: 500 } ); } }