['hours' => 24, 'intervalMs' => 900000], 'WEEKLY' => ['hours' => 168, 'intervalMs' => 7200000], 'MONTHLY' => ['hours' => 720, 'intervalMs' => 28800000], ]; 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', '') )); } /** * UUID سری نمودار: settings.chart_id؛ وگرنه پیش‌فرض گلد علی. * GET https://price.zaarbox.ir/api/history/{id} */ public function historyId(): string { $chartId = $this->config->getString('chart_id', ''); if ($chartId !== '') { return $chartId; } $legacy = $this->config->getString( 'zaarbox_gold_history_id', (string) config('price_providers.zaarbox_gold_history_id', '') ); if ($legacy !== '') { return $legacy; } return self::DEFAULT_HISTORY_ID; } private function cacheKey(): string { return self::CACHE_KEY . ':' . $this->historyId(); } /** * @return array{DAILY: array, WEEKLY: array, MONTHLY: array} */ public function getAllPrices(): array { $cached = Cache::get($this->cacheKey()); if (is_array($cached) && isset($cached['prices'])) { return $cached['prices']; } return $this->refreshCache(); } /** * @return array{DAILY: array, WEEKLY: array, MONTHLY: array} */ public function refreshCache(): array { $prices = $this->fetchChartPrices(); Cache::put($this->cacheKey(), [ 'prices' => $prices, 'refreshed_at' => now()->toIso8601String(), ], now()->addMinutes(self::CACHE_TTL_MINUTES)); return $prices; } /** * @return array{price: int, order_price: int, raw: array|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; } } /** * @return array{DAILY: array, WEEKLY: array, MONTHLY: array} */ private function fetchChartPrices(): array { $now = Carbon::now('UTC'); $prices = []; $responses = Http::pool(function ($pool) use ($now) { foreach (self::PERIODS as $key => $config) { $start = $now->copy()->subHours($config['hours']); $pool->as($key)->withHeaders([ 'Referer' => 'https://tablo.montest.ir/', 'User-Agent' => 'Mozilla/5.0', ])->get($this->historyUrl($start, $now)); } }); foreach (self::PERIODS as $key => $config) { $response = $responses[$key] ?? null; $start = $now->copy()->subHours($config['hours']); if (!$response || !$response->successful()) { Log::warning('Zaarbox price history fetch failed', [ 'period' => $key, 'status' => $response?->status(), ]); $prices[$key] = []; continue; } $history = $response->json('history') ?? []; $prices[$key] = $this->mapHistory( $history, $this->toMillis($start), $this->toMillis($now), $config['intervalMs'] ); } return $prices; } private function historyUrl(Carbon $start, Carbon $end): string { return sprintf( 'https://price.zaarbox.ir/api/history/%s?start=%s&end=%s&limit=1000000000', $this->historyId(), $this->toIso8601($start), $this->toIso8601($end) ); } private function toIso8601(Carbon $date): string { return $date->format('Y-m-d\TH:i:s') . '.' . str_pad((string) $date->millisecond, 3, '0', STR_PAD_LEFT) . 'Z'; } private function toMillis(Carbon $date): int { return ($date->getTimestamp() * 1000) + $date->millisecond; } /** * @param array> $history * @return array */ private function mapHistory(array $history, int $startMs, int $endMs, int $intervalMs): array { $points = []; foreach ($history as $entry) { if (!isset($entry['time'], $entry['price'])) { continue; } $timestamp = $this->parseTimestampMs($entry['time']); if ($timestamp === null) { continue; } $points[] = [ 'timestamp' => $timestamp, 'price' => (int) $entry['price'], ]; } usort($points, fn ($a, $b) => $a['timestamp'] <=> $b['timestamp']); $firstBucket = (int) (ceil($startMs / $intervalMs) * $intervalMs); if ($firstBucket < $startMs) { $firstBucket += $intervalMs; } $result = []; $index = 0; $lastPoint = null; $count = count($points); for ($bucket = $firstBucket; $bucket <= $endMs; $bucket += $intervalMs) { while ($index < $count && $points[$index]['timestamp'] <= $bucket) { $lastPoint = $points[$index]; $index++; } if ($lastPoint === null) { continue; } $result[] = [ 'value' => intdiv($lastPoint['price'], 1000), 'timestamp' => $bucket, ]; } return $result; } private function parseTimestampMs(string $time): ?int { try { return $this->toMillis(Carbon::parse($time)->utc()); } catch (\Throwable) { return null; } } /** * @param Collection> $collection * @return array|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; } }