Files
boursecu_server/app/Services/PriceSyncLogService.php
T

76 lines
2.4 KiB
PHP

<?php
namespace App\Services;
use App\Models\PriceSyncLog;
use App\Models\PriceSyncLogItem;
use Illuminate\Support\Facades\Schema;
class PriceSyncLogService
{
public function isAvailable(): bool
{
return Schema::hasTable('price_sync_logs') && Schema::hasTable('price_sync_log_items');
}
/**
* @param array<int, array<string, mixed>> $items
*/
public function record(string $source, ?string $sourceUrl, int $liquidGoldPrice, array $items): ?PriceSyncLog
{
if (! $this->isAvailable() || $items === []) {
return null;
}
$changedItems = array_values(array_filter(
$items,
static fn (array $item) => (bool) ($item['changed'] ?? false)
));
if ($changedItems === []) {
return null;
}
$log = PriceSyncLog::create([
'source' => $source,
'source_url' => $sourceUrl,
'liquid_gold_price' => $liquidGoldPrice,
'products_updated' => count($changedItems),
'created_at' => now(),
]);
foreach ($changedItems as $item) {
PriceSyncLogItem::create([
'log_id' => $log->id,
'product_id' => $item['product_id'] ?? null,
'product_title' => $item['product_title'] ?? null,
'reading_method' => $item['reading_method'] ?? null,
'source_name' => $item['source_name'] ?? null,
'base_price' => (int) ($item['base_price'] ?? 0),
'base_profit' => (int) ($item['base_profit'] ?? 0),
'offset_percent' => (float) ($item['offset_percent'] ?? 0),
'stored_price' => (int) ($item['new_price'] ?? 0),
'previous_price' => (int) ($item['old_price'] ?? 0),
]);
}
return $log->load('items');
}
/** هر تیک کران — حتی بدون تغییر قیمت محصول */
public function recordTick(string $source, ?string $sourceUrl, int $liquidGoldPrice, int $productsSynced): ?PriceSyncLog
{
if (! $this->isAvailable()) {
return null;
}
return PriceSyncLog::create([
'source' => $source,
'source_url' => $sourceUrl,
'liquid_gold_price' => $liquidGoldPrice,
'products_updated' => $productsSynced,
'created_at' => now(),
]);
}
}