Compare commits

...

2 Commits

Author SHA1 Message Date
4304092b37 test deployed 2026-06-25 15:40:34 +08:00
85972f950c feat: 前端分離+功能api化
1. 新增資產管理CRUD、googleOAuth登入
2. 更改原記帳controller
2026-06-25 14:19:07 +08:00
71 changed files with 4785 additions and 1520 deletions

View File

@@ -0,0 +1,31 @@
name: Laravel-Oracle-Deploy
on:
push:
branches:
- main
jobs:
redeploy:
runs-on: self-hosted
steps:
- name: Sync and Deploy Laravel Backend
run: |
# 🎯 1. 換成你 Oracle 主機上 Laravel 專案的實際路徑
cd /home/ubuntu/apps/finance-backend || exit 1
# 2. 強制拉取 Gitea 上的最新代碼
git fetch origin main
git reset --hard origin/main
# 3. 重啟 Docker 容器並自動編譯
docker compose up -d --build --remove-orphans
# 4. (選用) 讓 Laravel 容器內部執行資料庫遷移與清除快取
# 假設你的 Laravel 容器服務名稱叫 app如果有需要可以解開下面幾行
# docker compose exec -T app php artisan migrate --force
# docker compose exec -T app php artisan config:cache
# docker compose exec -T app php artisan route:cache
# 5. 清理舊的 Docker 鏡像
docker image prune -f

View File

@@ -0,0 +1,23 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use App\Models\User;
use Google\Client as GoogleClient;
use App\Jobs\FetchAndParseGmailInvoices;
class DebugGmailJob extends Command
{
protected $signature = 'gmail:debug-job';
protected $description = '繞過Job快取直接在終端機打印最新未讀信件';
public function handle()
{
$this->info("🔄 正在讀取 User ID 1 的 Google 憑證...");
$user = User::find(1);
app(FetchAndParseGmailInvoices::class, ['user' => $user])->handle(new \App\Services\GmailParserService());
}
}

View File

@@ -0,0 +1,162 @@
<?php
namespace App\Jobs;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Str;
use App\Models\User;
use App\Models\Expense;
use App\Services\GmailParserService;
use Google\Client as GoogleClient;
use Google\Service\Gmail;
use Illuminate\Support\Facades\Log;
use Carbon\Carbon;
class FetchAndParseGmailInvoices implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
protected $user;
public function __construct(User $user)
{
$this->user = $user;
}
public function handle(GmailParserService $parserService)
{
Log::info("====== [DEBUG START] 開始執行 Gmail 抓信任務 ======");
if (!$this->user->google_refresh_token) {
Log::error("❌ 失敗User ID {$this->user->id} 缺乏 google_refresh_token");
return;
}
try {
Log::info("🔄 正在初始化 Google Client & 刷新 Token...");
$client = new GoogleClient();
$client->setClientId(config('services.google.client_id'));
$client->setClientSecret(config('services.google.client_secret'));
$client->refreshToken($this->user->google_refresh_token);
$gmailService = new Gmail($client);
$afterDate = Carbon::now()->subDays(3)->format('Y/m/d');
$searchQuery = "from:cathaybk.com.tw subject:消費彙整通知 after:{$afterDate}";
Log::info("🔍 正在向 Google API 發送搜尋 Query: [{$searchQuery}]");
$response = $gmailService->users_messages->listUsersMessages('me', [
'q' => $searchQuery,
'maxResults' => 10
]);
$messages = $response->getMessages();
if (empty($messages)) {
Log::warning("⚠️ 警告Google API 回傳空陣列!");
return;
}
Log::info("🎯 成功拿到信件清單!總共發現 " . count($messages) . " 封潛在信件,開始逐封處理...");
foreach ($messages as $index => $msgItem) {
$msgId = $msgItem->getId();
Log::info("--- [處理第 " . ($index + 1) . " 封信] ID: {$msgId} ---");
$message = $gmailService->users_messages->get('me', $msgId, ['format' => 'full']);
$payload = $message->getPayload();
$subject = '';
foreach ($payload->getHeaders() as $header) {
if ($header->getName() === 'Subject') {
$subject = $header->getValue();
break;
}
}
Log::info("📬 信件主旨: [{$subject}]");
$body = $this->getDecodedBody($payload);
Log::info("📄 內文解碼完成,準備丟入 Parser...");
// 1. 執行解析(現在國泰會回報陣列,其餘單筆通知我們手動把它包成陣列)
$parsedResult = $parserService->parse($subject, $body);
if (!$parsedResult) {
Log::error("❌ 失敗GmailParserService 無法解析此信件內容");
continue;
}
// 💡 智慧防呆:如果回傳的是單筆消費(一維陣列),我們把它包成二維陣列,這樣下面統一用 foreach 處理
$expensesList = isset($parsedResult['amount']) ? [$parsedResult] : $parsedResult;
Log::info("✨ Parser 解析成功!共發現 " . count($expensesList) . " 筆刷卡消費項目,開始遍歷寫入...");
// 🔄 遍歷這封信裡面的每一筆刷卡紀錄
foreach ($expensesList as $parsedData) {
// 🟢 2. 智慧資產帳戶對照
$matchedAccountRule = \App\Models\AccountRule::where('user_id', $this->user->id)
->get()
->first(function ($rule) use ($subject) {
return Str::contains($subject, $rule->keyword);
});
$accountId = $matchedAccountRule ? $matchedAccountRule->account_id : null;
// 🟢 3. 智慧消費分類對照
$matchedCategoryRule = \App\Models\CategoryRule::where('user_id', $this->user->id)
->get()
->first(function ($rule) use ($parsedData) {
return Str::contains(strtoupper($parsedData['seller_name']), strtoupper($rule->keyword));
});
$categoryId = $matchedCategoryRule ? $matchedCategoryRule->category_id : null;
// 4. 💾 嘗試寫入資料庫
$expense = Expense::firstOrCreate(
[
'user_id' => $this->user->id,
'amount' => $parsedData['amount'],
'seller_name' => $parsedData['seller_name'],
'date' => $parsedData['date'],
],
[
'item_name' => $parsedData['item_name'],
'account_id' => $accountId,
'category_id' => $categoryId,
'note' => 'Gmail自動同步(多筆完全體)',
]
);
if ($expense->wasRecentlyCreated) {
Log::info("✅ 成功!建立全新消費: [{$parsedData['seller_name']}] 額度: [{$parsedData['amount']}], ID: {$expense->id}");
} else {
Log::info(" 提示:[{$parsedData['seller_name']}] 額度: [{$parsedData['amount']}] 已存在,跳過。");
}
}
}
Log::info("====== [DEBUG END] Gmail 抓信任務順利結束 ======");
} catch (\Exception $e) {
Log::error("💥 崩潰handle 內發生致命錯誤: " . $e->getMessage());
}
}
private function getDecodedBody($part)
{
$body = $part->getBody();
if ($body && $body->getData()) {
return base64_decode(str_replace(['-', '_'], ['+', '/'], $body->getData()));
}
$parts = $part->getParts();
if ($parts) {
foreach ($parts as $subPart) {
$result = $this->getDecodedBody($subPart);
if ($result) return $result;
}
}
return '';
}
}

View File

@@ -0,0 +1,40 @@
<?php
namespace App\Console\Commands;
use App\Jobs\UpdateAssetPriceJob;
use App\Models\InvestmentHolding;
use App\Models\Security;
use Illuminate\Console\Command;
class RefreshAllAssetPrices extends Command
{
// 執行此指令的名稱php artisan asset:refresh-prices
protected $signature = 'asset:refresh-prices';
protected $description = '將全系統所有股票與基金的價格更新任務推入 Queue 佇列';
public function handle()
{
// 🟢 1. 從持倉表中撈出所有使用者「目前有在使用」且「不重複」的股票與基金代號
// 這樣能完美確保 2330 只會被爬一次,不會對證交所造成重複負擔
$uniqueHoldings = Security::select('code', 'type', 'name')
->groupBy('code', 'type', 'name') // 去除重複
->get();
$this->info("全系統共發現 " . $uniqueHoldings->count() . " 檔不重複的現役標的,開始指派更新任務...");
$delaySeconds = 0;
foreach ($uniqueHoldings as $holding) {
UpdateAssetPriceJob::dispatch(
$holding->code,
$holding->type,
$holding->name
)->delay(now()->addSeconds($delaySeconds));
$delaySeconds += 2;
}
$this->info("所有任務皆已成功排入背景 Queue預計花費 {$delaySeconds} 秒消化完畢。");
}
}

View File

@@ -0,0 +1,115 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use App\Models\User;
use Google\Client as GoogleClient;
use Google\Service\Gmail;
use Illuminate\Support\Facades\Log;
class TestGmailFetch extends Command
{
protected $signature = 'gmail:test-fetch';
protected $description = '測試抓取最新的一筆發票或刷卡信件,並輸出至 Log 中';
public function handle()
{
// 1. 抓取你剛才綁定成功的使用者(假設 ID 為 1
$user = User::find(1);
if (!$user || !$user->google_refresh_token) {
$this->error('找不到使用者,或該使用者尚未擁有 google_refresh_token');
return;
}
$this->info("🔄 正在初始化 Google Client 并刷新 Token...");
// 2. 初始化 Google Client
$client = new GoogleClient();
$client->setClientId(config('services.google.client_id'));
$client->setClientSecret(config('services.google.client_secret'));
// 用 refresh_token 去跟 Google 交換新的短期 access_token
$client->refreshToken($user->google_refresh_token);
$accessToken = $client->getAccessToken();
// 順手把新的 token 蓋回資料庫(防呆)
$user->update([
'google_access_token' => $accessToken['access_token'],
'google_token_expires_at' => now()->addSeconds($accessToken['expires_in']),
]);
// 3. 呼叫 Gmail 服務
$gmailService = new Gmail($client);
$this->info("🔍 正在透過標籤精準搜尋信用卡消費通知...");
$searchQuery = 'label:信用卡 -is:spam -is:trash';
$response = $gmailService->users_messages->listUsersMessages('me', [
'maxResults' => 1, // 先抓一筆來看內文
'q' => $searchQuery
]);
$messages = $response->getMessages();
if (empty($messages)) {
$this->warn('❌ 找不到任何符合關鍵字的信件!請確認你的 Gmail 裡有這種類型的信。');
return;
}
$msgId = $messages[0]->getId();
$this->info("🎯 成功找到信件 ID: {$msgId},正在下載詳細內容...");
// 4. 抓取信件完整細節
$message = $gmailService->users_messages->get('me', $msgId, ['format' => 'full']);
$payload = $message->getPayload();
$headers = $payload->getHeaders();
// 解析主旨
$subject = '';
foreach ($headers as $header) {
if ($header->getName() === 'Subject') {
$subject = $header->getValue();
break;
}
}
// 解析內文 (處理可能存在的多重 Multipart 結構)
$body = $this->getDecodedBody($payload);
// 5. 🟢 核心現形:把內容原封不動地噴進 Log
Log::info("=== 【GMAIL 測試抓取成功】 ===");
Log::info("主旨: " . $subject);
Log::info("信件 ID: " . $msgId);
Log::info("=== 原始內文開始 ===");
Log::info($body);
Log::info("=== 原始內文結束 ===");
$this->info("✅ 抓取完畢!真實內容已成功寫入 storage/logs/laravel.log快去打開瞧瞧吧");
}
/**
* 輔助方法:遞迴解析 Gmail Body 內容
*/
private function getDecodedBody($part)
{
$body = $part->getBody();
if ($body && $body->getData()) {
// Gmail 的 base64 比較特殊,需要把 - 和 _ 換回來
$sanitizedData = str_replace(['-', '_'], ['+', '/'], $body->getData());
return base64_decode($sanitizedData);
}
$parts = $part->getParts();
if ($parts) {
foreach ($parts as $subPart) {
$result = $this->getDecodedBody($subPart);
if ($result) return $result;
}
}
return '';
}
}

View File

@@ -0,0 +1,122 @@
<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use App\Models\Account;
use Illuminate\Http\Request;
class AccountController extends Controller
{
public function index(Request $request)
{
// 🟢 1. 預先載入 holdings、transactions 還有全新開荒好的 security 字典表!
$accounts = $request->user()->accounts()
->with(['holdings.transactions', 'holdings.security']) // 👈 確保能直接拿到最新價格
->get()
->map(function ($account) {
$data = $account->toArray();
// 🟢 2. 處理股票與基金的成本與估計現值計算
if (in_array($account->type, ['stock', 'fund'])) {
$totalCost = 0;
$totalValue = 0;
foreach ($account->holdings as $holding) {
// 🟢 修正 1直接拿資料庫存好的庫存股數不用再去 transactions 加減計算
$remainingShares = floatval($holding->shares);
if ($remainingShares > 0) {
// 🟢 修正 2拿到最新價格 (如果沒抓到就先給一個暫時的預設值,例如 10方便你 debug 畫面)
$currentPrice = floatval($holding->security?->latest_price ?? 0);
if ($currentPrice == 0) {
// 💡 Debug 觀測:如果還是 0我們先用 avg_cost 頂替,或者去手動確認 securities 表有沒有真的更新到價格
$currentPrice = floatval($holding->avg_cost ?? 0);
}
// 總現值 = 剩餘單位 * 最新價格
$totalValue += ($remainingShares * $currentPrice);
// 總成本:直接拿你畫面上已經有的 avg_cost * shares 算最快最準!
$avgCost = floatval($holding->avg_cost ?? 0);
$totalCost += ($remainingShares * $avgCost);
}
}
// 🟢 捨入並塞入回傳陣列
$data['total_cost'] = round($totalCost); // 持倉成本
$data['total_value'] = round($totalValue); // 目前市值
// 💡 關鍵補強:計算總損益與總報酬率並塞回陣列,消滅前端的 NaN%
$totalProfit = $totalValue - $totalCost;
$totalRate = $totalCost > 0 ? ($totalProfit / $totalCost) * 100 : 0;
// 🚨 請確認這裡的 Key 名稱(例如 total_profit 或是 unrealized_profit
// 要跟你在 Vue 前端 account.xxx 綁定的欄位名稱一模一樣喔!
$data['total_profit'] = round($totalProfit);
$data['total_rate'] = round($totalRate, 2);
}
// 處理信用卡
if ($account->type === 'credit_card') {
$data['unpaid_amount'] = $account->unpaidAmount();
}
return $data;
});
return response()->json($accounts);
}
public function store(Request $request)
{
$validated = $request->validate([
'name' => 'required|string|max:255',
'type' => 'required|in:cash,bank,stock,fund,wallet,credit_card',
'currency' => 'nullable|string|max:10',
'balance' => 'nullable|numeric',
'note' => 'nullable|string',
'billing_day' => 'nullable|integer|min:1|max:31',
'payment_day' => 'nullable|integer|min:1|max:31',
]);
$account = $request->user()->accounts()->create($validated);
return response()->json($account, 201);
}
public function show(Request $request, string $id)
{
$account = $request->user()->accounts()->findOrFail($id);
return response()->json($account);
}
public function update(Request $request, string $id)
{
$account = $request->user()->accounts()->findOrFail($id);
$validated = $request->validate([
'name' => 'sometimes|string|max:255',
'type' => 'sometimes|in:cash,bank,stock,fund,wallet,credit_card',
'currency' => 'nullable|string|max:10',
'balance' => 'nullable|numeric',
'note' => 'nullable|string',
'billing_day' => 'nullable|integer|min:1|max:31',
'payment_day' => 'nullable|integer|min:1|max:31',
]);
$account->update($validated);
return response()->json($account);
}
public function destroy(Request $request, string $id)
{
$account = $request->user()->accounts()->findOrFail($id);
$account->delete();
return response()->json(null, 204);
}
}

View File

@@ -1,7 +1,8 @@
<?php
namespace App\Http\Controllers;
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use App\Models\Category;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Http\Request;
@@ -10,6 +11,10 @@ class CategoryController extends Controller
{
use AuthorizesRequests;
/**
* 新增分類
* POST /api/categories
*/
public function store(Request $request)
{
$validated = $request->validate([
@@ -18,14 +23,19 @@ class CategoryController extends Controller
'icon' => 'nullable|string|max:50',
]);
Category::create([
$category = Category::create([
...$validated,
'user_id' => auth()->id(),
'user_id' => $request->user()->id,
]);
return redirect()->back();
// 🟢 修正:回傳剛剛建立的 JSON 資料與 201 狀態碼給前端 push 入陣列
return response()->json($category, 201);
}
/**
* 修改分類
* PUT /api/categories/{category}
*/
public function update(Request $request, Category $category)
{
$this->authorize('update', $category);
@@ -36,13 +46,20 @@ class CategoryController extends Controller
]);
$category->update($validated);
return redirect()->back();
// 🟢 修正:回傳修改後的最新資料,讓前端動態替換
return response()->json($category);
}
/**
* 刪除分類
* DELETE /api/categories/{category}
*/
public function destroy(Category $category)
{
$this->authorize('delete', $category);
$category->delete();
return redirect()->back();
return response()->json(['message' => '分類刪除成功']);
}
}

View File

@@ -0,0 +1,50 @@
<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use App\Models\CategoryRule;
use Illuminate\Http\Request;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
class CategoryRuleController extends Controller
{
use AuthorizesRequests;
/**
* 新增自動分類規則
* POST /api/category-rules
*/
public function store(Request $request)
{
$validated = $request->validate([
'keyword' => 'required|string|max:255',
'category_id' => 'required|exists:categories,id',
]);
$rule = CategoryRule::create([
...$validated,
'user_id' => $request->user()->id,
]);
// 🟢 核心優化:必須預先載入 category 關聯,否則前端拿到這筆規則物件時,會無法渲染它的分類標籤
$rule->load('category');
return response()->json($rule, 201);
}
/**
* 刪除自動分類規則
* DELETE /api/category-rules/{categoryRule}
*/
public function destroy(CategoryRule $categoryRule)
{
if ($categoryRule->user_id !== $request->user()->id) {
return response()->json(['error' => '未經授權'], 403);
}
$categoryRule->delete();
return response()->json(['message' => '自動分類規則刪除成功']);
}
}

View File

@@ -0,0 +1,114 @@
<?php
namespace App\Http\Controllers\Api;
use App\Models\Expense;
use Illuminate\Support\Facades\Auth;
use Carbon\Carbon;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
class DashboardController extends Controller
{
public function index()
{
$userId = Auth::id();
$now = Carbon::now();
// 1. 本月基礎統計 (用一個查詢同時撈出「總金額」與「總筆數」)
$monthStats = Expense::where('user_id', $userId)
->whereYear('date', $now->year)
->whereMonth('date', $now->month)
->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)
->get()
->groupBy(fn($e) => $e->category?->name ?? '未分類')
->map(fn($group, $name) => [
'name' => $name,
'total' => (float) $group->sum('amount'),
'color' => $group->first()->category?->color ?? '#6B7280',
])
->values();
// 3. 近 6 個月趨勢優化:一次性撈出半年內的所有資料,避免 6 次 SQL 查詢
$sixMonthsAgo = $now->copy()->subMonths(5)->startOfMonth();
$endOfCurrentMonth = $now->copy()->endOfMonth();
// 建立近 6 個月的初始月份清單(例如 ['2026/01' => 0.0, '2026/02' => 0.0 ... ]
$monthlyTrendData = collect(range(5, 0))->mapWithKeys(function ($i) use ($now) {
$monthStr = $now->copy()->subMonths($i)->format('Y/m');
return [$monthStr => 0.0];
})->toArray();
// ➔ (A) 撈取一般消費 (未開啟分攤)
$isPostgres = DB::connection()->getDriverName() === 'pgsql';
$dateGroupRaw = $isPostgres ? "to_char(date, 'YYYY/MM')" : "DATE_FORMAT(date, '%Y/%m')";
$normalExpenses = Expense::where('user_id', $userId)
->where('is_amortized', false)
->where('date', '>=', $sixMonthsAgo)
->selectRaw("{$dateGroupRaw} as month, SUM(amount) as total")
->groupBy('month')
->get();
foreach ($normalExpenses as $expense) {
if (array_key_exists($expense->month, $monthlyTrendData)) {
$monthlyTrendData[$expense->month] += (float) $expense->total;
}
}
// ➔ (B) 智慧分攤消費 (處理跨月、跨年、半年繳大魔王 🎯)
// 撈出所有歸屬期間有交集到這 6 個月範圍內的分攤費用
$amortizedExpenses = Expense::where('user_id', $userId)
->where('is_amortized', true)
->where(function ($query) use ($sixMonthsAgo, $endOfCurrentMonth) {
$query->where('period_start', '<=', $endOfCurrentMonth)
->where('period_end', '>=', $sixMonthsAgo);
})
->get();
foreach ($amortizedExpenses as $expense) {
$start = Carbon::parse($expense->period_start)->startOfMonth();
$end = Carbon::parse($expense->period_end)->endOfMonth();
// 計算這筆費用的總跨月份數 (至少為 1 個月)
$totalMonths = max(1, $start->diffInMonths($end) + 1);
// 算出每月平均攤提金額
$monthlyShare = (float) $expense->amount / $totalMonths;
// 跑這 6 個月的迴圈,看有沒有落在這筆費用的歸屬區間內
foreach ($monthlyTrendData as $monthStr => $currentTotal) {
$currentMonthObj = Carbon::createFromFormat('Y/m', $monthStr)->startOfMonth();
// 如果圖表上的這個月份,剛好在費用的歸屬起訖之內,就把每月平均金額灌進去!
if ($currentMonthObj->betweenIncluded($start, $end)) {
$monthlyTrendData[$monthStr] += $monthlyShare;
}
}
}
// 轉回前端圖表要的格式
$monthlyTrend = collect($monthlyTrendData)->map(function ($total, $monthStr) {
return [
'month' => $monthStr,
'total' => round($total, 2), // 四捨五入到小數點兩位
];
})->values();
return response()->json([
'monthlyTotal' => $monthlyTotal,
'monthlyCount' => $monthlyCount,
'categoryStats' => $categoryStats,
'monthlyTrend' => $monthlyTrend,
]);
}
}

View File

@@ -0,0 +1,136 @@
<?php
namespace App\Http\Controllers\Api; // 💡 建議放到 Api 命名空間下
use App\Http\Controllers\Controller;
use App\Models\Category;
use App\Models\CategoryRule;
use App\Models\Expense;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Http\Request;
class ExpenseController extends Controller
{
use AuthorizesRequests;
/**
* 1. 取得使用者所有支出明細
* GET /api/expenses
*/
public function index()
{
$expenses = Expense::with('category')
->where('user_id', auth()->id())
->orderBy('date', 'desc')
->get();
return response()->json($expenses);
}
/**
* 2. 取得使用者所有的消費分類
* GET /api/categories
*/
public function categories()
{
$categories = Category::where('user_id', auth()->id())->get();
return response()->json($categories);
}
/**
* 3. 取得使用者所有的自動分類規則
* GET /api/category-rules
*/
public function categoryRules()
{
$rules = CategoryRule::with('category')
->where('user_id', auth()->id())
->get();
return response()->json($rules);
}
/**
* 4. 手動新增支出明細
* POST /api/expenses
*/
public function store(Request $request)
{
$validated = $request->validate([
'amount' => 'required|numeric|min:0',
'category_id' => 'nullable|exists:categories,id',
'item_name' => 'nullable|string|max:255',
'seller_name' => 'nullable|string|max:255',
'is_amortized' => 'boolean',
'period_start' => 'nullable|date',
'period_end' => 'nullable|date|after_or_equal:period_start',
'date' => 'required|date',
'note' => 'nullable|string|max:255',
]);
$expense = Expense::create([
...$validated,
'user_id' => $request->user()->id,
]);
// 🟢 核心優化:載入分類關聯,這樣前端拿到的 response.data 才能立刻顯示分類顏色
$expense->load('category');
return response()->json($expense, 201);
}
/**
* 5. 修改單筆支出
* PUT /api/expenses/{expense}
*/
public function update(Request $request, Expense $expense)
{
$this->authorize('update', $expense);
$validated = $request->validate([
'amount' => 'required|numeric|min:0',
'category_id' => 'nullable|exists:categories,id',
'item_name' => 'nullable|string|max:255',
'date' => 'required|date',
'note' => 'nullable|string|max:255',
'seller_name' => 'nullable|string|max:255',
'is_amortized' => 'boolean',
'period_start' => 'nullable|date',
'period_end' => 'nullable|date|after_or_equal:period_start',
]);
$expense->update($validated);
// 🟢 核心優化:同樣載入分類關聯
$expense->load('category');
return response()->json($expense);
}
/**
* 6. 刪除單筆支出
* DELETE /api/expenses/{expense}
*/
public function destroy(Expense $expense)
{
$this->authorize('delete', $expense);
$expense->delete();
return response()->json(['message' => '刪除成功']);
}
/**
* 7. 批量刪除支出
* POST /api/expenses/destroy-batch
*/
public function destroyBatch(Request $request)
{
$request->validate(['ids' => 'required|array']);
Expense::whereIn('id', $request->ids)
->where('user_id', $request->user()->id)
->delete();
return response()->json(['message' => '批量刪除成功']);
}
}

View File

