fix: 🐛 Coupon frontend, calculation and submitting

This commit is contained in:
IceToast 2023-06-02 14:54:02 +02:00 committed by IceToast
parent 2161464ee3
commit d365b122db

View file

@ -22,43 +22,32 @@
<!-- END CONTENT HEADER --> <!-- END CONTENT HEADER -->
<!-- MAIN CONTENT --> <!-- MAIN CONTENT -->
<section class="content"> <section class="content" x-data="couponForm()">
<div class="container-fluid"> <div class="container-fluid">
<form <form id="payment_form" action="{{ route('payment.pay') }}" method="POST">
id="payment_form"
action="{{ route('payment.pay') }}"
method="POST"
x-data="{
payment_method: '',
coupon_code: '',
clicked: false,
setCouponCode(event) {
this.coupon_code = event.target.value
}
}"
>
@csrf @csrf
@method('post') @method('post')
<div class="row d-flex justify-content-center flex-wrap"> <div class="row d-flex justify-content-center flex-wrap">
@if (!$productIsFree) @if (!$productIsFree)
<div class="col-xl-4"> <div class="col-xl-4">
<div class="card"> <div class="card">
<div class="card-header">
<h4 class="mb-0">
<i class="fas fa-money-check-alt"></i>
Payment Methods
</h4>
</div>
<div class="card-body"> <div class="card-body">
<ul class="list-group ">
<li class="list-group-item">
<div class="row">
<input type="hidden" name="product_id" value="{{ $product->id }}"> <input type="hidden" name="product_id" value="{{ $product->id }}">
<input type="hidden" name="payment_method" :value="payment_method" <input type="hidden" name="payment_method" :value="payment_method"
x-model="payment_method"> x-model="payment_method">
<div class="row">
<div class="col-lg-12"> <div class="col-lg-12">
<span class="h4">{{ __('Payment Methods') }}</span>
<div class="mt-2">
@foreach ($paymentGateways as $gateway) @foreach ($paymentGateways as $gateway)
<div class="row checkout-gateways"> <div
class="row checkout-gateways @if (!$loop->last) mb-2 @endif">
<div class="col-12 d-flex justify-content-between"> <div class="col-12 d-flex justify-content-between">
<label class="form-check-label h4 checkout-gateway-label" <label
class="form-check-label h5 checkout-gateway-label"
for="{{ $gateway->name }}"> for="{{ $gateway->name }}">
<span class="mr-3">{{ $gateway->name }}</span> <span class="mr-3">{{ $gateway->name }}</span>
</label> </label>
@ -67,7 +56,7 @@
value="{{ $gateway->name }}" value="{{ $gateway->name }}"
:class="payment_method === '{{ $gateway->name }}' ? :class="payment_method === '{{ $gateway->name }}' ?
'active' : ''" 'active' : ''"
@click="payment_method = '{{ $gateway->name }}'; clicked = true;" @click="payment_method = '{{ $gateway->name }}'; submitted = true;"
x-text="payment_method == '{{ $gateway->name }}' ? 'Selected' : 'Select'">Select</button> x-text="payment_method == '{{ $gateway->name }}' ? 'Selected' : 'Select'">Select</button>
</button> </button>
@ -77,49 +66,43 @@
</div> </div>
</div> </div>
</div> </div>
</div> </li>
</div>
<li class="list-group-item">
<div class="row">
<div class="col-lg-12">
@if ($isCouponsEnabled) @if ($isCouponsEnabled)
<div class="col-xl-4"> <span class="h4">{{ __('Coupon') }}</span>
<div class="card">
<div class="card-header"> <div class="d-flex mt-2">
<h4 class="mb-0"> <input type="text" id="coupon_code" name="coupon_code"
Coupon Code value="{{ old('coupon_code') }}" :value="coupon_code"
</h4>
</div>
<div class="card-body">
<div class="d-flex">
<input
type="text"
id="coupon_code"
name="coupon_code"
value="{{ old('coupon_code') }}"
:value="coupon_code"
class="form-control @error('coupon_code') is_invalid @enderror" class="form-control @error('coupon_code') is_invalid @enderror"
placeholder="SUMMER" placeholder="{{ __('Enter your coupon here...') }}"
x-on:change.debounce="setCouponCode($event)" x-on:change.debounce="setCouponCode($event)"
x-model="coupon_code" x-model="coupon_code" />
/> <button type="button" id="send_coupon_code"
<button @click="checkCoupon()" class="btn btn-success ml-3"
type="button"
id="send_coupon_code"
class="btn btn-success ml-3"
:disabled="!coupon_code.length" :disabled="!coupon_code.length"
:class="!coupon_code.length ? 'disabled' : ''" :class="!coupon_code.length ? 'disabled' : ''"
:value="coupon_code" :value="coupon_code">
>
{{ __('Submit') }} {{ __('Submit') }}
</button> </button>
</div> </div>
@error('coupon_code') @error('coupon_code')
<div class="text-danger"> <div class="text-danger">
{{ $message }} {{ $message }}
</div> </div>
@enderror @enderror
</div>
</div>
</div>
@endif @endif
</div>
</div>
</li>
</ul>
</div>
</div>
</div>
@endif @endif
<div class="col-xl-3"> <div class="col-xl-3">
<div class="card"> <div class="card">
@ -173,7 +156,7 @@
<li class="d-flex justify-content-between"> <li class="d-flex justify-content-between">
<span class="text-muted d-inline-block">{{ __('Subtotal') }}</span> <span class="text-muted d-inline-block">{{ __('Subtotal') }}</span>
<span class="text-muted d-inline-block"> <span class="text-muted d-inline-block">
{{ $product->formatToCurrency($discountedprice) }}</span> {{ $product->formatToCurrency($product->price) }}</span>
</li> </li>
<div class="d-flex justify-content-between"> <div class="d-flex justify-content-between">
<span class="text-muted d-inline-block">{{ __('Tax') }} <span class="text-muted d-inline-block">{{ __('Tax') }}
@ -184,7 +167,8 @@
<span class="text-muted d-inline-block"> <span class="text-muted d-inline-block">
+ {{ $product->formatToCurrency($taxvalue) }}</span> + {{ $product->formatToCurrency($taxvalue) }}</span>
</div> </div>
<div id="coupon_discount_details" class="d-flex justify-content-between" style="display: none !important;"> <div id="coupon_discount_details" class="d-flex justify-content-between"
style="display: none !important;">
<span class="text-muted d-inline-block"> <span class="text-muted d-inline-block">
{{ __('Coupon Discount') }} {{ __('Coupon Discount') }}
</span> </span>
@ -195,7 +179,7 @@
@if ($discountpercent && $discountvalue) @if ($discountpercent && $discountvalue)
<div class="d-flex justify-content-between"> <div class="d-flex justify-content-between">
<span class="text-muted d-inline-block">{{ __('Discount') }} <span class="text-muted d-inline-block">{{ __('Discount') }}
({{ $discountpercent }}%):</span> ({{ $discountpercent }}%)</span>
<span <span
class="text-muted d-inline-block">-{{ $product->formatToCurrency($discountvalue) }}</span> class="text-muted d-inline-block">-{{ $product->formatToCurrency($discountvalue) }}</span>
</div> </div>
@ -203,40 +187,36 @@
<hr class="text-white border-secondary"> <hr class="text-white border-secondary">
<div class="d-flex justify-content-between"> <div class="d-flex justify-content-between">
<span class="text-muted d-inline-block">{{ __('Total') }}</span> <span class="text-muted d-inline-block">{{ __('Total') }}</span>
<input id="total_price_input" type="hidden" value="{{ $product->getTotalPrice() }}"> <input id="total_price_input" type="hidden" x-model="totalPrice">
<span <span class="text-muted d-inline-block" x-text="totalPrice">
id="total_price"
class="text-muted d-inline-block"
>
{{ $product->formatToCurrency($total) }}
</span> </span>
</div> </div>
<template x-if="payment_method"> <template x-if="payment_method">
<div class="d-flex justify-content-between"> <div class="d-flex justify-content-between">
<span class="text-muted d-inline-block">{{ __('Pay with') }}</span> <span class="text-muted d-inline-block">{{ __('Pay with') }}</span>
<span class="text-muted d-inline-block" x-text="payment_method"></span> <span class="text-muted d-inline-block"
x-text="payment_method"></span>
</div> </div>
</template> </template>
</ul> </ul>
</li> </li>
</ul> </ul>
<button :disabled="(!payment_method || !clicked || coupon_code ? true : false) && {{ !$productIsFree }}" <button
:disabled="(!payment_method || !clicked || coupon_code) &&
{{ !$productIsFree }}"
id="submit_form_button" id="submit_form_button"
:class="(!payment_method || !clicked || coupon_code ? true : false) && {{ !$productIsFree }} ? 'disabled' : ''" :class="(!payment_method || !clicked || coupon_code) &&
:x-text="coupon_code" {{ !$productIsFree }} ? 'disabled' : ''"
class="btn btn-success float-right w-100"> :x-text="coupon_code" class="btn btn-success float-right w-100">
<i class="far fa-credit-card mr-2" @click="clicked == true"></i> <i class="far fa-credit-card mr-2" @click="clicked == true"></i>
@if ($productIsFree) @if ($productIsFree)
{{ __('Get for free') }} {{ __('Get for free') }}
@else @else
{{ __('Submit Payment') }} {{ __('Submit Payment') }}
@endif @endif
</button> </button>
<script> <script></script>
</script>
</div> </div>
</div> </div>
</div> </div>
@ -248,81 +228,100 @@
<!-- END CONTENT --> <!-- END CONTENT -->
<script> <script>
$(document).ready(function() { function couponForm() {
const productId = $("[name='product_id']").val() console.log("{{ $discountedprice }}", " {{ $discountpercent }}", "{{ $discountvalue }}",
let hasCouponCodeValue = $('#coupon_code').val().trim() !== '' " {{ $taxpercent }}", "{{ $taxvalue }}", "{{ $productIsFree }}", "{{ $total }}")
return {
// Get the product id from the url
productId: window.location.pathname.split('/').pop(),
payment_method: '',
coupon_code: '',
submitted: false,
totalPrice: {{ $discountedprice }},
$('#coupon_code').on('change', function(e) {
hasCouponCodeValue = e.target.value !== ''
})
function calcPriceWithCouponDiscount(couponValue, couponType) { setCouponCode(event) {
let totalPrice = $('#total_price_input').val() this.coupon_code = event.target.value
console.log(event.target.value)
if (typeof totalPrice == 'string') {
totalPrice = parseFloat(totalPrice)
}
if (couponType === 'percentage') {
totalPrice = totalPrice - (totalPrice * couponValue / 100)
$('#coupon_discount_value').text("- " + couponValue + "%")
} else if (couponType === 'amount') {
totalPrice = totalPrice - couponValue
$('#coupon_discount_value').text(totalPrice)
}
$('#total_price').text(totalPrice)
$('#total_price_input').val(totalPrice)
}
function checkCoupon() {
const couponCode = $('#coupon_code').val()
$.ajax({
url: "{{ route('admin.coupon.redeem') }}",
method: 'POST',
data: { couponCode: couponCode, productId: productId },
success: function(response) {
if (response.isValid && response.couponCode) {
Swal.fire({
icon: 'success',
text: 'The coupon was successfully added to your purchase.',
}).then(function(isConfirmed) {
calcPriceWithCouponDiscount(response.couponValue, response.couponType)
$('#submit_form_button').prop('disabled', false).removeClass('disabled')
$('#send_coupon_code').prop('disabled', true)
$('#coupon_discount_details').prop('disabled', false).show()
})
} else {
console.log('Invalid Coupon')
}
}, },
error: function(response) {
const responseJson = response.responseJSON
if (!responseJson.isValid) { async checkCoupon() {
console.log(this.coupon_code)
const response = await (fetch(
"{{ route('admin.coupon.redeem') }}", {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr(
'content')
},
body: JSON.stringify({
couponCode: this.coupon_code,
productId: this.productId
})
}
)
.then(response => response.json()).catch((error) => {
Swal.fire({ Swal.fire({
icon: 'error', icon: 'error',
title: 'Oops...', title: 'Oops...',
text: responseJson.error, text: "{{ __('The coupon code you entered is invalid.') }}"
}) })
} }))
}
if (response.isValid && response.couponCode) {
Swal.fire({
icon: 'success',
text: "{{ __('The coupon was successfully added to your purchase.') }}"
})
this.calcPriceWithCouponDiscount(response.couponValue, response
.couponType)
$('#submit_form_button').prop('disabled', false).removeClass(
'disabled')
$('#send_coupon_code').prop('disabled', true)
$('#coupon_discount_details').prop('disabled', false).show()
} else {
Swal.fire({
icon: 'error',
title: 'Oops...',
text: "{{ __('The coupon code you entered is invalid.') }}"
}) })
} }
$('#payment_form').on('submit', function(e) {
if (hasCouponCodeValue) { },
checkCoupon()
calcPriceWithCouponDiscount(couponValue, couponType) {
let newTotalPrice = this.totalPrice
if (couponType === 'percentage') {
newTotalPrice = newTotalPrice - (newTotalPrice * couponValue / 100)
$('#coupon_discount_value').text("- " + couponValue + "%")
} else if (couponType === 'amount') {
newTotalPrice = totanewTotalPricelPrice - couponValue
$('#coupon_discount_value').text(this.totalPrice)
} }
// get language for formatting currency
const lang = "{{ app()->getLocale() }}"
console.log(lang)
// format totalPrice to currency
this.totalPrice = newTotalPrice.toLocaleString(lang, {
style: 'currency',
currency: "{{ $product->currency_code }}",
}) })
$('#send_coupon_code').click(function(e) { console.log(newTotalPrice)
if (hasCouponCodeValue) { console.log(this.totalPrice)
checkCoupon()
$('#total_price_input').val(this.totalPrice)
},
}
} }
})
})
</script> </script>
@endsection @endsection