['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 { $candidates = $this->feedUrlCandidates(); return $candidates[0] ?? 'https://price.zaarbox.ir/api/free'; } /** * آدرس‌های فید `/api/free` به ترتیب failover — از کلید zaarbox_api_url. * مقدار می‌تواند تک‌URL (legacy) یا JSON آرایه/لیست جداشده با کاما/خط جدید باشد (تا ۵ مورد). * هر مورد به مسیر /api/free نرمال می‌شود. * * @return array */ public function feedUrlCandidates(): array { $raw = trim((string) $this->config->getString('zaarbox_api_url', '')); $urls = []; if ($raw !== '') { $decoded = json_decode($raw, true); if (is_array($decoded)) { foreach ($decoded as $item) { $value = is_array($item) ? ($item['url'] ?? '') : $item; $urls[] = trim((string) $value); } } else { foreach (preg_split('/[\r\n,]+/', $raw) ?: [] as $item) { $urls[] = trim((string) $item); } } } $candidates = array_values(array_filter( array_map(fn (string $u) => $this->normalizeFeedUrl($u), $urls), fn (string $u) => $u !== '' )); $candidates = array_values(array_unique($candidates)); if ($candidates === []) { $fallback = trim((string) config('price_providers.zaarbox_api_url', 'https://price.zaarbox.ir/api/free')); $candidates[] = $this->normalizeFeedUrl($fallback !== '' ? $fallback : 'https://price.zaarbox.ir/api/free'); } return array_slice($candidates, 0, 5); } /** نرمال‌سازی به آدرس فید — اگر مسیر /api/free نداشت اضافه می‌شود */ private function normalizeFeedUrl(string $url): string { $url = rtrim(trim($url), '/'); if ($url === '') { return ''; } if (preg_match('~/api/free$~i', $url)) { return $url; } return $url . '/api/free'; } /** * دریافت فید با failover — اولین سروری که آرایهٔ معتبر برگرداند. * * @return array>|null */ private function fetchFeedWithFailover(): ?array { foreach ($this->feedUrlCandidates() as $url) { try { $prices = Http::withoutVerifying() ->timeout(12) ->get($url) ->json(); if (is_array($prices) && $prices !== []) { return $prices; } } catch (\Throwable $e) { Log::warning('Partner feed url failed, trying next', [ 'url' => $url, 'message' => $e->getMessage(), ]); } } return null; } public function hasApiUrlConfigured(): bool { return $this->feedUrlCandidates() !== []; } /** کلید یا id ردیف انس در JSON تابلو (settings: zaarbox_ounce_key) */ public function ouncePriceIdentifier(): string { return trim((string) $this->config->getString( 'zaarbox_ounce_key', (string) config('price_providers.zaarbox_ounce_key', 'tala_ounce') )); } /** کلید یا 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(); } private function lastGoodCacheKey(): string { return $this->cacheKey() . self::LAST_GOOD_CACHE_SUFFIX; } /** * @param array{DAILY?: array, WEEKLY?: array, MONTHLY?: array} $prices */ private function hasChartData(array $prices): bool { foreach (['DAILY', 'WEEKLY', 'MONTHLY'] as $period) { if (! empty($prices[$period])) { return true; } } return false; } /** * @return array{DAILY: array, WEEKLY: array, MONTHLY: array}|null */ private function resolveLastGoodPrices(): ?array { $lastGood = Cache::get($this->lastGoodCacheKey()); if (is_array($lastGood['prices'] ?? null) && $this->hasChartData($lastGood['prices'])) { return $lastGood['prices']; } return null; } /** * @return array{DAILY: array, WEEKLY: array, MONTHLY: array} */ public function getAllPrices(): array { $snapshot = app(PriceSnapshotService::class); $minRial = $snapshot->minValidChartPriceRialForExternalFeed(); if ($this->config->getBool('chart_use_local_data', false)) { $sanitizedLocal = $snapshot->sanitizeChartPrices($snapshot->chartFromDatabase()); if ($this->hasChartData($sanitizedLocal)) { return $sanitizedLocal; } } $cached = Cache::get($this->cacheKey()); if (is_array($cached['prices'] ?? null) && $this->hasChartData($cached['prices'])) { return $snapshot->sanitizeChartPrices($cached['prices'], $minRial); } $fresh = $this->refreshCache(); $sanitized = $snapshot->sanitizeChartPrices($fresh, $minRial); if ($this->hasChartData($sanitized)) { return $sanitized; } $lastGood = $this->resolveLastGoodPrices(); if ($lastGood !== null) { return $snapshot->sanitizeChartPrices($lastGood, $minRial); } return $sanitized; } /** * @return array{DAILY: array, WEEKLY: array, MONTHLY: array} */ public function refreshCache(): array { $prices = $this->fetchChartPrices(); $cacheKey = $this->cacheKey(); $payload = [ 'prices' => $prices, 'refreshed_at' => now()->toIso8601String(), ]; if ($this->hasChartData($prices)) { Cache::put($cacheKey, $payload, now()->addMinutes(self::CACHE_TTL_MINUTES)); Cache::put($this->lastGoodCacheKey(), $payload, now()->addHours(24)); return $prices; } Log::warning('Zaarbox chart refresh returned no data', [ 'history_id' => $this->historyId(), ]); $lastGood = $this->resolveLastGoodPrices(); if ($lastGood !== null) { return $lastGood; } Cache::put($cacheKey, array_merge($payload, ['failed' => true]), now()->addMinutes(self::FAILED_CACHE_TTL_MINUTES)); return $prices; } /** * @param array> $prices * @return array|null */ public function findOunceFeedRow(array $prices): ?array { $identifier = $this->ouncePriceIdentifier(); if ($identifier !== '') { $row = $this->findFeedRow($prices, $identifier); if ($row !== null) { return $row; } } $row = collect($prices) ->map(fn ($item) => is_array($item) ? $item : (array) $item) ->filter(function (array $item) { $name = trim((string) ($item['name'] ?? '')); return $name !== '' && ( mb_strpos($name, 'انس') !== false || mb_strpos($name, 'اونس') !== false ); }) ->sortBy([ fn (array $item) => trim((string) ($item['key'] ?? '')) === 'tala_ounce' ? 0 : 1, fn (array $item) => (bool) ($item['active'] ?? false) ? 0 : 1, fn (array $item) => trim((string) ($item['category'] ?? '')) === 'ounce' ? 0 : 1, fn (array $item) => str_contains(trim((string) ($item['name'] ?? '')), 'اونس طلا') ? 0 : 1, fn (array $item) => str_contains(trim((string) ($item['name'] ?? '')), 'انس طلا') ? 0 : 1, fn (array $item) => mb_strlen(trim((string) ($item['name'] ?? ''))), ]) ->first(); return is_array($row) ? $row : null; } /** * @return array{price: int, name: string, raw: array|null} */ public function fetchOuncePrice(): array { $empty = ['price' => 0, 'name' => '', 'raw' => null]; if (! $this->hasApiUrlConfigured()) { return $empty; } try { // مثل fetchPrice — اول HTTP تازه؛ کش فقط fallback (کش خالی/قدیمی باعث null شدن gold_ounce می‌شد) $prices = $this->fetchPriceList(); if (! is_array($prices) || $prices === []) { $prices = $this->cachedPriceList(false); } if (! is_array($prices)) { return $empty; } $row = $this->findOunceFeedRow($prices); if ($row === null) { return $empty; } $price = $this->resolveReferenceProviderTotal($row); if ($price <= 0) { return $empty; } return [ 'price' => $price, 'name' => trim((string) ($row['name'] ?? 'اونس طلا')) ?: 'اونس طلا', 'raw' => $row, ]; } catch (\Throwable $e) { Log::warning('Zaarbox ounce price fetch failed', ['message' => $e->getMessage()]); return $empty; } } /** payload انس برای last/SSE — null یعنی نمایش خاموش یا بدون مظنه */ public function clientGoldOuncePayload(): ?array { if (! $this->config->getBool('show_gold_ounce_price', false)) { return null; } if (! $this->hasApiUrlConfigured()) { return null; } $ounce = $this->fetchOuncePrice(); if (($ounce['price'] ?? 0) <= 0) { return null; } $rawPrice = is_array($ounce['raw'] ?? null) ? ($ounce['raw']['price'] ?? $ounce['price']) : $ounce['price']; return [ 'price' => round((float) $rawPrice, 2), 'label' => self::formatOunceDisplayLabel((string) ($ounce['name'] ?? '')), ]; } private static function formatOunceDisplayLabel(string $name): string { $label = trim($name); $label = preg_replace('/\s+tala\.ir\s*$/iu', '', $label) ?? $label; $label = trim($label); return $label !== '' ? $label : 'اونس طلا'; } /** * @param array $payload * @return array */ public function attachGoldOunceToPayload(array $payload): array { $payload['gold_ounce'] = $this->clientGoldOuncePayload(); return $payload; } /** * @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 = $this->fetchFeedWithFailover(); if (!is_array($prices)) { return $empty; } $row = $this->findFeedRow($prices, $identifier); if ($row === null) { Log::warning('Zaarbox price row not found', [ 'identifier' => $identifier, 'api' => $this->apiUrl(), ]); return $empty; } $orderPrice = $this->resolveReferenceProviderTotal($row); return ['price' => $orderPrice, 'order_price' => $orderPrice, 'raw' => $row]; } catch (\Throwable $e) { Log::warning('Zaarbox price fetch failed', ['message' => $e->getMessage()]); return $empty; } } /** @return array>|null */ public function fetchPriceList(): ?array { return $this->fetchFeedWithFailover(); } /** * فید تابلو با کش کوتاه — کران هر ۳۰ث refresh می‌کند؛ list در بازهٔ کش همان فید را مصرف می‌کند. * * @return array>|null */ public function cachedPriceList(bool $forceRefresh = false): ?array { if ($forceRefresh) { Cache::forget(self::PRICE_LIST_CACHE_KEY); } $cached = Cache::get(self::PRICE_LIST_CACHE_KEY); if (is_array($cached)) { return $cached; } $prices = $this->fetchPriceList(); if ($prices !== null) { $this->storePriceListCache($prices); } return $prices; } /** فقط کش — برای /customer/product/list (بدون HTTP) */ public function getCachedPriceListOnly(): ?array { $cached = Cache::get(self::PRICE_LIST_CACHE_KEY); return is_array($cached) ? $cached : null; } /** @param array> $prices */ public function storePriceListCache(array $prices): void { Cache::put(self::PRICE_LIST_CACHE_KEY, $prices, now()->addSeconds(self::PRICE_LIST_CACHE_SECONDS)); } /** * @return array */ public function listProductOptions(): array { $prices = $this->fetchPriceList(); if ($prices === null) { return []; } return collect($prices) ->map(function ($row) { $row = is_array($row) ? $row : (array) $row; return [ 'key' => trim((string) ($row['key'] ?? '')), 'name' => trim((string) ($row['name'] ?? '')), 'id' => trim((string) ($row['id'] ?? '')), 'category' => trim((string) ($row['category'] ?? '')), 'active' => (bool) ($row['active'] ?? false), 'price' => $this->resolveReferenceProviderTotal($row), ]; }) ->filter(fn (array $row) => $row['key'] !== '') ->sortBy('name', SORT_NATURAL | SORT_FLAG_CASE) ->values() ->all(); } /** * @return array{order_price: int, raw: array|null} */ public function fetchLiveOrderPrice(?string $readingMethod, ?string $apiUrl = null): array { $empty = ['order_price' => 0, 'raw' => null]; $readingMethod = trim((string) $readingMethod); if ($readingMethod === '') { return $empty; } try { if ($apiUrl !== null && trim($apiUrl) !== '') { $prices = Http::withoutVerifying()->timeout(12)->get($apiUrl)->json(); } else { $prices = $this->fetchFeedWithFailover(); } if (!is_array($prices)) { return $empty; } $row = $this->findFeedRow($prices, $readingMethod); if ($row === null) { return $empty; } $orderPrice = $this->resolveReferenceProviderTotal($row); return ['order_price' => $orderPrice, 'raw' => $row]; } catch (\Throwable $e) { Log::warning('Zaarbox live board price fetch failed', ['message' => $e->getMessage()]); return $empty; } } public function syncProductsFromApi(bool $forceRefresh = false): bool { if (!Product::hasStoredPriceColumns()) { return false; } $prices = $this->cachedPriceList($forceRefresh); if ($prices === null) { return false; } return $this->applyPriceFeedToProducts($prices); } /** * اعمال فید zaarbox روی محصولات متغیر (reading_method) + مس محاسباتی + bubble + مظنه. * * @param array> $prices */ public function applyPriceFeedToProducts(array $prices): bool { $config = $this->config; $mainProductId = $config->mainProductId(); $hasExtremeKeys = Setting::whereIn('key', ['up_price', 'down_price'])->count() === 2; $copper = null; $dollar = null; $products = Product::query()->whereNotNull('reading_method')->get(); $currentTime = now()->format('H:i:s'); foreach ($products as $product) { $RPrice = $this->findFeedRow($prices, (string) $product->reading_method); if ($RPrice === null) { continue; } $row = $this->normalizeFeedRow($RPrice); $parts = $this->resolveReferenceBaseProfit($row); if (($row['name'] ?? '') === 'TGJU فلز مس') { $copper = $parts['price'] + $parts['profit']; } if (($row['name'] ?? '') === 'TGJU دلار') { $dollar = $parts['price'] + $parts['profit']; } ProductPriceService::syncFromReference( $product, $parts['price'], $parts['profit'] ); $productPrice = (float) ProductPriceService::adjustedTotal( $parts['price'], $parts['profit'], ProductPriceService::offsetPercent($product) ); if ( $hasExtremeKeys && $mainProductId && (int) $product->id === (int) $mainProductId ) { $config->trackDailyPriceExtreme($productPrice); } if ((int) ($product->bubble ?? 0) === 1) { $liquidGoldPrice = app(ProductDisplayPriceService::class)->resolveAppBasePrice(); $p = Product::find($product->id); if ($p && $liquidGoldPrice > 0) { $show = app(ConfigService::class)->isProductWithinTradingHours($product); $p->amount = $row['price'] / $liquidGoldPrice; $p->show = $show; $p->save(); } } } if ($copper !== null && $dollar !== null) { $cp = (int) round(($copper / 1000000) * $dollar); $copperProducts = Product::where('metal_id', 3)->get(); foreach ($copperProducts as $copperProduct) { ProductPriceService::syncFromReference($copperProduct, $cp, 0); } Product::where('metal_id', 3)->update([ 'updated_at' => Carbon::now()->format('Y-m-d H:i:s'), ]); if ( $hasExtremeKeys && $mainProductId && Product::where('id', $mainProductId)->where('metal_id', 3)->exists() ) { $mainCopper = Product::find($mainProductId); $extremePrice = $mainCopper ? (float) ($mainCopper->price + ($mainCopper->price_profit ?? 0)) : (float) $cp; $config->trackDailyPriceExtreme($extremePrice); } } return true; } /** * جستجو در فید zaarbox — key / id / name (همان reading_method ادمین) * * @param array> $prices * @return array|null */ public function findFeedRow(array $prices, string $identifier): ?array { $identifier = trim($identifier); if ($identifier === '') { return null; } $collection = collect($prices); foreach (['key', 'id', 'name'] as $field) { $row = $collection->firstWhere($field, $identifier); if (!empty($row)) { return is_array($row) ? $row : (array) $row; } } return null; } /** @param array $row */ public function normalizeFeedRow(array $row): array { if (($row['name'] ?? '') === 'گلد دات ای از آبشده - رسمی - نقد فردا') { $row['price'] = ($row['price'] ?? 0) / 4.3318; } return $row; } /** * base/profit مرجع zaarbox — وقتی price صفر است provider قیمت نداده (profit مقدار قدیمی است). * * @param array $row * @return array{price: int, profit: int} */ public function resolveReferenceBaseProfit(array $row): array { $normalized = $this->normalizeFeedRow($row); $price = (int) round((float) ($normalized['price'] ?? 0)); if ($price <= 0) { return ['price' => 0, 'profit' => 0]; } return [ 'price' => $price, 'profit' => (int) round((float) ($normalized['profit'] ?? 0)), ]; } /** * @param array $row */ public function resolveReferenceProviderTotal(array $row): int { $parts = $this->resolveReferenceBaseProfit($row); return $parts['price'] + $parts['profit']; } /** * قیمت نمایشی محصول از یک ردیف فید + offset درصد — بدون نوشتن DB * * @param array $row */ public function computeAdjustedProductPrice(Product $product, array $row): int { $parts = $this->resolveReferenceBaseProfit($row); if ($parts['price'] <= 0) { return 0; } if (FormulaPriceService::isEnabled($product)) { return FormulaPriceService::calculateForProduct($product, [ 'price' => $parts['price'], 'active' => true, ]) ?? 0; } return ProductPriceService::adjustedTotal( $parts['price'], $parts['profit'], ProductPriceService::offsetPercent($product) ); } public function syncProductFromApi(Product $product): bool { if (!Product::hasStoredPriceColumns()) { return false; } if (!$product->reading_method) { return false; } $prices = $this->fetchPriceList(); if ($prices === null) { return false; } $RPrice = $this->findFeedRow($prices, (string) $product->reading_method); if ($RPrice === null) { return false; } $row = $this->normalizeFeedRow($RPrice); $parts = $this->resolveReferenceBaseProfit($row); ProductPriceService::syncFromReference( $product, $parts['price'], $parts['profit'] ); return true; } /** * @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)->withoutVerifying()->timeout(12)->withHeaders([ 'Referer' => 'https://tablo.montest.ir/', 'User-Agent' => 'Mozilla/5.0', ])->get($this->historyUrl($start, $now)); } }); $minRial = app(PriceSnapshotService::class)->minValidChartPriceRialForExternalFeed(); foreach (self::PERIODS as $key => $config) { $response = $responses[$key] ?? null; $start = $now->copy()->subHours($config['hours']); if (!$response instanceof Response || !$response->successful()) { $logContext = ['period' => $key]; if ($response instanceof Response) { $logContext['status'] = $response->status(); } elseif ($response instanceof \Throwable) { $logContext['message'] = $response->getMessage(); } Log::warning('Zaarbox price history fetch failed', $logContext); $prices[$key] = []; continue; } $history = $response->json('history') ?? []; $prices[$key] = $this->mapHistory( $history, $this->toMillis($start), $this->toMillis($now), $config['intervalMs'], $minRial ); } return $prices; } private function historyUrl(Carbon $start, Carbon $end): string { $base = rtrim($this->apiUrl(), '/'); if (str_ends_with($base, '/free')) { $base = substr($base, 0, -strlen('/free')); } return sprintf( '%s/history/%s?start=%s&end=%s&limit=1000000000', $base, $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, int $minRial): 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) { if ($points[$index]['price'] > $minRial) { $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; } } }