Files
boursecu_server/app/Services/ZaarboxPriceService.php
T

596 lines
18 KiB
PHP

<?php
namespace App\Services;
use App\Models\Product;
use App\Models\Setting;
use Carbon\Carbon;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
class ZaarboxPriceService
{
public const CACHE_KEY = 'zaarbox_gold_prices';
/** کش فید تابلو — کران و list محصولات از همین استفاده می‌کنند */
public const PRICE_LIST_CACHE_KEY = 'zaarbox_price_list_feed';
private const CACHE_TTL_MINUTES = 35;
/** TTL کش فید — کران هر ۳۰ث refresh می‌کند؛ list فقط از همین می‌خواند */
private const PRICE_LIST_CACHE_SECONDS = 15;
private const DEFAULT_HISTORY_ID = 'ca3800a0-1f57-3528-b963-178f9168e04f';
private const PERIODS = [
'DAILY' => ['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<int, array{timestamp: int, value: int}>, WEEKLY: array, MONTHLY: array}
*/
public function getAllPrices(): array
{
if ($this->config->getBool('chart_use_local_data', false)) {
$local = app(PriceSnapshotService::class)->chartFromDatabase();
if (! empty($local['DAILY'])) {
return $local;
}
}
$cached = Cache::get($this->cacheKey());
if (is_array($cached) && isset($cached['prices'])) {
return $cached['prices'];
}
return $this->refreshCache();
}
/**
* @return array{DAILY: array<int, array{timestamp: int, value: int}>, 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<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->findFeedRow($prices, $identifier);
if ($row === null) {
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<int, array<string, mixed>>|null */
public function fetchPriceList(): ?array
{
try {
$prices = Http::withoutVerifying()
->timeout(20)
->get($this->apiUrl())
->json();
return is_array($prices) ? $prices : null;
} catch (\Throwable $e) {
Log::warning('Zaarbox price list fetch failed', ['message' => $e->getMessage()]);
return null;
}
}
/**
* فید تابلو با کش کوتاه — کران هر ۳۰ث refresh می‌کند؛ list در بازهٔ کش همان فید را مصرف می‌کند.
*
* @return array<int, array<string, mixed>>|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<int, array<string, mixed>> $prices */
public function storePriceListCache(array $prices): void
{
Cache::put(self::PRICE_LIST_CACHE_KEY, $prices, now()->addSeconds(self::PRICE_LIST_CACHE_SECONDS));
}
/**
* @return array<int, array{key: string, name: string, id: string, category: string, active: bool}>
*/
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),
];
})
->filter(fn (array $row) => $row['key'] !== '')
->sortBy('name', SORT_NATURAL | SORT_FLAG_CASE)
->values()
->all();
}
/**
* @return array{order_price: int, raw: array<string, mixed>|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 {
$url = $apiUrl ?: $this->apiUrl();
$prices = Http::withoutVerifying()->timeout(20)->get($url)->json();
if (!is_array($prices)) {
return $empty;
}
$row = $this->findFeedRow($prices, $readingMethod);
if ($row === null) {
return $empty;
}
$orderPrice = (int) round((float) ($row['price'] ?? 0) + (float) ($row['profit'] ?? 0));
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<int, array<string, mixed>> $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);
if (($row['name'] ?? '') === 'TGJU فلز مس') {
$copper = ($row['price'] ?? 0) + ($row['profit'] ?? 0);
}
if (($row['name'] ?? '') === 'TGJU دلار') {
$dollar = ($row['price'] ?? 0) + ($row['profit'] ?? 0);
}
ProductPriceService::syncFromReference(
$product,
(int) $row['price'],
(int) ($row['profit'] ?? 0)
);
$productPrice = (float) ProductPriceService::adjustedTotal(
(int) $row['price'],
(int) ($row['profit'] ?? 0),
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 = ($currentTime >= $product->auto_open_at && $currentTime <= $product->auto_close_at);
$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<int, array<string, mixed>> $prices
* @return array<string, mixed>|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;
}
/**
* قیمت نمایشی محصول از یک ردیف فید + offset درصد — بدون نوشتن DB
*
* @param array<string, mixed> $row
*/
public function computeAdjustedProductPrice(Product $product, array $row): int
{
$normalized = $this->normalizeFeedRow($row);
return ProductPriceService::adjustedTotal(
(int) ($normalized['price'] ?? 0),
(int) ($normalized['profit'] ?? 0),
ProductPriceService::offsetPercent($product)
);
}
/** @param array<string, mixed> $row */
public function normalizeFeedRow(array $row): array
{
if (($row['name'] ?? '') === 'گلد دات ای از آبشده - رسمی - نقد فردا') {
$row['price'] = ($row['price'] ?? 0) / 4.3318;
}
return $row;
}
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);
ProductPriceService::syncFromReference(
$product,
(int) $row['price'],
(int) ($row['profit'] ?? 0)
);
return true;
}
/**
* @return array{DAILY: array<int, array{timestamp: int, value: int}>, 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<int, array<string, mixed>> $history
* @return array<int, array{timestamp: int, value: int}>
*/
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;
}
}
}