parfum/app/Traits/Purchase/WithAddItem.php

101 lines
3.0 KiB
PHP

<?php
namespace App\Traits\Purchase;
use App\Models\Bottle;
use App\Models\Perfume;
use App\Models\Product;
use App\Models\PurchaseItem;
use Illuminate\Support\Str;
trait WithAddItem
{
public function addItem(string $type)
{
switch ($type) {
case 'perfume':
$model = Perfume::class;
$id = $this->form->perfume_id;
$quantity = replaceCurrency($this->form->quantity_perfume);
break;
case 'product':
$model = Product::class;
$id = $this->form->product_id;
$quantity = replaceCurrency($this->form->quantity_product);
break;
case 'bottle':
$model = Bottle::class;
$id = $this->form->bottle_id;
$quantity = replaceCurrency($this->form->quantity_bottle);
break;
default:
$this->toast('Tipe item tidak dikenal.', 'Gagal', 'danger');
return;
}
$itemModel = $model::find($id);
if (! $itemModel) {
$this->toast(Str::ucfirst($type).' tidak ditemukan, silakan periksa kembali.', 'Gagal', 'danger');
return;
}
$costPrice = (int) $itemModel->cost_price;
if ($quantity <= 0) {
$this->toast('Jumlah '.$type.' tidak valid, silakan periksa kembali.', 'Gagal', 'danger');
return;
}
if ($costPrice <= 0) {
$this->toast('Harga '.$type.' tidak valid, silakan periksa kembali.', 'Gagal', 'danger');
return;
}
$existingItem = $this->form->cartItems
->where('purchasable_type', $model)
->where('purchasable_id', $itemModel->id)
->first();
if ($existingItem) {
$existingItem->quantity += $quantity;
$existingItem->total_price = $existingItem->unit_price * $existingItem->quantity;
$existingItem->save();
$existingItem->refresh();
$this->form->cartItems = $this->form->cartItems->map(fn ($i) => $i->id === $existingItem->id ? $existingItem : $i);
$this->toast('Jumlah '.$type.' diperbarui di keranjang.', 'Berhasil');
} else {
$item = PurchaseItem::create([
'purchasable_id' => $itemModel->id,
'purchasable_type' => $model,
'quantity' => $quantity,
'unit_price' => $costPrice,
'total_price' => $costPrice * $quantity,
]);
$this->form->cartItems->push($item);
$this->toast(Str::ucfirst($type).' ditambahkan ke keranjang.', 'Berhasil');
}
$this->form->total = currency($this->form->cartItems->sum('total_price'), '');
$this->reset('form.perfume_id');
$this->reset('form.product_id');
$this->reset('form.bottle_id');
$this->reset('form.quantity_perfume');
$this->reset('form.quantity_product');
$this->reset('form.quantity_bottle');
}
}