Files
boursecu_server/app/Services/ProductPriceService.php
T
2026-06-02 16:00:33 +03:30

58 lines
1.9 KiB
PHP

<?php
namespace App\Services;
use App\Models\Product;
class ProductPriceService
{
public static function referenceTotal(int $basePrice, int $baseProfit = 0): int
{
return $basePrice + $baseProfit;
}
public static function adjustedTotal(int $basePrice, int $baseProfit, float $offsetPercent): int
{
$reference = self::referenceTotal($basePrice, $baseProfit);
return (int) round($reference * (1 + ($offsetPercent / 100)));
}
/** مرجع API + درصد محصول → ذخیره در price (سود خرید/فروش جداگانه در سفارش اعمال می‌شود) */
public static function offsetPercent(Product $product): float
{
return Product::hasPriceOffsetColumn()
? (float) ($product->price_offset_percent ?? 0)
: 0.0;
}
public static function syncFromReference(Product $product, int $basePrice, int $baseProfit = 0): void
{
$offsetPercent = self::offsetPercent($product);
Product::where('id', $product->id)->update([
'price' => self::adjustedTotal($basePrice, $baseProfit, $offsetPercent),
'price_profit' => 0,
]);
}
/** وقتی فقط درصد در ادمین عوض می‌شود (بدون sync جدید) */
public static function reapplyOffsetPercent(Product $product, float $newOffsetPercent, ?float $oldOffsetPercent = null): void
{
if (!Product::hasPriceOffsetColumn()) {
return;
}
$oldOffset = $oldOffsetPercent ?? self::offsetPercent($product);
$currentTotal = (int) ($product->price + ($product->price_profit ?? 0));
$reference = $oldOffset != 0.0
? (int) round($currentTotal / (1 + $oldOffset / 100))
: $currentTotal;
Product::where('id', $product->id)->update([
'price' => (int) round($reference * (1 + ($newOffsetPercent / 100))),
'price_profit' => 0,
]);
}
}