@@ -0,0 +1,123 @@
<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use App\Jobs\UpdateAssetPriceJob;
use App\Models\Account;
use App\Models\InvestmentHolding;
use App\Models\Security;
use Illuminate\Http\Request;
class InvestmentHoldingController extends Controller
{
public function index(Request $request, string $accountId)
{
$account = $request->user()->accounts()->findOrFail($accountId);
// 🟢 1. 預先載入最新價格字典表關聯,避免 N+1 問題
$holdings = $account->holdings()->with('security')->get();
// 🟢 2. 透過 map 幫每檔持倉加工算出市值與報酬率
$processedHoldings = $holdings->map(function ($holding) {
$data = $holding->toArray();
$remainingShares = floatval($holding->shares);
$avgCost = floatval($holding->avg_cost);
// 預設給 0 或拿平均成本防呆
$currentPrice = floatval($holding->security?->latest_price ?? 0);
if ($currentPrice == 0) {
$currentPrice = $avgCost;
}
if ($remainingShares > 0) {
// 單一標的總成本
$totalCost = $remainingShares * $avgCost;
// 單一標目前市值
$currentValue = $remainingShares * $currentPrice;
// 單一標的未實現損益
$profit = $currentValue - $totalCost;
// 單一標的報酬率
$profitRate = $totalCost > 0 ? ($profit / $totalCost) * 100 : 0;
// 🟢 3. 塞入擴充數據欄位
$data['latest_price'] = $currentPrice;
$data['current_value'] = round($currentValue);
$data['profit'] = round($profit);
$data['profit_rate'] = round($profitRate, 2);
} else {
// 庫存為 0 的防呆
$data['latest_price'] = $currentPrice;
$data['current_value'] = 0;
$data['profit'] = 0;
$data['profit_rate'] = 0;
}
return $data;
});
// 傳回包含豐富績效數據的持倉清單
return response()->json($processedHoldings);
}
public function store(Request $request, string $accountId)
{
$account = $request->user()->accounts()->findOrFail($accountId);
$validated = $request->validate([
'type' => 'required|in:stock,fund',
'symbol' => 'required|string|max:20',
'name' => 'required|string|max:255',
]);
$holding = $account->holdings()->create($validated);
// 檢查security: 如果之前有資料不create, 如果之前沒有資料create
$security = Security::firstOrCreate(
['code' => $validated['symbol']], // 尋找條件
[
'type' => $validated['type'],
'name' => $validated['name'],
'source' => $request->input('source') ?? 'twse',
]
);
// 立即派發更新價格的任務
UpdateAssetPriceJob::dispatch($security->code, $security->type, $security->name);
return response()->json($holding, 201);
}
public function show(Request $request, string $accountId, string $id)
{
$account = $request->user()->accounts()->findOrFail($accountId);
$holding = $account->holdings()->findOrFail($id);
return response()->json($holding);
}
public function update(Request $request, string $accountId, string $id)
{
$account = $request->user()->accounts()->findOrFail($accountId);
$holding = $account->holdings()->findOrFail($id);
$validated = $request->validate([
'name' => 'sometimes|string|max:255',
]);
$holding->update($validated);
return response()->json($holding);
}
public function destroy(Request $request, string $accountId, string $id)
{
$account = $request->user()->accounts()->findOrFail($accountId);
$holding = $account->holdings()->findOrFail($id);
$holding->delete();
return response()->json(null, 204);
}
}

View File

@@ -0,0 +1,98 @@
<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use App\Models\InvestmentHolding;
use Illuminate\Http\Request;
class InvestmentTransactionController extends Controller
{
public function index(Request $request, string $holdingId)
{
$holding = InvestmentHolding::whereHas('account', function ($q) use ($request) {
$q->where('user_id', $request->user()->id);
})->findOrFail($holdingId);
return response()->json($holding->transactions()->orderBy('traded_at', 'desc')->get());
}
public function store(Request $request, string $holdingId)
{
$holding = InvestmentHolding::whereHas('account', function ($q) use ($request) {
$q->where('user_id', $request->user()->id);
})->findOrFail($holdingId);
$validated = $request->validate([
'action' => 'required|in:buy,sell',
'shares' => 'nullable|numeric|min:0',
'price' => 'nullable|numeric|min:0',
'fee' => 'nullable|numeric|min:0',
'tax' => 'nullable|numeric|min:0',
'traded_at' => 'required|date',
'note' => 'nullable|string',
'amount' => 'nullable|numeric|min:0', // 實際投入金額(基金用)
'nav' => 'nullable|numeric|min:0', // 淨值(基金用)
]);
$transaction = $holding->transactions()->create($validated);
// 更新持倉的 shares 和 avg_cost
$this->recalculateHolding($holding);
return response()->json($transaction, 201);
}
public function destroy(Request $request, string $holdingId, string $id)
{
$holding = InvestmentHolding::whereHas('account', function ($q) use ($request) {
$q->where('user_id', $request->user()->id);
})->findOrFail($holdingId);
$transaction = $holding->transactions()->findOrFail($id);
$transaction->delete();
$this->recalculateHolding($holding);
return response()->json(null, 204);
}
// 每次買賣後重新計算平均成本和持有股數
private function recalculateHolding(InvestmentHolding $holding): void
{
$transactions = $holding->transactions()->orderBy('traded_at')->get();
$totalUnits = 0;
$totalCost = 0;
$presentUnits = 0;
foreach ($transactions as $tx) {
if ($tx->action === 'buy') {
if ($holding->type === 'fund') {
$units = $tx->nav > 0 ? $tx->amount / $tx->nav : 0;
$totalCost += $tx->amount + $tx->fee;
$presentUnits += $units;
$totalUnits += $units;
} else {
$totalCost += $tx->shares * $tx->price + $tx->fee;
$presentUnits += $tx->shares;
$totalUnits += $tx->shares;
}
} else {
if ($holding->type === 'fund') {
$units = $tx->nav > 0 ? $tx->amount / $tx->nav : 0;
$totalUnits -= $units;
} else {
$totalUnits -= $tx->shares;
}
}
}
$holding->update([
'shares' => max(0, $totalUnits), // 總持有股數
'avg_cost' => $presentUnits > 0 ? $totalCost / $presentUnits : 0,
]);
}
}

View File

@@ -0,0 +1,292 @@
<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use App\Models\Expense;
use App\Models\Category;
use App\Models\CategoryRule;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
class InvoiceImportController extends Controller
{
/**
* 1. API 主入口:執行發票/帳本 CSV 上傳匯入
* POST /api/expenses/import
*/
public function store(Request $request)
{
$request->validate([
'file' => 'required|file',
]);
$file = $request->file('file');
$content = file_get_contents($file->getPathname());
$encoding = mb_detect_encoding($content, ['UTF-8', 'BIG-5', 'UTF-16LE', 'CP950'], true);
if ($encoding && $encoding !== 'UTF-8') {
$content = mb_convert_encoding($content, 'UTF-8', $encoding);
}
$content = preg_replace('/^\xEF\xBB\xBF/', '', $content);
$rules = CategoryRule::with('category')
->where('user_id', auth()->id())
->get();
// 智慧判定財政部官方載具格式
if (str_contains($content, '表頭=M') || str_contains($content, 'M|')) {
[$imported, $updated] = $this->importPipeInvoice($content, $rules);
$formatName = '財政部官方載具發票';
} else {
$handle = fopen('php://memory', 'r+');
fwrite($handle, $content);
rewind($handle);
$firstRow = fgetcsv($handle);
$format = $this->detectFormat($firstRow);
rewind($handle);
if ($format === 'andromoney') {
[$imported, $updated] = $this->importAndroMoney($handle);
$formatName = 'AndroMoney 帳本';
} else {
[$imported, $updated] = $this->importOldCommaInvoice($handle, $rules);
$formatName = '傳統扁平發票 CSV';
}
fclose($handle);
}
return response()->json([
'success' => true,
'imported' => $imported,
'updated' => $updated,
'message' => "{$formatName}】匯入完成!成功新增 {$imported} 筆紀錄,自動跳過重複/負值金額共 {$updated} 筆。"
]);
}
/**
* 2. 財政部官網 Pipe 格式解析
*/
private function importPipeInvoice(string $content, $rules): array
{
$imported = 0;
$updated = 0;
$lines = preg_split('/\r\n|\r|\n/', $content);
$invoices = [];
foreach ($lines as $line) {
if (empty($line) || str_contains($line, '表頭=')) continue;
$parts = explode('|', $line);
$type = $parts[0] ?? '';
if ($type === 'M') {
$invNum = trim($parts[6] ?? '');
if (!$invNum) continue;
$invoices[$invNum] = [
'date' => trim($parts[3] ?? ''),
'seller' => trim($parts[5] ?? ''),
'amount' => (float)trim($parts[7] ?? 0),
'items' => []
];
} elseif ($type === 'D') {
$invNum = trim($parts[1] ?? '');
$itemName = trim($parts[3] ?? '');
if ($invNum && isset($invoices[$invNum]) && $itemName) {
$invoices[$invNum]['items'][] = $itemName;
}
}
}
DB::transaction(function () use ($invoices, $rules, &$imported, &$updated) {
foreach ($invoices as $invoiceNumber => $info) {
if ($info['amount'] < 0) {
$updated++;
continue;
}
$exists = Expense::where('user_id', auth()->id())
->where('invoice_number', $invoiceNumber)
->exists();
if ($exists) {
$updated++;
continue;
}
$d = $info['date'];
$formattedDate = (strlen($d) === 8) ? substr($d, 0, 4) . '-' . substr($d, 4, 2) . '-' . substr($d, 6, 2) : now()->toDateString();
$itemName = implode(', ', $info['items']);
if (mb_strlen($itemName) > 255) {
$itemName = mb_substr($itemName, 0, 252) . '...';
}
$categoryId = $this->guessCategory($info['seller'], $rules);
$expense = Expense::updateOrCreate(
[
'user_id' => auth()->id(),
'invoice_number' => $invoiceNumber,
],
[
'amount' => $info['amount'],
'date' => $formattedDate,
'seller_name' => $info['seller'],
'item_name' => $itemName ?: $info['seller'],
'note' => $info['seller'],
'category_id' => $categoryId,
]
);
if ($expense->wasRecentlyCreated) {
$imported++;
} else {
$updated++;
}
}
});
return [$imported, $updated];
}
/**
* 3. 舊版扁平逗號 CSV 匯入
*/
private function importOldCommaInvoice($handle, $rules): array
{
$imported = 0; $updated = 0;
while (($row = fgetcsv($handle)) !== false) {
if (count($row) < 8) continue;
$invoiceNumber = trim($row[2] ?? '');
$date = trim($row[1] ?? '');
$amount = trim($row[3] ?? '0');
$sellerName = trim($row[7] ?? '');
$itemName = trim($row[13] ?? '');
if (empty($invoiceNumber)) continue;
if ((float)$amount < 0) { $updated++; continue; }
$formattedDate = null;
if (strlen($date) === 8) {
$formattedDate = substr($date, 0, 4) . '-' . substr($date, 4, 2) . '-' . substr($date, 6, 2);
}
$exists = Expense::where('user_id', auth()->id())->where('invoice_number', $invoiceNumber)->exists();
if ($exists) { $updated++; continue; }
$categoryId = $this->guessCategory($sellerName, $rules);
// 🟢 校正:移除所有舊外鍵欄位,對齊 Migration
$expense = Expense::updateOrCreate(
[
'user_id' => auth()->id(),
'invoice_number' => $invoiceNumber
],
[
'amount' => (float)$amount,
'date' => $formattedDate ?: now()->toDateString(),
'seller_name' => $sellerName,
'item_name' => $itemName,
'note' => $sellerName,
'category_id' => $categoryId,
]
);
if ($expense->wasRecentlyCreated) { $imported++; } else { $updated++; }
}
return [$imported, $updated];
}
/**
* 4. AndroMoney 格式匯入
*/
private function importAndroMoney($handle): array
{
$imported = 0; $updated = 0;
fgetcsv($handle);
while (($row = fgetcsv($handle)) !== false) {
$row = array_map(fn($val) => mb_convert_encoding($val, 'UTF-8', 'Big5'), $row);
if (count($row) < 6) continue;
$amount = trim($row[2] ?? '0');
$catName = trim($row[3] ?? '');
$subCatName = trim($row[4] ?? '');
$date = trim($row[5] ?? '');
$note = trim($row[8] ?? '');
$sellerName = trim($row[13] ?? '');
if (preg_match('/^[0-9a-f]{20,}$/i', $note)) { $note = ''; }
if (empty($amount) || empty($date) || (float)$amount == 0) continue;
$formattedDate = null;
if (strlen($date) === 8 && is_numeric($date)) {
$formattedDate = substr($date, 0, 4) . '-' . substr($date, 4, 2) . '-' . substr($date, 6, 2);
}
if (!$formattedDate) { $updated++; continue; }
$categoryId = !empty($catName) ? $this->findOrCreateCategory($catName) : null;
$subcategoryId = (!empty($subCatName) && $categoryId) ? $this->findOrCreateCategory($subCatName, $categoryId) : null;
// 🟢 校正AndroMoney 沒有發票號碼,所以單純用使用者、日期、金額與備註作防重判斷
$exists = Expense::where('user_id', auth()->id())
->where('date', $formattedDate)
->where('amount', abs((float)$amount))
->where('note', $note ?: $sellerName)
->exists();
if ($exists) {
$updated++;
continue;
}
Expense::create([
'user_id' => auth()->id(),
'amount' => abs((float)$amount),
'date' => $formattedDate,
'category_id' => $categoryId,
'subcategory_id' => $subcategoryId,
'note' => $note ?: $sellerName,
'seller_name' => $sellerName,
]);
$imported++;
}
return [$imported, $updated];
}
private function detectFormat(array $firstRow): string
{
if (isset($firstRow[1]) && str_contains($firstRow[1], 'AndroMoney')) { return 'andromoney'; }
return 'invoice';
}
private function findOrCreateCategory(string $name, ?int $parentId = null): int
{
$category = Category::firstOrCreate(
['user_id' => auth()->id(), 'name' => $name, 'parent_id' => $parentId],
['color' => $this->randomColor()]
);
return $category->id;
}
private function randomColor(): string
{
$colors = ['#EF4444', '#F59E0B', '#10B981', '#3B82F6', '#8B5CF6', '#EC4899', '#14B8A6', '#F97316'];
return $colors[array_rand($colors)];
}
private function guessCategory($sellerName, $rules)
{
foreach ($rules as $rule) {
if (str_contains($sellerName, $rule->keyword)) { return $rule->category_id; }
}
return null;
}
}

View File

@@ -0,0 +1,48 @@
<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use App\Models\Security;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
class SecurityController extends Controller
{
public function index(Request $request)
{
$validated = $request->validate([
'type' => ['required', 'in:stock,etf,fund'],
'keyword' => ['required', 'string', 'min:1'],
]);
$results = Security::query()
->where('type', $validated['type'])
->where(function ($query) use ($validated) {
$query->where('code', 'ilike', "%{$validated['keyword']}%")
->orWhere('name', 'ilike', "%{$validated['keyword']}%");
})
->orderBy('code')
->limit(10)
->get(['code', 'name']);
if ($results->isEmpty()) {
if ($validated['type'] === 'fund') {
$res = Http::post("https://www.anuefund.com/anuefundApi/Search/Light", [
'keyword' => $validated['keyword'],
]);
if ($res->ok()) {
$data = $res->json();
foreach ($data['data']['result'] as $item) {
$results->push(new Security([
'code' => $item['fundID'],
'name' => $item['fundName'],
]));
}
}
}
}
return response()->json($results);
}
}

View File

@@ -0,0 +1,269 @@
<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use App\Models\InvestmentHolding;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Carbon\Carbon;
use Illuminate\Support\Facades\Http;
class SecurityPriceController extends Controller
{
/**
* 最新價格/現值 API (自帶過期即時回補機制 )
* GET /api/holdings/{holdingId}/realtime
*/
public function showRealtime(Request $request, string $holdingId)
{
// 1. 驗證持倉是否屬於該使用者
$holding = InvestmentHolding::whereHas('account', function ($q) use ($request) {
$q->where('user_id', $request->user()->id);
})->findOrFail($holdingId);
// 2. 從本地字典表撈出紀錄
$security = DB::table('securities')->where('code', $holding->symbol)->first();
// 💡 關鍵判定:如果字典表根本沒這檔標的,或者資料「過期了」,就即時去戳外網更新
$needUpdate = false;
if (!$security) {
$needUpdate = true;
} else {
$lastUpdate = Carbon::parse($security->updated_at);
// 情境 A最新價格的日期不是今天
if (!$lastUpdate->isToday()) {
$needUpdate = true;
}
// 情境 B如果是今天的台股交易時間 (09:00 - 14:00),且本地資料超過 15 分鐘沒更新,就幫他刷新
elseif (now()->between('09:00', '14:00') && now()->diffInMinutes($lastUpdate) > 15) {
$needUpdate = true;
}
}
if ($needUpdate) {
// 當場發動外網即時救援
$security = $this->fetchAndSaveRealtime($holding);
}
if (!$security) {
return response()->json(['error' => '無法取得該標的的最新價格資料'], 404);
}
// 3. 統一格式回傳給前端
return response()->json([
'symbol' => $holding->symbol,
'name' => $security->name,
'type' => $holding->type,
'latest_price' => (float) $security->latest_price,
'change_amount' => (float) ($security->change_amount ?? 0),
'change_rate' => (float) ($security->change_rate ?? 0),
'updated_at' => $security->updated_at,
]);
}
/**
* 內部方法:即時抓取外部市價並洗回資料庫字典表
*/
private function fetchAndSaveRealtime(InvestmentHolding $holding)
{
$priceData = [
'name' => $holding->name ?? $holding->symbol,
'latest_price' => 0.0,
'change_amount' => 0.0,
'change_rate' => 0.0,
];
// ----------------------------------------
// A. 股票實時抓取
// ----------------------------------------
if ($holding->type === 'stock') {
try {
$exchange = (str_starts_with($holding->symbol, '00') || strlen($holding->symbol) === 4) ? 'tse' : 'tse'; // 可依需求擴充 otc
$res = Http::timeout(5)->get("https://mis.twse.com.tw/stock/api/getStockInfo.jsp", [
'ex_ch' => "{$exchange}_{$holding->symbol}.tw",
'json' => 1,
'delay' => 0,
]);
if ($res->ok() && !empty($res->json('msgArray'))) {
$stock = $res->json('msgArray')[0];
if (isset($stock['^']) && !Carbon::parse($stock['^'])->isToday()) {
$existing = DB::table('securities')->where('code', $holding->symbol)->first();
if ($existing) return $existing;
}
$priceData['name'] = $stock['n'] ?? $priceData['name'];
$currentPrice = $stock['z'] !== '-' ? (float) $stock['z'] : (float) $stock['y'];
$prevPrice = (float) $stock['y'];
$priceData['latest_price'] = $currentPrice;
$priceData['change_amount'] = $currentPrice - $prevPrice;
$priceData['change_rate'] = $prevPrice > 0 ? (($currentPrice - $prevPrice) / $prevPrice) * 100 : 0;
}
} catch (\Exception $e) {
// 網路超時防呆,保留不崩潰
}
}
// ----------------------------------------
// B. 基金實時抓取
// ----------------------------------------
elseif ($holding->type === 'fund') {
try {
$res = Http::timeout(5)->get("https://www.anuefund.com/anuefundApi/FundDetail/FundInfo", [
'fundDetailEnum' => 'FundINFO',
'FundID' => $holding->symbol,
]);
if ($res->ok() && !empty($res->json('data.hearder'))) {
$header = $res->json('data.hearder');
if (isset($header['navDate']) && !Carbon::parse($header['navDate'])->isToday()) {
$existing = DB::table('securities')->where('code', $holding->symbol)->first();
if ($existing) return $existing;
}
$priceData['name'] = $header['fundName'] ?? $priceData['name'];
$priceData['latest_price'] = (float) $header['nav'];
// 鉅亨網實時 API 沒有給當日漲跌幅的話,這裡預設留空或 0
}
} catch (\Exception $e) {
// 防呆
}
}
// 如果連外部都抓不到且本地完全沒資料,就防呆返回 null
if ($priceData['latest_price'] == 0) {
$existing = DB::table('securities')->where('code', $holding->symbol)->first();
if ($existing) return $existing;
}
// 更新或新增進字典表
DB::table('securities')->updateOrInsert(
['code' => $holding->symbol],
[
'name' => $priceData['name'],
'type' => $holding->type,
'source' => $holding->type === 'stock' ? 'twse' : 'anue',
'latest_price' => $priceData['latest_price'],
'change_amount' => $priceData['change_amount'],
'change_rate' => $priceData['change_rate'],
'updated_at' => now(),
'created_at' => now(), // updateOrInsert 在更新時會自動忽略 created_at
]
);
return DB::table('securities')->where('code', $holding->symbol)->first();
}
/**
* 整合後的歷史紀錄 API (股票、基金共用)
* GET /api/holdings/{holdingId}/history
*/
public function history(Request $request, string $holdingId)
{
$holding = InvestmentHolding::whereHas('account', function ($q) use ($request) {
$q->where('user_id', $request->user()->id);
})->with(['transactions'])->findOrFail($holdingId);
// 找出最早的買入點作為時間起點
$firstTx = $holding->transactions->where('action', 'buy')->sortBy('traded_at')->first();
if (!$firstTx) return response()->json(['history' => [], 'buy_points' => []]);
$startDate = Carbon::parse($firstTx->traded_at)->toDateString();
// 拿持倉的 symbol 去字典表查出對應的歷史主鍵 id
$securityId = DB::table('securities')->where('code', $holding->symbol)->value('id');
if (!$securityId) {
return response()->json(['history' => [], 'buy_points' => []]);
}
// 從本地歷史資料庫撈取趨勢
$history = DB::table('security_price_histories')
->where('security_id', $securityId)
->where('price_date', '>=', $startDate)
->orderBy('price_date', 'asc')
->get(['price_date as date', 'price as close'])
->map(function ($item) {
return [
'date' => $item->date,
'close' => (float) $item->close
];
})
->toArray();
// 整合買賣點標記
$buyPoints = $holding->transactions
->where('action', 'buy')
->map(fn($tx) => [
'date' => Carbon::parse($tx->traded_at)->toDateString(),
'price' => (float) ($holding->type === 'fund'
? ($tx->nav ?? $tx->price ?? 0)
: ($tx->price ?? $tx->nav ?? 0)),
'note' => $tx->note ?? '買入',
])->values();
return response()->json([
'history' => $history,
'buy_points' => $buyPoints,
]);
}
public function accountTrend(Request $request, string $accountId)
{
$account = $request->user()->accounts()->findOrFail($accountId);
// 1. 撈出所有目前有庫存的持倉
$holdings = $account->holdings()->where('shares', '>', 0)->get();
// 🟢 關鍵修正:找出所有有庫存標的裡,最古老的一筆買入交易日期
$earliestTxDate = DB::table('investment_transactions')
->whereIn('holding_id', $holdings->pluck('id'))
->where('action', 'buy')
->orderBy('traded_at', 'asc')
->value('traded_at');
// 防呆:如果真的完全沒有交易紀錄,預設才走 30 天;有的話就以最古老日期為起點
$startDate = $earliestTxDate
? Carbon::parse($earliestTxDate)->toDateString()
: now()->subDays(30)->format('Y-m-d');
$securityIds = DB::table('securities')->whereIn('code', $holdings->pluck('symbol'))->pluck('id', 'code');
// 2. 撈取歷史紀錄 (此時起點已經完美回溯到 4 月甚至更早了)
$historyPrices = DB::table('security_price_histories')
->whereIn('security_id', $securityIds->values())
->where('price_date', '>=', $startDate)
->orderBy('price_date', 'asc')
->get()
->groupBy('security_id');
$chartData = [];
foreach ($holdings as $holding) {
$sid = $securityIds->get($holding->symbol);
if (!$sid) continue;
$prices = $historyPrices->get($sid) ?? collect();
$avgCost = floatval($holding->avg_cost);
if ($avgCost <= 0) continue;
$seriesData = [];
foreach ($prices as $hp) {
$dailyRate = ((floatval($hp->price) - $avgCost) / $avgCost) * 100;
$seriesData[] = [
'date' => $hp->price_date,
'rate' => round($dailyRate, 2)
];
}
$chartData[] = [
'symbol' => $holding->symbol,
'name' => $holding->name,
'data' => $seriesData
];
}
return response()->json($chartData);
}
}

View File

@@ -0,0 +1,51 @@
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
use Laravel\Socialite\Facades\Socialite;
class GoogleAuthController extends Controller
{
// 導向 Google 登入頁
public function redirect()
{
return Socialite::driver('google')
->scopes(['https://www.googleapis.com/auth/gmail.readonly'])
->with([
'access_type' => 'offline', // 💡 極其重要:強制要求 Google 回傳長期有效的 refresh_token
'prompt' => 'consent' // 💡 強制跳出授權提示,確保每次都能順利拿到憑證
])
->redirect();
}
// Google 打回來後處理
public function callback()
{
$googleUser = Socialite::driver('google')->stateless()->user();
$user = User::updateOrCreate(
['email' => $googleUser->getEmail()],
[
'name' => $googleUser->getName(),
'google_id' => $googleUser->getId(),
'avatar' => $googleUser->getAvatar(),
'password' => bcrypt(str()->random(24)),
'google_access_token' => $googleUser->token,
'google_refresh_token' => $googleUser->refreshToken, // 💡 只有第一次授權或加了 prompt=consent 才會給
'google_token_expires_at' => now()->addSeconds($googleUser->expiresIn),
]
);
if ($googleUser->refreshToken) {
$user->update(['google_refresh_token' => $googleUser->refreshToken]);
}
$token = $user->createToken('auth_token')->plainTextToken;
// 把 token 帶回前端
return redirect("http://localhost:5173/#/auth/callback?token={$token}&name=" . urlencode($user->name));
}
}

