Files
boursecu_server/app/Services/LivePriceTickService.php
2026-07-07 16:35:14 +03:30

100 lines
3.5 KiB
PHP
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<?php
namespace App\Services;
use App\Http\Controllers\Site\ReportController;
use App\Models\PriceSyncLog;
use App\Models\Product;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;
class LivePriceTickService
{
private const LOCK_SECONDS = 25;
public function tick(): ?PriceSyncLog
{
$lock = Cache::lock('prices:tick', self::LOCK_SECONDS);
if (! $lock->get()) {
return null;
}
$syncLog = null;
try {
$config = app(ConfigService::class);
$sync = app(ProductPriceSyncService::class);
$zaarbox = app(ZaarboxPriceService::class);
/*
| ۱. montzar / zaarbox زنده + کش ۱۵ثانیه‌ای /api/price/last
| (قبل از sync محصولات تا آبشدهٔ «قیمت اپ» تازه باشد)
*/
$request = Request::create('/api/price/last', 'GET', ['force_refresh' => '1']);
$result = app(ReportController::class)->lastPrice($request);
$payload = is_array($result)
? $result
: (json_decode($result->getContent(), true) ?: []);
if (! is_array($payload)) {
$payload = [];
}
/*
| ۲. فید zaarbox برای محصولات متغیر (reading_method)
*/
if ($zaarbox->isEnabled() || Product::query()->whereNotNull('reading_method')->exists()) {
try {
$zaarbox->cachedPriceList(true);
} catch (\Throwable $e) {
Log::warning('Zaarbox feed refresh in tick failed', ['message' => $e->getMessage()]);
}
}
/*
| ۳. همگام‌سازی قیمت محصولات
*/
if ($config->isStore()) {
$sync->syncStorePrices(true);
$source = 'zaarbox';
$sourceUrl = $zaarbox->apiUrl();
} else {
$sync->syncAll(true);
$source = $config->priceProvider() ?: 'legacy';
$sourceUrl = $source === 'zaarbox'
? $zaarbox->apiUrl()
: null;
}
$liquidGold = (int) ($payload['price'] ?? $config->getInt('montzar_live_price', 0));
if ($liquidGold <= 0) {
$liquidGold = app(ProductDisplayPriceService::class)->resolveHistoricalBasePrice();
}
$tickSource = (string) ($payload['price_source'] ?? $source);
if ($tickSource === '') {
$tickSource = $source;
}
$activeProducts = Product::query()
->where('active', 1)
->whereNotNull('reading_method')
->count();
$syncLog = app(PriceSyncLogService::class)->recordTick($tickSource, $sourceUrl, $liquidGold, $activeProducts);
app(LivePriceCacheService::class)->markTick();
// last از put داخل lastPrice؛ list بعد از sync محصولات
app(PriceBroadcastService::class)->broadcastListIfChanged();
// ارسال قیمت به کانال‌ها — مستقل از SSE؛ تشخیص تغییر قیمت + cooldown داخل سرویس است
app(PriceChannelBroadcastService::class)->broadcastIfEligible();
} finally {
$lock->release();
}
return $syncLog;
}
}