mirror of
https://github.com/anna-sara/lan_kiosk
synced 2026-09-03 10:25:02 +02:00
100 lines
2.4 KiB
PHP
100 lines
2.4 KiB
PHP
<?php
|
|
|
|
namespace App\Http\Controllers;
|
|
|
|
use App\Models\Purchase;
|
|
use Illuminate\Http\Request;
|
|
use App\Models\Customer;
|
|
use Illuminate\Support\Facades\DB;
|
|
|
|
class PurchaseController extends Controller
|
|
{
|
|
/**
|
|
* Display a listing of the resource.
|
|
*/
|
|
public function index()
|
|
{
|
|
$purchases = Purchase::get();
|
|
return $purchases->toJson();
|
|
}
|
|
|
|
/**
|
|
* Show the form for creating a new resource.
|
|
*/
|
|
public function create()
|
|
{
|
|
//
|
|
}
|
|
|
|
/**
|
|
* Store a newly created resource in storage.
|
|
*/
|
|
public function store(Request $request)
|
|
{
|
|
$data = $request->validate([
|
|
'customer_id' => 'required',
|
|
'amount' => 'nullable',
|
|
]);
|
|
|
|
// Look the customer up before writing anything — creating the purchase
|
|
// first would leave a line item behind that no balance ever paid for
|
|
$customer = Customer::findOrFail( $data['customer_id'] );
|
|
$amount = (int) $data['amount'];
|
|
|
|
DB::transaction(function () use ($customer, $amount) {
|
|
$customer->amount_left = $customer->amount_left - $amount;
|
|
$customer->save();
|
|
|
|
Purchase::create([
|
|
'customer_id' => $customer->id,
|
|
'amount' => $amount,
|
|
]);
|
|
});
|
|
|
|
return redirect('customer/' . $customer->id);
|
|
}
|
|
|
|
/**
|
|
* Display the specified resource.
|
|
*/
|
|
public function show(Purchase $purchase)
|
|
{
|
|
//
|
|
}
|
|
|
|
/**
|
|
* Show the form for editing the specified resource.
|
|
*/
|
|
public function edit(Purchase $purchase)
|
|
{
|
|
//
|
|
}
|
|
|
|
/**
|
|
* Update the specified resource in storage.
|
|
*/
|
|
public function update(Request $request, Purchase $purchase)
|
|
{
|
|
//
|
|
}
|
|
|
|
/**
|
|
* Remove the specified resource from storage.
|
|
*/
|
|
public function destroy($id)
|
|
{
|
|
$purchase = Purchase::findOrFail( $id );
|
|
$customer = Customer::findOrFail( $purchase->customer_id );
|
|
|
|
// store() takes the amount off this customer's balance, so removing the
|
|
// purchase puts it back on the same balance
|
|
$customer->amount_left = $customer->amount_left + (int) $purchase->amount;
|
|
$customer->save();
|
|
|
|
$purchase->delete();
|
|
|
|
return response()->json([
|
|
'success' => true, 'message' => 'Purchase deleted successfully'
|
|
]);
|
|
}
|
|
}
|