localgreenchain/pages/api/agents/transport-tracker/analytics.ts
Claude b7332c4c15
Deploy TransportTrackerAgent with REST API endpoints
Add comprehensive API deployment for the TransportTrackerAgent (Agent 2):

- GET/POST /api/agents/transport-tracker - Agent status and control (start/stop/run/pause/resume)
- GET /api/agents/transport-tracker/analytics - Network stats and user-specific analytics
- GET /api/agents/transport-tracker/patterns - Detected inefficiency patterns with filtering
- GET /api/agents/transport-tracker/savings - Carbon savings vs conventional logistics

Features:
- Real-time agent status and metrics monitoring
- User transport analysis with efficiency ratings
- Pattern detection for high-carbon events and cold chain breaks
- Carbon savings calculator with environmental equivalents
2025-11-23 00:24:25 +00:00

80 lines
2.5 KiB
TypeScript

/**
* API Route: TransportTrackerAgent Analytics
* GET /api/agents/transport-tracker/analytics - Get network stats and user analytics
* GET /api/agents/transport-tracker/analytics?userId=xxx - Get specific user analytics
*/
import type { NextApiRequest, NextApiResponse } from 'next';
import { getTransportTrackerAgent } from '../../../../lib/agents/TransportTrackerAgent';
export default async function handler(
req: NextApiRequest,
res: NextApiResponse
) {
if (req.method !== 'GET') {
return res.status(405).json({ success: false, error: 'Method not allowed' });
}
try {
const agent = getTransportTrackerAgent();
const { userId } = req.query;
// If userId provided, return user-specific analytics
if (userId && typeof userId === 'string') {
const userAnalysis = agent.getUserAnalysis(userId);
if (!userAnalysis) {
return res.status(404).json({
success: false,
error: `No analytics found for user: ${userId}`
});
}
return res.status(200).json({
success: true,
data: {
user: userAnalysis,
recommendations: userAnalysis.recommendations,
efficiency: {
rating: userAnalysis.efficiency,
carbonPerKm: userAnalysis.carbonPerKm,
totalCarbonKg: userAnalysis.totalCarbonKg
}
}
});
}
// Otherwise, return network-wide analytics
const networkStats = agent.getNetworkStats();
if (!networkStats) {
return res.status(200).json({
success: true,
data: {
message: 'No network statistics available yet. Run the agent to collect data.',
networkStats: null
}
});
}
res.status(200).json({
success: true,
data: {
networkStats,
insights: {
avgCarbonPerEvent: networkStats.avgCarbonPerEvent,
avgDistancePerEvent: networkStats.avgDistancePerEvent,
greenTransportPercentage: networkStats.greenTransportPercentage,
topMethods: Object.entries(networkStats.methodDistribution)
.sort(([, a], [, b]) => (b as number) - (a as number))
.slice(0, 5)
.map(([method, count]) => ({ method, count }))
},
trends: networkStats.dailyTrends
}
});
} catch (error: any) {
console.error('Error fetching transport tracker analytics:', error);
res.status(500).json({ success: false, error: error.message || 'Internal server error' });
}
}