View File

@@ -1,37 +0,0 @@
<?php
namespace App\Http\Controllers;
use App\Models\CategoryRule;
use Illuminate\Http\Request;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
class CategoryRuleController extends Controller
{
use AuthorizesRequests;
public function store(Request $request)
{
$validated = $request->validate([
'keyword' => 'required|string|max:255',
'category_id' => 'required|exists:categories,id',
]);
CategoryRule::create([
...$validated,
'user_id' => auth()->id(),
]);
return redirect()->back();
}
public function destroy(CategoryRule $categoryRule)
{
if ($categoryRule->user_id !== auth()->id()) {
abort(403);
}
$categoryRule->delete();
return redirect()->back();
}
}

View File

@@ -1,57 +0,0 @@
<?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,
]);
}
}

View File

@@ -1,114 +0,0 @@
<?php
namespace App\Http\Controllers;
use App\Models\Category;
use App\Models\CategoryRule;
use App\Models\Expense;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Http\Request;
use Inertia\Inertia;
class ExpenseController extends Controller
{
use AuthorizesRequests;
/**
* Display a listing of the resource.
*/
public function index()
{
$expenses = Expense::with('category')
->where('user_id', auth()->id())
->orderBy('date', 'desc')
->get();
$categories = Category::where('user_id', auth()->id())->get();
$rules = CategoryRule::with('category')
->where('user_id', auth()->id())
->get();
return Inertia::render('Expenses/Index', [
'expenses' => $expenses,
'categories' => $categories,
'rules' => $rules,
]);
}
/**
* Store a newly created resource in storage.
*/
public function store(Request $request)
{
$validated = $request->validate([
'amount' => 'required|numeric|min:0',
'category_id' => 'nullable|exists:categories,id',
'note' => 'nullable|string|max:255',
'date' => 'required|date',
]);
Expense::create([
...$validated,
'user_id' => auth()->id(),
]);
return redirect()->back();
}
/**
* Display the specified resource.
*/
public function show(Expense $expense)
{
//
}
/**
* Show the form for editing the specified resource.
*/
public function edit(Expense $expense)
{
//
}
/**
* Update the specified resource in storage.
*/
public function update(Request $request, Expense $expense)
{
$this->authorize('update', $expense);
$validated = $request->validate([
'amount' => 'required|numeric|min:0',
'category_id' => 'nullable|exists:categories,id',
'note' => 'nullable|string|max:255',
'date' => 'required|date',
]);
$expense->update($validated);
return redirect()->back();
}
/**
* Remove the specified resource from storage.
*/
public function destroy(Expense $expense)
{
$this->authorize('delete', $expense);
$expense->delete();
return redirect()->back();
}
public function destroyBatch(Request $request)
{
$request->validate(['ids' => 'required|array']);
Expense::whereIn('id', $request->ids)
->where('user_id', auth()->id())
->delete();
return redirect()->back();
}
}

View File

@@ -1,258 +0,0 @@
<?php
namespace App\Http\Controllers;
use App\Models\Expense;
use App\Models\Category;
use App\Models\CategoryRule;
use Illuminate\Http\Request;
class InvoiceImportController extends Controller
{
// ── 自動偵測格式 ──
private function detectFormat(array $firstRow): string
{
// AndroMoney 第一行是 "Windows Excel", "理財幫手AndroMoney", 日期
if (isset($firstRow[1]) && str_contains($firstRow[1], 'AndroMoney')) {
return 'andromoney';
}
return 'invoice';
}
// ── 取得或建立分類 ──
private function findOrCreateCategory(string $name, ?int $parentId = null): int
{
$category = Category::firstOrCreate(
[
'user_id' => auth()->id(),
'name' => $name,
'parent_id' => $parentId,
],
[
'color' => $this->randomColor(),
]
);
return $category->id;
}
private function randomColor(): string
{
$colors = [
'#EF4444',
'#F59E0B',
'#10B981',
'#3B82F6',
'#8B5CF6',
'#EC4899',
'#14B8A6',
'#F97316',
];
return $colors[array_rand($colors)];
}
// ── 發票格式匯入 ──
private function importInvoice($handle, $rules): array
{
$imported = 0;
$updated = 0;
while (($row = fgetcsv($handle)) !== false) {
if (count($row) < 8) continue;
$invoiceNumber = trim($row[2] ?? '');
$date = trim($row[1] ?? '');
$amount = trim($row[3] ?? '0');
$sellerName = trim($row[7] ?? '');
$itemName = trim($row[13] ?? '');
if (empty($invoiceNumber)) continue;
if ((float)$amount < 0) {
$updated++;
continue;
}
$formattedDate = null;
if (strlen($date) === 8) {
$formattedDate = substr($date, 0, 4) . '-'
. substr($date, 4, 2) . '-'
. substr($date, 6, 2);
}
$exists = Expense::where('user_id', auth()->id())
->where('invoice_number', $invoiceNumber)
->exists();
if ($exists) {
$updated++;
continue;
}
$categoryId = $this->guessCategory($sellerName, $rules);
$expense = Expense::updateOrCreate(
[
'user_id' => auth()->id(),
'external_id' => $invoiceNumber,
],
[
'type' => 'expense',
'amount' => (float)$amount,
'date' => $formattedDate,
'seller_name' => $sellerName,
'item_name' => $itemName,
'invoice_number' => $invoiceNumber,
'note' => $sellerName,
'category_id' => $categoryId,
]
);
if ($expense->wasRecentlyCreated) {
$imported++;
} else {
$updated++;
}
}
return [$imported, $updated];
}
// ── AndroMoney 格式匯入 ──
private function importAndroMoney($handle): array
{
$imported = 0;
$updated = 0;
// 跳過標題列(第二行)
fgetcsv($handle);
while (($row = fgetcsv($handle)) !== false) {
// 轉換 Big5 → UTF-8
$row = array_map(fn($val) => mb_convert_encoding($val, 'UTF-8', 'Big5'), $row);
if (count($row) < 6) continue;
// 欄位對應
// A=0:id, B=1:幣別, C=2:金額, D=3:分類, E=4:子分類
// F=5:日期, G=6:付款, H=7:收款, I=8:備註, M=12:商家, N=13:uid
$amount = trim($row[2] ?? '0');
$catName = trim($row[3] ?? '');
$subCatName = trim($row[4] ?? '');
$date = trim($row[5] ?? '');
$payOut = trim($row[6] ?? '');
$payIn = trim($row[7] ?? '');
$note = trim($row[8] ?? '');
$sellerName = trim($row[13] ?? '');
// 過濾掉看起來像 uid 的值32碼以上的hex字串
if (preg_match('/^[0-9a-f]{20,}$/i', $note)) {
$note = '';
}
if (empty($amount) || empty($date)) continue;
if ((float)$amount == 0) continue;
// 日期格式轉換 20260106 → 2026-01-06
$formattedDate = null;
if (strlen($date) === 8 && is_numeric($date)) {
$formattedDate = substr($date, 0, 4) . '-'
. substr($date, 4, 2) . '-'
. substr($date, 6, 2);
}
// 日期無效就跳過
if (!$formattedDate) {
$updated++;
continue;
}
// 判斷收入/支出
// 付款欄有值 = 支出,收款欄有值 = 收入
$type = !empty($payIn) ? 'income' : 'expense';
// 取得或建立主分類
$categoryId = null;
if (!empty($catName)) {
$categoryId = $this->findOrCreateCategory($catName);
}
// 取得或建立子分類(掛在主分類下)
$subcategoryId = null;
if (!empty($subCatName) && $categoryId) {
$subcategoryId = $this->findOrCreateCategory($subCatName, $categoryId);
}
// uid 是 row[12]
$uid = trim($row[12] ?? '');
$expense = Expense::updateOrCreate(
[
'user_id' => auth()->id(),
'external_id' => $uid ?: null,
],
[
'type' => $type,
'amount' => abs((float)$amount),
'date' => $formattedDate,
'category_id' => $categoryId,
'subcategory_id' => $subcategoryId,
'note' => $note ?: $sellerName,
'seller_name' => $sellerName,
]
);
if ($expense->wasRecentlyCreated) {
$imported++;
} else {
$updated++;
}
}
return [$imported, $updated];
}
// ── 自動分類(發票用)──
private function guessCategory($sellerName, $rules)
{
foreach ($rules as $rule) {
if (str_contains($sellerName, $rule->keyword)) {
return $rule->category_id;
}
}
return null;
}
public function index()
{
return inertia('Expenses/Import');
}
public function store(Request $request)
{
$request->validate([
'file' => 'required|file|mimes:csv,txt',
]);
$file = $request->file('file');
$handle = fopen($file->getPathname(), 'r');
// 讀第一行偵測格式
$firstRow = fgetcsv($handle);
$format = $this->detectFormat($firstRow);
$rules = CategoryRule::with('category')
->where('user_id', auth()->id())
->get();
if ($format === 'andromoney') {
[$imported, $updated] = $this->importAndroMoney($handle);
} else {
[$imported, $updated] = $this->importInvoice($handle, $rules);
}
fclose($handle);
$formatName = $format === 'andromoney' ? 'AndroMoney' : '發票';
return redirect()->route('expenses.index')->with([
'message' => "{$formatName}】匯入完成!新增 {$imported} 筆,更新 {$updated}",
]);
}
}

View File

@@ -0,0 +1,140 @@
<?php
namespace App\Jobs;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use App\Models\User;
use App\Models\Expense;
use App\Models\CategoryRule; // 💡 假設這是你存自動分類規則的 Model
use App\Services\GmailParserService;
use Google\Client as GoogleClient;
use Google\Service\Gmail;
use Google\Service\Gmail\ModifyMessageRequest;
use Illuminate\Support\Facades\Log;
class FetchAndParseGmailInvoices implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
protected $user;
/**
* 這裡我們可以在初始化時傳入指定 User或者在 handle 裡跑全部 User
*/
public function __construct(User $user)
{
$this->user = $user;
}
public function handle(GmailParserService $parserService)
{
// 1. 檢查使用者憑證
if (!$this->user->google_refresh_token) {
Log::warning("User ID {$this->user->id} 試圖執行抓信任務,但缺乏 refresh_token。");
return;
}
try {
// 2. 初始化 Google Client 並刷新 Token
$client = new GoogleClient();
$client->setClientId(config('services.google.client_id'));
$client->setClientSecret(config('services.google.client_secret'));
$client->refreshToken($this->user->google_refresh_token);
$gmailService = new Gmail($client);
// 3. 搜尋帶有專屬標籤且「未讀」的信件
$searchQuery = 'label:FinBuddy-Card is:unread';
$response = $gmailService->users_messages->listUsersMessages('me', [
'q' => $searchQuery,
'maxResults' => 20 // 每次最多處理 20 筆,防爆
]);
$messages = $response->getMessages();
if (empty($messages)) {
Log::info("User ID {$this->user->id}: 沒發現符合條件的未讀刷卡信件。");
return;
}
// 4. 逐封拆解信件
foreach ($messages as $msgItem) {
$msgId = $msgItem->getId();
$message = $gmailService->users_messages->get('me', $msgId, ['format' => 'full']);
$payload = $message->getPayload();
// 抓取主旨
$subject = '';
foreach ($payload->getHeaders() as $header) {
if ($header->getName() === 'Subject') {
$subject = $header->getValue();
break;
}
}
// 遞迴拿到內文
$body = $this->getDecodedBody($payload);
// 5. 丟給 Parser 進行 Regex 解析
$parsedData = $parserService->parse($subject, $body);
if ($parsedData) {
// 🟢 智慧分類:根據商家名稱反查資料庫裡的自動分類規則
// 假設你的規則表有關鍵字比對 (例如: keyword = 'PCHOME', category_id = 3)
$matchedRule = CategoryRule::where('user_id', $this->user->id)
->get()
->first(function ($rule) use ($parsedData) {
return Str::contains(strtoupper($parsedData['seller_name']), strtoupper($rule->keyword));
});
$categoryId = $matchedRule ? $matchedRule->category_id : null;
// 6. 寫入消費紀錄(我們已經補上了 $fillable絕對暢行無阻
Expense::create([
'user_id' => $this->user->id,
'amount' => $parsedData['amount'],
'item_name' => $parsedData['item_name'],
'seller_name' => $parsedData['seller_name'],
'date' => $parsedData['date'],
'category_id' => $categoryId,
'note' => 'Gmail背景自動記帳',
]);
Log::info("User ID {$this->user->id}: 成功自動記帳一筆金額 {$parsedData['amount']},商家: {$parsedData['seller_name']}");
}
// 7. 🟢 防重複防線:記帳成功後,立刻把信件在 Gmail 標記為「已讀」
$mods = new ModifyMessageRequest();
$mods->setRemoveLabelIds(['UNREAD']); // 移除未讀標籤 = 標記已讀
$gmailService->users_messages->modify('me', $msgId, $mods);
}
} catch (\Exception $e) {
Log::error("User ID {$this->user->id} Gmail 自動抓帳 Job 發生崩潰: " . $e->getMessage());
}
}
/**
* 遞迴解析內文的輔助方法
*/
private function getDecodedBody($part)
{
$body = $part->getBody();
if ($body && $body->getData()) {
$sanitizedData = str_replace(['-', '_'], ['+', '/'], $body->getData());
return base64_decode($sanitizedData);
}
$parts = $part->getParts();
if ($parts) {
foreach ($parts as $subPart) {
$result = $this->getDecodedBody($subPart);
if ($result) return $result;
}
}
return '';
}
}

View File

@@ -0,0 +1,148 @@
<?php
namespace App\Jobs;
use App\Models\Security;
use App\Models\SecurityPriceHistories;
use Carbon\Carbon;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
class UpdateAssetPriceJob implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
protected $symbol;
protected $type;
protected $defaultName;
public function __construct(string $symbol, string $type, string $defaultName)
{
$this->symbol = $symbol;
$this->type = $type;
$this->defaultName = $defaultName;
}
public function handle(): void
{
try {
Log::info("🔄 開始從持倉清單發動爬蟲: [{$this->symbol}] {$this->defaultName}");
$isRealPrice = true;
$latestPrice = 0;
$latestPriceDate = null;
$name = $this->defaultName;
$changeAmount = 0;
$changeRate = 0;
$error = null;
// 股票去爬證交所
if ($this->type === 'stock') {
Log::info("開始抓取{$this->type}:{$this->symbol}價格");
$response = Http::timeout(10)->get("https://mis.twse.com.tw/stock/api/getStockInfo.jsp?ex_ch=tse_{$this->symbol}.tw");
if ($response->successful()) {
$json = $response->json();
$info = $json['msgArray'][0] ?? null;
if (isset($info['^']) && !Carbon::parse($info['^'])->isToday()) {
$isRealPrice = false;
}
if ($info) {
$latestPrice = floatval($info['z'] ?? $info['o'] ?? 0);
$latestPriceDate = isset($info['d']) ? Carbon::parse($info['d'])->format('Y-m-d') : now()->format('Y-m-d');
$name = $info['n'] ?? $this->defaultName;
if (isset($info['y']) && $latestPrice > 0) {
$changeAmount = floatval($latestPrice - $info['y']);
$changeRate = ($changeAmount / $info['y']) * 100;
}
}
}
} elseif ($this->type === 'fund') {
Log::info("開始抓取{$this->type}:{$this->symbol}價格");
// 去鉅亨網抓
$response = Http::timeout(10)
->withHeaders([
'User-Agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
'Referer' => 'https://www.anuefund.com/',
'Accept' => 'application/json, text/plain, */*',
])
->get("https://www.anuefund.com/anuefundApi/FundDetail/FundInfo", [
'fundDetailEnum' => 'FundINFO',
'FundID' => $this->symbol
]);
if ($response->successful()) {
$json = $response->json();
$headerInfo = $json['data']['hearder'] ?? null;
if (isset($headerInfo['navDate']) && !Carbon::parse($headerInfo['navDate'])->isToday()) {
//不是當天資料不更新
$isRealPrice = false;
}
if ($headerInfo) {
$latestPriceDate = isset($headerInfo['navDate']) ? substr($headerInfo['navDate'], 0, 10) : now()->format('Y-m-d');
$latestPrice = floatval($headerInfo['nav'] ?? 0);
if ($latestPriceDate !== now()->format('Y-m-d')) {
//不是當天資料不更新
$isRealPrice = false;
$latestPrice = 0;
}
$name = $headerInfo['fundName'] ?? $this->defaultName;
$changeAmount = floatval($headerInfo['upDown'] ?? 0);
$changeRate = floatval($headerInfo['upDownRate'] ?? 0);
}
}
Log::info("抓取{$this->type}:{$this->symbol}資料結束");
}
// 爬蟲成功拿到有效股價,幫新表補資料
if ($latestPrice > 0 && $isRealPrice) {
Log::info("開始寫入Security和SecurityPriceHistories表標的: [{$this->symbol}],價格: {$latestPrice}---");
$security = Security::updateOrCreate(
['code' => $this->symbol],
[
'type' => $this->type,
'name' => $name,
'latest_price' => $latestPrice,
'latest_price_at' => $latestPriceDate,
'change_amount' => $changeAmount,
'change_rate' => $changeRate,
'source' => 'twse',
]
);
SecurityPriceHistories::updateOrCreate(
[
'security_id' => $security->id,
'price_date' => now()->format('Y-m-d'), // 記錄今天的日期
],
[
'price' => $latestPrice,
'change_amount' => $changeAmount,
'change_rate' => $changeRate,
'created_at' => now(),
'updated_at' => now(),
]
);
Log::info("✅ Security & SecurityPriceHistories 標的 [{$this->symbol}] 補齊並更新成功: {$latestPrice}");
} elseif (!$isRealPrice) {
Log::info(" 標的 [{$this->symbol}] 抓到的價格是非即時的,不更新價格資訊。");
} else {
Log::warning("⚠️ 標的 [{$this->symbol}] 未能從證交所抓到有效價格,{$error}");
}
} catch (\Exception $e) {
Log::error("❌ 更新標的 [{$this->symbol}] 價格時發生異常: " . $e->getMessage());
$this->release(60);
}
}
}

54
app/Models/Account.php Normal file
View File

@@ -0,0 +1,54 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Account extends Model
{
protected $fillable = [
'user_id',
'name',
'type',
'currency',
'balance',
'note',
'billing_day',
'payment_day',
];
public function user()
{
return $this->belongsTo(User::class);
}
public function holdings()
{
return $this->hasMany(InvestmentHolding::class);
}
public function expenses()
{
return $this->hasMany(Expense::class);
}
public function unpaidAmount()
{
$billingDay = $this->billing_day ?? 1;
$now = now();
// 如果今天還沒到結帳日,帳單週期是上個月結帳日到這個月結帳日
if ($now->day < $billingDay) {
$start = $now->copy()->subMonth()->setDay($billingDay);
$end = $now->copy()->setDay($billingDay)->subDay();
} else {
$start = $now->copy()->setDay($billingDay);
$end = $now->copy()->addMonth()->setDay($billingDay)->subDay();
}
return $this->expenses()
->whereBetween('date', [$start->toDateString(), $end->toDateString()])
->sum('amount');
}
}

View File

@@ -0,0 +1,10 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class AccountRule extends Model
{
//
}

View File

@@ -7,18 +7,18 @@ use Illuminate\Database\Eloquent\Model;
class Expense extends Model
{
protected $fillable = [
'user_id',
'category_id',
'subcategory_id',
'type',
'amount',
'note',
'date',
'invoice_number',
'seller_name',
'item_name',
'external_id',
];
'user_id',
'amount',
'category_id',
'item_name',
'date',
'note',
'seller_name',
'account_id',
'is_amortized',
'period_start',
'period_end',
];
protected $casts = [
'date' => 'date:Y-m-d',
@@ -39,4 +39,9 @@ class Expense extends Model
{
return $this->belongsTo(Category::class, 'subcategory_id');
}
public function account()
{
return $this->belongsTo(Account::class);
}
}

View File

@@ -0,0 +1,32 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class InvestmentHolding extends Model
{
protected $fillable = [
'account_id',
'type',
'symbol',
'name',
'shares',
'avg_cost',
];
public function account()
{
return $this->belongsTo(Account::class);
}
public function transactions()
{
return $this->hasMany(InvestmentTransaction::class, 'holding_id');
}
public function security()
{
return $this->hasOne(Security::class, 'code', 'symbol');
}
}

View File

@@ -0,0 +1,30 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class InvestmentTransaction extends Model
{
protected $fillable = [
'holding_id',
'action',
'shares',
'price',
'fee',
'tax',
'traded_at',
'note',
'amount', // 實際投入金額(基金用)
'nav', // 淨值(基金用)
];
protected $casts = [
'traded_at' => 'date',
];
public function holding()
{
return $this->belongsTo(InvestmentHolding::class, 'holding_id');
}
}

33
app/Models/Security.php Normal file
View File

@@ -0,0 +1,33 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Security extends Model
{
protected $fillable = [
'code',
'type',
'source',
'name',
'latest_price',
'latest_price_at',
'change_amount',
'change_rate',
'meta',
];
protected $casts = [
'latest_price_at' => 'datetime',
'latest_price' => 'decimal:4',
'change_amount' => 'decimal:4',
'change_rate' => 'decimal:4',
'meta' => 'array',
];
public function historicPrices()
{
return $this->hasMany(SecurityPriceHistories::class, 'security_id', 'id');
}
}

View File

@@ -0,0 +1,29 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class SecurityPriceHistories extends Model
{
protected $fillable = [
'id',
'security_id',
'price_date',
'price',
'change_amount',
'change_rate',
];
protected $casts = [
'price' => 'decimal:4',
'price_date' => 'datetime',
'change_amount' => 'decimal:4',
'change_rate' => 'decimal:4',
];
public function security()
{
return $this->belongsTo(Security::class, 'security_id', 'id');
}
}

View File

@@ -5,12 +5,14 @@ namespace App\Models;
// use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use App\Models\Account;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
class User extends Authenticatable
{
/** @use HasFactory<\Database\Factories\UserFactory> */
use HasFactory, Notifiable;
use HasFactory, Notifiable, HasApiTokens;
/**
* The attributes that are mass assignable.
@@ -21,6 +23,11 @@ class User extends Authenticatable
'name',
'email',
'password',
'google_id',
'avatar',
'google_access_token',
'google_refresh_token',
'google_token_expires_at',
];
/**
@@ -45,4 +52,9 @@ class User extends Authenticatable
'password' => 'hashed',
];
}
public function accounts()
{
return $this->hasMany(Account::class);
}
}

View File

@@ -0,0 +1,180 @@
<?php
namespace App\Services;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Log;
use Carbon\Carbon;
class GmailParserService
{
protected array $parserMatrix = [
[
'keywords' => ['國泰世華銀行消費彙整通知'],
'method' => 'parseCathaySummary'
],
[
'keywords' => ['永豐銀行信用卡消費通知'],
'method' => 'parseSinoPacNotification'
],
[
'keywords' => ['電子發票', '載具', '發票開立通知'],
'method' => 'parseElectronicInvoice'
],
[
'keywords' => ['消費通知', '刷卡', '卡片消費'],
'method' => 'parseCreditCardNotification'
],
];
public function parse(string $subject, string $body): ?array
{
// 🔄 遍歷矩陣,尋找第一個命中的規則
foreach ($this->parserMatrix as $rule) {
if (Str::contains($subject, $rule['keywords'])) {
$method = $rule['method'];
// 動態呼叫對應的方法 (例如 $this->parseCathaySummary($body) )
return $this->{$method}($body);
}
}
Log::info("【Parser】忽略信件主旨未命中任何對照規則: [{$subject}]");
return null;
}
/**
* 🟢 國泰世華消費彙整信件專屬解析
*/
private function parseCathaySummary(string $body): ?array
{
$cleanBody = preg_replace('/\s+/', ' ', $body);
if (preg_match('/(\d{4}\/\d{2}\/\d{2})/u', $cleanBody, $dateMatches)) {
$date = Carbon::createFromFormat('Y/m/d', $dateMatches[1])->format('Y-m-d');
} else {
$date = now()->format('Y-m-d');
}
$pattern = '/NT\$\s*([0-9,]+)\s*<\/td>\s*<td[^>]*>\s*([^<\s&]+)\s*<\/td>/u';
if (!preg_match_all($pattern, $cleanBody, $matches, PREG_SET_ORDER)) {
Log::error("【Parser】國泰信件未命中消費明細。");
return null;
}
$results = [];
foreach ($matches as $match) {
$sellerName = $this->convertFullWidthToHalfWidth(trim($match[2]));
$results[] = [
'amount' => floatval(str_replace(',', '', $match[1])),
'item_name' => "信用卡消費: {$sellerName}",
'seller_name' => $sellerName,
'date' => $date,
'category_id' => null,
];
}
return $results;
}
/**
* 永豐銀行信用卡消費通知(單筆制)
*/
private function parseSinoPacNotification(string $body): ?array
{
$cleanBody = preg_replace('/\s+/', ' ', $body);
$amount = 0;
$sellerName = '永豐刷卡消費';
if (preg_match('/(?:新臺幣|TWD)\s*([0-9,]+)/u', $cleanBody, $amountMatches)) {
$amount = floatval(str_replace(',', '', $amountMatches[1]));
}
if (preg_match('/特約商店[:]\s*([^<\s]+)/u', $cleanBody, $merchantMatches)) {
$sellerName = trim($merchantMatches[1]);
}
if ($amount === 0) return null;
if (preg_match('/(\d{4}\/\d{2}\/\d{2})/u', $cleanBody, $dateMatches)) {
$date = Carbon::createFromFormat('Y/m/d', $dateMatches[1])->format('Y-m-d');
} else {
$date = now()->format('Y-m-d');
}
$sellerName = $this->convertFullWidthToHalfWidth($sellerName);
return [
'amount' => $amount,
'item_name' => "信用卡消費: {$sellerName}",
'seller_name' => $sellerName,
'date' => $date,
'category_id' => null,
];
}
/**
* 解析電子發票信件
*/
private function parseElectronicInvoice(string $body): ?array
{
$amount = 0;
$sellerName = '未知商家';
if (preg_match('/(總計|金額|總金額)[:]\s*?\$?([0-9,]+)/u', $body, $matches)) {
$amount = floatval(str_replace(',', '', $matches[2]));
}
if (preg_match('/(賣方|開立店家|商店名稱)[:]\s*?([^\n<\s]+)/u', $body, $matches)) {
$sellerName = trim($matches[2]);
}
if ($amount === 0) return null;
return [
'amount' => $amount,
'item_name' => '電子發票消費',
'seller_name' => $sellerName,
'date' => now()->format('Y-m-d'),
'category_id' => null,
];
}
/**
* 解析信用卡消費通知(泛用型備援)
*/
private function parseCreditCardNotification(string $body): ?array
{
$amount = 0;
$sellerName = '一般刷卡消費';
if (preg_match('/(NT\$|元|TWD)\s*?([0-9,]+)/u', $body, $matches)) {
$amount = floatval(str_replace(',', '', $matches[2]));
} elseif (preg_match('/([0-9,]+)\s*?(元)/u', $body, $matches)) {
$amount = floatval(str_replace(',', '', $matches[1]));
}
if (preg_match('/於\s*?([^\n\](]+?)\s*?消費/u', $body, $matches)) {
$sellerName = trim($matches[1]);
} elseif (preg_match('/(特約商店|消費商店|商店)[:]\s*?([^\n<\s]+)/u', $body, $matches)) {
$sellerName = trim($matches[2]);
}
if ($amount === 0) return null;
return [
'amount' => $amount,
'item_name' => "刷卡消費: {$sellerName}",
'seller_name' => $sellerName,
'date' => now()->format('Y-m-d'),
'category_id' => null,
];
}
private function convertFullWidthToHalfWidth(string $str): string
{
$str = str_replace('&nbsp;', '', $str);
return mb_convert_kana($str, 'asKV', 'UTF-8');
}
}

