106 lines
No EOL
2.8 KiB
PHP
106 lines
No EOL
2.8 KiB
PHP
<?php
|
|
|
|
namespace App\Http\Controllers;
|
|
|
|
use App\Models\Asset;
|
|
use Illuminate\Http\JsonResponse;
|
|
use Illuminate\Http\Request;
|
|
use Illuminate\Support\Facades\Auth;
|
|
|
|
class AssetController extends Controller
|
|
{
|
|
public function index(): JsonResponse
|
|
{
|
|
$assets = Asset::orderBy('symbol')->get();
|
|
|
|
return response()->json($assets);
|
|
}
|
|
|
|
public function current(): JsonResponse
|
|
{
|
|
// Get the first/default user (since no auth)
|
|
$user = \App\Models\User::first();
|
|
$asset = $user ? $user->asset : null;
|
|
|
|
return response()->json([
|
|
'asset' => $asset,
|
|
]);
|
|
}
|
|
|
|
public function setCurrent(Request $request)
|
|
{
|
|
$validated = $request->validate([
|
|
'symbol' => 'required|string|max:10',
|
|
'full_name' => 'nullable|string|max:255',
|
|
]);
|
|
|
|
$asset = Asset::findOrCreateBySymbol(
|
|
$validated['symbol'],
|
|
$validated['full_name'] ?? null
|
|
);
|
|
|
|
// Get or create the first/default user (since no auth)
|
|
$user = \App\Models\User::first();
|
|
|
|
if (!$user) {
|
|
// Create a default user if none exists
|
|
$user = \App\Models\User::create([
|
|
'name' => 'Default User',
|
|
'email' => 'user@example.com',
|
|
'password' => 'password', // This will be hashed automatically
|
|
'asset_id' => $asset->id,
|
|
]);
|
|
} else {
|
|
$user->update(['asset_id' => $asset->id]);
|
|
}
|
|
|
|
return back()->with('success', 'Asset set successfully!');
|
|
}
|
|
|
|
public function store(Request $request): JsonResponse
|
|
{
|
|
$validated = $request->validate([
|
|
'symbol' => 'required|string|max:10|unique:assets,symbol',
|
|
'full_name' => 'nullable|string|max:255',
|
|
]);
|
|
|
|
$asset = Asset::create([
|
|
'symbol' => strtoupper($validated['symbol']),
|
|
'full_name' => $validated['full_name'],
|
|
]);
|
|
|
|
return response()->json([
|
|
'success' => true,
|
|
'message' => 'Asset created successfully!',
|
|
'asset' => $asset,
|
|
], 201);
|
|
}
|
|
|
|
public function show(Asset $asset): JsonResponse
|
|
{
|
|
$asset->load('assetPrices');
|
|
$currentPrice = $asset->currentPrice();
|
|
|
|
return response()->json([
|
|
'asset' => $asset,
|
|
'current_price' => $currentPrice,
|
|
]);
|
|
}
|
|
|
|
public function search(Request $request): JsonResponse
|
|
{
|
|
$query = $request->get('q');
|
|
|
|
if (!$query) {
|
|
return response()->json([]);
|
|
}
|
|
|
|
$assets = Asset::where('symbol', 'like', "%{$query}%")
|
|
->orWhere('full_name', 'like', "%{$query}%")
|
|
->orderBy('symbol')
|
|
->limit(10)
|
|
->get();
|
|
|
|
return response()->json($assets);
|
|
}
|
|
} |