dstpabuaran.com/app/Services/Concerns/HasStockAdjustment.php

48 lines
1.3 KiB
PHP

<?php
namespace App\Services\Concerns;
use App\Enums\ProductStockQuality;
use Illuminate\Database\Eloquent\Model;
trait HasStockAdjustment
{
private const QUALITY_STOCK_MAP = [
ProductStockQuality::GOOD->value => 'stock',
ProductStockQuality::REJECT->value => 'reject_stock',
];
private function adjustStock(Model $model, string $field, int $quantity, int $sign): void
{
if ($sign > 0) {
$model->increment($field, $quantity);
} else {
$model->decrement($field, $quantity);
}
}
private function adjustVariantStock(int $variantId, int $quantity, int $sign, string $stockType): void
{
$field = self::QUALITY_STOCK_MAP[$stockType] ?? 'stock';
$this->adjustStock(
model: app(\App\Models\ProductVariant::class)->newQuery()->findOrFail($variantId),
field: $field,
quantity: $quantity,
sign: $sign,
);
}
private function applyStock(array $items, string $stockType, int $sign): void
{
foreach ($items as $item) {
$this->adjustVariantStock($item['product_variant_id'], $item['quantity'], $sign, $stockType);
}
}
private function reverseStock(array $items, string $stockType, int $sign): void
{
$this->applyStock($items, $stockType, -$sign);
}
}