Fixes for cart and payment/paypal processing

This commit is contained in:
Deon George 2024-08-10 22:17:21 +10:00
parent efbb3d091f
commit f1dd68a737
10 changed files with 271 additions and 189 deletions

View File

@ -42,27 +42,53 @@ class CheckoutController extends Controller
->with('success','Checkout saved'); ->with('success','Checkout saved');
} }
public function cart_invoice(Request $request,Invoice $o=NULL) /**
* Add an invoice to the cart
*
* @param Request $request
* @param Invoice $o
* @return \Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|\Illuminate\Foundation\Application
* @note The route validates that the user can see the invoice
*/
public function cart_invoice(Request $request,Invoice $o)
{ {
if ($o) { $request->session()->put('invoice.cart.'.$o->id,$o->id);
$request->session()->put('invoice.cart.'.$o->id,$o->id);
return view('theme.backend.adminlte.checkout.cart');
}
/**
* Remove an item from the cart
*
* @param Request $request
* @return string
*/
public function cart_remove(Request $request): string
{
if ($id=$request->post('id')) {
$cart = $request->session()->pull('invoice.cart');
unset($cart[$id]);
$request->session()->put('invoice.cart',$cart);
} }
if (! $request->session()->get('invoice.cart')) return '';
return redirect()
->to('u/home');
return view('theme.backend.adminlte.u.invoice.cart')
->with('invoices',Invoice::find(array_values($request->session()->get('invoice.cart'))));
} }
public function fee(Request $request,Checkout $o): float public function fee(Request $request): float
{ {
return $o->fee($request->post('total',0)); if ((! $request->post('checkout_id') || (! $request->post('total'))))
return 0;
$co = Checkout::findOrFail($request->post('checkout_id'));
return $co->fee($request->post('total'));
} }
public function pay(Request $request,Checkout $o) public function pay()
{ {
return redirect('pay/paypal/authorise'); // @todo Currently sending all payments to paypal
return redirect()
->action([PaypalController::class,'authorise']);
} }
} }

View File

@ -3,9 +3,9 @@
namespace App\Http\Controllers; namespace App\Http\Controllers;
use Illuminate\Http\RedirectResponse; use Illuminate\Http\RedirectResponse;
use Illuminate\Support\Arr;
use App\Http\Requests\PaymentAddEdit; use App\Http\Requests\PaymentAddEdit;
use Illuminate\Support\Arr;
use App\Models\{Payment,PaymentItem}; use App\Models\{Payment,PaymentItem};
class PaymentController extends Controller class PaymentController extends Controller

View File

