import { NextResponse } from 'next/server'; import { getDbPool } from '@/lib/db'; import { RowDataPacket } from 'mysql2'; // GET /api/ausgaben/stats - Get monthly statistics export async function GET(request: Request) { try { const { searchParams } = new URL(request.url); const month = searchParams.get('month'); const year = searchParams.get('year'); if (!month || !year) { return NextResponse.json( { success: false, error: 'Month and year are required' }, { status: 400 } ); } const pool = getDbPool(); // Get total ausgaben and breakdown by payment type const query = ` SELECT SUM(CASE WHEN Wie IN ('EC-R', 'EC-B', 'bar-R', 'bar-B', 'Ueber') THEN Wieviel ELSE 0 END) as totalAusgaben, SUM(CASE WHEN Wie = 'EC-R' THEN Wieviel ELSE 0 END) as ECR, SUM(CASE WHEN Wie = 'EC-B' THEN Wieviel ELSE 0 END) as ECB, SUM(CASE WHEN Wie = 'bar-R' THEN Wieviel ELSE 0 END) as barR, SUM(CASE WHEN Wie = 'bar-B' THEN Wieviel ELSE 0 END) as barB, SUM(CASE WHEN Wie = 'Einnahme' THEN Wieviel ELSE 0 END) as Einnahmen, SUM(CASE WHEN Wie = 'Ueber' THEN Wieviel ELSE 0 END) as Ueberweisungen FROM Ausgaben WHERE YEAR(Datum) = ? AND MONTH(Datum) = ? `; const [rows] = await pool.query(query, [year, month]); const data = rows[0] || { totalAusgaben: 0, ECR: 0, ECB: 0, barR: 0, barB: 0, Einnahmen: 0, Ueberweisungen: 0, }; // Convert string values from MySQL to numbers const parsedData = { totalAusgaben: parseFloat(data.totalAusgaben) || 0, ECR: parseFloat(data.ECR) || 0, ECB: parseFloat(data.ECB) || 0, barR: parseFloat(data.barR) || 0, barB: parseFloat(data.barB) || 0, Einnahmen: parseFloat(data.Einnahmen) || 0, Ueberweisungen: parseFloat(data.Ueberweisungen) || 0, }; return NextResponse.json({ success: true, data: parsedData, }); } catch (error) { console.error('Database error:', error); return NextResponse.json( { success: false, error: 'Database error' }, { status: 500 } ); } }