File: /home/armgroup/libs/app/Http/Livewire/Admin/Order/UpdateQuantity.php
<?php
namespace App\Http\Livewire\Admin\Order;
use App\Http\Livewire\ConvertEmptyStringsToNull;
use App\Http\Livewire\General;
use App\Models\Order;
use App\Models\OrderProduct;
use App\Models\Product;
use Illuminate\Support\Facades\DB;
use Livewire\Component;
class UpdateQuantity extends Component
{
use ConvertEmptyStringsToNull;
use General;
public $quantity;
public Order $order;
public Product $product;
public $orderProductsCount;
public OrderProduct $orderProduct;
public function render()
{
return view('livewire.admin.order.update-quantity');
}
public function update()
{
$this->validate([
'quantity' => 'required|integer|min:0|max:999999999999999|not_in:'.$this->orderProduct->quantity,
], [
'quantity.not_in' => 'تعداد باید مخالف مقدار فعلی باشد.',
]);
if ($this->isLastProduct()) {
$this->quantity = $this->orderProduct->quantity;
$this->ajaxDoneMessage('با حذف این مورد هیچ محصولی در سفارش نخواهد بود! برای حذف کل سفارش از دکمه حذف در لیست سفارشات استفاده کنید.',
'warning');
return;
}
$diff_quantity = $this->orderProduct->quantity - $this->quantity;
DB::transaction(function () use ($diff_quantity) {
$this->order->update([
'price' => $this->order->price - ($this->orderProduct->price * $diff_quantity),
'discount' => $this->order->discount - ($this->orderProduct->discount * $diff_quantity),
]);
if ($this->quantity == 0) {
$this->orderProduct->delete();
} else {
$this->orderProduct->update([
'quantity' => $this->quantity,
]);
}
});
saveActivity("محصولات سفارش {$this->order->tracking_code} ویرایش شد", $this->order);
$this->doneMessage();
return redirect()->route('admin.orders.edit', $this->order);
}
private function isLastProduct(): bool
{
return $this->quantity == 0 && $this->orderProductsCount == 1;
}
}