parfum/app/Traits/Purchase/WithUpdateStock.php
2025-12-15 21:10:18 +07:00

106 lines
3.3 KiB
PHP

<?php
namespace App\Traits\Purchase;
use App\Models\Bottle;
use App\Models\Perfume;
use App\Models\Product;
use App\Services\StockActivityLogService;
trait WithUpdateStock
{
public function increaseOutletStock($outlet, $item): void
{
$quantity = $item->quantity;
switch ($item->purchasable_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->purchasable_id)->first();
if ($existing) {
$previousStock = $existing->pivot->stock ?? 0;
$outlet->{$relation}()->updateExistingPivot($item->purchasable_id, [
'stock' => $previousStock + $quantity,
]);
} else {
$previousStock = 0;
$outlet->{$relation}()->attach($item->purchasable_id, [
'stock' => $quantity,
]);
}
StockActivityLogService::log(
logName: 'Belanja',
event: 'Menambah',
description: 'Stok '.$item->purchasable->name.' di '.$outlet->name.' bertambah '.formatCurrencyNumber($quantity),
performedOn: $item->purchasable,
outlet: $outlet,
quantityChange: $quantity,
previousStock: $previousStock,
newStock: $previousStock + $quantity,
extraProperties: [
'purchasable_id' => $item->purchasable_id,
'purchasable_type' => $item->purchasable_type,
'purchase_id' => $item->purchase_id ?? null,
]
);
}
public function decreaseOutletStock($outlet, $item): void
{
$quantity = $item->quantity;
switch ($item->purchasable_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->purchasable_id)->first();
if ($existing) {
$currentStock = $existing->pivot->stock ?? 0;
$newStock = max(0, $currentStock - $quantity);
$outlet->{$relation}()->updateExistingPivot($item->purchasable_id, [
'stock' => $newStock,
]);
}
StockActivityLogService::log(
logName: 'Belanja',
event: 'Mengurangi',
description: 'Stok '.$item->purchasable->name.' di '.$outlet->name.' berkurang '.$quantity,
performedOn: $item->purchasable,
outlet: $outlet,
quantityChange: $quantity,
previousStock: $currentStock,
newStock: $newStock,
extraProperties: [
'purchasable_id' => $item->purchasable_id,
'purchasable_type' => $item->purchasable_type,
'purchase_id' => $item->purchase_id,
]
);
}
}