Files
boursecu_server/app/Services/CustomerAppNotifyService.php
T

103 lines
3.1 KiB
PHP
Raw Normal View History

2026-07-27 22:09:08 +03:30
<?php
namespace App\Services;
use App\Models\AppNotification;
use App\Models\AppNotificationRecipient;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
/**
* اعلان تراکنشی داخل اپ برای یک مشتری — همان مسیر SSE اعلان ادمین (بدون OTP).
*/
class CustomerAppNotifyService
{
public function __construct(
private readonly ConfigService $config,
private readonly PriceStreamService $stream,
) {
}
/**
* خرید / فروش / واریز / برداشت — فقط وقتی اعلان داخل اپ روشن است.
*/
public function notifyCustomer(
int $customerId,
string $title,
string $body,
string $severity = 'info'
): ?AppNotification {
if ($customerId <= 0) {
return null;
}
2026-07-28 21:01:42 +03:30
if (! $this->config->getBool('has_page_notification', true)) {
2026-07-27 22:09:08 +03:30
return null;
}
$title = mb_substr(trim($title), 0, 191);
$body = mb_substr(trim($body), 0, 5000);
if ($title === '' || $body === '') {
return null;
}
if (! in_array($severity, ['info', 'success', 'warning', 'danger'], true)) {
$severity = 'info';
}
try {
2026-07-28 21:57:29 +03:30
$payload = [
'title' => $title,
'body' => $body,
'severity' => $severity,
'is_active' => true,
'created_by' => null,
'audience_type' => AppNotificationAudienceService::TYPE_CUSTOMERS,
'segment_keys' => null,
'audience_label' => 'سیستمی — مشتری '.$customerId,
'recipients_count' => 1,
];
if (\Illuminate\Support\Facades\Schema::hasColumn('app_notifications', 'is_system')) {
$payload['is_system'] = true;
}
$row = DB::transaction(function () use ($customerId, $payload) {
$row = AppNotification::create($payload);
2026-07-27 22:09:08 +03:30
AppNotificationRecipient::query()->insert([
'notification_id' => $row->id,
'customer_id' => $customerId,
'created_at' => now(),
'updated_at' => now(),
]);
return $row;
});
$this->broadcastToCustomer($row, $customerId);
return $row;
} catch (\Throwable $e) {
Log::warning('CustomerAppNotify failed', [
'customer_id' => $customerId,
'error' => $e->getMessage(),
]);
return null;
}
}
private function broadcastToCustomer(AppNotification $row, int $customerId): void
{
$payload = [
'id' => $row->id,
'title' => $row->title,
'body' => $row->body,
'severity' => $row->severity,
'created_at' => optional($row->created_at)?->toIso8601String(),
];
$this->stream->publishForCustomer($customerId, 'app_notification', $payload);
}
}