Files
boursecu_server/app/Services/SmsBilling/SmsAlertService.php
T

81 lines
2.1 KiB
PHP

<?php
namespace App\Services\SmsBilling;
use App\Models\Setting;
use App\Models\SmsWallet;
use App\Models\User;
class SmsAlertService
{
public const MAX_ALERT_DAYS = 3;
public function __construct(
private SmsWalletService $walletService,
) {
}
public function maybeSendLowBalanceAlerts(SmsWallet $wallet): void
{
if (! SmsWalletService::isBillingOperational()) {
return;
}
if ($wallet->balance > 0) {
return;
}
if ((int) $wallet->alert_days_sent >= self::MAX_ALERT_DAYS) {
return;
}
$today = now()->toDateString();
if ($wallet->last_alert_date && $wallet->last_alert_date->toDateString() === $today) {
return;
}
$appName = trim((string) Setting::where('key', 'name_fa')->value('value'));
if ($appName === '') {
$appName = 'این نسخه';
}
$message = "موجودی کیف پول پیامک {$appName} صفر یا منفی شده است. لطفاً کیف پول را شارژ کنید.";
if (! app(\App\Services\ConfigService::class)->isSmsNotifEnabled('sms_notif_wallet_alert')) {
return;
}
foreach ($this->alertRecipients() as $mobile) {
app(SmsGatewayService::class)->send($mobile, $message, 'wallet_alert', isAlert: true);
}
$wallet->refresh();
$wallet->alert_days_sent = (int) $wallet->alert_days_sent + 1;
$wallet->last_alert_date = $today;
$wallet->save();
}
/** @return list<string> */
private function alertRecipients(): array
{
$numbers = [SmsWalletService::SUPER_ADMIN_MOBILE];
$adminNumbers = User::query()
->where('send_sms', true)
->where('active', true)
->pluck('mobile')
->all();
foreach ($adminNumbers as $number) {
$normalized = trim((string) $number);
if ($normalized !== '') {
$numbers[] = $normalized;
}
}
return array_values(array_unique($numbers));
}
}