Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
118 changes: 58 additions & 60 deletions app/Http/Controllers/CategoryAnalysisController.php
Original file line number Diff line number Diff line change
Expand Up @@ -47,91 +47,89 @@ public function __invoke(Request $request)
->get()
->keyBy('category_id');

// Cumulative totals up to (and including) the selected month, for the
// monthly average. Averaged over the months from the first transaction
// to the selected month.
$cumulativeTotals = Transaction::select(
'category_id',
DB::raw('SUM(CASE WHEN amount < 0 THEN ABS(amount) ELSE 0 END) as expense_total'),
DB::raw('SUM(CASE WHEN amount > 0 THEN amount ELSE 0 END) as income_total')
)
->whereNotNull('category_id')
->whereDoesntHave('category', fn ($q) => $q->where('type', 'transfer'))
->where('date', '<=', $monthEnd)
->groupBy('category_id')
->get()
->keyBy('category_id');

$monthsElapsed = 1;
if ($selectedMonth >= $firstMonth) {
$monthsElapsed = Carbon::createFromFormat('Y-m', $firstMonth)->startOfMonth()->diffInMonths($selectedDate) + 1;
}

// Load the full category tree so aggregation works at any nesting depth.
$allCategories = Category::orderBy('sort_order')->orderBy('name')->get();
$childrenByParent = $allCategories->groupBy('parent_id');

$totalExpenses = $categoryTotals->sum('expense_total');
$totalIncome = $categoryTotals->sum('income_total');

