91 lines
2.7 KiB
PHP
91 lines
2.7 KiB
PHP
<?php
|
||
|
||
declare(strict_types=1);
|
||
|
||
namespace App\Http\Controllers\Transactions;
|
||
|
||
use App\Http\Controllers\Controller;
|
||
use App\Models\Transactions\Entry;
|
||
use App\Models\User;
|
||
use Illuminate\Http\JsonResponse;
|
||
use Illuminate\Http\RedirectResponse;
|
||
use Illuminate\Http\Request;
|
||
|
||
class EntryController extends Controller
|
||
{
|
||
public function index(): JsonResponse
|
||
{
|
||
$tracker = User::default()->tracker;
|
||
|
||
if (! $tracker) {
|
||
return response()->json([]);
|
||
}
|
||
|
||
return response()->json($tracker->entries()->orderBy('date', 'desc')->get());
|
||
}
|
||
|
||
public function store(Request $request): RedirectResponse
|
||
{
|
||
$validated = $request->validate([
|
||
'date' => 'required|date|before_or_equal:today',
|
||
'quantity' => 'required|numeric|min:0.000001',
|
||
'unit_price' => 'nullable|numeric|min:0.01',
|
||
'total_cost' => 'nullable|numeric|min:0.01',
|
||
]);
|
||
|
||
$tracker = User::default()->tracker;
|
||
|
||
if (! $tracker) {
|
||
return back()->withErrors(['tracker' => 'No tracker found. Please complete onboarding first.']);
|
||
}
|
||
|
||
// If unit_price and total_cost provided, verify the calculation
|
||
if (isset($validated['unit_price'], $validated['total_cost'])) {
|
||
$calculatedTotal = $validated['quantity'] * $validated['unit_price'];
|
||
if (abs($calculatedTotal - $validated['total_cost']) > 0.01) {
|
||
return back()->withErrors([
|
||
'total_cost' => 'Total cost does not match quantity × unit price.',
|
||
]);
|
||
}
|
||
}
|
||
|
||
$tracker->entries()->create($validated);
|
||
|
||
return back()->with('success', 'Entry added successfully!');
|
||
}
|
||
|
||
public function summary(): JsonResponse
|
||
{
|
||
$tracker = User::default()->tracker;
|
||
|
||
if (! $tracker) {
|
||
return response()->json([
|
||
'total_quantity' => 0,
|
||
'total_cost' => 0,
|
||
'average_cost_per_unit' => 0,
|
||
]);
|
||
}
|
||
|
||
return response()->json([
|
||
'total_quantity' => Entry::totalQuantity($tracker->id),
|
||
'total_cost' => Entry::totalCost($tracker->id),
|
||
'average_cost_per_unit' => Entry::averageCostPerUnit($tracker->id),
|
||
]);
|
||
}
|
||
|
||
public function destroy(Entry $entry): JsonResponse
|
||
{
|
||
$tracker = User::default()->tracker;
|
||
|
||
if (! $tracker || $entry->tracker_id !== $tracker->id) {
|
||
return response()->json(['error' => 'Entry not found.'], 404);
|
||
}
|
||
|
||
$entry->delete();
|
||
|
||
return response()->json([
|
||
'success' => true,
|
||
'message' => 'Entry deleted successfully!',
|
||
]);
|
||
}
|
||
}
|