fix some bugs
This commit is contained in:
@@ -0,0 +1,97 @@
|
||||
<?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;
|
||||
}
|
||||
|
||||
if (! $this->config->getBool('has_page_notification', false)) {
|
||||
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 {
|
||||
$row = DB::transaction(function () use ($customerId, $title, $body, $severity) {
|
||||
$row = AppNotification::create([
|
||||
'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,
|
||||
]);
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user