Files
boursecu_server/app/Services/ZaarboxPriceService.php
T
2026-06-04 14:40:02 +03:30

101 lines
2.7 KiB
PHP

<?php
namespace App\Services;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
class ZaarboxPriceService
{
public function __construct(private ConfigService $config)
{
}
public function isEnabled(): bool
{
return $this->config->usesZaarboxPricing();
}
public function apiUrl(): string
{
$url = trim((string) $this->config->getString(
'zaarbox_api_url',
(string) config('price_providers.zaarbox_api_url', 'https://price.zaarbox.ir/api/free')
));
return $url !== '' ? $url : 'https://price.zaarbox.ir/api/free';
}
/** کلید یا id ردیف در JSON تابلو (settings: zaarbox_price_key) */
public function priceIdentifier(): string
{
return trim((string) $this->config->getString(
'zaarbox_price_key',
(string) config('price_providers.zaarbox_price_key', '')
));
}
/**
* @return array{price: int, order_price: int, raw: array<string, mixed>|null}
*/
public function fetchPrice(): array
{
$empty = ['price' => 0, 'order_price' => 0, 'raw' => null];
$identifier = $this->priceIdentifier();
if ($identifier === '') {
return $empty;
}
try {
$prices = Http::withoutVerifying()
->timeout(20)
->get($this->apiUrl())
->json();
if (!is_array($prices)) {
return $empty;
}
$row = $this->findRow(collect($prices), $identifier);
if (empty($row)) {
Log::warning('Zaarbox price row not found', [
'identifier' => $identifier,
'api' => $this->apiUrl(),
]);
return $empty;
}
$base = (float) ($row['price'] ?? 0);
$profit = (float) ($row['profit'] ?? 0);
$orderPrice = (int) round($base + $profit);
return ['price' => $orderPrice, 'order_price' => $orderPrice, 'raw' => $row];
} catch (\Throwable $e) {
Log::warning('Zaarbox price fetch failed', ['message' => $e->getMessage()]);
return $empty;
}
}
/**
* @param Collection<int, array<string, mixed>> $collection
* @return array<string, mixed>|null
*/
private function findRow(Collection $collection, string $identifier): ?array
{
$row = $collection->firstWhere('key', $identifier);
if (!empty($row)) {
return $row;
}
$row = $collection->firstWhere('id', $identifier);
if (!empty($row)) {
return $row;
}
return null;
}
}