incr/app/Http/Controllers/TrackerController.php

101 lines
3 KiB
PHP

<?php
declare(strict_types=1);
namespace App\Http\Controllers;
use App\Models\Asset;
use App\Models\User;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
class TrackerController extends Controller
{
public function show(): JsonResponse
{
$tracker = User::default()->tracker;
if (! $tracker) {
return response()->json(null);
}
return response()->json($tracker->load('asset'));
}
public function store(Request $request): RedirectResponse|JsonResponse
{
$validated = $request->validate([
'label' => 'required|string|max:255',
'unit' => 'required|string|max:50',
'price_tracking_enabled' => 'boolean',
'symbol' => 'nullable|string|max:10',
'full_name' => 'nullable|string|max:255',
]);
$user = User::default();
if ($user->tracker) {
return response()->json(['error' => 'Tracker already exists.'], 409);
}
$assetId = null;
if (! empty($validated['symbol'])) {
$asset = Asset::findOrCreateBySymbol($validated['symbol'], $validated['full_name'] ?? null);
$assetId = $asset->id;
}
$user->tracker()->create([
'label' => $validated['label'],
'unit' => $validated['unit'],
'price_tracking_enabled' => $validated['price_tracking_enabled'] ?? false,
'asset_id' => $assetId,
]);
return back();
}
public function update(Request $request): RedirectResponse|JsonResponse
{
$validated = $request->validate([
'label' => 'sometimes|string|max:255',
'unit' => 'sometimes|string|max:50',
'price_tracking_enabled' => 'sometimes|boolean',
'symbol' => 'nullable|string|max:10',
'full_name' => 'nullable|string|max:255',
]);
$tracker = User::default()->tracker;
if (! $tracker) {
return response()->json(['error' => 'No tracker found.'], 404);
}
if (array_key_exists('symbol', $validated)) {
if ($validated['symbol']) {
$asset = Asset::findOrCreateBySymbol($validated['symbol'], $validated['full_name'] ?? null);
$tracker->asset_id = $asset->id;
} else {
$tracker->asset_id = null;
}
}
$update = [];
if (isset($validated['label'])) {
$update['label'] = $validated['label'];
}
if (isset($validated['unit'])) {
$update['unit'] = $validated['unit'];
}
if (array_key_exists('price_tracking_enabled', $validated)) {
$update['price_tracking_enabled'] = $validated['price_tracking_enabled'];
}
if (array_key_exists('symbol', $validated)) {
$update['asset_id'] = $tracker->asset_id;
}
$tracker->update($update);
return back();
}
}