98 lines
3.3 KiB
PHP
98 lines
3.3 KiB
PHP
<?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();
|
||
}
|
||
|
||
$activeProducts = Product::query()
|
||
->where('active', 1)
|
||
->whereNotNull('reading_method')
|
||
->count();
|
||
|
||
$syncLog = app(PriceSyncLogService::class)->recordTick($source, $sourceUrl, $liquidGold, $activeProducts);
|
||
|
||
if ($payload !== []) {
|
||
app(PriceSnapshotService::class)->recordTick($payload);
|
||
}
|
||
|
||
app(LivePriceCacheService::class)->markTick();
|
||
|
||
$broadcastPayload = $payload;
|
||
dispatch(function () use ($broadcastPayload) {
|
||
app(PriceBroadcastService::class)->broadcastAfterPriceUpdate($broadcastPayload);
|
||
})->afterResponse();
|
||
} finally {
|
||
$lock->release();
|
||
}
|
||
|
||
return $syncLog;
|
||
}
|
||
}
|