@ -2,8 +2,8 @@
namespace App\Http\Controllers; namespace App\Http\Controllers;
use App\Models\PaymentItem;
use Carbon\Carbon; use Carbon\Carbon;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log; use Illuminate\Support\Facades\Log;
use PayPalCheckoutSdk\Core\PayPalHttpClient; use PayPalCheckoutSdk\Core\PayPalHttpClient;
@ -13,14 +13,13 @@ use PayPalCheckoutSdk\Orders\OrdersCreateRequest;
use PayPalCheckoutSdk\Orders\OrdersCaptureRequest; use PayPalCheckoutSdk\Orders\OrdersCaptureRequest;
use PayPalHttp\HttpException; use PayPalHttp\HttpException;
use App\Models\Checkout; use App\Models\{Checkout,Invoice,Payment,PaymentItem};
use App\Models\Invoice;
use App\Models\Payment;
class PaypalController extends Controller class PaypalController extends Controller
{ {
private $client; private PayPalHttpClient $client;
private $o = NULL;
protected const cart_url = 'u/checkout/cart';
// Create a new instance with our paypal credentials // Create a new instance with our paypal credentials
public function __construct() public function __construct()
@ -31,27 +30,30 @@ class PaypalController extends Controller
$environment = new ProductionEnvironment(config('paypal.live_client_id'),config('paypal.live_secret')); $environment = new ProductionEnvironment(config('paypal.live_client_id'),config('paypal.live_secret'));
$this->client = new PayPalHttpClient($environment); $this->client = new PayPalHttpClient($environment);
$this->o = Checkout::where('name','paypal')->firstOrFail();
} }
public function cancel(Request $request) public function cancel()
{ {
return redirect()->to('u/invoice/cart'); return redirect()
->to(self::cart_url);
} }
/** /**
* Authorize a paypal payment, and redirect the user to pay. * Authorize a paypal payment, and redirect the user to pay.
* *
* @param Request $request * @return RedirectResponse
* @return \Illuminate\Http\RedirectResponse * @throws \PayPalHttp\IOException
*/ */
public function authorise(Request $request) public function authorise()
{ {
$co = Checkout::where('name','ilike','paypal')->firstOrFail();
$currency = 'AUD'; // @todo TO determine from DB.; $currency = 'AUD'; // @todo TO determine from DB.;
$cart = $request->session()->get('invoice.cart'); $cart = request()->session()->get('invoice.cart');
if (! $cart) if (! $cart)
return redirect()->to('u/home'); return redirect()
->to('u/home');
$invoices = Invoice::find($cart); $invoices = Invoice::find($cart);
@ -61,7 +63,7 @@ class PaypalController extends Controller
// Paypal Purchase Units // Paypal Purchase Units
$items = collect(); $items = collect();
foreach ($invoices as $io) { foreach ($invoices as $io) {
$fee = $this->o->fee($io->due,count($cart)); $fee = $co->fee($io->due,count($cart));
$total = round($io->due+$fee,2); $total = round($io->due+$fee,2);
$items->push([ $items->push([
@ -100,7 +102,7 @@ class PaypalController extends Controller
$data->put('application_context',[ $data->put('application_context',[
'return_url' => url('pay/paypal/capture'), 'return_url' => url('pay/paypal/capture'),
'cancel_url' => url('u/invoice/cart'), 'cancel_url' => url(self::cart_url),
]); ]);
$paypal->body = $data->toArray(); $paypal->body = $data->toArray();
@ -111,12 +113,16 @@ class PaypalController extends Controller
} catch (HttpException $e) { } catch (HttpException $e) {
Log::error('Paypal Exception',['request'=>$paypal,'response'=>$e->getMessage()]); Log::error('Paypal Exception',['request'=>$paypal,'response'=>$e->getMessage()]);
return redirect()->to('u/invoice/cart')->withErrors('Paypal Exception: '.$e->getCode()); return redirect()
->to(self::cart_url)
->withErrors('Paypal Exception: '.$e->getCode());
} catch (\HttpException $e) { } catch (\HttpException $e) {
Log::error('HTTP Exception',['request'=>$request,'response'=>$e->getMessage()]); Log::error('HTTP Exception',['request'=>$this->client,'response'=>$e->getMessage()]);
return redirect()->to('u/invoice/cart')->withErrors('HTTP Exception: '.$e->getCode()); return redirect()
->to(self::cart_url)
->withErrors('HTTP Exception: '.$e->getCode());
} }
// Get the approval link // Get the approval link
@ -128,18 +134,21 @@ class PaypalController extends Controller
} }
} }
if ($redirect_url) { if ($redirect_url)
return redirect()->away($redirect_url); return redirect()
} ->away($redirect_url);
return redirect()->to('u/invoice/cart')->withErrors('An error occurred with Paypal?'); return redirect()
->to(self::cart_url)
->withErrors('An error occurred with Paypal?');
} }
/** /**
* Capture a paypal payment * Capture a paypal payment
* *
* @param Request $request * @param Request $request
* @return \Illuminate\Http\RedirectResponse * @return RedirectResponse
* @throws \PayPalHttp\IOException
*/ */
public function capture(Request $request) public function capture(Request $request)
{ {
@ -179,23 +188,32 @@ class PaypalController extends Controller
if ($redirect_url) { if ($redirect_url) {
Log::error('Paypal Capture: Redirect back to Paypal.'); Log::error('Paypal Capture: Redirect back to Paypal.');
return redirect()->away($redirect_url); return redirect()
->away($redirect_url);
} }
return redirect()->to('u/invoice/cart')->withErrors('An error occurred with Paypal?'); return redirect()
->to(self::cart_url)
->withErrors('An error occurred with Paypal?');
} catch (\HttpException $e) { } catch (\HttpException $e) {
Log::error('HTTP Exception',['request'=>$paypal,'response'=>$e->getMessage()]); Log::error('HTTP Exception',['request'=>$paypal,'response'=>$e->getMessage()]);
return redirect()->to('u/invoice/cart')->withErrors('HTTP Exception: '.$e->getCode()); return redirect()
->to(self::cart_url)
->withErrors('HTTP Exception: '.$e->getCode());
} }
if (! $response OR ! $response->result->purchase_units) { if ((! $response) || (! $response->result->purchase_units)) {
Log::error('Paypal Capture: No Purchase Units?'); Log::error('Paypal Capture: No Purchase Units?');
return redirect()->to('u/invoice/cart')->withErrors('Paypal Exception: NPU'); return redirect()
->to(self::cart_url)
->withErrors('Paypal Exception: NPU');
} }
$co = Checkout::where('name','ilike','paypal')->firstOrFail();
// If we got here, we got a payment // If we got here, we got a payment
foreach ($response->result->purchase_units as $pu) { foreach ($response->result->purchase_units as $pu) {
foreach ($pu->payments->captures as $cap) { foreach ($pu->payments->captures as $cap) {
@ -219,7 +237,7 @@ class PaypalController extends Controller
} }
$po->paid_at = Carbon::parse($cap->create_time); $po->paid_at = Carbon::parse($cap->create_time);
$po->checkout_id = $this->o->id; $po->checkout_id = $co->id;
$po->checkout_data = $cap->id; $po->checkout_data = $cap->id;
list($account_id,$fee) = explode(':',$cap->custom_id); list($account_id,$fee) = explode(':',$cap->custom_id);
@ -246,7 +264,11 @@ class PaypalController extends Controller
} }
$request->session()->forget('invoice.cart'); $request->session()->forget('invoice.cart');
Log::info('Paypal Payment Recorded',['po'=>$po->id]); Log::info('Paypal Payment Recorded',['po'=>$po->id]);
return redirect()->to('u/home')->with('success','Payment recorded thank you.');
return redirect()
->to('u/home')
->with('success','Payment recorded thank you.');
} }
} }