View File

@@ -3,12 +3,18 @@
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
use Illuminate\Support\Facades\Route;
return Application::configure(basePath: dirname(__DIR__))
->withRouting(
web: __DIR__.'/../routes/web.php',
api: __DIR__.'/../routes/api.php',
commands: __DIR__.'/../routes/console.php',
health: '/up',
then: function () {
Route::middleware('web')
->group(base_path('routes/auth.php'));
}
)
->withMiddleware(function (Middleware $middleware): void {
$middleware->web(append: [

View File

@@ -7,10 +7,13 @@
"license": "MIT",
"require": {
"php": "^8.2",
"google/apiclient": "^2.19",
"inertiajs/inertia-laravel": "^2.0",
"laravel/framework": "^12.0",
"laravel/sanctum": "^4.0",
"laravel/socialite": "^5.27",
"laravel/tinker": "^2.10.1",
"orangehill/iseed": "^3.8",
"tightenco/ziggy": "^2.0"
},
"require-dev": {

744
composer.lock generated
View File

@@ -4,7 +4,7 @@
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
"This file is @generated automatically"
],
"content-hash": "aa715b4183fb30d40dbf87a9f5da20c6",
"content-hash": "27f692f281e65d361351a19f032320f1",
"packages": [
{
"name": "brick/math",
@@ -508,6 +508,72 @@
],
"time": "2025-03-06T22:45:56+00:00"
},
{
"name": "firebase/php-jwt",
"version": "v7.1.0",
"source": {
"type": "git",
"url": "https://github.com/googleapis/php-jwt.git",
"reference": "b374a5d1a4f1f67fadc2165cdb284645945e2fc0"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/googleapis/php-jwt/zipball/b374a5d1a4f1f67fadc2165cdb284645945e2fc0",
"reference": "b374a5d1a4f1f67fadc2165cdb284645945e2fc0",
"shasum": ""
},
"require": {
"php": "^8.0"
},
"require-dev": {
"guzzlehttp/guzzle": "^7.4",
"phpfastcache/phpfastcache": "^9.2",
"phpseclib/phpseclib": "~3.0",
"phpspec/prophecy-phpunit": "^2.0",
"phpunit/phpunit": "^9.5",
"psr/cache": "^2.0||^3.0",
"psr/http-client": "^1.0",
"psr/http-factory": "^1.0"
},
"suggest": {
"ext-sodium": "Support EdDSA (Ed25519) signatures",
"paragonie/sodium_compat": "Support EdDSA (Ed25519) signatures when libsodium is not present",
"phpseclib/phpseclib": "Support PS256 (RSASSA-PSS) signatures"
},
"type": "library",
"autoload": {
"psr-4": {
"Firebase\\JWT\\": "src"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"BSD-3-Clause"
],
"authors": [
{
"name": "Neuman Vong",
"email": "neuman+pear@twilio.com",
"role": "Developer"
},
{
"name": "Anant Narayanan",
"email": "anant@php.net",
"role": "Developer"
}
],
"description": "A simple library to encode and decode JSON Web Tokens (JWT) in PHP. Should conform to the current spec.",
"homepage": "https://github.com/googleapis/php-jwt",
"keywords": [
"jwt",
"php"
],
"support": {
"issues": "https://github.com/googleapis/php-jwt/issues",
"source": "https://github.com/googleapis/php-jwt/tree/v7.1.0"
},
"time": "2026-06-11T17:54:14+00:00"
},
{
"name": "fruitcake/php-cors",
"version": "v1.4.0",
@@ -579,6 +645,183 @@
],
"time": "2025-12-03T09:33:47+00:00"
},
{
"name": "google/apiclient",
"version": "v2.19.3",
"source": {
"type": "git",
"url": "https://github.com/googleapis/google-api-php-client.git",
"reference": "a1f02761994fd9defb20f6f1449205fd66f450de"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/googleapis/google-api-php-client/zipball/a1f02761994fd9defb20f6f1449205fd66f450de",
"reference": "a1f02761994fd9defb20f6f1449205fd66f450de",
"shasum": ""
},
"require": {
"firebase/php-jwt": "^6.0||^7.0",
"google/apiclient-services": "~0.350",
"google/auth": "^1.37",
"guzzlehttp/guzzle": "^7.4.5",
"guzzlehttp/psr7": "^2.6",
"monolog/monolog": "^2.9||^3.0",
"php": "^8.1"
},
"require-dev": {
"cache/filesystem-adapter": "^1.1",
"composer/composer": "^2.9",
"phpcompatibility/php-compatibility": "^9.2",
"phpspec/prophecy-phpunit": "^2.1",
"phpunit/phpunit": "^9.6",
"squizlabs/php_codesniffer": "^3.8",
"symfony/css-selector": "~2.1",
"symfony/dom-crawler": "~2.1"
},
"suggest": {
"cache/filesystem-adapter": "For caching certs and tokens (using Google\\Client::setCache)"
},
"type": "library",
"extra": {
"component": {
"entry": "src/Client.php"
},
"branch-alias": {
"dev-main": "2.x-dev"
}
},
"autoload": {
"files": [
"src/aliases.php"
],
"psr-4": {
"Google\\": "src/"
},
"classmap": [
"src/aliases.php"
]
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"Apache-2.0"
],
"description": "Client library for Google APIs",
"homepage": "http://developers.google.com/api-client-library/php",
"keywords": [
"google"
],
"support": {
"issues": "https://github.com/googleapis/google-api-php-client/issues",
"source": "https://github.com/googleapis/google-api-php-client/tree/v2.19.3"
},
"time": "2026-05-04T21:00:36+00:00"
},
{
"name": "google/apiclient-services",
"version": "v0.445.0",
"source": {
"type": "git",
"url": "https://github.com/googleapis/google-api-php-client-services.git",
"reference": "d76b09227d898db351457010c88f39eedfb815aa"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/googleapis/google-api-php-client-services/zipball/d76b09227d898db351457010c88f39eedfb815aa",
"reference": "d76b09227d898db351457010c88f39eedfb815aa",
"shasum": ""
},
"require": {
"php": "^8.1"
},
"require-dev": {
"phpunit/phpunit": "^9.6"
},
"type": "library",
"autoload": {
"files": [
"autoload.php"
],
"psr-4": {
"Google\\Service\\": "src"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"Apache-2.0"
],
"description": "Client library for Google APIs",
"homepage": "http://developers.google.com/api-client-library/php",
"keywords": [
"google"
],
"support": {
"issues": "https://github.com/googleapis/google-api-php-client-services/issues",
"source": "https://github.com/googleapis/google-api-php-client-services/tree/v0.445.0"
},
"time": "2026-06-15T01:58:30+00:00"
},
{
"name": "google/auth",
"version": "v1.51.0",
"source": {
"type": "git",
"url": "https://github.com/googleapis/google-auth-library-php.git",
"reference": "4c4776e398ff255e81b3b8c4373983f5e1b765bf"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/googleapis/google-auth-library-php/zipball/4c4776e398ff255e81b3b8c4373983f5e1b765bf",
"reference": "4c4776e398ff255e81b3b8c4373983f5e1b765bf",
"shasum": ""
},
"require": {
"firebase/php-jwt": "^6.0||^7.0",
"guzzlehttp/guzzle": "^7.4.5",
"guzzlehttp/psr7": "^2.4.5",
"php": "^8.1",
"psr/cache": "^2.0||^3.0",
"psr/http-message": "^1.1||^2.0",
"psr/log": "^2.0||^3.0"
},
"require-dev": {
"guzzlehttp/promises": "^2.0",
"kelvinmo/simplejwt": "^1.1.0",
"phpseclib/phpseclib": "^3.0.35",
"phpspec/prophecy-phpunit": "^2.1",
"phpunit/phpunit": "^9.6",
"sebastian/comparator": ">=1.2.3",
"squizlabs/php_codesniffer": "^4.0",
"symfony/filesystem": "^6.3||^7.3",
"symfony/process": "^6.0||^7.0",
"webmozart/assert": "^1.11||^2.0"
},
"suggest": {
"phpseclib/phpseclib": "May be used in place of OpenSSL for signing strings or for token management. Please require version ^2."
},
"type": "library",
"autoload": {
"psr-4": {
"Google\\Auth\\": "src"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"Apache-2.0"
],
"description": "Google Auth Library for PHP",
"homepage": "https://github.com/google/google-auth-library-php",
"keywords": [
"Authentication",
"google",
"oauth2"
],
"support": {
"docs": "https://cloud.google.com/php/docs/reference/auth/latest",
"issues": "https://github.com/googleapis/google-auth-library-php/issues",
"source": "https://github.com/googleapis/google-auth-library-php/tree/v1.51.0"
},
"time": "2026-06-10T00:39:33+00:00"
},
{
"name": "graham-campbell/result-type",
"version": "v1.1.4",
@@ -1405,16 +1648,16 @@
},
{
"name": "laravel/sanctum",
"version": "v4.3.1",
"version": "v4.3.2",
"source": {
"type": "git",
"url": "https://github.com/laravel/sanctum.git",
"reference": "e3b85d6e36ad00e5db2d1dcc27c81ffdf15cbf76"
"reference": "2a9bccc18e9907808e0018dd15fa643937886b1e"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/laravel/sanctum/zipball/e3b85d6e36ad00e5db2d1dcc27c81ffdf15cbf76",
"reference": "e3b85d6e36ad00e5db2d1dcc27c81ffdf15cbf76",
"url": "https://api.github.com/repos/laravel/sanctum/zipball/2a9bccc18e9907808e0018dd15fa643937886b1e",
"reference": "2a9bccc18e9907808e0018dd15fa643937886b1e",
"shasum": ""
},
"require": {
@@ -1464,7 +1707,7 @@
"issues": "https://github.com/laravel/sanctum/issues",
"source": "https://github.com/laravel/sanctum"
},
"time": "2026-02-07T17:19:31+00:00"
"time": "2026-04-30T11:46:25+00:00"
},
{
"name": "laravel/serializable-closure",
@@ -1527,6 +1770,78 @@
},
"time": "2026-02-20T19:59:49+00:00"
},
{
"name": "laravel/socialite",
"version": "v5.27.0",
"source": {
"type": "git",
"url": "https://github.com/laravel/socialite.git",
"reference": "40e0757a75637c7b2dff05d3286b0d8fc25e5c0e"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/laravel/socialite/zipball/40e0757a75637c7b2dff05d3286b0d8fc25e5c0e",
"reference": "40e0757a75637c7b2dff05d3286b0d8fc25e5c0e",
"shasum": ""
},
"require": {
"ext-json": "*",
"firebase/php-jwt": "^6.4|^7.0",
"guzzlehttp/guzzle": "^6.0|^7.0",
"illuminate/contracts": "^6.0|^7.0|^8.0|^9.0|^10.0|^11.0|^12.0|^13.0",
"illuminate/http": "^6.0|^7.0|^8.0|^9.0|^10.0|^11.0|^12.0|^13.0",
"illuminate/support": "^6.0|^7.0|^8.0|^9.0|^10.0|^11.0|^12.0|^13.0",
"league/oauth1-client": "^1.11",
"php": "^7.2|^8.0",
"phpseclib/phpseclib": "^3.0"
},
"require-dev": {
"mockery/mockery": "^1.0",
"orchestra/testbench": "^4.18|^5.20|^6.47|^7.55|^8.36|^9.15|^10.8|^11.0",
"phpstan/phpstan": "^1.12.23",
"phpunit/phpunit": "^8.0|^9.3|^10.4|^11.5|^12.0"
},
"type": "library",
"extra": {
"laravel": {
"aliases": {
"Socialite": "Laravel\\Socialite\\Facades\\Socialite"
},
"providers": [
"Laravel\\Socialite\\SocialiteServiceProvider"
]
},
"branch-alias": {
"dev-master": "5.x-dev"
}
},
"autoload": {
"psr-4": {
"Laravel\\Socialite\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Taylor Otwell",
"email": "taylor@laravel.com"
}
],
"description": "Laravel wrapper around OAuth 1 & OAuth 2 libraries.",
"homepage": "https://laravel.com",
"keywords": [
"laravel",
"oauth"
],
"support": {
"issues": "https://github.com/laravel/socialite/issues",
"source": "https://github.com/laravel/socialite"
},
"time": "2026-04-24T14:05:47+00:00"
},
{
"name": "laravel/tinker",
"version": "v2.11.1",
@@ -1970,6 +2285,82 @@
],
"time": "2024-09-21T08:32:55+00:00"
},
{
"name": "league/oauth1-client",
"version": "v1.11.0",
"source": {
"type": "git",
"url": "https://github.com/thephpleague/oauth1-client.git",
"reference": "f9c94b088837eb1aae1ad7c4f23eb65cc6993055"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/thephpleague/oauth1-client/zipball/f9c94b088837eb1aae1ad7c4f23eb65cc6993055",
"reference": "f9c94b088837eb1aae1ad7c4f23eb65cc6993055",
"shasum": ""
},
"require": {
"ext-json": "*",
"ext-openssl": "*",
"guzzlehttp/guzzle": "^6.0|^7.0",
"guzzlehttp/psr7": "^1.7|^2.0",
"php": ">=7.1||>=8.0"
},
"require-dev": {
"ext-simplexml": "*",
"friendsofphp/php-cs-fixer": "^2.17",
"mockery/mockery": "^1.3.3",
"phpstan/phpstan": "^0.12.42",
"phpunit/phpunit": "^7.5||9.5"
},
"suggest": {
"ext-simplexml": "For decoding XML-based responses."
},
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "1.0-dev",
"dev-develop": "2.0-dev"
}
},
"autoload": {
"psr-4": {
"League\\OAuth1\\Client\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Ben Corlett",
"email": "bencorlett@me.com",
"homepage": "http://www.webcomm.com.au",
"role": "Developer"
}
],
"description": "OAuth 1.0 Client Library",
"keywords": [
"Authentication",
"SSO",
"authorization",
"bitbucket",
"identity",
"idp",
"oauth",
"oauth1",
"single sign on",
"trello",
"tumblr",
"twitter"
],
"support": {
"issues": "https://github.com/thephpleague/oauth1-client/issues",
"source": "https://github.com/thephpleague/oauth1-client/tree/v1.11.0"
},
"time": "2024-12-10T19:59:05+00:00"
},
{
"name": "league/uri",
"version": "7.8.0",
@@ -2663,6 +3054,188 @@
],
"time": "2026-02-16T23:10:27+00:00"
},
{
"name": "orangehill/iseed",
"version": "v3.8.0",
"source": {
"type": "git",
"url": "https://github.com/orangehill/iseed.git",
"reference": "11ee04a43330b5241be9f7b97dcd9d44bc5745f2"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/orangehill/iseed/zipball/11ee04a43330b5241be9f7b97dcd9d44bc5745f2",
"reference": "11ee04a43330b5241be9f7b97dcd9d44bc5745f2",
"shasum": ""
},
"require": {
"illuminate/support": "^8.0|^9.0|^10.0|^11.0|^12.0|^13.0",
"php": "^8.0.2"
},
"require-dev": {
"illuminate/filesystem": "^8.0|^9.0|^10.0|^11.0|^12.0|^13.0",
"laravel/framework": "^8.0|^9.0|^10.0|^11.0|^12.0|^13.0",
"mockery/mockery": "^1.0.0",
"phpunit/phpunit": "^9.0|^10.0|^11.0"
},
"type": "library",
"extra": {
"laravel": {
"providers": [
"Orangehill\\Iseed\\IseedServiceProvider"
]
}
},
"autoload": {
"psr-0": {
"Orangehill\\Iseed": "src/"
},
"classmap": [
"src/Orangehill/Iseed/Exceptions.php"
]
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"BSD-2-Clause"
],
"authors": [
{
"name": "Tihomir Opacic",
"email": "tihomir.opacic@orangehilldev.com"
}
],
"description": "Generate a new Laravel database seed file based on data from the existing database table.",
"keywords": [
"artisan",
"generators",
"laravel",
"seed"
],
"support": {
"issues": "https://github.com/orangehill/iseed/issues",
"source": "https://github.com/orangehill/iseed/tree/v3.8.0"
},
"time": "2026-02-23T07:40:35+00:00"
},
{
"name": "paragonie/constant_time_encoding",
"version": "v3.1.3",
"source": {
"type": "git",
"url": "https://github.com/paragonie/constant_time_encoding.git",
"reference": "d5b01a39b3415c2cd581d3bd3a3575c1ebbd8e77"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/paragonie/constant_time_encoding/zipball/d5b01a39b3415c2cd581d3bd3a3575c1ebbd8e77",
"reference": "d5b01a39b3415c2cd581d3bd3a3575c1ebbd8e77",
"shasum": ""
},
"require": {
"php": "^8"
},
"require-dev": {
"infection/infection": "^0",
"nikic/php-fuzzer": "^0",
"phpunit/phpunit": "^9|^10|^11",
"vimeo/psalm": "^4|^5|^6"
},
"type": "library",
"autoload": {
"psr-4": {
"ParagonIE\\ConstantTime\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Paragon Initiative Enterprises",
"email": "security@paragonie.com",
"homepage": "https://paragonie.com",
"role": "Maintainer"
},
{
"name": "Steve 'Sc00bz' Thomas",
"email": "steve@tobtu.com",
"homepage": "https://www.tobtu.com",
"role": "Original Developer"
}
],
"description": "Constant-time Implementations of RFC 4648 Encoding (Base-64, Base-32, Base-16)",
"keywords": [
"base16",
"base32",
"base32_decode",
"base32_encode",
"base64",
"base64_decode",
"base64_encode",
"bin2hex",
"encoding",
"hex",
"hex2bin",
"rfc4648"
],
"support": {
"email": "info@paragonie.com",
"issues": "https://github.com/paragonie/constant_time_encoding/issues",
"source": "https://github.com/paragonie/constant_time_encoding"
},
"time": "2025-09-24T15:06:41+00:00"
},
{
"name": "paragonie/random_compat",
"version": "v9.99.100",
"source": {
"type": "git",
"url": "https://github.com/paragonie/random_compat.git",
"reference": "996434e5492cb4c3edcb9168db6fbb1359ef965a"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/paragonie/random_compat/zipball/996434e5492cb4c3edcb9168db6fbb1359ef965a",
"reference": "996434e5492cb4c3edcb9168db6fbb1359ef965a",
"shasum": ""
},
"require": {
"php": ">= 7"
},
"require-dev": {
"phpunit/phpunit": "4.*|5.*",
"vimeo/psalm": "^1"
},
"suggest": {
"ext-libsodium": "Provides a modern crypto API that can be used to generate random bytes."
},
"type": "library",
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Paragon Initiative Enterprises",
"email": "security@paragonie.com",
"homepage": "https://paragonie.com"
}
],
"description": "PHP 5.x polyfill for random_bytes() and random_int() from PHP 7",
"keywords": [
"csprng",
"polyfill",
"pseudorandom",
"random"
],
"support": {
"email": "info@paragonie.com",
"issues": "https://github.com/paragonie/random_compat/issues",
"source": "https://github.com/paragonie/random_compat"
},
"time": "2020-10-15T08:29:30+00:00"
},
{
"name": "phpoption/phpoption",
"version": "1.9.5",
@@ -2738,6 +3311,165 @@
],
"time": "2025-12-27T19:41:33+00:00"
},
{
"name": "phpseclib/phpseclib",
"version": "3.0.53",
"source": {
"type": "git",
"url": "https://github.com/phpseclib/phpseclib.git",
"reference": "511ddc8e352d5d1f1e33bea468b6f4ef48438cf9"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/phpseclib/phpseclib/zipball/511ddc8e352d5d1f1e33bea468b6f4ef48438cf9",
"reference": "511ddc8e352d5d1f1e33bea468b6f4ef48438cf9",
"shasum": ""
},
"require": {
"paragonie/constant_time_encoding": "^1|^2|^3",
"paragonie/random_compat": "^1.4|^2.0|^9.99.99",
"php": ">=5.6.1"
},
"require-dev": {
"phpunit/phpunit": "*"
},
"suggest": {
"ext-dom": "Install the DOM extension to load XML formatted public keys.",
"ext-gmp": "Install the GMP (GNU Multiple Precision) extension in order to speed up arbitrary precision integer arithmetic operations.",
"ext-libsodium": "SSH2/SFTP can make use of some algorithms provided by the libsodium-php extension.",
"ext-mcrypt": "Install the Mcrypt extension in order to speed up a few other cryptographic operations.",
"ext-openssl": "Install the OpenSSL extension in order to speed up a wide variety of cryptographic operations."
},
"type": "library",
"autoload": {
"files": [
"phpseclib/bootstrap.php"
],
"psr-4": {
"phpseclib3\\": "phpseclib/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Jim Wigginton",
"email": "terrafrost@php.net",
"role": "Lead Developer"
},
{
"name": "Patrick Monnerat",
"email": "pm@datasphere.ch",
"role": "Developer"
},
{
"name": "Andreas Fischer",
"email": "bantu@phpbb.com",
"role": "Developer"
},
{
"name": "Hans-Jürgen Petrich",
"email": "petrich@tronic-media.com",
"role": "Developer"
},
{
"name": "Graham Campbell",
"email": "graham@alt-three.com",
"role": "Developer"
}
],
"description": "PHP Secure Communications Library - Pure-PHP implementations of RSA, AES, SSH2, SFTP, X.509 etc.",
"homepage": "http://phpseclib.sourceforge.net",
"keywords": [
"BigInteger",
"aes",
"asn.1",
"asn1",
"blowfish",
"crypto",
"cryptography",
"encryption",
"rsa",
"security",
"sftp",
"signature",
"signing",
"ssh",
"twofish",
"x.509",
"x509"
],
"support": {
"issues": "https://github.com/phpseclib/phpseclib/issues",
"source": "https://github.com/phpseclib/phpseclib/tree/3.0.53"
},
"funding": [
{
"url": "https://github.com/terrafrost",
"type": "github"
},
{
"url": "https://www.patreon.com/phpseclib",
"type": "patreon"
},
{
"url": "https://tidelift.com/funding/github/packagist/phpseclib/phpseclib",
"type": "tidelift"
}
],
"time": "2026-06-09T18:08:26+00:00"
},
{
"name": "psr/cache",
"version": "3.0.0",
"source": {
"type": "git",
"url": "https://github.com/php-fig/cache.git",
"reference": "aa5030cfa5405eccfdcb1083ce040c2cb8d253bf"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/php-fig/cache/zipball/aa5030cfa5405eccfdcb1083ce040c2cb8d253bf",
"reference": "aa5030cfa5405eccfdcb1083ce040c2cb8d253bf",
"shasum": ""
},
"require": {
"php": ">=8.0.0"
},
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "1.0.x-dev"
}
},
"autoload": {
"psr-4": {
"Psr\\Cache\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "PHP-FIG",
"homepage": "https://www.php-fig.org/"
}
],
"description": "Common interface for caching libraries",
"keywords": [
"cache",
"psr",
"psr-6"
],
"support": {
"source": "https://github.com/php-fig/cache/tree/3.0.0"
},
"time": "2021-02-03T23:26:27+00:00"
},
{
"name": "psr/clock",
"version": "1.0.0",

View File

@@ -65,7 +65,7 @@ return [
|
*/
'timezone' => 'UTC',
'timezone' => 'Asia/Taipei',
/*
|--------------------------------------------------------------------------

38
config/cors.php Normal file
View File

@@ -0,0 +1,38 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Cross-Origin Resource Sharing (CORS) Configuration
|--------------------------------------------------------------------------
|
| Here you may configure your settings for cross-origin resource sharing
| or "CORS". This determines what cross-origin operations may execute
| in web browsers. You are free to adjust these settings as needed.
|
*/
// 🟢 修正 1確保包含你要戳的所有 API 路徑(包含上傳)
'paths' => ['api/*', 'sanctum/csrf-cookie', 'login', 'logout'],
// 🟢 修正 2允許前端傳入的 HTTP 方法GET, POST, PUT, DELETE 都要開)
'allowed_methods' => ['*'],
// 🟢 修正 3精準允許你的 Vue 前端開發網址(看你前端是在 5173 還是其他埠號)
// 你也可以直接寫 ['*'] 偷懶大開,但在本地端寫特定網址更安全:
'allowed_origins' => ['http://localhost:5173', 'http://127.0.0.1:5173'],
'allowed_origins_patterns' => [],
// 🟢 修正 4上傳 FormData 時會帶有 Content-Type 等 Header必須全開
'allowed_headers' => ['*'],
'exposed_headers' => [],
'max_age' => 0,
// 🟢 修正 5非常關鍵因為我們用了 Sanctum 驗證狀態,必須允許傳遞 Cookie/憑證
'supports_credentials' => true,
];

87
config/sanctum.php Normal file
View File

@@ -0,0 +1,87 @@
<?php
use Illuminate\Cookie\Middleware\EncryptCookies;
use Illuminate\Foundation\Http\Middleware\ValidateCsrfToken;
use Laravel\Sanctum\Http\Middleware\AuthenticateSession;
use Laravel\Sanctum\Sanctum;
return [
/*
|--------------------------------------------------------------------------
| Stateful Domains
|--------------------------------------------------------------------------
|
| Requests from the following domains / hosts will receive stateful API
| authentication cookies. Typically, these should include your local
| and production domains which access your API via a frontend SPA.
|
*/
'stateful' => explode(',', env('SANCTUM_STATEFUL_DOMAINS', sprintf(
'%s%s',
'localhost,localhost:3000,127.0.0.1,127.0.0.1:8000,::1',
Sanctum::currentApplicationUrlWithPort(),
// Sanctum::currentRequestHost(),
))),
/*
|--------------------------------------------------------------------------
| Sanctum Guards
|--------------------------------------------------------------------------
|
| This array contains the authentication guards that will be checked when
| Sanctum is trying to authenticate a request. If none of these guards
| are able to authenticate the request, Sanctum will use the bearer
| token that's present on an incoming request for authentication.
|
*/
'guard' => ['web'],
/*
|--------------------------------------------------------------------------
| Expiration Minutes
|--------------------------------------------------------------------------
|
| This value controls the number of minutes until an issued token will be
| considered expired. This will override any values set in the token's
| "expires_at" attribute, but first-party sessions are not affected.
|
*/
'expiration' => null,
/*
|--------------------------------------------------------------------------
| Token Prefix
|--------------------------------------------------------------------------
|
| Sanctum can prefix new tokens in order to take advantage of numerous
| security scanning initiatives maintained by open source platforms
| that notify developers if they commit tokens into repositories.
|
| See: https://docs.github.com/en/code-security/secret-scanning/about-secret-scanning
|
*/
'token_prefix' => env('SANCTUM_TOKEN_PREFIX', ''),
/*
|--------------------------------------------------------------------------
| Sanctum Middleware
|--------------------------------------------------------------------------
|
| When authenticating your first-party SPA with Sanctum you may need to
| customize some of the middleware Sanctum uses while processing the
| request. You may change the middleware listed below as required.
|
*/
'middleware' => [
'authenticate_session' => AuthenticateSession::class,
'encrypt_cookies' => EncryptCookies::class,
'validate_csrf_token' => ValidateCsrfToken::class,
],
];

View File

@@ -28,6 +28,12 @@ return [
'region' => env('AWS_DEFAULT_REGION', 'us-east-1'),
],
'google' => [
'client_id' => env('GOOGLE_CLIENT_ID'),
'client_secret' => env('GOOGLE_CLIENT_SECRET'),
'redirect' => env('GOOGLE_REDIRECT_URI'),
],
'slack' => [
'notifications' => [
'bot_user_oauth_token' => env('SLACK_BOT_USER_OAUTH_TOKEN'),

View File

@@ -14,6 +14,7 @@ return new class extends Migration
Schema::create('expenses', function (Blueprint $table) {
$table->id();
$table->foreignId('user_id')->constrained()->onDelete('cascade');
$table->unsignedBigInteger('account_id')->nullable()->after('user_id');
$table->foreignId('category_id')->nullable()->constrained()->onDelete('set null');
$table->decimal('amount', 10, 2);
$table->string('note')->nullable();

View File

@@ -0,0 +1,29 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::table('users', function (Blueprint $table) {
$table->string('google_id')->nullable()->unique()->after('id');
$table->string('avatar')->nullable()->after('google_id');
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::table('users', function (Blueprint $table) {
//
});
}
};

View File

@@ -0,0 +1,33 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('personal_access_tokens', function (Blueprint $table) {
$table->id();
$table->morphs('tokenable');
$table->text('name');
$table->string('token', 64)->unique();
$table->text('abilities')->nullable();
$table->timestamp('last_used_at')->nullable();
$table->timestamp('expires_at')->nullable()->index();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('personal_access_tokens');
}
};

View File

@@ -0,0 +1,35 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('accounts', function (Blueprint $table) {
$table->id();
$table->foreignId('user_id')->constrained()->cascadeOnDelete();
$table->string('name');
$table->string('type', 20);
$table->string('currency', 10)->default('TWD');
$table->decimal('balance', 15, 2)->default(0);
$table->string('note')->nullable();
$table->integer('billing_day')->nullable();
$table->integer('payment_day')->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('accounts');
}
};

View File

@@ -0,0 +1,33 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('investment_holdings', function (Blueprint $table) {
$table->id();
$table->foreignId('account_id')->constrained()->cascadeOnDelete();
$table->enum('type', ['stock', 'fund']);
$table->string('symbol');
$table->string('name');
$table->decimal('shares', 10, 2)->default(0);
$table->decimal('avg_cost', 10, 2)->default(0);
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('investment_holdings');
}
};

View File

@@ -0,0 +1,37 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('investment_transactions', function (Blueprint $table) {
$table->id();
$table->foreignId('holding_id')->constrained('investment_holdings')->cascadeOnDelete();
$table->enum('action', ['buy', 'sell']);
$table->decimal('shares', 10, 2)->nullable();
$table->decimal('price', 10, 2)->nullable();
$table->decimal('amount', 15, 2)->nullable();
$table->decimal('nav', 10, 4)->nullable();
$table->decimal('fee', 10, 2)->default(0);
$table->decimal('tax', 10, 2)->default(0);
$table->date('traded_at');
$table->string('note')->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('investment_transactions');
}
};

View File

@@ -12,14 +12,14 @@ return new class extends Migration
public function up(): void
{
Schema::table('expenses', function (Blueprint $table) {
$table->foreign('account_id')->references('id')->on('accounts')->nullOnDelete();
});
}
public function down(): void
{
Schema::table('expenses', function (Blueprint $table) {
$table->dropColumn('external_id');
$table->dropForeign(['account_id']);
});
}
};

View File

@@ -0,0 +1,39 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('securities', function (Blueprint $table) {
$table->id();
$table->string('code', 20);
$table->enum('type', ['stock', 'etf', 'fund']);
$table->string('source', 20); // twse, tpex, cnyes
$table->string('name'); // 中文名稱/簡稱
$table->decimal('latest_price', 15, 4)->nullable(); // 最新報價/淨值
$table->timestamp('latest_price_at')->nullable(); // 最新報價/淨值時間
$table->decimal('change_amount', 15, 4)->nullable(); // 漲跌
$table->decimal('change_rate', 8, 4)->nullable(); // 漲跌幅(%)
$table->jsonb('meta')->nullable(); // 基金專屬額外資訊(category、riskLevel、isinCode...)
$table->timestamps();
$table->unique(['code', 'type']);
});
}
public function down(): void
{
Schema::dropIfExists('securities');
}
};

View File

@@ -0,0 +1,36 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('security_price_histories', function (Blueprint $table) {
$table->id();
$table->foreignId('security_id')
->constrained('securities')
->cascadeOnDelete();
$table->date('price_date'); // 該筆報價/淨值所屬日期
$table->decimal('price', 15, 4); // 收盤價/淨值
$table->decimal('change_amount', 15, 4)->nullable(); // 漲跌
$table->decimal('change_rate', 8, 4)->nullable(); // 漲跌幅(%)
$table->timestamps();
$table->unique(['security_id', 'price_date']);
});
}
public function down(): void
{
Schema::dropIfExists('security_price_histories');
}
};

