70 lines
2.1 KiB
PHP
70 lines
2.1 KiB
PHP
|
|
<?php
|
|||
|
|
|
|||
|
|
namespace App\Http\Controllers\Transactions;
|
|||
|
|
|
|||
|
|
use App\Http\Controllers\Controller;
|
|||
|
|
use App\Models\Transactions\Purchase;
|
|||
|
|
use Illuminate\Http\JsonResponse;
|
|||
|
|
use Illuminate\Http\Request;
|
|||
|
|
use Illuminate\Support\Facades\Redirect;
|
|||
|
|
|
|||
|
|
class PurchaseController extends Controller
|
|||
|
|
{
|
|||
|
|
public function index(): JsonResponse
|
|||
|
|
{
|
|||
|
|
$purchases = Purchase::orderBy('date', 'desc')->get();
|
|||
|
|
|
|||
|
|
return response()->json($purchases);
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
public function store(Request $request): \Illuminate\Http\RedirectResponse
|
|||
|
|
{
|
|||
|
|
$validated = $request->validate([
|
|||
|
|
'date' => 'required|date|before_or_equal:today',
|
|||
|
|
'shares' => 'required|numeric|min:0.000001',
|
|||
|
|
'price_per_share' => 'required|numeric|min:0.01',
|
|||
|
|
'total_cost' => 'required|numeric|min:0.01',
|
|||
|
|
]);
|
|||
|
|
|
|||
|
|
// Verify calculation is correct
|
|||
|
|
$calculatedTotal = $validated['shares'] * $validated['price_per_share'];
|
|||
|
|
if (abs($calculatedTotal - $validated['total_cost']) > 0.01) {
|
|||
|
|
return back()->withErrors([
|
|||
|
|
'total_cost' => 'Total cost does not match shares × price per share.'
|
|||
|
|
]);
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
Purchase::create([
|
|||
|
|
'date' => $validated['date'],
|
|||
|
|
'shares' => $validated['shares'],
|
|||
|
|
'price_per_share' => $validated['price_per_share'],
|
|||
|
|
'total_cost' => $validated['total_cost'],
|
|||
|
|
]);
|
|||
|
|
|
|||
|
|
return Redirect::back()->with('success', 'Purchase added successfully!');
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
public function summary()
|
|||
|
|
{
|
|||
|
|
$totalShares = Purchase::totalShares();
|
|||
|
|
$totalInvestment = Purchase::totalInvestment();
|
|||
|
|
$averageCost = Purchase::averageCostPerShare();
|
|||
|
|
|
|||
|
|
return response()->json([
|
|||
|
|
'total_shares' => $totalShares,
|
|||
|
|
'total_investment' => $totalInvestment,
|
|||
|
|
'average_cost_per_share' => $averageCost,
|
|||
|
|
]);
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* Remove the specified purchase.
|
|||
|
|
*/
|
|||
|
|
public function destroy(Purchase $purchase)
|
|||
|
|
{
|
|||
|
|
$purchase->delete();
|
|||
|
|
|
|||
|
|
return Redirect::back()->with('success', 'Purchase deleted successfully!');
|
|||
|
|
}
|
|||
|
|
}
|