parfum/app/Traits/Order/WithUpdateStock.php

102 lines
3.3 KiB
PHP

<?php
namespace App\Traits\Order;
use App\Models\Bottle;
use App\Models\Perfume;
use App\Models\Product;
trait WithUpdateStock
{
public function increaseOutletStock($outlet, $item)
{
$quantity = $item->quantity;
switch ($item->orderable_type) {
case Perfume::class:
$relation = 'perfumes';
break;
case Product::class:
$relation = 'products';
break;
case Bottle::class:
$relation = 'bottles';
break;
default:
return;
}
$existing = $outlet->{$relation}()->withPivot('stock')->where("{$relation}.id", $item->orderable_id)->first();
if ($existing) {
$currentStock = $existing->pivot->stock ?? 0;
$outlet->{$relation}()->updateExistingPivot($item->orderable_id, [
'stock' => $currentStock + $quantity,
]);
} else {
$outlet->{$relation}()->attach($item->orderable_id, [
'stock' => $quantity,
]);
}
activity('Order')
->performedOn($item->orderable)
->causedBy(auth()->user())
->withProperties([
'orderable_id' => $item->orderable_id,
'orderable_type' => $item->orderable_type,
'outlet_id' => $outlet->id,
'quantity_change' => $quantity,
'previous_stock' => $currentStock,
'new_stock' => $currentStock + $quantity,
'purchase_id' => $item->purchase_id ?? null,
])
->event('Menambah')
->log('Stok '.$item->orderable->name.' di '.$outlet->name.' bertambah '.currency($quantity));
}
public function decreaseOutletStock($outlet, $item)
{
$quantity = $item->quantity;
switch ($item->orderable_type) {
case Perfume::class:
$relation = 'perfumes';
break;
case Product::class:
$relation = 'products';
break;
case Bottle::class:
$relation = 'bottles';
break;
default:
return;
}
$existing = $outlet->{$relation}()->withPivot('stock')->where("{$relation}.id", $item->orderable_id)->first();
if ($existing) {
$currentStock = $existing->pivot->stock ?? 0;
$newStock = max(0, $currentStock - $quantity);
$outlet->{$relation}()->updateExistingPivot($item->orderable_id, [
'stock' => $newStock,
]);
}
activity('Order')
->performedOn($item->orderable)
->causedBy(auth()->user())
->withProperties([
'orderable_id' => $item->orderable_id,
'orderable_type' => $item->orderable_type,
'outlet_id' => $outlet->id,
'quantity_change' => $quantity,
'previous_stock' => $currentStock,
'new_stock' => $currentStock - $quantity,
'purchase_id' => $item->purchase_id ?? null,
])
->event('Mengurangi')
->log('Stok '.$item->orderable->name.' di '.$outlet->name.' berkurang '.currency($quantity));
}
}