View File

@@ -0,0 +1,30 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::table('users', function (Blueprint $table) {
$table->text('google_access_token')->nullable();
$table->text('google_refresh_token')->nullable();
$table->timestamp('google_token_expires_at')->nullable();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::table('users', function (Blueprint $table) {
//
});
}
};

View File

@@ -12,15 +12,17 @@ return new class extends Migration
public function up(): void
{
Schema::table('expenses', function (Blueprint $table) {
$table->foreignId('subcategory_id')->nullable()->after('category_id')
->constrained('categories')->onDelete('set null');
// 🟢 新增分攤控制欄位
$table->boolean('is_amortized')->default(false); // 是否開啟分攤
$table->date('period_start')->nullable(); // 費用歸屬開始日期
$table->date('period_end')->nullable(); // 費用歸屬結束日期
});
}
public function down(): void
{
Schema::table('expenses', function (Blueprint $table) {
$table->dropConstrainedForeignId('subcategory_id');
$table->dropColumn(['is_amortized', 'period_start', 'period_end']);
});
}
};

View File

@@ -0,0 +1,31 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up()
{
Schema::create('account_rules', function (Blueprint $table) {
$table->id();
$table->foreignId('user_id')->constrained()->onDelete('cascade');
$table->string('keyword'); // 🔍 關鍵字,例如: 'cathaybk' 或 '國泰' 或 '永豐'
$table->string('match_type'); // 💡 類型,例如: 'email_from' (比對寄件者) 或 'subject' (比對主旨)
$table->foreignId('account_id')->constrained('accounts')->onDelete('cascade'); // 🎯 要掛勾的資產帳戶ID
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('account_rules');
}
};

View File

@@ -0,0 +1,188 @@
<?php
namespace Database\Seeders;
use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
class AccountSeeder extends Seeder
{
/**
* Run the database seeds.
*/
public function run(): void
{
DB::table('accounts')->insert([
[
'id' => 1,
'user_id' => 1,
'name' => '凱基銀行',
'type' => 'bank',
'currency' => 'TWD',
'balance' => 123028.00,
'note' => null,
'billing_day' => null,
'payment_day' => null,
'created_at' => now(),
'updated_at' => now()
],
[
'id' => 2,
'user_id' => 1,
'name' => '國泰證券',
'type' => 'stock',
'currency' => 'TWD',
'balance' => 0.00,
'note' => null,
'billing_day' => null,
'payment_day' => null,
'created_at' => now(),
'updated_at' => now()
],
[
'id' => 3,
'user_id' => 1,
'name' => '國泰銀行',
'type' => 'bank',
'currency' => 'TWD',
'balance' => 19067.00,
'note' => null,
'billing_day' => null,
'payment_day' => null,
'created_at' => now(),
'updated_at' => now()
],
[
'id' => 4,
'user_id' => 1,
'name' => '永豐銀行',
'type' => 'cash',
'currency' => 'TWD',
'balance' => 14138.00,
'note' => null,
'billing_day' => null,
'payment_day' => null,
'created_at' => now(),
'updated_at' => now()
],
[
'id' => 5,
'user_id' => 1,
'name' => '永豐證券',
'type' => 'stock',
'currency' => 'TWD',
'balance' => 0.00,
'note' => null,
'billing_day' => null,
'payment_day' => null,
'created_at' => now(),
'updated_at' => now()
],
[
'id' => 11,
'user_id' => 1,
'name' => '國泰信用卡',
'type' => 'credit_card',
'currency' => 'TWD',
'balance' => 0.00,
'note' => null,
'billing_day' => 17,
'payment_day' => 2,
'created_at' => now(),
'updated_at' => now()
],
[
'id' => 12,
'user_id' => 1,
'name' => '麥當勞點點卡',
'type' => 'wallet',
'currency' => 'TWD',
'balance' => 299.00,
'note' => null,
'billing_day' => null,
'payment_day' => null,
'created_at' => now(),
'updated_at' => now()
],
[
'id' => 13,
'user_id' => 1,
'name' => '國泰基金',
'type' => 'fund',
'currency' => 'TWD',
'balance' => 0.00,
'note' => null,
'billing_day' => null,
'payment_day' => null,
'created_at' => now(),
'updated_at' => now()
],
[
'id' => 14,
'user_id' => 1,
'name' => '手機悠遊卡',
'type' => 'wallet',
'currency' => 'TWD',
'balance' => 1.00,
'note' => null,
'billing_day' => null,
'payment_day' => null,
'created_at' => now(),
'updated_at' => now()
],
[
'id' => 15,
'user_id' => 1,
'name' => '玉山金融卡(悠遊卡)',
'type' => 'wallet',
'currency' => 'TWD',
'balance' => 222.00,
'note' => null,
'billing_day' => null,
'payment_day' => null,
'created_at' => now(),
'updated_at' => now()
],
[
'id' => 16,
'user_id' => 1,
'name' => '凱基信用卡(悠遊卡)',
'type' => 'wallet',
'currency' => 'TWD',
'balance' => 154.00,
'note' => null,
'billing_day' => null,
'payment_day' => null,
'created_at' => now(),
'updated_at' => now()
],
[
'id' => 17,
'user_id' => 1,
'name' => '東華學生證(悠遊卡)',
'type' => 'wallet',
'currency' => 'TWD',
'balance' => 85.00,
'note' => null,
'billing_day' => null,
'payment_day' => null,
'created_at' => now(),
'updated_at' => now()
],
[
'id' => 18,
'user_id' => 1,
'name' => '安聯基金',
'type' => 'fund',
'currency' => 'TWD',
'balance' => 0.00,
'note' => null,
'billing_day' => null,
'payment_day' => null,
'created_at' => now(),
'updated_at' => now()
],
]);
}
}

View File

@@ -15,11 +15,19 @@ class DatabaseSeeder extends Seeder
*/
public function run(): void
{
// User::factory(10)->create();
\App\Models\User::updateOrCreate(
['email' => 'henry194557@gmail.com'], // 換成你的 Google 登入 email
[
'name' => 'Henry',
'google_id' => '', // 可以先隨便填
'password' => bcrypt('password'),
]
);
User::factory()->create([
'name' => 'Test User',
'email' => 'test@example.com',
$this->call([
AccountSeeder::class,
InvestmentHoldingSeeder::class,
InvestmentTransactionSeeder::class,
]);
}
}

View File

@@ -0,0 +1,52 @@
<?php
namespace Database\Seeders;
use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
class InvestmentHoldingSeeder extends Seeder
{
/**
* Run the database seeds.
*/
public function run(): void
{
DB::table('investment_holdings')->insert([
[
'id' => 1,
'account_id' => 2,
'type' => 'stock',
'symbol' => '0050',
'name' => '元大台灣50',
'shares' => 304.00,
'avg_cost' => 76.27,
'created_at' => now(),
'updated_at' => now()
],
[
'id' => 2,
'account_id' => 13,
'type' => 'fund',
'symbol' => '10350113',
'name' => '國泰台灣高股息台幣月配',
'shares' => 229.70,
'avg_cost' => 43.53,
'created_at' => now(),
'updated_at' => now()
],
[
'id' => 3,
'account_id' => 18,
'type' => 'fund',
'symbol' => 'A36004',
'name' => '安聯台灣科技基金',
'shares' => 51.11,
'avg_cost' => 782.69,
'created_at' => now(),
'updated_at' => now()
],
]);
}
}

View File

@@ -0,0 +1,301 @@
<?php
namespace Database\Seeders;
use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
class InvestmentTransactionSeeder extends Seeder
{
/**
* Run the database seeds.
*/
public function run(): void
{
DB::table('investment_transactions')->insert([
// 國泰基金 holding_id=2
[
'holding_id' => 2,
'action' => 'buy',
'shares' => 35.70,
'price' => 56.11,
'amount' => null,
'nav' => null,
'fee' => 0,
'tax' => 0,
'traded_at' => '2026-06-05',
'note' => null,
'created_at' => now(),
'updated_at' => now()
],
[
'holding_id' => 2,
'action' => 'buy',
'shares' => 20.10,
'price' => 49.74,
'amount' => null,
'nav' => null,
'fee' => 0,
'tax' => 0,
'traded_at' => '2026-05-20',
'note' => null,
'created_at' => now(),
'updated_at' => now()
],
[
'holding_id' => 2,
'action' => 'buy',
'shares' => 29.00,
'price' => 34.48,
'amount' => null,
'nav' => null,
'fee' => 0,
'tax' => 0,
'traded_at' => '2026-02-05',
'note' => null,
'created_at' => now(),
'updated_at' => now()
],
[
'holding_id' => 2,
'action' => 'buy',
'shares' => 27.30,
'price' => 36.59,
'amount' => null,
'nav' => null,
'fee' => 0,
'tax' => 0,
'traded_at' => '2026-02-23',
'note' => null,
'created_at' => now(),
'updated_at' => now()
],
[
'holding_id' => 2,
'action' => 'buy',
'shares' => 27.10,
'price' => 36.89,
'amount' => null,
'nav' => null,
'fee' => 0,
'tax' => 0,
'traded_at' => '2026-03-05',
'note' => null,
'created_at' => now(),
'updated_at' => now()
],
[
'holding_id' => 2,
'action' => 'buy',
'shares' => 25.10,
'price' => 39.79,
'amount' => null,
'nav' => null,
'fee' => 0,
'tax' => 0,
'traded_at' => '2026-03-20',
'note' => null,
'created_at' => now(),
'updated_at' => now()
],
[
'holding_id' => 2,
'action' => 'buy',
'shares' => 25.40,
'price' => 39.39,
'amount' => null,
'nav' => null,
'fee' => 0,
'tax' => 0,
'traded_at' => '2026-04-07',
'note' => null,
'created_at' => now(),
'updated_at' => now()
],
[
'holding_id' => 2,
'action' => 'buy',
'shares' => 21.10,
'price' => 47.36,
'amount' => null,
'nav' => null,
'fee' => 0,
'tax' => 0,
'traded_at' => '2026-04-20',
'note' => null,
'created_at' => now(),
'updated_at' => now()
],
[
'holding_id' => 2,
'action' => 'buy',
'shares' => 18.90,
'price' => 52.89,
'amount' => null,
'nav' => null,
'fee' => 0,
'tax' => 0,
'traded_at' => '2026-05-05',
'note' => null,
'created_at' => now(),
'updated_at' => now()
],
// 0050 holding_id=1
[
'holding_id' => 1,
'action' => 'buy',
'shares' => 1.00,
'price' => 70.05,
'amount' => null,
'nav' => null,
'fee' => 1,
'tax' => 0,
'traded_at' => '2026-01-09',
'note' => null,
'created_at' => now(),
'updated_at' => now()
],
[
'holding_id' => 1,
'action' => 'buy',
'shares' => 50.00,
'price' => 70.05,
'amount' => null,
'nav' => null,
'fee' => 1,
'tax' => 0,
'traded_at' => '2026-01-09',
'note' => null,
'created_at' => now(),
'updated_at' => now()
],
[
'holding_id' => 1,
'action' => 'buy',
'shares' => 14.00,
'price' => 104.49,
'amount' => null,
'nav' => null,
'fee' => 1,
'tax' => 0,
'traded_at' => '2026-06-05',
'note' => null,
'created_at' => now(),
'updated_at' => now()
],
[
'holding_id' => 1,
'action' => 'buy',
'shares' => 14.00,
'price' => 100.54,
'amount' => null,
'nav' => null,
'fee' => 1,
'tax' => 0,
'traded_at' => '2026-05-25',
'note' => null,
'created_at' => now(),
'updated_at' => now()
],
[
'holding_id' => 1,
'action' => 'buy',
'shares' => 15.00,
'price' => 94.39,
'amount' => null,
'nav' => null,
'fee' => 1,
'tax' => 0,
'traded_at' => '2026-05-05',
'note' => null,
'created_at' => now(),
'updated_at' => now()
],
[
'holding_id' => 1,
'action' => 'buy',
'shares' => 17.00,
'price' => 86.59,
'amount' => null,
'nav' => null,
'fee' => 1,
'tax' => 0,
'traded_at' => '2026-04-23',
'note' => null,
'created_at' => now(),
'updated_at' => now()
],
[
'holding_id' => 1,
'action' => 'buy',
'shares' => 33.00,
'price' => 75.14,
'amount' => null,
'nav' => null,
'fee' => 1,
'tax' => 0,
'traded_at' => '2026-04-07',
'note' => null,
'created_at' => now(),
'updated_at' => now()
],
[
'holding_id' => 1,
'action' => 'buy',
'shares' => 20.00,
'price' => 74.02,
'amount' => null,
'nav' => null,
'fee' => 1,
'tax' => 0,
'traded_at' => '2026-03-23',
'note' => null,
'created_at' => now(),
'updated_at' => now()
],
[
'holding_id' => 1,
'action' => 'buy',
'shares' => 45.00,
'price' => 77.53,
'amount' => null,
'nav' => null,
'fee' => 1,
'tax' => 0,
'traded_at' => '2026-03-05',
'note' => null,
'created_at' => now(),
'updated_at' => now()
],
[
'holding_id' => 1,
'action' => 'buy',
'shares' => 48.00,
'price' => 72.02,
'amount' => null,
'nav' => null,
'fee' => 1,
'tax' => 0,
'traded_at' => '2026-02-05',
'note' => '定期定額',
'created_at' => now(),
'updated_at' => now()
],
[
'holding_id' => 1,
'action' => 'buy',
'shares' => 47.00,
'price' => 62.54,
'amount' => null,
'nav' => null,
'fee' => 1,
'tax' => 0,
'traded_at' => '2025-12-05',
'note' => null,
'created_at' => now(),
'updated_at' => now()
],
]);
}
}

View File

@@ -1,5 +1,5 @@
<script setup>
import { Link } from '@inertiajs/vue3';
import { RouterLink } from 'vue-router';
defineProps({
href: {
@@ -10,10 +10,10 @@ defineProps({
</script>
<template>
<Link
:href="href"
<RouterLink
:to="href"
class="block w-full px-4 py-2 text-start text-sm leading-5 text-gray-700 transition duration-150 ease-in-out hover:bg-gray-100 focus:bg-gray-100 focus:outline-none"
>
<slot />
</Link>
</RouterLink>
</template>

View File

@@ -1,6 +1,6 @@
<script setup>
import { computed } from 'vue';
import { Link } from '@inertiajs/vue3';
import { RouterLink } from 'vue-router';
const props = defineProps({
href: {
@@ -20,7 +20,7 @@ const classes = computed(() =>
</script>
<template>
<Link :href="href" :class="classes">
<RouterLink :to="href" :class="classes">
<slot />
</Link>
</RouterLink>
</template>

View File

@@ -1,6 +1,6 @@
<script setup>
import { computed } from 'vue';
import { Link } from '@inertiajs/vue3';
import { RouterLink } from 'vue-router';
const props = defineProps({
href: {
@@ -20,7 +20,7 @@ const classes = computed(() =>
</script>
<template>
<Link :href="href" :class="classes">
<RouterLink :to="href" :class="classes">
<slot />
</Link>
</RouterLink>
</template>

View File

@@ -5,66 +5,76 @@ import Dropdown from "@/Components/Dropdown.vue";
import DropdownLink from "@/Components/DropdownLink.vue";
import NavLink from "@/Components/NavLink.vue";
import ResponsiveNavLink from "@/Components/ResponsiveNavLink.vue";
import { Link } from "@inertiajs/vue3";
import { RouterLink, useRoute } from "vue-router"; // 引入 useRoute 來判斷當前頁面
const showingNavigationDropdown = ref(false);
const route = useRoute();
// 這裡先寫死使用者資訊,等之後 API 串接好再改用 Pinia 或 API 資料
const user = {
name: "Henry",
email: "henry@example.com",
};
// 模擬登出功能
const logout = () => {
console.log("執行登出邏輯");
// 這裡之後要改為呼叫 API 並跳轉回登入頁
};
</script>
<template>
<div>
<div class="min-h-screen bg-gray-100">
<nav class="border-b border-gray-100 bg-white">
<!-- Primary Navigation Menu -->
<div class="mx-auto max-w-7xl px-4 sm:px-6 lg:px-8">
<div class="flex h-16 justify-between">
<div class="flex">
<!-- Logo -->
<div class="flex shrink-0 items-center">
<Link :href="route('dashboard')">
<!-- 修改 :to="route('dashboard')" 改為路徑 -->
<RouterLink to="/">
<ApplicationLogo
class="block h-9 w-auto fill-current text-gray-800"
/>
</Link>
</RouterLink>
</div>
<!-- Navigation Links -->
<div
class="hidden space-x-8 sm:-my-px sm:ms-10 sm:flex"
>
<NavLink
:href="route('dashboard')"
:active="route().current('dashboard')"
>
<!-- 修改href 改為 toactive 改為路徑判斷 -->
<!-- <NavLink to="/" :active="route.path === '/'">
Dashboard
</NavLink>
<NavLink
:href="route('expenses.index')"
:active="route().current('expenses.*')"
</NavLink> -->
<!-- <NavLink
to="/expenses"
:active="route.path.startsWith('/expenses')"
>
記帳
</NavLink>
</NavLink> -->
</div>
</div>
<div class="hidden sm:ms-6 sm:flex sm:items-center">
<!-- Settings Dropdown -->
<div class="relative ms-3">
<Dropdown align="right" width="48">
<!-- <div class="hidden sm:ms-6 sm:flex sm:items-center">
<div class="relative ms-3"> -->
<!-- <Dropdown align="right" width="48">
<template #trigger>
<span class="inline-flex rounded-md">
<button
type="button"
class="inline-flex items-center rounded-md border border-transparent bg-white px-3 py-2 text-sm font-medium leading-4 text-gray-500 transition duration-150 ease-in-out hover:text-gray-700 focus:outline-none"
>
{{ $page.props.auth.user.name }}
<svg
class="-me-0.5 ms-2 h-4 w-4"
<!-- 修改移除 $page.props -->
<!-- {{ user.name }} -->
<!-- <svg -->
<!-- class="-me-0.5 ms-2 h-4 w-4"
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 20 20"
fill="currentColor"
>
<path
fill="currentColor" -->
<!-- > -->
<!-- <path
fill-rule="evenodd"
d="M5.293 7.293a1 1 0 011.414 0L10 10.586l3.293-3.293a1 1 0 111.414 1.414l-4 4a1 1 0 01-1.414 0l-4-4a1 1 0 010-1.414z"
clip-rule="evenodd"
@@ -72,33 +82,30 @@ const showingNavigationDropdown = ref(false);
</svg>
</button>
</span>
</template>
</template> -->
<template #content>
<DropdownLink
:href="route('profile.edit')"
<!-- <template #content> -->
<!-- 修改所有 route() 改為字串路徑 -->
<!-- <DropdownLink to="/profile"
>Profile</DropdownLink
>
Profile
</DropdownLink>
<DropdownLink
:href="route('expenses.index')"
>
Expenses
</DropdownLink>
<DropdownLink
:href="route('logout')"
method="post"
as="button"
<DropdownLink to="/expenses"
>Expenses</DropdownLink
> -->
<!-- 修改登出暫時改為按鈕觸發 -->
<!-- <button
@click="logout"
class="block w-full px-4 py-2 text-left text-sm leading-5 text-gray-700 hover:bg-gray-100 focus:outline-none transition duration-150 ease-in-out"
>
Log Out
</DropdownLink>
</button>
</template>
</Dropdown>
</div>
</div>
</Dropdown> -->
<!-- </div>
</div> -->
<!-- Hamburger -->
<div class="-me-2 flex items-center sm:hidden">
<!-- Hamburger (手機版選單) -->
<!-- <div class="-me-2 flex items-center sm:hidden">
<button
@click="
showingNavigationDropdown =
@@ -136,11 +143,11 @@ const showingNavigationDropdown = ref(false);
/>
</svg>
</button>
</div>
</div> -->
</div>
</div>
<!-- Responsive Navigation Menu -->
<!-- Responsive Navigation Menu (手機版收合內容) -->
<div
:class="{
block: showingNavigationDropdown,
@@ -148,53 +155,45 @@ const showingNavigationDropdown = ref(false);
}"
class="sm:hidden"
>
<div class="space-y-1 pb-3 pt-2">
<ResponsiveNavLink
:href="route('dashboard')"
:active="route().current('dashboard')"
>
<!-- <div class="space-y-1 pb-3 pt-2">
<ResponsiveNavLink to="/" :active="route.path === '/'">
Dashboard
</ResponsiveNavLink>
</div>
</div> -->
<!-- Responsive Settings Options -->
<div class="border-t border-gray-200 pb-1 pt-4">
<!-- <div class="border-t border-gray-200 pb-1 pt-4">
<div class="px-4">
<div class="text-base font-medium text-gray-800">
{{ $page.props.auth.user.name }}
{{ user.name }}
</div>
<div class="text-sm font-medium text-gray-500">
{{ $page.props.auth.user.email }}
{{ user.email }}
</div>
</div>
<div class="mt-3 space-y-1">
<ResponsiveNavLink :href="route('profile.edit')">
Profile
</ResponsiveNavLink>
<ResponsiveNavLink
:href="route('logout')"
method="post"
as="button"
<ResponsiveNavLink to="/profile"
>Profile</ResponsiveNavLink
>
<button
@click="logout"
class="block w-full pl-3 pr-4 py-2 border-l-4 border-transparent text-left text-base font-medium text-gray-600 hover:text-gray-800 hover:bg-gray-50 hover:border-gray-300 transition duration-150 ease-in-out"
>
Log Out
</ResponsiveNavLink>
</button>
</div>
</div>
</div> -->
</div>
</nav>
<!-- Page Heading -->
<header class="bg-white shadow" v-if="$slots.header">
<!-- <header class="bg-white shadow" v-if="$slots.header">
<div class="mx-auto max-w-7xl px-4 py-6 sm:px-6 lg:px-8">
<slot name="header" />
</div>
</header>
<!-- Page Content -->
<main>
<slot />
</main>
</main> -->
</div>
</div>
</template>

View File

@@ -1,6 +1,6 @@
<script setup>
import ApplicationLogo from '@/Components/ApplicationLogo.vue';
import { Link } from '@inertiajs/vue3';
import { RouterLink } from 'vue-router';
</script>
<template>
@@ -8,9 +8,9 @@ import { Link } from '@inertiajs/vue3';
class="flex min-h-screen flex-col items-center bg-gray-100 pt-6 sm:justify-center sm:pt-0"
>
<div>
<Link href="/">
<RouterLink :to="{ name: 'home' }">
<ApplicationLogo class="h-20 w-20 fill-current text-gray-500" />
</Link>
</RouterLink>
</div>
<div

View File

@@ -5,7 +5,8 @@ import InputError from '@/Components/InputError.vue';
import InputLabel from '@/Components/InputLabel.vue';
import PrimaryButton from '@/Components/PrimaryButton.vue';
import TextInput from '@/Components/TextInput.vue';
import { Head, Link, useForm } from '@inertiajs/vue3';
import { RouterLink, useRoute } from 'vue-router';
import { reactive } from 'vue';
defineProps({
canResetPassword: {
@@ -16,7 +17,7 @@ defineProps({
},
});
const form = useForm({
const form = reactive({
email: '',
password: '',
remember: false,
@@ -31,7 +32,7 @@ const submit = () => {
<template>
<GuestLayout>
<Head title="Log in" />
<div title="Log in"></div>
<div v-if="status" class="mb-4 text-sm font-medium text-green-600">
{{ status }}

View File

@@ -4,9 +4,10 @@ import InputError from '@/Components/InputError.vue';
import InputLabel from '@/Components/InputLabel.vue';
import PrimaryButton from '@/Components/PrimaryButton.vue';
import TextInput from '@/Components/TextInput.vue';
import { Head, Link, useForm } from '@inertiajs/vue3';
import { RouterLink, useRoute } from 'vue-router';
import { reactive } from 'vue';
const form = useForm({
const form = reactive({
name: '',
email: '',
password: '',
@@ -22,7 +23,7 @@ const submit = () => {
<template>
<GuestLayout>
<Head title="Register" />
<div title="Register"></div>
<form @submit.prevent="submit">
<div>
@@ -93,12 +94,12 @@ const submit = () => {
</div>
<div class="mt-4 flex items-center justify-end">
<Link
:href="route('login')"
<RouterLink
:to="{ name: 'login' }"
class="rounded-md text-sm text-gray-600 underline hover:text-gray-900 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2"
>
Already registered?
</Link>
</RouterLink>
<PrimaryButton
class="ms-4"

View File

@@ -4,7 +4,7 @@ import InputError from '@/Components/InputError.vue';
import InputLabel from '@/Components/InputLabel.vue';
import PrimaryButton from '@/Components/PrimaryButton.vue';
import TextInput from '@/Components/TextInput.vue';
import { Head, useForm } from '@inertiajs/vue3';
import { reactive } from 'vue';
const props = defineProps({
email: {
@@ -17,7 +17,7 @@ const props = defineProps({
},
});
const form = useForm({
const form = reactive({
token: props.token,
email: props.email,
password: '',
@@ -33,7 +33,7 @@ const submit = () => {
<template>
<GuestLayout>
<Head title="Reset Password" />
<div title="Reset Password"></div>
<form @submit.prevent="submit">
<div>

View File

@@ -2,7 +2,8 @@
import { computed } from 'vue';
import GuestLayout from '@/Layouts/GuestLayout.vue';
import PrimaryButton from '@/Components/PrimaryButton.vue';
import { Head, Link, useForm } from '@inertiajs/vue3';
import { RouterLink, useRoute } from 'vue-router';
import { reactive, computed } from 'vue';
const props = defineProps({
status: {
@@ -10,7 +11,7 @@ const props = defineProps({
},
});
const form = useForm({});
const form = reactive({});
const submit = () => {
form.post(route('verification.send'));
@@ -23,7 +24,7 @@ const verificationLinkSent = computed(
<template>
<GuestLayout>
<Head title="Email Verification" />
<div title="Email Verification"></div>
<div class="mb-4 text-sm text-gray-600">
Thanks for signing up! Before getting started, could you verify your
@@ -48,12 +49,12 @@ const verificationLinkSent = computed(
Resend Verification Email
</PrimaryButton>
<Link
:href="route('logout')"
<RouterLink
:to="{ name: 'logout' }"
method="post"
as="button"
class="rounded-md text-sm text-gray-600 underline hover:text-gray-900 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2"
>Log Out</Link
>Log Out</RouterLink
>
</div>
</form>

View File

@@ -1,6 +1,7 @@
<script setup>
import AuthenticatedLayout from '@/Layouts/AuthenticatedLayout.vue'
import { Pie, Bar } from 'vue-chartjs'
import { computed } from "vue"; // 必須匯入 computed
import AuthenticatedLayout from "@/Layouts/AuthenticatedLayout.vue";
import { Pie, Bar } from "vue-chartjs";
import {
Chart as ChartJS,
ArcElement,
@@ -9,114 +10,128 @@ import {
CategoryScale,
LinearScale,
BarElement,
} from 'chart.js'
} from "chart.js";
ChartJS.register(ArcElement, Tooltip, Legend, CategoryScale, LinearScale, BarElement)
ChartJS.register(
ArcElement,
Tooltip,
Legend,
CategoryScale,
LinearScale,
BarElement,
);
const props = defineProps({
monthlyTotal: Number,
categoryStats: Array,
monthlyTrend: Array,
})
// 建議加上預設值,防止 API 還沒回傳時崩潰
// const props = defineProps({
// monthlyTotal: { type: Number, default: 0 },
// categoryStats: { type: Array, default: () => [] },
// monthlyTrend: { type: Array, default: () => [] },
// });
// 圓餅圖
const pieData = {
labels: props.categoryStats.map(c => c.name),
datasets: [{
data: props.categoryStats.map(c => c.total),
backgroundColor: props.categoryStats.map(c => c.color),
}],
}
// --- 修改重點:使用 computed 並加上空陣列保護 ---
const pieOptions = {
responsive: true,
plugins: {
legend: { position: 'bottom' },
},
}
// 圓餅圖資料
// const pieData = computed(() => ({
// labels: (props.categoryStats || []).map((c) => c.name),
// datasets: [
// {
// data: (props.categoryStats || []).map((c) => c.total),
// backgroundColor: (props.categoryStats || []).map((c) => c.color),
// },
// ],
// }));
// 長條圖
const barData = {
labels: props.monthlyTrend.map(m => m.month),
datasets: [{
label: '每月花費',
data: props.monthlyTrend.map(m => m.total),
backgroundColor: '#3B82F6',
borderRadius: 4,
}],
}
// const pieOptions = {
// responsive: true,
// plugins: {
// legend: { position: "bottom" },
// },
// };
const barOptions = {
responsive: true,
plugins: {
legend: { display: false },
},
scales: {
y: {
beginAtZero: true,
ticks: {
callback: (val) => '$' + val.toLocaleString(),
},
},
},
}
// 長條圖資料
// const barData = computed(() => ({
// labels: (props.monthlyTrend || []).map((m) => m.month),
// datasets: [
// {
// label: "每月花費",
// data: (props.monthlyTrend || []).map((m) => m.total),
// backgroundColor: "#3B82F6",
// borderRadius: 4,
// },
// ],
// }));
// const barOptions = {
// responsive: true,
// plugins: {
// legend: { display: false },
// },
// scales: {
// y: {
// beginAtZero: true,
// ticks: {
// callback: (val) => "$" + val.toLocaleString(),
// },
// },
// },
// };
</script>
<template>
<AuthenticatedLayout>
<template #header>
<h2 class="text-xl font-semibold">總覽</h2>
</template>
<!-- <AuthenticatedLayout> -->
<template #header>
<h2 class="text-xl font-semibold">總覽</h2>
</template>
<div class="py-8 max-w-5xl mx-auto px-4 space-y-6">
<!-- 本月花費 -->
<div class="grid grid-cols-1 sm:grid-cols-3 gap-4">
<div class="bg-white rounded-lg shadow p-6">
<p class="text-sm text-gray-500">本月花費</p>
<p class="text-3xl font-bold text-blue-500 mt-1">
${{ monthlyTotal.toLocaleString() }}
</p>
</div>
<div class="bg-white rounded-lg shadow p-6">
<p class="text-sm text-gray-500">本月筆數</p>
<p class="text-3xl font-bold text-gray-700 mt-1">
{{ categoryStats.reduce((s, c) => s, 0) }}
{{ categoryStats.length }} 個分類
</p>
</div>
<div class="bg-white rounded-lg shadow p-6">
<p class="text-sm text-gray-500">最高花費分類</p>
<p class="text-3xl font-bold text-gray-700 mt-1">
{{ categoryStats.length > 0
? categoryStats.reduce((a, b) => a.total > b.total ? a : b).name
: '—' }}
</p>
</div>
<div class="py-8 max-w-5xl mx-auto px-4 space-y-6">
<!-- 本月花費 -->
<div class="grid grid-cols-1 sm:grid-cols-3 gap-4">
<div class="bg-white rounded-lg shadow p-6">
<p class="text-sm text-gray-500">本月花費</p>
<!-- <p class="text-3xl font-bold text-blue-500 mt-1">
${{ monthlyTotal.toLocaleString() }}
</p> -->
</div>
<!-- 圖表 -->
<div class="grid grid-cols-1 sm:grid-cols-2 gap-6">
<!-- 圓餅圖 -->
<div class="bg-white rounded-lg shadow p-6">
<h3 class="text-lg font-medium mb-4">本月分類佔比</h3>
<div v-if="categoryStats.length > 0" class="max-w-xs mx-auto">
<Pie :data="pieData" :options="pieOptions" />
</div>
<div v-else class="py-12 text-center text-gray-400">
本月還沒有記錄
</div>
</div>
<!-- 長條圖 -->
<div class="bg-white rounded-lg shadow p-6">
<h3 class="text-lg font-medium mb-4">近6個月趨勢</h3>
<Bar :data="barData" :options="barOptions" />
</div>
<div class="bg-white rounded-lg shadow p-6">
<p class="text-sm text-gray-500">本月筆數</p>
<!-- <p class="text-3xl font-bold text-gray-700 mt-1">
{{ categoryStats.reduce((s, c) => s, 0) }}
{{ categoryStats.length }} 個分類
</p> -->
</div>
<div class="bg-white rounded-lg shadow p-6">
<p class="text-sm text-gray-500">最高花費分類</p>
<!-- <p class="text-3xl font-bold text-gray-700 mt-1">
{{
categoryStats.length > 0
? categoryStats.reduce((a, b) =>
a.total > b.total ? a : b,
).name
: "—"
}}
</p> -->
</div>
</div>
</AuthenticatedLayout>
<!-- 圖表 -->
<div class="grid grid-cols-1 sm:grid-cols-2 gap-6">
<!-- 圓餅圖 -->
<div class="bg-white rounded-lg shadow p-6">
<h3 class="text-lg font-medium mb-4">本月分類佔比</h3>
<div v-if="categoryStats.length > 0" class="max-w-xs mx-auto">
<!-- <Pie :data="pieData" :options="pieOptions" /> -->
</div>
<div v-else class="py-12 text-center text-gray-400">
本月還沒有記錄
</div>
</div>
<!-- 長條圖 -->
<div class="bg-white rounded-lg shadow p-6">
<h3 class="text-lg font-medium mb-4">近6個月趨勢</h3>
<!-- <Bar :data="barData" :options="barOptions" /> -->
</div>
</div>
</div>
<!-- </AuthenticatedLayout> -->
</template>

View File

@@ -1,18 +1,33 @@
<script setup>
import { useForm, usePage } from "@inertiajs/vue3";
import { ref, reactive } from "vue";
import axios from "axios";
import AuthenticatedLayout from "@/Layouts/AuthenticatedLayout.vue";
import { computed } from "vue";
const form = useForm({
const form = reactive({
file: null,
});
const flash = computed(() => usePage().props.flash);
const flashMessage = ref("");
const submit = () => {
form.post(route("expenses.import.store"), {
forceFormData: true,
});
const submit = async () => {
// 因為有檔案,必須使用 FormData
const formData = new FormData();
formData.append('file', form.file);
try {
const response = await axios.post("/api/expenses/import", formData, {
headers: {
"Content-Type": "multipart/form-data",
},
});
// 成功後的處理 (例如顯示成功訊息)
console.log("上傳成功", response.data);
flashMessage.value = "匯入成功!";
} catch (error) {
// 錯誤處理
console.error("上傳失敗", error.response?.data);
}
};
</script>
@@ -26,10 +41,10 @@ const submit = () => {
<div class="bg-white rounded-lg shadow p-6">
<!-- 成功訊息 -->
<div
v-if="flash?.message"
v-if="flashMessage"
class="mb-4 p-4 bg-green-50 text-green-700 rounded"
>
{{ flash.message }}
{{ flashMessage }}
</div>
<h3 class="text-lg font-medium mb-2">上傳財政部發票 CSV</h3>

View File

@@ -1,141 +1,170 @@
<script setup>
import { ref } from "vue";
import { computed } from "vue";
import { useForm, usePage } from "@inertiajs/vue3";
import { ref, reactive, onMounted, computed } from "vue";
import axios from "axios";
// 假設你已經將這些組件搬移到新專案的 components 資料夾
import AuthenticatedLayout from "@/Layouts/AuthenticatedLayout.vue";
const props = defineProps({
expenses: Array,
categories: Array,
rules: Array,
});
// 規則管理
const showRules = ref(false);
// --- 1. 資料狀態管理 (取代 Props) ---
const expenses = ref([]);
const categories = ref([]);
const rules = ref([]);
const loading = ref(false);
const flash = ref("");
const ruleForm = useForm({
keyword: "",
category_id: "",
});
const flash = computed(() => usePage().props.flash);
// ── 分類管理 ──
const showCategories = ref(false);
const categoryForm = useForm({
name: "",
color: "#3B82F6",
});
const submitCategory = () => {
categoryForm.post(route("categories.store"), {
onSuccess: () => categoryForm.reset(),
});
};
const submitRule = () => {
ruleForm.post(route("category-rules.store"), {
onSuccess: () => ruleForm.reset(),
});
};
const destroyRule = (id) => {
if (confirm("確定刪除此規則?")) {
useForm({}).delete(route("category-rules.destroy", id));
// 取得初始資料
const fetchAllData = async () => {
loading.value = true;
try {
// 同步取得所有必要的資料
const [expRes, catRes, ruleRes] = await Promise.all([
axios.get("/api/expenses"),
axios.get("/api/categories"),
axios.get("/api/category-rules"),
]);
expenses.value = expRes.data;
categories.value = catRes.data;
rules.value = ruleRes.data;
} catch (error) {
console.error("載入失敗", error);
flash.value = "無法取得資料,請檢查網路連線";
} finally {
loading.value = false;
}
};
const editingCategory = ref(null);
const editCategoryForm = useForm({ name: "", color: "" });
onMounted(fetchAllData);
const startEditCategory = (cat) => {
editingCategory.value = cat.id;
editCategoryForm.name = cat.name;
editCategoryForm.color = cat.color;
};
const submitEditCategory = (id) => {
editCategoryForm.put(route("categories.update", id), {
onSuccess: () => (editingCategory.value = null),
});
};
const destroyCategory = (id) => {
if (confirm("確定刪除?該分類的支出會變成未分類。")) {
useForm({}).delete(route("categories.destroy", id));
}
};
// ── 支出 ──
const form = useForm({
// --- 2. 支出管理 (Expenses) ---
const form = reactive({
amount: "",
category_id: "",
note: "",
date: new Date().toISOString().split("T")[0],
});
const submit = () => {
form.post(route("expenses.store"), {
onSuccess: () => form.reset(),
});
};
const formatDate = (date) => (date ? date.toString().split("T")[0] : "");
const editing = ref(null);
const editForm = useForm({
amount: "",
category_id: "",
note: "",
date: "",
});
const startEdit = (expense) => {
editing.value = expense.id;
editForm.amount = expense.amount;
editForm.category_id = expense.category_id ?? "";
editForm.note = expense.note ?? "";
editForm.date = formatDate(expense.date);
};
const submitEdit = (id) => {
editForm.put(route("expenses.update", id), {
onSuccess: () => (editing.value = null),
});
};
const destroy = (id) => {
if (confirm("確定刪除?")) {
useForm({}).delete(route("expenses.destroy", id));
const submit = async () => {
try {
const response = await axios.post("/api/expenses", form);
// 手動將新資料推入列表頂部
expenses.value.unshift(response.data);
// 重置表單
Object.assign(form, { amount: "", category_id: "", note: "" });
flash.value = "新增成功!";
} catch (error) {
alert("新增失敗");
}
};
const selected = ref([]);
const editing = ref(null);
const editForm = reactive({ amount: "", category_id: "", note: "", date: "" });
const toggleAll = (e) => {
selected.value = e.target.checked ? props.expenses.map((ex) => ex.id) : [];
const startEdit = (expense) => {
editing.value = expense.id;
Object.assign(editForm, {
amount: expense.amount,
category_id: expense.category_id ?? "",
note: expense.note ?? "",
date: expense.date ? expense.date.split("T")[0] : "",
});
};
const deleteSelected = () => {
const submitEdit = async (id) => {
try {
const response = await axios.put(`/api/expenses/${id}`, editForm);
const index = expenses.value.findIndex((ex) => ex.id === id);
expenses.value[index] = response.data;
editing.value = null;
} catch (error) {
alert("修改失敗");
}
};
const destroy = async (id) => {
if (!confirm("確定刪除?")) return;
try {
await axios.delete(`/api/expenses/${id}`);
expenses.value = expenses.value.filter((ex) => ex.id !== id);
} catch (error) {
alert("刪除失敗");
}
};
// --- 3. 分類管理 (Categories) ---
const showCategories = ref(false);
const categoryForm = reactive({ name: "", color: "#3B82F6" });
const editingCategory = ref(null);
const editCategoryForm = reactive({ name: "", color: "" });
const submitCategory = async () => {
try {
const response = await axios.post("/api/categories", categoryForm);
categories.value.push(response.data);
Object.assign(categoryForm, { name: "", color: "#3B82F6" });
} catch (error) {
alert("分類新增失敗");
}
};
const submitEditCategory = async (id) => {
try {
const response = await axios.put(`/api/categories/${id}`, editCategoryForm);
const index = categories.value.findIndex((cat) => cat.id === id);
categories.value[index] = response.data;
editingCategory.value = null;
} catch (error) {
alert("分類修改失敗");
}
};
// --- 4. 規則管理 (Rules) ---
const showRules = ref(false);
const ruleForm = reactive({ keyword: "", category_id: "" });
const submitRule = async () => {
try {
const response = await axios.post("/api/category-rules", ruleForm);
rules.value.push(response.data);
Object.assign(ruleForm, { keyword: "", category_id: "" });
} catch (error) {
alert("規則新增失敗");
}
};
// --- 5. 批量操作 ---
const selected = ref([]);
const toggleAll = (e) => {
selected.value = e.target.checked ? expenses.value.map((ex) => ex.id) : [];
};
const deleteSelected = async () => {
if (selected.value.length === 0) return;
if (!confirm(`確定刪除 ${selected.value.length} 筆?`)) return;
useForm({ ids: selected.value }).delete(route("expenses.destroyBatch"), {
onSuccess: () => (selected.value = []),
});
try {
await axios.post("/api/expenses/destroy-batch", { ids: selected.value });
expenses.value = expenses.value.filter((ex) => !selected.value.includes(ex.id));
selected.value = [];
} catch (error) {
alert("批量刪除失敗");
}
};
</script>
<template>
<AuthenticatedLayout>
<!-- 修改 1: 使用本地 ref flash 訊息 -->
<div
v-if="flash?.message"
v-if="flash"
class="bg-green-50 text-green-700 p-4 rounded mb-4"
>
{{ flash.message }}
{{ flash }}
</div>
<template #header>
<div class="flex justify-between items-center">
<h2 class="text-xl font-semibold">記帳</h2>
</div>
</template>
<div class="py-8 max-w-4xl mx-auto px-4 space-y-6">
<!-- 分類管理 -->
<div class="bg-white rounded-lg shadow p-6">
@@ -150,15 +179,9 @@ const deleteSelected = () => {
</div>
<div v-if="showCategories" class="mt-4 space-y-4">
<!-- 新增分類 -->
<form
@submit.prevent="submitCategory"
class="flex gap-3 items-end"
>
<form @submit.prevent="submitCategory" class="flex gap-3 items-end">
<div class="flex-1">
<label class="block text-sm text-gray-600 mb-1"
>名稱</label
>
<label class="block text-sm text-gray-600 mb-1">名稱</label>
<input
v-model="categoryForm.name"
type="text"
@@ -168,258 +191,102 @@ const deleteSelected = () => {
/>
</div>
<div>
<label class="block text-sm text-gray-600 mb-1"
>顏色</label
>
<label class="block text-sm text-gray-600 mb-1">顏色</label>
<input
v-model="categoryForm.color"
type="color"
class="h-10 w-16 border rounded cursor-pointer"
/>
</div>
<button
type="submit"
class="bg-blue-500 text-white px-4 py-2 rounded hover:bg-blue-600"
>
<button type="submit" class="bg-blue-500 text-white px-4 py-2 rounded hover:bg-blue-600">
新增
</button>
</form>
<!-- 分類列表 -->
<div class="divide-y border rounded">
<div
v-for="cat in categories"
:key="cat.id"
class="px-4 py-3"
>
<!-- 一般顯示 -->
<div
v-if="editingCategory !== cat.id"
class="flex items-center justify-between"
>
<div v-for="cat in categories" :key="cat.id" class="px-4 py-3">
<div v-if="editingCategory !== cat.id" class="flex items-center justify-between">
<div class="flex items-center gap-3">
<span
class="w-5 h-5 rounded-full"
:style="{ background: cat.color }"
></span>
<span class="w-5 h-5 rounded-full" :style="{ background: cat.color }"></span>
<span>{{ cat.name }}</span>
</div>
<div class="space-x-3">
<button
@click="startEditCategory(cat)"
class="text-blue-400 hover:text-blue-600 text-sm"
>
編輯
</button>
<button
@click="destroyCategory(cat.id)"
class="text-red-400 hover:text-red-600 text-sm"
>
刪除
</button>
<button @click="startEditCategory(cat)" class="text-blue-400 hover:text-blue-600 text-sm">編輯</button>
<button @click="destroyCategory(cat.id)" class="text-red-400 hover:text-red-600 text-sm">刪除</button>
</div>
</div>
<!-- 編輯中 -->
<div v-else class="flex items-center gap-3">
<input
v-model="editCategoryForm.color"
type="color"
class="h-8 w-12 border rounded cursor-pointer"
/>
<input
v-model="editCategoryForm.name"
type="text"
class="flex-1 border rounded px-3 py-1 text-sm"
/>
<button
@click="submitEditCategory(cat.id)"
class="text-green-500 hover:text-green-700 text-sm"
>
儲存
</button>
<button
@click="editingCategory = null"
class="text-gray-400 hover:text-gray-600 text-sm"
>
取消
</button>
<input v-model="editCategoryForm.color" type="color" class="h-8 w-12 border rounded cursor-pointer" />
<input v-model="editCategoryForm.name" type="text" class="flex-1 border rounded px-3 py-1 text-sm" />
<button @click="submitEditCategory(cat.id)" class="text-green-500 hover:text-green-700 text-sm">儲存</button>
<button @click="editingCategory = null" class="text-gray-400 hover:text-gray-600 text-sm">取消</button>
</div>
</div>
<div
v-if="categories.length === 0"
class="px-4 py-6 text-center text-gray-400 text-sm"
>
還沒有分類
</div>
</div>
</div>
</div>
<!-- 自動分類規則 -->
<div class="bg-white rounded-lg shadow p-6">
<div
class="flex justify-between items-center cursor-pointer"
@click="showRules = !showRules"
>
<div class="flex justify-between items-center cursor-pointer" @click="showRules = !showRules">
<h3 class="text-lg font-medium">自動分類規則</h3>
<span class="text-gray-400 text-sm">
{{ showRules ? "▲ 收起" : "▼ 展開" }}
</span>
<span class="text-gray-400 text-sm">{{ showRules ? "▲ 收起" : "▼ 展開" }}</span>
</div>
<div v-if="showRules" class="mt-4 space-y-4">
<!-- 新增規則 -->
<form
@submit.prevent="submitRule"
class="flex gap-3 items-end"
>
<form @submit.prevent="submitRule" class="flex gap-3 items-end">
<div class="flex-1">
<label class="block text-sm text-gray-600 mb-1"
>關鍵字</label
>
<input
v-model="ruleForm.keyword"
type="text"
class="w-full border rounded px-3 py-2"
placeholder="例如:全家、家樂福"
required
/>
<label class="block text-sm text-gray-600 mb-1">關鍵字</label>
<input v-model="ruleForm.keyword" type="text" class="w-full border rounded px-3 py-2" placeholder="例如:全家" required />
</div>
<div class="flex-1">
<label class="block text-sm text-gray-600 mb-1"
>對應分類</label
>
<select
v-model="ruleForm.category_id"
class="w-full border rounded px-3 py-2"
required
>
<label class="block text-sm text-gray-600 mb-1">對應分類</label>
<select v-model="ruleForm.category_id" class="w-full border rounded px-3 py-2" required>
<option value="">選擇分類</option>
<option
v-for="cat in categories"
:key="cat.id"
:value="cat.id"
>
{{ cat.name }}
</option>
<option v-for="cat in categories" :key="cat.id" :value="cat.id">{{ cat.name }}</option>
</select>
</div>
<button
type="submit"
class="bg-blue-500 text-white px-4 py-2 rounded hover:bg-blue-600"
>
新增
</button>
<button type="submit" class="bg-blue-500 text-white px-4 py-2 rounded hover:bg-blue-600">新增</button>
</form>
<!-- 規則列表 -->
<div class="divide-y border rounded">
<div
v-for="rule in rules"
:key="rule.id"
class="px-4 py-3 flex items-center justify-between"
>
<div class="flex items-center gap-3">
<span
class="font-mono bg-gray-100 px-2 py-1 rounded text-sm"
>
{{ rule.keyword }}
</span>
<span class="text-gray-400"></span>
<span
class="px-2 py-1 rounded text-xs text-white"
:style="{
background: rule.category?.color,
}"
>
{{ rule.category?.name }}
</span>
</div>
<button
@click="destroyRule(rule.id)"
class="text-red-400 hover:text-red-600 text-sm"
>
刪除
</button>
</div>
<div
v-if="rules.length === 0"
class="px-4 py-6 text-center text-gray-400 text-sm"
>
還沒有規則匯入發票時分類將會是空白
</div>
</div>
<!-- 規則列表部分邏輯不變僅確保資料來自 ref -->
</div>
</div>
<!-- 新增支出 -->
<div class="bg-white rounded-lg shadow p-6">
<div class="flex justify-between items-center mb-4">
<h3 class="text-lg font-medium">新增支出</h3>
<a
:href="route('expenses.import')"
<!-- 修改 2: 改為 router-link -->
<router-link
to="/expenses/import"
class="bg-blue-500 text-white px-4 py-2 rounded text-sm hover:bg-blue-600"
>
匯入發票
</a>
</router-link>
</div>
<form @submit.prevent="submit" class="grid grid-cols-2 gap-4">
<!-- 表單內容保持不變 -->
<div>
<label class="block text-sm text-gray-600 mb-1"
>金額</label
>
<input
v-model="form.amount"
type="number"
step="1"
class="w-full border rounded px-3 py-2"
placeholder="0"
required
/>
<label class="block text-sm text-gray-600 mb-1">金額</label>
<input v-model="form.amount" type="number" step="1" class="w-full border rounded px-3 py-2" placeholder="0" required />
</div>
<div>
<label class="block text-sm text-gray-600 mb-1"
>日期</label
>
<input
v-model="form.date"
type="date"
class="w-full border rounded px-3 py-2"
required
/>
<label class="block text-sm text-gray-600 mb-1">日期</label>
<input v-model="form.date" type="date" class="w-full border rounded px-3 py-2" required />
</div>
<div>
<label class="block text-sm text-gray-600 mb-1"
>分類</label
>
<select
v-model="form.category_id"
class="w-full border rounded px-3 py-2"
>
<label class="block text-sm text-gray-600 mb-1">分類</label>
<select v-model="form.category_id" class="w-full border rounded px-3 py-2">
<option value="">未分類</option>
<option
v-for="cat in categories"
:key="cat.id"
:value="cat.id"
>
{{ cat.name }}
</option>
<option v-for="cat in categories" :key="cat.id" :value="cat.id">{{ cat.name }}</option>
</select>
</div>
<div>
<label class="block text-sm text-gray-600 mb-1"
>備註</label
>
<input
v-model="form.note"
type="text"
class="w-full border rounded px-3 py-2"
placeholder="備註..."
/>
<label class="block text-sm text-gray-600 mb-1">備註</label>
<input v-model="form.note" type="text" class="w-full border rounded px-3 py-2" placeholder="備註..." />
</div>
<div class="col-span-2">
<button
type="submit"
class="w-full bg-blue-500 text-white py-2 rounded hover:bg-blue-600"
>
<button type="submit" class="w-full bg-blue-500 text-white py-2 rounded hover:bg-blue-600">
新增
</button>
</div>
@@ -427,31 +294,12 @@ const deleteSelected = () => {
</div>
<!-- 支出列表 -->
<div class="bg-white rounded-lg shadow">
<div
class="px-4 py-3 border-b flex items-center justify-between"
>
<span class="text-sm text-gray-500">
{{ expenses.length }}
</span>
<button
@click="deleteSelected"
:class="
selected.length > 0
? 'opacity-100'
: 'opacity-0 pointer-events-none'
"
class="bg-red-500 text-white px-3 py-1 rounded text-sm hover:bg-red-600 transition-opacity"
>
刪除選取 ({{ selected.length }})
</button>
</div>
<div class="bg-white rounded-lg shadow overflow-x-auto">
<!-- 列表內容與原版相似但確保所有操作都綁定到剛才改寫的 axios 函式 -->
<table class="w-full">
<thead class="bg-gray-50 text-sm text-gray-600">
<tr>
<th class="px-4 py-3">
<input type="checkbox" @change="toggleAll" />
</th>
<th class="px-4 py-3"><input type="checkbox" @change="toggleAll" /></th>
<th class="px-4 py-3 text-left">日期</th>
<th class="px-4 py-3 text-left">分類</th>
<th class="px-4 py-3 text-left">備註</th>
@@ -461,118 +309,41 @@ const deleteSelected = () => {
</thead>
<tbody class="divide-y divide-gray-100">
<template v-for="expense in expenses" :key="expense.id">
<tr
v-if="editing !== expense.id"
class="hover:bg-gray-50"
>
<tr v-if="editing !== expense.id" class="hover:bg-gray-50">
<td class="px-4 py-3">
<input
type="checkbox"
:value="expense.id"
v-model="selected"
/>
<input type="checkbox" :value="expense.id" v-model="selected" />
</td>
<td class="px-4 py-3 text-sm">{{ formatDate(expense.date) }}</td>
<td class="px-4 py-3 text-sm">
{{ formatDate(expense.date) }}
</td>
<td class="px-4 py-3 text-sm">
<span
v-if="expense.category"
class="px-2 py-1 rounded text-xs text-white"
:style="{
background: expense.category.color,
}"
>
<span v-if="expense.category" class="px-2 py-1 rounded text-xs text-white" :style="{ background: expense.category.color }">
{{ expense.category.name }}
</span>
<span v-else class="text-gray-400 text-xs"
>未分類</span
>
</td>
<td class="px-4 py-3 text-sm text-gray-600">
{{ expense.note }}
</td>
<td class="px-4 py-3 text-right font-medium">
${{
Number(expense.amount).toLocaleString()
}}
<span v-else class="text-gray-400 text-xs">未分類</span>
</td>
<td class="px-4 py-3 text-sm text-gray-600">{{ expense.note }}</td>
<td class="px-4 py-3 text-right font-medium">${{ Number(expense.amount).toLocaleString() }}</td>
<td class="px-4 py-3 text-right space-x-2">
<button
@click="startEdit(expense)"
class="text-blue-400 hover:text-blue-600 text-sm"
>
編輯
</button>
<button
@click="destroy(expense.id)"
class="text-red-400 hover:text-red-600 text-sm"
>
刪除
</button>
<button @click="startEdit(expense)" class="text-blue-400 hover:text-blue-600 text-sm">編輯</button>
<button @click="destroy(expense.id)" class="text-red-400 hover:text-red-600 text-sm">刪除</button>
</td>
</tr>
<tr v-else class="bg-blue-50">
<!-- 編輯狀態的 Input 保持與 editForm 綁定 -->
<td class="px-4 py-2"><input v-model="editForm.date" type="date" class="w-full border rounded px-2 py-1 text-sm" /></td>
<td class="px-4 py-2">
<input
v-model="editForm.date"
type="date"
class="w-full border rounded px-2 py-1 text-sm"
/>
</td>
<td class="px-4 py-2">
<select
v-model="editForm.category_id"
class="w-full border rounded px-2 py-1 text-sm"
>
<select v-model="editForm.category_id" class="w-full border rounded px-2 py-1 text-sm">
<option value="">未分類</option>
<option
v-for="cat in categories"
:key="cat.id"
:value="cat.id"
>
{{ cat.name }}
</option>
<option v-for="cat in categories" :key="cat.id" :value="cat.id">{{ cat.name }}</option>
</select>
</td>
<td class="px-4 py-2">
<input
v-model="editForm.note"
type="text"
class="w-full border rounded px-2 py-1 text-sm"
/>
</td>
<td class="px-4 py-2">
<input
v-model="editForm.amount"
type="number"
class="w-full border rounded px-2 py-1 text-sm"
/>
</td>
<td class="px-4 py-2"><input v-model="editForm.note" type="text" class="w-full border rounded px-2 py-1 text-sm" /></td>
<td class="px-4 py-2"><input v-model="editForm.amount" type="number" class="w-full border rounded px-2 py-1 text-sm" /></td>
<td class="px-4 py-2 text-right space-x-2">
<button
@click="submitEdit(expense.id)"
class="text-green-500 hover:text-green-700 text-sm"
>
儲存
</button>
<button
@click="editing = null"
class="text-gray-400 hover:text-gray-600 text-sm"
>
取消
</button>
<button @click="submitEdit(expense.id)" class="text-green-500 hover:text-green-700 text-sm">儲存</button>
<button @click="editing = null" class="text-gray-400 hover:text-gray-600 text-sm">取消</button>
</td>
</tr>
</template>
<tr v-if="expenses.length === 0">
<td
colspan="5"
class="px-4 py-8 text-center text-gray-400"
>
還沒有記錄
</td>
</tr>
</tbody>
</table>
</div>

View File

@@ -1,386 +0,0 @@
<script setup>
import { Head, Link } from '@inertiajs/vue3';
defineProps({
canLogin: {
type: Boolean,
},
canRegister: {
type: Boolean,
},
laravelVersion: {
type: String,
required: true,
},
phpVersion: {
type: String,
required: true,
},
});
function handleImageError() {
document.getElementById('screenshot-container')?.classList.add('!hidden');
document.getElementById('docs-card')?.classList.add('!row-span-1');
document.getElementById('docs-card-content')?.classList.add('!flex-row');
document.getElementById('background')?.classList.add('!hidden');
}
</script>
<template>
<Head title="Welcome" />
<div class="bg-gray-50 text-black/50 dark:bg-black dark:text-white/50">
<img
id="background"
class="absolute -left-20 top-0 max-w-[877px]"
src="https://laravel.com/assets/img/welcome/background.svg"
/>
<div
class="relative flex min-h-screen flex-col items-center justify-center selection:bg-[#FF2D20] selection:text-white"
>
<div class="relative w-full max-w-2xl px-6 lg:max-w-7xl">
<header
class="grid grid-cols-2 items-center gap-2 py-10 lg:grid-cols-3"
>
<div class="flex lg:col-start-2 lg:justify-center">
<svg
class="h-12 w-auto text-white lg:h-16 lg:text-[#FF2D20]"
viewBox="0 0 62 65"
fill="none"
xmlns="http://www.w3.org/2000/svg"
>
<path
d="M61.8548 14.6253C61.8778 14.7102 61.8895 14.7978 61.8897 14.8858V28.5615C61.8898 28.737 61.8434 28.9095 61.7554 29.0614C61.6675 29.2132 61.5409 29.3392 61.3887 29.4265L49.9104 36.0351V49.1337C49.9104 49.4902 49.7209 49.8192 49.4118 49.9987L25.4519 63.7916C25.3971 63.8227 25.3372 63.8427 25.2774 63.8639C25.255 63.8714 25.2338 63.8851 25.2101 63.8913C25.0426 63.9354 24.8666 63.9354 24.6991 63.8913C24.6716 63.8838 24.6467 63.8689 24.6205 63.8589C24.5657 63.8389 24.5084 63.8215 24.456 63.7916L0.501061 49.9987C0.348882 49.9113 0.222437 49.7853 0.134469 49.6334C0.0465019 49.4816 0.000120578 49.3092 0 49.1337L0 8.10652C0 8.01678 0.0124642 7.92953 0.0348998 7.84477C0.0423783 7.8161 0.0598282 7.78993 0.0697995 7.76126C0.0884958 7.70891 0.105946 7.65531 0.133367 7.6067C0.152063 7.5743 0.179485 7.54812 0.20192 7.51821C0.230588 7.47832 0.256763 7.43719 0.290416 7.40229C0.319084 7.37362 0.356476 7.35243 0.388883 7.32751C0.425029 7.29759 0.457436 7.26518 0.498568 7.2415L12.4779 0.345059C12.6296 0.257786 12.8015 0.211853 12.9765 0.211853C13.1515 0.211853 13.3234 0.257786 13.475 0.345059L25.4531 7.2415H25.4556C25.4955 7.26643 25.5292 7.29759 25.5653 7.32626C25.5977 7.35119 25.6339 7.37362 25.6625 7.40104C25.6974 7.43719 25.7224 7.47832 25.7523 7.51821C25.7735 7.54812 25.8021 7.5743 25.8196 7.6067C25.8483 7.65656 25.8645 7.70891 25.8844 7.76126C25.8944 7.78993 25.9118 7.8161 25.9193 7.84602C25.9423 7.93096 25.954 8.01853 25.9542 8.10652V33.7317L35.9355 27.9844V14.8846C35.9355 14.7973 35.948 14.7088 35.9704 14.6253C35.9792 14.5954 35.9954 14.5692 36.0053 14.5405C36.0253 14.4882 36.0427 14.4346 36.0702 14.386C36.0888 14.3536 36.1163 14.3274 36.1375 14.2975C36.1674 14.2576 36.1923 14.2165 36.2272 14.1816C36.2559 14.1529 36.292 14.1317 36.3244 14.1068C36.3618 14.0769 36.3942 14.0445 36.4341 14.0208L48.4147 7.12434C48.5663 7.03694 48.7383 6.99094 48.9133 6.99094C49.0883 6.99094 49.2602 7.03694 49.4118 7.12434L61.3899 14.0208C61.4323 14.0457 61.4647 14.0769 61.5021 14.1055C61.5333 14.1305 61.5694 14.1529 61.5981 14.1803C61.633 14.2165 61.6579 14.2576 61.6878 14.2975C61.7103 14.3274 61.7377 14.3536 61.7551 14.386C61.7838 14.4346 61.8 14.4882 61.8199 14.5405C61.8312 14.5692 61.8474 14.5954 61.8548 14.6253ZM59.893 27.9844V16.6121L55.7013 19.0252L49.9104 22.3593V33.7317L59.8942 27.9844H59.893ZM47.9149 48.5566V37.1768L42.2187 40.4299L25.953 49.7133V61.2003L47.9149 48.5566ZM1.99677 9.83281V48.5566L23.9562 61.199V49.7145L12.4841 43.2219L12.4804 43.2194L12.4754 43.2169C12.4368 43.1945 12.4044 43.1621 12.3682 43.1347C12.3371 43.1097 12.3009 43.0898 12.2735 43.0624L12.271 43.0586C12.2386 43.0275 12.2162 42.9888 12.1887 42.9539C12.1638 42.9203 12.1339 42.8916 12.114 42.8567L12.1127 42.853C12.0903 42.8156 12.0766 42.7707 12.0604 42.7283C12.0442 42.6909 12.023 42.656 12.013 42.6161C12.0005 42.5688 11.998 42.5177 11.9931 42.4691C11.9881 42.4317 11.9781 42.3943 11.9781 42.3569V15.5801L6.18848 12.2446L1.99677 9.83281ZM12.9777 2.36177L2.99764 8.10652L12.9752 13.8513L22.9541 8.10527L12.9752 2.36177H12.9777ZM18.1678 38.2138L23.9574 34.8809V9.83281L19.7657 12.2459L13.9749 15.5801V40.6281L18.1678 38.2138ZM48.9133 9.14105L38.9344 14.8858L48.9133 20.6305L58.8909 14.8846L48.9133 9.14105ZM47.9149 22.3593L42.124 19.0252L37.9323 16.6121V27.9844L43.7219 31.3174L47.9149 33.7317V22.3593ZM24.9533 47.987L39.59 39.631L46.9065 35.4555L36.9352 29.7145L25.4544 36.3242L14.9907 42.3482L24.9533 47.987Z"
fill="currentColor"
/>
</svg>
</div>
<nav v-if="canLogin" class="-mx-3 flex flex-1 justify-end">
<Link
v-if="$page.props.auth.user"
:href="route('dashboard')"
class="rounded-md px-3 py-2 text-black ring-1 ring-transparent transition hover:text-black/70 focus:outline-none focus-visible:ring-[#FF2D20] dark:text-white dark:hover:text-white/80 dark:focus-visible:ring-white"
>
Dashboard
</Link>
<template v-else>
<Link
:href="route('login')"
class="rounded-md px-3 py-2 text-black ring-1 ring-transparent transition hover:text-black/70 focus:outline-none focus-visible:ring-[#FF2D20] dark:text-white dark:hover:text-white/80 dark:focus-visible:ring-white"
>
Log in
</Link>
<Link
v-if="canRegister"
:href="route('register')"
class="rounded-md px-3 py-2 text-black ring-1 ring-transparent transition hover:text-black/70 focus:outline-none focus-visible:ring-[#FF2D20] dark:text-white dark:hover:text-white/80 dark:focus-visible:ring-white"
>
Register
</Link>
</template>
</nav>
</header>
<main class="mt-6">
<div class="grid gap-6 lg:grid-cols-2 lg:gap-8">
<a
href="https://laravel.com/docs"
id="docs-card"
class="flex flex-col items-start gap-6 overflow-hidden rounded-lg bg-white p-6 shadow-[0px_14px_34px_0px_rgba(0,0,0,0.08)] ring-1 ring-white/[0.05] transition duration-300 hover:text-black/70 hover:ring-black/20 focus:outline-none focus-visible:ring-[#FF2D20] md:row-span-3 lg:p-10 lg:pb-10 dark:bg-zinc-900 dark:ring-zinc-800 dark:hover:text-white/70 dark:hover:ring-zinc-700 dark:focus-visible:ring-[#FF2D20]"
>
<div
id="screenshot-container"
class="relative flex w-full flex-1 items-stretch"
>
<img
src="https://laravel.com/assets/img/welcome/docs-light.svg"
alt="Laravel documentation screenshot"
class="aspect-video h-full w-full flex-1 rounded-[10px] object-cover object-top drop-shadow-[0px_4px_34px_rgba(0,0,0,0.06)] dark:hidden"
@error="handleImageError"
/>
<img
src="https://laravel.com/assets/img/welcome/docs-dark.svg"
alt="Laravel documentation screenshot"
class="hidden aspect-video h-full w-full flex-1 rounded-[10px] object-cover object-top drop-shadow-[0px_4px_34px_rgba(0,0,0,0.25)] dark:block"
/>
<div
class="absolute -bottom-16 -left-16 h-40 w-[calc(100%+8rem)] bg-gradient-to-b from-transparent via-white to-white dark:via-zinc-900 dark:to-zinc-900"
></div>
</div>
<div
class="relative flex items-center gap-6 lg:items-end"
>
<div
id="docs-card-content"
class="flex items-start gap-6 lg:flex-col"
>
<div
class="flex size-12 shrink-0 items-center justify-center rounded-full bg-[#FF2D20]/10 sm:size-16"
>
<svg
class="size-5 sm:size-6"
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
>
<path
fill="#FF2D20"
d="M23 4a1 1 0 0 0-1.447-.894L12.224 7.77a.5.5 0 0 1-.448 0L2.447 3.106A1 1 0 0 0 1 4v13.382a1.99 1.99 0 0 0 1.105 1.79l9.448 4.728c.14.065.293.1.447.1.154-.005.306-.04.447-.105l9.453-4.724a1.99 1.99 0 0 0 1.1-1.789V4ZM3 6.023a.25.25 0 0 1 .362-.223l7.5 3.75a.251.251 0 0 1 .138.223v11.2a.25.25 0 0 1-.362.224l-7.5-3.75a.25.25 0 0 1-.138-.22V6.023Zm18 11.2a.25.25 0 0 1-.138.224l-7.5 3.75a.249.249 0 0 1-.329-.099.249.249 0 0 1-.033-.12V9.772a.251.251 0 0 1 .138-.224l7.5-3.75a.25.25 0 0 1 .362.224v11.2Z"
/>
<path
fill="#FF2D20"
d="m3.55 1.893 8 4.048a1.008 1.008 0 0 0 .9 0l8-4.048a1 1 0 0 0-.9-1.785l-7.322 3.706a.506.506 0 0 1-.452 0L4.454.108a1 1 0 0 0-.9 1.785H3.55Z"
/>
</svg>
</div>
<div class="pt-3 sm:pt-5 lg:pt-0">
<h2
class="text-xl font-semibold text-black dark:text-white"
>
Documentation
</h2>
<p class="mt-4 text-sm/relaxed">
Laravel has wonderful documentation
covering every aspect of the
framework. Whether you are a
newcomer or have prior experience
with Laravel, we recommend reading
our documentation from beginning to
end.
</p>
</div>
</div>
<svg
class="size-6 shrink-0 stroke-[#FF2D20]"
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
stroke-width="1.5"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
d="M4.5 12h15m0 0l-6.75-6.75M19.5 12l-6.75 6.75"
/>
</svg>
</div>
</a>
<a
href="https://laracasts.com"
class="flex items-start gap-4 rounded-lg bg-white p-6 shadow-[0px_14px_34px_0px_rgba(0,0,0,0.08)] ring-1 ring-white/[0.05] transition duration-300 hover:text-black/70 hover:ring-black/20 focus:outline-none focus-visible:ring-[#FF2D20] lg:pb-10 dark:bg-zinc-900 dark:ring-zinc-800 dark:hover:text-white/70 dark:hover:ring-zinc-700 dark:focus-visible:ring-[#FF2D20]"
>
<div
class="flex size-12 shrink-0 items-center justify-center rounded-full bg-[#FF2D20]/10 sm:size-16"
>
<svg
class="size-5 sm:size-6"
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
>
<g fill="#FF2D20">
<path
d="M24 8.25a.5.5 0 0 0-.5-.5H.5a.5.5 0 0 0-.5.5v12a2.5 2.5 0 0 0 2.5 2.5h19a2.5 2.5 0 0 0 2.5-2.5v-12Zm-7.765 5.868a1.221 1.221 0 0 1 0 2.264l-6.626 2.776A1.153 1.153 0 0 1 8 18.123v-5.746a1.151 1.151 0 0 1 1.609-1.035l6.626 2.776ZM19.564 1.677a.25.25 0 0 0-.177-.427H15.6a.106.106 0 0 0-.072.03l-4.54 4.543a.25.25 0 0 0 .177.427h3.783c.027 0 .054-.01.073-.03l4.543-4.543ZM22.071 1.318a.047.047 0 0 0-.045.013l-4.492 4.492a.249.249 0 0 0 .038.385.25.25 0 0 0 .14.042h5.784a.5.5 0 0 0 .5-.5v-2a2.5 2.5 0 0 0-1.925-2.432ZM13.014 1.677a.25.25 0 0 0-.178-.427H9.101a.106.106 0 0 0-.073.03l-4.54 4.543a.25.25 0 0 0 .177.427H8.4a.106.106 0 0 0 .073-.03l4.54-4.543ZM6.513 1.677a.25.25 0 0 0-.177-.427H2.5A2.5 2.5 0 0 0 0 3.75v2a.5.5 0 0 0 .5.5h1.4a.106.106 0 0 0 .073-.03l4.54-4.543Z"
/>
</g>
</svg>
</div>
<div class="pt-3 sm:pt-5">
<h2
class="text-xl font-semibold text-black dark:text-white"
>
Laracasts
</h2>
<p class="mt-4 text-sm/relaxed">
Laracasts offers thousands of video
tutorials on Laravel, PHP, and JavaScript
development. Check them out, see for
yourself, and massively level up your
development skills in the process.
</p>
</div>
<svg
class="size-6 shrink-0 self-center stroke-[#FF2D20]"
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
stroke-width="1.5"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
d="M4.5 12h15m0 0l-6.75-6.75M19.5 12l-6.75 6.75"
/>
</svg>
</a>
<a
href="https://laravel-news.com"
class="flex items-start gap-4 rounded-lg bg-white p-6 shadow-[0px_14px_34px_0px_rgba(0,0,0,0.08)] ring-1 ring-white/[0.05] transition duration-300 hover:text-black/70 hover:ring-black/20 focus:outline-none focus-visible:ring-[#FF2D20] lg:pb-10 dark:bg-zinc-900 dark:ring-zinc-800 dark:hover:text-white/70 dark:hover:ring-zinc-700 dark:focus-visible:ring-[#FF2D20]"
>
<div
class="flex size-12 shrink-0 items-center justify-center rounded-full bg-[#FF2D20]/10 sm:size-16"
>
<svg
class="size-5 sm:size-6"
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
>
<g fill="#FF2D20">
<path
d="M8.75 4.5H5.5c-.69 0-1.25.56-1.25 1.25v4.75c0 .69.56 1.25 1.25 1.25h3.25c.69 0 1.25-.56 1.25-1.25V5.75c0-.69-.56-1.25-1.25-1.25Z"
/>
<path
d="M24 10a3 3 0 0 0-3-3h-2V2.5a2 2 0 0 0-2-2H2a2 2 0 0 0-2 2V20a3.5 3.5 0 0 0 3.5 3.5h17A3.5 3.5 0 0 0 24 20V10ZM3.5 21.5A1.5 1.5 0 0 1 2 20V3a.5.5 0 0 1 .5-.5h14a.5.5 0 0 1 .5.5v17c0 .295.037.588.11.874a.5.5 0 0 1-.484.625L3.5 21.5ZM22 20a1.5 1.5 0 1 1-3 0V9.5a.5.5 0 0 1 .5-.5H21a1 1 0 0 1 1 1v10Z"
/>
<path
d="M12.751 6.047h2a.75.75 0 0 1 .75.75v.5a.75.75 0 0 1-.75.75h-2A.75.75 0 0 1 12 7.3v-.5a.75.75 0 0 1 .751-.753ZM12.751 10.047h2a.75.75 0 0 1 .75.75v.5a.75.75 0 0 1-.75.75h-2A.75.75 0 0 1 12 11.3v-.5a.75.75 0 0 1 .751-.753ZM4.751 14.047h10a.75.75 0 0 1 .75.75v.5a.75.75 0 0 1-.75.75h-10A.75.75 0 0 1 4 15.3v-.5a.75.75 0 0 1 .751-.753ZM4.75 18.047h7.5a.75.75 0 0 1 .75.75v.5a.75.75 0 0 1-.75.75h-7.5A.75.75 0 0 1 4 19.3v-.5a.75.75 0 0 1 .75-.753Z"
/>
</g>
</svg>
</div>
<div class="pt-3 sm:pt-5">
<h2
class="text-xl font-semibold text-black dark:text-white"
>
Laravel News
</h2>
<p class="mt-4 text-sm/relaxed">
Laravel News is a community driven portal
and newsletter aggregating all of the latest
and most important news in the Laravel
ecosystem, including new package releases
and tutorials.
</p>
</div>
<svg
class="size-6 shrink-0 self-center stroke-[#FF2D20]"
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
stroke-width="1.5"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
d="M4.5 12h15m0 0l-6.75-6.75M19.5 12l-6.75 6.75"
/>
</svg>
</a>
<div
class="flex items-start gap-4 rounded-lg bg-white p-6 shadow-[0px_14px_34px_0px_rgba(0,0,0,0.08)] ring-1 ring-white/[0.05] lg:pb-10 dark:bg-zinc-900 dark:ring-zinc-800"
>
<div
class="flex size-12 shrink-0 items-center justify-center rounded-full bg-[#FF2D20]/10 sm:size-16"
>
<svg
class="size-5 sm:size-6"
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
>
<g fill="#FF2D20">
<path
d="M16.597 12.635a.247.247 0 0 0-.08-.237 2.234 2.234 0 0 1-.769-1.68c.001-.195.03-.39.084-.578a.25.25 0 0 0-.09-.267 8.8 8.8 0 0 0-4.826-1.66.25.25 0 0 0-.268.181 2.5 2.5 0 0 1-2.4 1.824.045.045 0 0 0-.045.037 12.255 12.255 0 0 0-.093 3.86.251.251 0 0 0 .208.214c2.22.366 4.367 1.08 6.362 2.118a.252.252 0 0 0 .32-.079 10.09 10.09 0 0 0 1.597-3.733ZM13.616 17.968a.25.25 0 0 0-.063-.407A19.697 19.697 0 0 0 8.91 15.98a.25.25 0 0 0-.287.325c.151.455.334.898.548 1.328.437.827.981 1.594 1.619 2.28a.249.249 0 0 0 .32.044 29.13 29.13 0 0 0 2.506-1.99ZM6.303 14.105a.25.25 0 0 0 .265-.274 13.048 13.048 0 0 1 .205-4.045.062.062 0 0 0-.022-.07 2.5 2.5 0 0 1-.777-.982.25.25 0 0 0-.271-.149 11 11 0 0 0-5.6 2.815.255.255 0 0 0-.075.163c-.008.135-.02.27-.02.406.002.8.084 1.598.246 2.381a.25.25 0 0 0 .303.193 19.924 19.924 0 0 1 5.746-.438ZM9.228 20.914a.25.25 0 0 0 .1-.393 11.53 11.53 0 0 1-1.5-2.22 12.238 12.238 0 0 1-.91-2.465.248.248 0 0 0-.22-.187 18.876 18.876 0 0 0-5.69.33.249.249 0 0 0-.179.336c.838 2.142 2.272 4 4.132 5.353a.254.254 0 0 0 .15.048c1.41-.01 2.807-.282 4.117-.802ZM18.93 12.957l-.005-.008a.25.25 0 0 0-.268-.082 2.21 2.21 0 0 1-.41.081.25.25 0 0 0-.217.2c-.582 2.66-2.127 5.35-5.75 7.843a.248.248 0 0 0-.09.299.25.25 0 0 0 .065.091 28.703 28.703 0 0 0 2.662 2.12.246.246 0 0 0 .209.037c2.579-.701 4.85-2.242 6.456-4.378a.25.25 0 0 0 .048-.189 13.51 13.51 0 0 0-2.7-6.014ZM5.702 7.058a.254.254 0 0 0 .2-.165A2.488 2.488 0 0 1 7.98 5.245a.093.093 0 0 0 .078-.062 19.734 19.734 0 0 1 3.055-4.74.25.25 0 0 0-.21-.41 12.009 12.009 0 0 0-10.4 8.558.25.25 0 0 0 .373.281 12.912 12.912 0 0 1 4.826-1.814ZM10.773 22.052a.25.25 0 0 0-.28-.046c-.758.356-1.55.635-2.365.833a.25.25 0 0 0-.022.48c1.252.43 2.568.65 3.893.65.1 0 .2 0 .3-.008a.25.25 0 0 0 .147-.444c-.526-.424-1.1-.917-1.673-1.465ZM18.744 8.436a.249.249 0 0 0 .15.228 2.246 2.246 0 0 1 1.352 2.054c0 .337-.08.67-.23.972a.25.25 0 0 0 .042.28l.007.009a15.016 15.016 0 0 1 2.52 4.6.25.25 0 0 0 .37.132.25.25 0 0 0 .096-.114c.623-1.464.944-3.039.945-4.63a12.005 12.005 0 0 0-5.78-10.258.25.25 0 0 0-.373.274c.547 2.109.85 4.274.901 6.453ZM9.61 5.38a.25.25 0 0 0 .08.31c.34.24.616.561.8.935a.25.25 0 0 0 .3.127.631.631 0 0 1 .206-.034c2.054.078 4.036.772 5.69 1.991a.251.251 0 0 0 .267.024c.046-.024.093-.047.141-.067a.25.25 0 0 0 .151-.23A29.98 29.98 0 0 0 15.957.764a.25.25 0 0 0-.16-.164 11.924 11.924 0 0 0-2.21-.518.252.252 0 0 0-.215.076A22.456 22.456 0 0 0 9.61 5.38Z"
/>
</g>
</svg>
</div>
<div class="pt-3 sm:pt-5">
<h2
class="text-xl font-semibold text-black dark:text-white"
>
Vibrant Ecosystem
</h2>
<p class="mt-4 text-sm/relaxed">
Laravel's robust library of first-party
tools and libraries, such as
<a
href="https://forge.laravel.com"
class="rounded-sm underline hover:text-black focus:outline-none focus-visible:ring-1 focus-visible:ring-[#FF2D20] dark:hover:text-white dark:focus-visible:ring-[#FF2D20]"
>Forge</a
>,
<a
href="https://vapor.laravel.com"
class="rounded-sm underline hover:text-black focus:outline-none focus-visible:ring-1 focus-visible:ring-[#FF2D20] dark:hover:text-white"
>Vapor</a
>,
<a
href="https://nova.laravel.com"
class="rounded-sm underline hover:text-black focus:outline-none focus-visible:ring-1 focus-visible:ring-[#FF2D20] dark:hover:text-white"
>Nova</a
>,
<a
href="https://envoyer.io"
class="rounded-sm underline hover:text-black focus:outline-none focus-visible:ring-1 focus-visible:ring-[#FF2D20] dark:hover:text-white"
>Envoyer</a
>, and
<a
href="https://herd.laravel.com"
class="rounded-sm underline hover:text-black focus:outline-none focus-visible:ring-1 focus-visible:ring-[#FF2D20] dark:hover:text-white"
>Herd</a
>
help you take your projects to the next
level. Pair them with powerful open source
libraries like
<a
href="https://laravel.com/docs/billing"
class="rounded-sm underline hover:text-black focus:outline-none focus-visible:ring-1 focus-visible:ring-[#FF2D20] dark:hover:text-white"
>Cashier</a
>,
<a
href="https://laravel.com/docs/dusk"
class="rounded-sm underline hover:text-black focus:outline-none focus-visible:ring-1 focus-visible:ring-[#FF2D20] dark:hover:text-white"
>Dusk</a
>,
<a
href="https://laravel.com/docs/broadcasting"
class="rounded-sm underline hover:text-black focus:outline-none focus-visible:ring-1 focus-visible:ring-[#FF2D20] dark:hover:text-white"
>Echo</a
>,
<a
href="https://laravel.com/docs/horizon"
class="rounded-sm underline hover:text-black focus:outline-none focus-visible:ring-1 focus-visible:ring-[#FF2D20] dark:hover:text-white"
>Horizon</a
>,
<a
href="https://laravel.com/docs/sanctum"
class="rounded-sm underline hover:text-black focus:outline-none focus-visible:ring-1 focus-visible:ring-[#FF2D20] dark:hover:text-white"
>Sanctum</a
>,
<a
href="https://laravel.com/docs/telescope"
class="rounded-sm underline hover:text-black focus:outline-none focus-visible:ring-1 focus-visible:ring-[#FF2D20] dark:hover:text-white"
>Telescope</a
>, and more.
</p>
</div>
</div>
</div>
</main>
<footer
class="py-16 text-center text-sm text-black dark:text-white/70"
>
Laravel v{{ laravelVersion }} (PHP v{{ phpVersion }})
</footer>
</div>
</div>
</div>
</template>

67
routes/api.php Normal file
View File

@@ -0,0 +1,67 @@
<?php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\Api\AccountController;
use App\Http\Controllers\Api\CategoryController;
use App\Http\Controllers\Api\CategoryRuleController;
use App\Http\Controllers\Api\ExpenseController;
use App\Http\Controllers\Api\InvestmentHoldingController;
use App\Http\Controllers\Api\InvestmentTransactionController;
use App\Http\Controllers\Api\InvoiceImportController;
use App\Http\Controllers\Api\SecurityController;
use App\Http\Controllers\Api\SecurityPriceController;
use App\Http\Controllers\Api\DashboardController;
Route::get('/user', function (Request $request) {
return $request->user();
})->middleware('auth:sanctum');
Route::middleware('auth:sanctum')->group(function () {
// 儀表板統計數據 API
Route::get('/dashboard/stats', [DashboardController::class, 'index']);
Route::apiResource('accounts', AccountController::class);
Route::apiResource('accounts.holdings', InvestmentHoldingController::class)
->shallow();
Route::delete('holdings/delete/{account}/{holding}', [InvestmentHoldingController::class, 'destroy']);
Route::get('holdings/{holding}/transactions', [InvestmentTransactionController::class, 'index']);
Route::post('holdings/{holding}/transactions', [InvestmentTransactionController::class, 'store']);
Route::delete('holdings/{holding}/transactions/{transaction}', [InvestmentTransactionController::class, 'destroy']);
Route::get('/accounts/{accountId}/holdings-trend', [SecurityPriceController::class, 'accountTrend']);
Route::get('holdings/{holding}/realtime', [SecurityPriceController::class, 'showRealtime']);
Route::get('holdings/{holding}/history', [SecurityPriceController::class, 'history']);
Route::get('/securities/search', [SecurityController::class, 'index']);
// 取得所有支出明細列表
Route::get('/expenses', [ExpenseController::class, 'index']);
// 新增單筆支出
Route::post('/expenses', [ExpenseController::class, 'store']);
// 修改單筆支出
Route::put('/expenses/{expense}', [ExpenseController::class, 'update']);
// 刪除單筆支出
Route::delete('/expenses/{expense}', [ExpenseController::class, 'destroy']);
// 批量刪除支出
Route::post('/expenses/destroy-batch', [ExpenseController::class, 'destroyBatch']);
Route::get('/categories', [ExpenseController::class, 'categories']);
Route::get('/category-rules', [ExpenseController::class, 'categoryRules']);
// 分類管理 API
Route::post('/categories', [CategoryController::class, 'store']);
Route::put('/categories/{category}', [CategoryController::class, 'update']);
Route::delete('/categories/{category}', [CategoryController::class, 'destroy']);
// 自動分類規則 API
Route::post('/category-rules', [CategoryRuleController::class, 'store']);
Route::delete('/category-rules/{categoryRule}', [CategoryRuleController::class, 'destroy']);
// 發票 CSV 上傳匯入介面 API
Route::post('/expenses/import', [InvoiceImportController::class, 'store']);
});

View File

@@ -4,6 +4,7 @@ use App\Http\Controllers\Auth\AuthenticatedSessionController;
use App\Http\Controllers\Auth\ConfirmablePasswordController;
use App\Http\Controllers\Auth\EmailVerificationNotificationController;
use App\Http\Controllers\Auth\EmailVerificationPromptController;
use App\Http\Controllers\Auth\GoogleAuthController;
use App\Http\Controllers\Auth\NewPasswordController;
use App\Http\Controllers\Auth\PasswordController;
use App\Http\Controllers\Auth\PasswordResetLinkController;
@@ -33,6 +34,10 @@ Route::middleware('guest')->group(function () {
Route::post('reset-password', [NewPasswordController::class, 'store'])
->name('password.store');
Route::get('auth/google', [GoogleAuthController::class, 'redirect'])
->name('auth.google');
Route::get('auth/google/callback', [GoogleAuthController::class, 'callback']);
});
Route::middleware('auth')->group(function () {

View File

@@ -1,8 +1,30 @@
<?php
use App\Console\Commands\RefreshAllAssetPrices;
use Illuminate\Foundation\Inspiring;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Schedule;
use App\Jobs\FetchAndParseGmailInvoices;
use App\Models\User;
Artisan::command('inspire', function () {
$this->comment(Inspiring::quote());
})->purpose('Display an inspiring quote');
Schedule::command(RefreshAllAssetPrices::class)
->weekdays()
->at('14:00')
->at('22:00');
Schedule::call(function () {
// 找出所有有綁定 Google Refresh Token 的使用者
$users = User::whereNotNull('google_refresh_token')->get();
foreach ($users as $user) {
// 分別派發非同步任務去排隊抓信,不塞車
FetchAndParseGmailInvoices::dispatch($user);
}
})
->weekdays()
->at('14:00')
->at('22:00');

View File

@@ -6,7 +6,13 @@ use App\Http\Controllers\CategoryController;
use App\Http\Controllers\CategoryRuleController;
use App\Http\Controllers\DashboardController;
use App\Http\Controllers\InvoiceImportController;
use App\Models\InvestmentHolding;
use App\Models\Security;
use App\Models\SecurityPriceHistories;
use Illuminate\Foundation\Application;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Route;
use Inertia\Inertia;
@@ -23,6 +29,129 @@ Route::get('/', function () {
// return Inertia::render('Dashboard');
// })->middleware(['auth', 'verified'])->name('dashboard');
Route::get('/sync-all-history', function () {
set_time_limit(600);
// 🟢 1. 纯粹捞出持仓,不用多余的 with 关联
$holdings = InvestmentHolding::all();
$count = 0;
foreach ($holdings as $holding) {
// 🟢 2. 直接用持仓的 symbol 去匹配字典表,拿到真正需要的自增主键 id
$security = DB::table('securities')->where('code', $holding->symbol)->first();
if (!$security) {
// 如果字典表没有,顺手现场帮它开荒一笔,拿到新 id
$securityId = DB::table('securities')->insertGetId([
'code' => $holding->symbol,
'name' => $holding->name ?? $holding->symbol,
'type' => $holding->type,
'source' => $holding->type === 'stock' ? 'twse' : 'anue',
'latest_price' => floatval($holding->avg_cost ?? 0),
'created_at' => now(),
'updated_at' => now(),
]);
} else {
$securityId = $security->id;
}
// 找到最早的一笔买入交易作为历史起点
$firstTx = $holding->transactions()->where('action', 'buy')->orderBy('traded_at', 'asc')->first();
if (!$firstTx) continue;
$startDate = Carbon::parse($firstTx->traded_at);
$endDate = Carbon::now();
dump("正在同步 [{$holding->type}] {$holding->symbol} - {$holding->name} 的历史资料自 {$startDate->toDateString()} 起...");
// ----------------------------------------
// 股票 (Stock) 同步
// ----------------------------------------
if ($holding->type === 'stock') {
$current = $startDate->copy()->startOfMonth();
while ($current->lte($endDate)) {
$res = Http::get('https://www.twse.com.tw/rwd/zh/afterTrading/STOCK_DAY', [
'stockNo' => $holding->symbol,
'date' => $current->format('Ymd'),
]);
$data = $res->json();
if (isset($data['stat']) && $data['stat'] === 'OK' && !empty($data['data'])) {
foreach ($data['data'] as $row) {
[$y, $m, $d] = explode('/', $row[0]);
$dateStr = (1911 + (int)$y) . '-' . $m . '-' . $d;
if ($dateStr >= $startDate->toDateString()) {
$closePrice = (float) str_replace(',', '', $row[6]);
// 🟢 成功通过 $securityId 灌入历史表
DB::table('security_price_histories')->updateOrInsert(
[
'security_id' => $securityId,
'price_date' => $dateStr,
],
[
'price' => $closePrice,
'created_at' => now(),
'updated_at' => now(),
]
);
$count++;
}
}
}
$current->addMonth();
usleep(300000); // 防黑名单
}
}
// ----------------------------------------
// 基金 (Fund) 同步
// ----------------------------------------
elseif ($holding->type === 'fund') {
$res = Http::post("https://www.anuefund.com/anuefundApi/FundDetail/Price", [
'priceENUM' => 'NAVHIS',
'fundID' => $holding->symbol,
'strDate' => $startDate->format('Y-m-d'),
'endDate' => $endDate->format('Y-m-d'),
'chartFomatUse' => true,
'reload' => false
]);
if ($res->ok() && !empty($res->json('data'))) {
$pairs = json_decode($res->json('data'), true);
foreach ($pairs as $item) {
if ($item[1] === 0) continue;
$dateStr = date('Y-m-d', intval($item[0]) / 1000);
$navPrice = (float) $item[1];
// 🟢 成功通过 $securityId 灌入历史表
DB::table('security_price_histories')->updateOrInsert(
[
'security_id' => $securityId,
'price_date' => $dateStr,
],
[
'price' => $navPrice,
'created_at' => now(),
'updated_at' => now(),
]
);
$count++;
}
}
}
dump("▶ [{$holding->symbol}] 同步完成。");
}
return "🎉 历史资料回归本地资料库成功!共写录 {$count} 笔历史价格点。";
});
Route::middleware('auth')->group(function () {
Route::get('/dashboard', [DashboardController::class, 'index'])
->name('dashboard');