// Sum a category's own totals plus every descendant's, recursively.
$subtreeTotals = function (Category $category) use (&$subtreeTotals, $categoryTotals, $childrenByParent): array {
// Build a full recursive node (own totals + every descendant's), pruning
// subtrees with no activity. Works at any nesting depth.
$buildNode = function (Category $category) use (&$buildNode, $categoryTotals, $cumulativeTotals, $monthsElapsed, $childrenByParent, $totalExpenses, $totalIncome): ?array {
$expense = (float) ($categoryTotals[$category->id]?->expense_total ?? 0);
$income = (float) ($categoryTotals[$category->id]?->income_total ?? 0);
$count = (int) ($categoryTotals[$category->id]?->transaction_count ?? 0);
// Monthly averages are additive across the subtree (constant divisor).
$avgMonthlyExpense = (float) ($cumulativeTotals[$category->id]?->expense_total ?? 0) / $monthsElapsed;
$avgMonthlyIncome = (float) ($cumulativeTotals[$category->id]?->income_total ?? 0) / $monthsElapsed;

$children = [];
foreach ($childrenByParent[$category->id] ?? [] as $child) {
$childTotals = $subtreeTotals($child);
$expense += $childTotals['expense'];
$income += $childTotals['income'];
$count += $childTotals['count'];
$childNode = $buildNode($child);
if ($childNode !== null) {
$expense += $childNode['expense'];
$income += $childNode['income'];
$count += $childNode['transactionCount'];
$avgMonthlyExpense += $childNode['avgMonthlyExpense'];
$avgMonthlyIncome += $childNode['avgMonthlyIncome'];
$children[] = $childNode;
}
}

if ($expense <= 0 && $income <= 0) {
return null;
}

return ['expense' => $expense, 'income' => $income, 'count' => $count];
return [
'id' => $category->id,
'name' => $category->name,
'type' => $category->type,
'expense' => round($expense, 2),
'income' => round($income, 2),
'transactionCount' => $count,
'expensePercent' => $totalExpenses > 0 ? round(($expense / $totalExpenses) * 100, 1) : 0,
'incomePercent' => $totalIncome > 0 ? round(($income / $totalIncome) * 100, 1) : 0,
'avgMonthlyExpense' => round($avgMonthlyExpense, 2),
'avgMonthlyIncome' => round($avgMonthlyIncome, 2),
'budget' => $category->budget_monthly,
'children' => $children,
];
};

$hierarchy = [];
$treemapData = [];

foreach ($allCategories->whereNull('parent_id') as $parent) {
$parentTotals = $subtreeTotals($parent);
$parentExpense = $parentTotals['expense'];
$parentIncome = $parentTotals['income'];
$parentTxCount = $parentTotals['count'];

$children = [];
foreach ($childrenByParent[$parent->id] ?? [] as $child) {
$childTotals = $subtreeTotals($child);
$childExpense = $childTotals['expense'];
$childIncome = $childTotals['income'];
$childTxCount = $childTotals['count'];

if ($childExpense > 0 || $childIncome > 0) {
$children[] = [
'id' => $child->id,
'name' => $child->name,
'type' => $child->type,
'expense' => round($childExpense, 2),
'income' => round($childIncome, 2),
'transactionCount' => $childTxCount,
'expensePercent' => $totalExpenses > 0 ? round(($childExpense / $totalExpenses) * 100, 1) : 0,
'incomePercent' => $totalIncome > 0 ? round(($childIncome / $totalIncome) * 100, 1) : 0,
'budget' => $child->budget_monthly,
];
}
}

if ($parentExpense > 0 || $parentIncome > 0) {
$hierarchy[] = [
'id' => $parent->id,
'name' => $parent->name,
'type' => $parent->type,
'expense' => round($parentExpense, 2),
'income' => round($parentIncome, 2),
'transactionCount' => $parentTxCount,
'expensePercent' => $totalExpenses > 0 ? round(($parentExpense / $totalExpenses) * 100, 1) : 0,
'incomePercent' => $totalIncome > 0 ? round(($parentIncome / $totalIncome) * 100, 1) : 0,
'budget' => $parent->budget_monthly,
'children' => $children,
];

if ($parentExpense > 0) {
$treemapData[] = [
'x' => $parent->name,
'y' => round($parentExpense, 2),
];
}
foreach ($allCategories->whereNull('parent_id') as $root) {
$node = $buildNode($root);
if ($node !== null) {
$hierarchy[] = $node;
}
}

usort($treemapData, fn ($a, $b) => $b['y'] <=> $a['y']);

return Inertia::render('Categories/Analysis', [
'selectedMonth' => $selectedMonth,
'prevMonth' => $prevMonth,
'nextMonth' => $nextMonth,
'hierarchy' => $hierarchy,
'treemapData' => $treemapData,
'totalExpenses' => round($totalExpenses, 2),
'totalIncome' => round($totalIncome, 2),
]);
Expand Down
34 changes: 31 additions & 3 deletions app/Http/Controllers/CategoryController.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,10 @@
namespace App\Http\Controllers;

use App\Models\Category;
use App\Models\Transaction;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
use Inertia\Inertia;

class CategoryController extends Controller
Expand All @@ -17,7 +20,27 @@ public function index()
->orderBy('name')
->get();

$tree = $categories->map(fn ($cat) => $this->mapTreeNode($cat))->toArray();
// Per-category monthly average: each category's own total (matching the
// direct Buchungen count) over the months from the first transaction to now.
$now = now();
$firstMonth = Transaction::selectRaw("strftime('%Y-%m', MIN(date)) as m")->value('m');
$monthsElapsed = 1;
if ($firstMonth) {
$monthsElapsed = Carbon::createFromFormat('Y-m', $firstMonth)->startOfMonth()->diffInMonths($now->copy()->startOfMonth()) + 1;
}

$totals = Transaction::select(
'category_id',
DB::raw('SUM(CASE WHEN amount < 0 THEN ABS(amount) ELSE 0 END) as expense_total'),
DB::raw('SUM(CASE WHEN amount > 0 THEN amount ELSE 0 END) as income_total')
)
->whereNotNull('category_id')
->where('date', '<=', $now->toDateString())
->groupBy('category_id')
->get()
->keyBy('category_id');

$tree = $categories->map(fn ($cat) => $this->mapTreeNode($cat, $totals, $monthsElapsed))->toArray();

return Inertia::render('Categories/Index', [
'categories' => $tree,
Expand Down Expand Up @@ -66,8 +89,12 @@ public function destroy(Category $category)
return redirect()->back()->with('success', 'Kategorie gelöscht.');
}

private function mapTreeNode(Category $category): array
private function mapTreeNode(Category $category, $totals, int $monthsElapsed): array
{
$amount = $category->type === 'income'
? (float) ($totals[$category->id]->income_total ?? 0)
: (float) ($totals[$category->id]->expense_total ?? 0);

$node = [
'key' => $category->id,
'data' => [
Expand All @@ -78,12 +105,13 @@ private function mapTreeNode(Category $category): array
'parent_id' => $category->parent_id,
'budget_monthly' => $category->budget_monthly,
'transactionsCount' => $category->transactions_count ?? 0,
'monthlyAverage' => round($amount / $monthsElapsed, 2),
],
'children' => [],
];

if ($category->children->isNotEmpty()) {
$node['children'] = $category->children->map(fn ($child) => $this->mapTreeNode($child))->toArray();
$node['children'] = $category->children->map(fn ($child) => $this->mapTreeNode($child, $totals, $monthsElapsed))->toArray();
}

return $node;
Expand Down
Loading
Loading