- Updated the voucher discount calculation to handle error cases more gracefully. - Reset voucher discount and selection if an error occurs during discount calculation. - Improved user feedback by displaying error messages when voucher validation fails.
99 lines
2.7 KiB
PHP
99 lines
2.7 KiB
PHP
<?php
|
|
|
|
namespace App\Traits\Order;
|
|
|
|
use App\Enums\UserStatus;
|
|
use App\Models\Customer;
|
|
use App\Models\Voucher;
|
|
use Livewire\Attributes\Computed;
|
|
|
|
trait WithMember
|
|
{
|
|
public string $searchMember = '';
|
|
|
|
#[Computed]
|
|
public function members(): array
|
|
{
|
|
if ($this->searchMember === '') {
|
|
return [];
|
|
}
|
|
|
|
return Customer::whereHas('user', fn ($q) => $q->where('status', UserStatus::ACTIVE))
|
|
->where('phone_number', 'like', '%'.$this->searchMember.'%')
|
|
->get()
|
|
->map(fn ($customer) => [
|
|
'id' => $customer->id,
|
|
'name' => $customer?->name,
|
|
'phone_number' => $customer?->phone_number,
|
|
])
|
|
->toArray();
|
|
}
|
|
|
|
public function updatedFormVoucherId(?string $voucherId = null): void
|
|
{
|
|
$voucher = Voucher::find($voucherId);
|
|
|
|
if (! $voucher) {
|
|
$this->voucherDiscount = 0;
|
|
|
|
$this->total = $this->getTotal();
|
|
|
|
return;
|
|
}
|
|
|
|
$subtotal = $this->getSubtotal();
|
|
|
|
$voucherDiscountResult = $this->calculateDiscount($subtotal, $voucher->id);
|
|
|
|
if (is_array($voucherDiscountResult)) {
|
|
// Error case - reset voucher discount and show error
|
|
$this->voucherDiscount = 0;
|
|
$this->form->voucher_id = ''; // Reset voucher selection
|
|
$this->toast($voucherDiscountResult['message'], 'Error', 'danger');
|
|
} else {
|
|
$this->voucherDiscount = $voucherDiscountResult;
|
|
}
|
|
|
|
$this->total = $this->getTotal();
|
|
}
|
|
|
|
public function updatedFormMemberId(?string $memberId = null): void
|
|
{
|
|
$customer = Customer::with('user')->find($memberId);
|
|
|
|
if (! $customer) {
|
|
$this->voucherDiscount = 0;
|
|
|
|
$this->form->voucher_id = '';
|
|
|
|
$this->vouchers = [];
|
|
|
|
$this->total = $this->getTotal();
|
|
|
|
return;
|
|
}
|
|
|
|
$this->loadVouchers($customer->user?->id, $this->form->outlet_id);
|
|
}
|
|
|
|
public function updatedFormOutletId(?string $outletId = null): void
|
|
{
|
|
$customer = Customer::with('user')->find($this->form->member_id);
|
|
if (! $customer) {
|
|
return;
|
|
}
|
|
|
|
$this->loadVouchers($customer->user?->id, $outletId);
|
|
}
|
|
|
|
private function loadVouchers(?string $memberId, ?string $outletId): void
|
|
{
|
|
$this->vouchers = Voucher::whereHas('users', fn ($q) => $q->where('user_id', $memberId))
|
|
->whereHas('outlets', fn ($q) => $q->where('outlet_id', $outletId))
|
|
->active()
|
|
->orderBy('discount_amount', 'desc')
|
|
->pluck('name', 'id')
|
|
->toArray();
|
|
}
|
|
}
|