mirror of
https://github.com/henry4682/finance_app.git
synced 2026-07-16 00:10:00 +00:00
fix: add md & fix dateformat & add note
All checks were successful
Laravel-Oracle-Deploy / redeploy (push) Successful in 1m10s
All checks were successful
Laravel-Oracle-Deploy / redeploy (push) Successful in 1m10s
This commit is contained in:
@@ -15,21 +15,42 @@ class DashboardController extends Controller
|
||||
$userId = Auth::id();
|
||||
$now = Carbon::now();
|
||||
|
||||
$latestMonth = $now->copy();
|
||||
$latestYear = $latestMonth->year;
|
||||
|
||||
// 1. 本月基礎統計 (用一個查詢同時撈出「總金額」與「總筆數」)
|
||||
$monthStats = Expense::where('user_id', $userId)
|
||||
->whereYear('date', $now->year)
|
||||
->whereMonth('date', $now->month)
|
||||
->whereYear('date', $latestYear)
|
||||
->whereMonth('date', $latestMonth)
|
||||
->selectRaw('SUM(amount) as total_amount, COUNT(id) as total_count')
|
||||
->first();
|
||||
|
||||
if (!$monthStats || $monthStats->total_amount == 0) {
|
||||
// 改用 first() 確保能抓到單筆資料
|
||||
$latestExpense = Expense::where('user_id', $userId)->latest('date')->first();
|
||||
|
||||
if ($latestExpense) {
|
||||
$targetDate = Carbon::parse($latestExpense->date);
|
||||
$latestYear = $targetDate->year;
|
||||
$latestMonth = $targetDate->month;
|
||||
|
||||
// 重新撈取該月份的統計資料
|
||||
$monthStats = Expense::where('user_id', $userId)
|
||||
->whereYear('date', $latestYear)
|
||||
->whereMonth('date', $latestMonth)
|
||||
->selectRaw('SUM(amount) as total_amount, COUNT(id) as total_count')
|
||||
->first();
|
||||
}
|
||||
}
|
||||
|
||||
$monthlyTotal = (float) ($monthStats->total_amount ?? 0);
|
||||
$monthlyCount = (int) ($monthStats->total_count ?? 0);
|
||||
|
||||
// 2. 本月分類統計(圓餅圖)- 保持集合操作即可
|
||||
$categoryStats = Expense::with('category')
|
||||
->where('user_id', $userId)
|
||||
->whereYear('date', $now->year)
|
||||
->whereMonth('date', $now->month)
|
||||
->whereYear('date', $latestYear)
|
||||
->whereMonth('date', $latestMonth)
|
||||
->get()
|
||||
->groupBy(fn($e) => $e->category?->name ?? '未分類')
|
||||
->map(fn($group, $name) => [
|
||||
@@ -86,12 +107,12 @@ class DashboardController extends Controller
|
||||
$monthlyShare = (float) $expense->amount / $totalMonths;
|
||||
|
||||
// 跑這 6 個月的迴圈,看有沒有落在這筆費用的歸屬區間內
|
||||
foreach ($monthlyTrendData as $monthStr => $currentTotal) {
|
||||
foreach ($monthlyTrendData as $monthStr => &$currentTotal) {
|
||||
$currentMonthObj = Carbon::createFromFormat('Y/m', $monthStr)->startOfMonth();
|
||||
|
||||
// 如果圖表上的這個月份,剛好在費用的歸屬起訖之內,就把每月平均金額灌進去!
|
||||
if ($currentMonthObj->betweenIncluded($start, $end)) {
|
||||
$monthlyTrendData[$monthStr] += $monthlyShare;
|
||||
$currentTotal += $monthlyShare;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user