View File

@ -3,7 +3,7 @@
namespace App\Http\Requests; namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest; use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Gate;
use Illuminate\Validation\Rule; use Illuminate\Validation\Rule;
/** /**
@ -18,7 +18,7 @@ class CheckoutAddEdit extends FormRequest
*/ */
public function authorize() public function authorize()
{ {
return Auth::user()->isWholesaler(); return Gate::allows('wholesaler');
} }
/** /**

View File

@ -3,7 +3,7 @@
namespace App\Http\Requests; namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest; use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Gate;
use App\Models\Invoice; use App\Models\Invoice;
@ -19,7 +19,7 @@ class PaymentAddEdit extends FormRequest
*/ */
public function authorize() public function authorize()
{ {
return Auth::user()->isWholesaler(); return Gate::allows('wholesaler');
} }
/** /**

View File

@ -0,0 +1,140 @@
@use(App\Models\Checkout)
@use(App\Models\Invoice)
@extends('adminlte::layouts.app')
@section('htmlheader_title')
Payment Cart
@endsection
@section('page_title')
Payments
@endsection
@section('contentheader_title')
Payment Cart
@endsection
@section('contentheader_description')
@endsection
@section('main-content')
<div class="row">
<div class="col-4">
<div class="card card-dark">
<div class="card-header p-2">
<span class="card-title">Invoices to Pay</span>
</div>
<div class="card-body">
<form method="POST" action="{{ url('u/checkout/pay') }}">
@csrf
<input type="hidden" name="type" value="invoice">
<!-- @todo This is currently forcing only paypal -->
<x-leenooks::form.select id="checkout_id" name="checkout_id" icon="fa-credit-card" label="Payment Method" feedback="Payment Method is required" choose="true" :options="Checkout::active()->where('name','ilike','paypal')->orderBy('name')->get()->map(function ($item) { $item->value = $item->name; return $item; })"/>
<table id="invoices" class="table table-sm w-100">
<tr>
<th>Invoice</th>
<th class="text-right">Balance Due</th>
</tr>
@foreach (($invoices=Invoice::whereIn('id',session('invoice.cart',[]))->get()) as $io)
<input type="hidden" name="invoice_id[]" value="{{ $io->id }}">
<tr>
<td><a class="cart_delete text-dark" data-id="{{ $io->id }}" data-value="{{ $io->due }}" href="{{ url('/u/cart/delete',$io->id) }}"><i class="fas fa-trash-alt"></i></a> {{ $io->sid }}</td>
<td class="text-right">{{ number_format($io->due,2) }}</td>
</tr>
@endforeach
<tfoot>
<tr>
<th class="text-right">Sub Total</th>
<td class="text-right"><span id="subtotal">{{ number_format($invoices->sum('due'),2) }}</span></td>
</tr>
<tr>
<th class="text-right">Payment Fees</th>
<td class="text-right"><span id="payfee">TBA</span></td>
</tr>
<tr>
<th class="text-right">Payment Total</th>
<th class="text-right"><span id="paytotal">TBA</span></th>
</tr>
<tr>
<th colspan="2">
<!-- Buttons -->
<x-leenooks::button.cancel/>
<x-leenooks::button.submit class="float-right" disabled>Pay</x-leenooks::button.submit>
<a href="{{ url('/home') }}" class="mt-4 btn btn-sm btn-primary">Add Invoice</a>
</th>
</tr>
</tfoot>
</table>
</form>
</div>
</div>
</div>
</div>
<x-leenooks::errors/>
@endsection
@section('page-scripts')
<script type="text/javascript">
var subtotal = {{ $invoices->sum('due') }};
function fee_total() {
$.ajax({
type: 'POST',
data: {
total: subtotal,
checkout_id: $('#checkout_id').val()
},
dataType: 'json',
url: '{{ url('u/checkout/fee') }}',
timeout: 5000,
error: function() {
alert('Failed to submit, please try again...');
},
success: function(data) {
$('span[id=payfee]').html(data.toFixed(2));
$('span[id=paytotal]').html((subtotal+data).toFixed(2));
$('button[type=submit]').prop('disabled',false);
}
});
}
$(document).ready(function() {
if ($('#checkout_id').val())
fee_total();
$('#checkout_id').on('change',fee_total);
$('.cart_delete').click(function(item) {
var that = $(this);
// Delete
$.ajax({
url: '{{ url('u/checkout/cart/remove') }}',
method: 'POST',
data: {id: that.data('id')},
}).done(function(data) {
that.closest('tr').hide();
that.closest('tr').parent().find('input').attr('disabled',true);
subtotal -= that.data('value');
$('span[id=subtotal]').html(subtotal.toFixed(2));
if ($('#checkout_id').val())
fee_total();
}).fail(function(data) {
alert('Hmm, that didnt work?');
});
// Clear the data cache
that.removeData();
return false;
});
});
</script>
@append

View File

@ -18,9 +18,7 @@
@endsection @endsection
@section('main-content') @section('main-content')
<!-- Main content -->
<div class="invoice p-3 mb-3"> <div class="invoice p-3 mb-3">
<!-- title row -->
<div class="row"> <div class="row">
<div class="col-8"> <div class="col-8">
<h2> <h2>
@ -31,10 +29,8 @@
<div class="col-4 text-right"> <div class="col-4 text-right">
<h1 class="text-uppercase">Tax Invoice</h1> <h1 class="text-uppercase">Tax Invoice</h1>
</div> </div>
<!-- /.col -->
</div> </div>
<!-- info row -->
<div class="row invoice-info"> <div class="row invoice-info">
<div class="col-4 invoice-col"> <div class="col-4 invoice-col">
<address> <address>
@ -84,12 +80,10 @@
</table> </table>
</div> </div>
</div> </div>
<!-- /.row -->
<!-- Table row -->
<div class="row"> <div class="row">
<div class="col-12 table-responsive"> <div class="col">
<table class="table table-striped table-hover"> <table class="table table-responsive table-striped table-hover">
<thead> <thead>
<tr> <tr>
<th>Qty</th> <th>Qty</th>
@ -144,15 +138,11 @@
</tbody> </tbody>
</table> </table>
</div> </div>
<!-- /.col -->
</div> </div>
<!-- /.row -->
<!-- padding -->
<div class="row pb-5"></div> <div class="row pb-5"></div>
<div class="row"> <div class="row">
<!-- accepted payments column -->
<div class="col-6"> <div class="col-6">
<p class="lead">Payment Methods:</p> <p class="lead">Payment Methods:</p>
@ -172,7 +162,6 @@
</p> </p>
</div> </div>
<!-- /.col -->
<div class="ml-auto col-4"> <div class="ml-auto col-4">
<table class="table"> <table class="table">
<tr> <tr>
@ -213,18 +202,14 @@
@endif @endif
</table> </table>
</div> </div>
<!-- /.col -->
</div> </div>
<!-- /.row -->
<!-- this row will not appear when printing --> <!-- this row will not appear when printing -->
<div class="row d-print-none"> <div class="row d-print-none">
<div class="col-12"> <div class="col-12">
<a href="javascript:window.print();" class="btn btn-default"><i class="fas fa-print"></i> Print</a> <button type="button" id="print" class="btn btn-default"><i class="fas fa-print"></i> Print</button>
@if($o->id) @if($o->id)
<a href="{{ url('u/invoice/cart',$o->id) }}" class="btn btn-success float-right"> <a href="{{ url('u/checkout/cart',$o->id) }}" class="btn btn-success float-right"><i class="fas fa-credit-card"></i> Pay</a>
<i class="fas fa-credit-card"></i> Pay
</a>
{{-- {{--
<a href="{{ url(sprintf('u/invoice/%s/pdf',$o->id)) }}" class="btn btn-primary float-right mr-2"> <a href="{{ url(sprintf('u/invoice/%s/pdf',$o->id)) }}" class="btn btn-primary float-right mr-2">
<i class="fas fa-download"></i> Download PDF <i class="fas fa-download"></i> Download PDF
@ -234,7 +219,23 @@
</div> </div>
</div> </div>
</div> </div>
<!-- /.content -->
<div class="clearfix"></div>
@endsection @endsection
@section('page-styles')
<style media="print">
/* Dont show URL and date in print output */
@page {
size: auto; /* auto is the initial value */
margin: 0; /* this affects the margin in the printer settings */
}
</style>
@append
@section('page-scripts')
<script type="text/javascript">
$(document).ready(function() {
$('#print').on('click',function() {
window.print();
})
});
</script>
@append

