parfum/app/Traits/Order/WithManageItem.php

56 lines
1.7 KiB
PHP

<?php
namespace App\Traits\Order;
use App\Models\OrderItem;
trait WithManageItem
{
/**
* Adds a new order item or updates the quantity if it already exists in the order.
*
* @param mixed $model The model instance (Perfume, Bottle, or Product)
* @param int $quantity The quantity to add
* @param string|null $quality The quality of the item
*/
protected function addOrUpdateOrderItem($model, int $quantity, ?string $quality = null): void
{
$existing = $this->items->firstWhere(fn ($i) => $i->orderable_type === get_class($model) && $i->orderable_id === $model->id && $i->quality === $quality);
if ($existing) {
$existing->increment('quantity', $quantity);
$existing->refresh();
} else {
$existing = OrderItem::create([
'user_id' => auth()->id(),
'orderable_id' => $model->id,
'orderable_type' => get_class($model),
'quality' => $quality,
'cogs' => $model->cost_price ?? 0,
'quantity' => $quantity,
'unit_price' => $model->sale_price ?? 0,
]);
$this->items->push($existing);
}
$this->items = $this->items->map(fn ($i) => $i->id === $existing->id ? $existing : $i);
$this->subtotal = $this->getSubtotal();
$this->total = $this->getTotal();
}
public function deleteItem(OrderItem $item): void
{
$this->items = $this->items->reject(fn ($i) => $i->id === $item->id);
$item->delete();
// Recalculate totals
$this->subtotal = $this->getSubTotal();
$this->total = $this->getTotal();
$this->toast('Item berhasil dihapus.');
}
}