← back to Omega Watches 2
src/app/api/dashboard/chart-data/route.ts
54 lines
import { NextRequest, NextResponse } from "next/server";
import { query } from "@/lib/db";
import { getSession } from "@/lib/auth";
export const dynamic = "force-dynamic";
export async function GET(request: NextRequest) {
const session = await getSession(request);
if (!session) {
return NextResponse.json(
{ success: false, error: { code: "UNAUTHORIZED", message: "Login required" } },
{ status: 401 }
);
}
const dailyActivity = await query(`
SELECT
me.sale_date::date AS date,
COUNT(*) AS event_count,
COUNT(*) FILTER (WHERE me.event_type = 'auction_realized') AS auctions,
COUNT(*) FILTER (WHERE me.event_type = 'marketplace_sold') AS marketplace,
COUNT(*) FILTER (WHERE me.event_type = 'dealer_ask') AS dealer_asks,
AVG(me.price_usd)::NUMERIC(14,2) AS avg_price
FROM market_event me
WHERE me.sale_date >= CURRENT_DATE - 30
AND NOT me.is_quarantined
AND me.sale_date IS NOT NULL
GROUP BY me.sale_date::date
ORDER BY date
`);
const sourceHealth = await query(`
SELECT
ds.display_name AS name,
ds.source_type,
ds.is_active,
COALESCE(sh.success_rate_pct, 0)::INTEGER AS success_rate,
COALESCE(sh.total_runs, 0)::INTEGER AS total_runs,
COALESCE(sh.total_records_inserted, 0)::INTEGER AS records
FROM data_source ds
LEFT JOIN source_health sh ON ds.id = sh.source_id
WHERE ds.is_active = true
ORDER BY sh.total_runs DESC NULLS LAST
`);
return NextResponse.json({
success: true,
data: {
daily_activity: dailyActivity,
source_health: sourceHealth,
},
});
}