View File

@ -1,109 +0,0 @@
@extends('adminlte::layouts.app')
@section('htmlheader_title')
Payment Cart
@endsection
@section('page_title')
Payments
@endsection
@section('contentheader_title')
Payment Cart
@endsection
@section('contentheader_description')
@endsection
@section('main-content')
<div class="row">
<div class="col-4">
<div class="card card-dark">
<div class="card-header">
<span class="card-title">Invoices to Pay</span>
</div>
<div class="card-body">
<form method="POST" action="{{ url('u/checkout/pay') }}">
@csrf
<input type="hidden" name="type" value="invoice">
<div class="input-group mb-5">
<div class="input-group-prepend">
<span class="input-group-text">Payment Method</span>
</div>
<select class="form-control" id="paymethod" name="checkout_id[]" required>
<option></option>
@foreach (\App\Models\Checkout::active()->orderBy('name')->get() as $oo)
<option value="{{ $oo->id }}">{{ $oo->name }}</option>
@endforeach
</select>
</div>
<table id="invoices" class="table table-sm w-100">
<tr>
<th>Invoice</th>
<th class="text-right">Balance Due</th>
</tr>
@foreach ($invoices as $io)
<input type="hidden" name="invoice_id[]" value="{{ $io->id }}">
<tr>
<td>{{ $io->sid }}</td>
<td class="text-right">{{ number_format($io->due,2) }}</td>
</tr>
@endforeach
<tfoot>
<tr>
<th class="text-right">Sub Total</th>
<td class="text-right">{{ number_format($invoices->sum('due'),2) }}</td>
</tr>
<tr>
<th class="text-right">Payment Fees</th>
<td class="text-right"><span id="payfee">TBA</span></td>
</tr>
<tr>
<th class="text-right">Payment Total</th>
<th class="text-right"><span id="paytotal">TBA</span></th>
</tr>
<tr>
<th colspan="2">
<input type="submit" class="btn btn-dark mt-2" name="pay" value="Cancel">
<input type="submit" class="btn btn-success mt-2 float-right" name="pay" value="Submit" disabled>
<a href="{{ url('/home') }}" class="btn btn-danger mt-2 float-right mr-2">Add Invoice</a>
</th>
</tr>
</tfoot>
</table>
</form>
</div>
</div>
</div>
</div>
@endsection
@section('page-scripts')
<script>
$(document).ready(function() {
$('#paymethod').on('change',function(item) {
$.ajax({
type: "POST",
data: {total: {{ $invoices->sum('due') }},count: {{ $invoices->count() }} },
dataType: "json",
cache: true,
url: '{{ url('api/u/checkout/fee') }}'+'/'+$(this).val(),
timeout: 25000,
error: function(x) {
alert("Failed to submit, please try again...");
},
success: function(data) {
$("span[id=payfee]").html(data.toFixed(2));
$("span[id=paytotal]").html(({{ $invoices->sum('due') }}+data).toFixed(2));
$("input[type=submit]").prop('disabled',false);
}
});
});
});
</script>
@append

