mirror of
https://github.com/henry4682/finance_app.git
synced 2026-07-16 00:10:00 +00:00
buid new app
This commit is contained in:
57
app/Http/Controllers/DashboardController.php
Normal file
57
app/Http/Controllers/DashboardController.php
Normal file
@@ -0,0 +1,57 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Models\Expense;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Inertia\Inertia;
|
||||
use Carbon\Carbon;
|
||||
|
||||
class DashboardController extends Controller
|
||||
{
|
||||
public function index()
|
||||
{
|
||||
$userId = Auth::id();
|
||||
$now = Carbon::now();
|
||||
|
||||
// 本月花費
|
||||
$monthlyTotal = Expense::where('user_id', $userId)
|
||||
->whereYear('date', $now->year)
|
||||
->whereMonth('date', $now->month)
|
||||
->sum('amount');
|
||||
|
||||
// 本月分類統計(圓餅圖)
|
||||
$categoryStats = Expense::with('category')
|
||||
->where('user_id', $userId)
|
||||
->whereYear('date', $now->year)
|
||||
->whereMonth('date', $now->month)
|
||||
->get()
|
||||
->groupBy(fn($e) => $e->category?->name ?? '未分類')
|
||||
->map(fn($group, $name) => [
|
||||
'name' => $name,
|
||||
'total' => $group->sum('amount'),
|
||||
'color' => $group->first()->category?->color ?? '#6B7280',
|
||||
])
|
||||
->values();
|
||||
|
||||
// 近6個月趨勢
|
||||
$monthlyTrend = collect(range(5, 0))->map(function ($i) use ($userId, $now) {
|
||||
$month = $now->copy()->subMonths($i);
|
||||
$total = Expense::where('user_id', $userId)
|
||||
->whereYear('date', $month->year)
|
||||
->whereMonth('date', $month->month)
|
||||
->sum('amount');
|
||||
|
||||
return [
|
||||
'month' => $month->format('Y/m'),
|
||||
'total' => (float) $total,
|
||||
];
|
||||
});
|
||||
|
||||
return Inertia::render('Dashboard', [
|
||||
'monthlyTotal' => (float) $monthlyTotal,
|
||||
'categoryStats' => $categoryStats,
|
||||
'monthlyTrend' => $monthlyTrend,
|
||||
]);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user