Files
boursecu_server/app/Services/PriceChannelBroadcastService.php
T
2026-07-07 18:21:36 +03:30

463 lines
17 KiB
PHP

<?php
namespace App\Services;
use App\Http\Controllers\Controller;
use App\Models\Product;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
/**
* ارسال قیمت لحظه‌ای به کانال‌های پیام‌رسان (بله، تلگرام، روبیکا).
*
* اصول (طبق rule ساعت کاری):
* • هیچ تنظیمی را بازنویسی نمی‌کند — فقط می‌خواند.
* • فقط پیام‌رسان‌هایی که ادمین انتخاب کرده و توکن + مقصد دارند ارسال می‌شود.
* • قیمت هر محصول از قیمت پایه ذخیره‌شده + کارمزد نمایش همان اپ ساخته می‌شود.
*/
class PriceChannelBroadcastService
{
private const COOLDOWN_CACHE_KEY = 'price_channel:last_sent_at';
private const SIGNATURE_CACHE_KEY = 'price_channel:last_signature';
private const SUPPORTED_MESSENGERS = ['bale', 'telegram', 'rubika'];
/** مثقال بازار آبشده (گرم) — وقتی تنظیم change_mesghal خالی باشد */
private const DEFAULT_CHANGE_MESGHAL = 4.3318;
public function __construct(private readonly ConfigService $config)
{
}
/**
* نقطه‌ی ورود — بعد از تغییر قیمت صدا زده می‌شود.
* فقط وقتی قابلیت روشن است، پیام‌رسانی انتخاب شده و فاصله‌ی مجاز گذشته باشد ارسال می‌کند.
*/
public function broadcastIfEligible(): void
{
try {
if (! $this->config->getBool('price_channel_enabled', false)) {
return;
}
$targets = $this->resolveActiveTargets();
if ($targets === []) {
Log::debug('PriceChannel: enabled ولی هیچ مقصد فعالی نیست (توکن/مقصد را چک کن)');
return;
}
// شرط ۱ (ارزان): از آخرین «ارسال واقعی» حداقل price_channel_min_seconds گذشته باشد.
// چون فقط روی ارسال واقعی markSent می‌کنیم، یک بررسیِ بی‌ارسال تایمر را ریست نمی‌کند
// و ارسالِ بعدی را عقب نمی‌اندازد.
if (! $this->cooldownElapsed()) {
return;
}
$products = $this->eligibleProducts();
if ($products === []) {
Log::debug('PriceChannel: محصول واجد شرایطی نیست (active/قیمت/ساعت کاری)');
return;
}
// شرط ۲: قیمت نسبت به آخرین ارسال واقعاً تغییر کرده باشد؛ وگرنه چیزی نفرست
// و تایمر را هم دست نزن (تا سرِ اولین تغییرِ بعدی بلافاصله بفرستد).
$signature = $this->priceSignature($products);
if ($signature === Cache::get(self::SIGNATURE_CACHE_KEY)) {
return;
}
$message = $this->buildMessage($products);
if ($message === '') {
return;
}
$results = [];
foreach ($targets as $messenger => $target) {
$results[$messenger] = $this->dispatchToMessenger($messenger, $target['token'], $target['chat_ids'], $message);
}
// فقط بعد از ارسال واقعی: تایمر cooldown و امضای قیمت به‌روزرسانی می‌شوند
$this->markSent();
Cache::put(self::SIGNATURE_CACHE_KEY, $signature, now()->addDay());
Log::info('PriceChannel: قیمت به کانال ارسال شد', [
'targets' => array_keys($targets),
'products' => count($products),
'results' => $results,
]);
} catch (\Throwable $e) {
Log::warning('PriceChannelBroadcast failed', ['message' => $e->getMessage()]);
}
}
/** امضای قیمت محصولات واجد شرایط — برای تشخیص تغییر قیمت */
private function priceSignature(array $products): string
{
$parts = [];
foreach ($products as $product) {
$parts[] = $product->id . ':' . (int) ($product->price ?? 0)
. ':' . ((int) ($product->open_buy)) . ((int) ($product->open_sell));
}
return md5(implode('|', $parts));
}
/**
* ارسال دستی (عیب‌یابی) — cooldown و شرط تغییر قیمت را نادیده می‌گیرد.
* وضعیت روشن/خاموش، انتخاب پیام‌رسان، توکن و مقصد همچنان لازم است.
*
* @return array<string, mixed>
*/
public function forceSend(): array
{
$message = $this->buildMessage();
$targets = $this->resolveActiveTargets();
$results = [];
foreach ($targets as $messenger => $target) {
$results[$messenger] = $message === ''
? ['skipped' => 'پیام خالی است (محصول واجد شرایط نیست)']
: $this->dispatchToMessenger($messenger, $target['token'], $target['chat_ids'], $message);
}
if ($message !== '' && $targets !== []) {
$this->markSent();
$products = $this->eligibleProducts();
if ($products !== []) {
Cache::put(self::SIGNATURE_CACHE_KEY, $this->priceSignature($products), now()->addDay());
}
}
return [
'sent' => $message !== '' && $targets !== [],
'results' => $results,
];
}
/**
* گزارش وضعیت — چرا ارسال می‌شود یا نمی‌شود.
*
* @return array<string, mixed>
*/
public function diagnose(): array
{
$selected = $this->selectedMessengers();
$messengers = [];
foreach (self::SUPPORTED_MESSENGERS as $messenger) {
$token = trim((string) $this->config->getString($this->tokenKey($messenger), ''));
$chatIds = $this->parseList($this->config->getString($this->chatIdsKey($messenger), ''));
$isSelected = in_array($messenger, $selected, true);
$messengers[$messenger] = [
'selected' => $isSelected,
'has_token' => $token !== '',
'destinations' => $chatIds,
'will_send' => $isSelected && $token !== '' && $chatIds !== [],
];
}
$message = $this->buildMessage();
return [
'enabled' => $this->config->getBool('price_channel_enabled', false),
'selected_messengers' => $selected,
'min_seconds' => $this->config->getInt('price_channel_min_seconds', 120),
'cooldown_elapsed' => $this->cooldownElapsed(),
'eligible_products' => count($this->eligibleProducts()),
'messengers' => $messengers,
'active_targets' => array_keys($this->resolveActiveTargets()),
'message_preview' => $message,
];
}
/**
* پیام‌رسان‌های قابل ارسال: انتخاب‌شده + توکن معتبر + حداقل یک مقصد.
*
* @return array<string, array{token: string, chat_ids: array<int, string>}>
*/
private function resolveActiveTargets(): array
{
$selected = $this->selectedMessengers();
if ($selected === []) {
return [];
}
$targets = [];
foreach ($selected as $messenger) {
$token = trim((string) $this->config->getString($this->tokenKey($messenger), ''));
$chatIds = $this->parseList($this->config->getString($this->chatIdsKey($messenger), ''));
if ($token === '' || $chatIds === []) {
continue;
}
$targets[$messenger] = ['token' => $token, 'chat_ids' => $chatIds];
}
return $targets;
}
/** @return array<int, string> */
private function selectedMessengers(): array
{
$raw = $this->parseList($this->config->getString('price_channel_messengers', ''));
return array_values(array_filter(
array_map(static fn ($m) => strtolower(trim($m)), $raw),
static fn ($m) => in_array($m, self::SUPPORTED_MESSENGERS, true)
));
}
private function tokenKey(string $messenger): string
{
return match ($messenger) {
'bale' => 'bale_bot_token',
'telegram' => 'telegram_bot_token',
'rubika' => 'rubika_bot_token',
default => '',
};
}
private function chatIdsKey(string $messenger): string
{
return "price_channel_{$messenger}_to";
}
/**
* ساخت متن پیام قیمت — مرتب و بر اساس داده‌ی هر محصول.
*/
public function buildMessage(?array $products = null): string
{
$products = $products ?? $this->eligibleProducts();
if ($products === []) {
return '';
}
$channelDiff = (float) $this->config->getInt('price_channel_diff', 0);
$diffBuy = (float) $this->config->displayBuyPriceDiffRial();
$diffSell = (float) $this->config->displaySellPriceDiffRial();
$mesghal = $this->changeMesghal();
$lines = [];
$lines[] = $this->header();
$lines[] = '';
foreach ($products as $product) {
$base = (float) ($product->price ?? 0);
// 🔴 خرید (مشتری می‌فروشد، پایین‌تر) — 🟢 فروش (مشتری می‌خرد، بالاتر)
$low = $base - $diffSell - $channelDiff;
$high = $base + $diffBuy + $channelDiff;
$lines[] = '🛒 ' . trim((string) $product->title);
$lines[] = '🔴 خرید ' . $this->formatPrice($low) . ' 🟢 فروش ' . $this->formatPrice($high);
if ($this->isGramUnit($product) && $mesghal > 0) {
$lines[] = '💰 هر گرم: ' . $this->formatPrice($low / $mesghal)
. ' / ' . $this->formatPrice($high / $mesghal);
}
$lines[] = '';
}
$footer = $this->footerLines();
if ($footer !== []) {
$lines[] = '➖➖➖➖➖➖';
foreach ($footer as $line) {
$lines[] = $line;
}
}
return trim(implode("\n", $lines));
}
private function header(): string
{
$name = trim((string) $this->config->getString('name_fa', ''));
$time = now()->format('H:i');
$title = $name !== '' ? "📊 قیمت لحظه‌ای {$name}" : '📊 قیمت لحظه‌ای';
return $title . "\n🕐 ساعت " . $time;
}
/**
* @return array<int, Product>
*/
private function eligibleProducts(): array
{
$products = Product::query()
->where('active', 1)
->orderBy('id')
->get();
// قیمت زنده را روی مدل‌ها می‌گذارد (بدون UPDATE دیتابیس) تا پیام و تشخیص تغییر
// مستقل از cron/tick و همیشه تازه باشد.
try {
$display = app(ProductDisplayPriceService::class);
$display->warmLivePriceCache();
$display->enrichForApi($products);
} catch (\Throwable $e) {
Log::debug('PriceChannel enrich live price failed', ['message' => $e->getMessage()]);
}
$eligible = [];
foreach ($products as $product) {
if ((int) ($product->price ?? 0) <= 0) {
continue;
}
if (! ($product->open_buy || $product->open_sell)) {
continue;
}
if (! $this->config->isProductWithinTradingHours($product)) {
continue;
}
$eligible[] = $product;
}
return $eligible;
}
private function isGramUnit(Product $product): bool
{
return trim((string) ($product->unit ?? '')) === 'گرم';
}
/** قیمت را به واحد نمایش (تقسیم بر ۱۰٬۰۰۰) با جداکننده‌ی هزارگان می‌برد */
private function formatPrice(float $value): string
{
return number_format(max(0, $value) / 10000, 0);
}
private function changeMesghal(): float
{
$fromConfig = $this->config->get('change_mesghal');
$value = (float) ($fromConfig ?: config('change_mesghal', self::DEFAULT_CHANGE_MESGHAL));
return $value > 0 ? $value : self::DEFAULT_CHANGE_MESGHAL;
}
/**
* خطوط پایانی — فقط مقادیر پرشده نمایش داده می‌شوند (آیدی چنل، شماره، لینک).
*
* @return array<int, string>
*/
private function footerLines(): array
{
$lines = [];
foreach (['price_channel_footer_id', 'price_channel_footer_phone', 'price_channel_footer_link'] as $key) {
$value = trim((string) $this->config->getString($key, ''));
if ($value !== '') {
$lines[] = $value;
}
}
return $lines;
}
/**
* @param array<int, string> $chatIds
* @return array<string, string> chatId => نتیجه (ok / خطا)
*/
private function dispatchToMessenger(string $messenger, string $token, array $chatIds, string $message): array
{
$results = [];
foreach ($chatIds as $chatId) {
try {
$response = match ($messenger) {
'bale' => $this->sendBale($token, $chatId, $message),
'telegram' => $this->sendTelegram($token, $chatId, $message),
'rubika' => $this->sendRubika($token, $chatId, $message),
default => null,
};
$status = $response?->status() ?? 0;
$ok = $response?->successful() ?? false;
$results[$chatId] = $ok ? "ok ({$status})" : "failed ({$status}): " . trim((string) $response?->body());
if (! $ok) {
Log::warning("PriceChannel {$messenger} send not ok", [
'chat_id' => $chatId,
'status' => $status,
'body' => $response?->body(),
]);
}
} catch (\Throwable $e) {
$results[$chatId] = 'exception: ' . $e->getMessage();
Log::warning("PriceChannel {$messenger} send failed", [
'chat_id' => $chatId,
'message' => $e->getMessage(),
]);
}
}
return $results;
}
private function sendBale(string $token, string $chatId, string $message): \Illuminate\Http\Client\Response
{
return Http::withOptions(Controller::httpClientOptions())
->withoutVerifying()
->timeout(6)
->post("https://tapi.bale.ai/bot{$token}/sendMessage", [
'chat_id' => $chatId,
'text' => $message,
]);
}
private function sendTelegram(string $token, string $chatId, string $message): \Illuminate\Http\Client\Response
{
return Http::withOptions(Controller::httpClientOptions())
->timeout(6)
->post("https://api.telegram.org/bot{$token}/sendMessage", [
'chat_id' => $chatId,
'text' => $message,
]);
}
private function sendRubika(string $token, string $chatId, string $message): \Illuminate\Http\Client\Response
{
return Http::withOptions(Controller::httpClientOptions())
->withoutVerifying()
->timeout(6)
->post("https://botapi.rubika.ir/v3/{$token}/sendMessage", [
'chat_id' => $chatId,
'text' => $message,
]);
}
/** حداقل فاصله‌ی مجاز بین دو ارسال — جلوگیری از سیل پیام در هر تیک ۱۰ثانیه‌ای */
private function cooldownElapsed(): bool
{
$minSeconds = max(0, $this->config->getInt('price_channel_min_seconds', 120));
if ($minSeconds === 0) {
return true;
}
$lastSent = Cache::get(self::COOLDOWN_CACHE_KEY);
if ($lastSent === null) {
return true;
}
return now()->timestamp - (int) $lastSent >= $minSeconds;
}
private function markSent(): void
{
Cache::put(self::COOLDOWN_CACHE_KEY, now()->timestamp, now()->addDay());
}
/** @return array<int, string> */
private function parseList(string $raw): array
{
$parts = preg_split('/[,\n]+/', trim($raw)) ?: [];
return array_values(array_filter(array_map('trim', $parts), static fn ($p) => $p !== ''));
}
}