View File

@ -25,10 +25,7 @@ Route::group(['middleware'=>['auth:api','role:wholesaler']], function() {
}); });
Route::group(['middleware'=>'auth:api'], function() { Route::group(['middleware'=>'auth:api'], function() {
Route::post('/u/checkout/fee/{o}',[CheckoutController::class,'fee']) Route::any('/intuit/accounting/list',[AccountingController::class,'list']);
->where('o','[0-9]+');
Route::any('/intuit/accounting/list',[AccountingController::class,'list']);
}); });
Route::any('/intuit/webhook',[Webhook::class,'webhook']); Route::any('/intuit/webhook',[Webhook::class,'webhook']);

View File

@ -180,17 +180,22 @@ Route::group(['middleware'=>['auth'],'prefix'=>'u'],function() {
Route::get('home/{o}',[HomeController::class,'home']) Route::get('home/{o}',[HomeController::class,'home'])
->where('o','[0-9]+') ->where('o','[0-9]+')
->middleware('can:view,o'); ->middleware('can:view,o');
Route::redirect('checkout/pay','pay/paypal/authorise');
Route::view('checkout/cart','theme.backend.adminlte.checkout.cart');
Route::get('checkout/cart/{o}',[CheckoutController::class,'cart_invoice'])
->where('o','[0-9]+')
->middleware('can:view,o');
Route::post('checkout/cart/remove',[CheckoutController::class,'cart_remove']);
Route::post('checkout/fee',[CheckoutController::class,'fee']);
Route::post('checkout/pay',[CheckoutController::class,'pay']);
Route::get('invoice/{o}',[InvoiceController::class,'view']) Route::get('invoice/{o}',[InvoiceController::class,'view'])
->where('o','[0-9]+') ->where('o','[0-9]+')
->middleware('can:view,o'); ->middleware('can:view,o');
Route::get('invoice/{o}/pdf',[InvoiceController::class,'pdf']) Route::get('invoice/{o}/pdf',[InvoiceController::class,'pdf'])
->where('o','[0-9]+') ->where('o','[0-9]+')
->middleware('can:view,o'); ->middleware('can:view,o');
Route::get('invoice/cart',[CheckoutController::class,'cart_invoice']);
Route::get('invoice/cart/{o}',[CheckoutController::class,'cart_invoice'])
->where('o','[0-9]+')
->middleware('can:view,o');
Route::get('service/{o}',[ServiceController::class,'home']) Route::get('service/{o}',[ServiceController::class,'home'])
->where('o','[0-9]+') ->where('o','[0-9]+')
->middleware('can:view,o'); ->middleware('can:view,o');