HEX
Server: nginx/1.18.0
System: Linux test-ipsremont 5.4.0-214-generic #234-Ubuntu SMP Fri Mar 14 23:50:27 UTC 2025 x86_64
User: ips (1000)
PHP: 8.0.30
Disabled: pcntl_alarm,pcntl_fork,pcntl_waitpid,pcntl_wait,pcntl_wifexited,pcntl_wifstopped,pcntl_wifsignaled,pcntl_wifcontinued,pcntl_wexitstatus,pcntl_wtermsig,pcntl_wstopsig,pcntl_signal,pcntl_signal_get_handler,pcntl_signal_dispatch,pcntl_get_last_error,pcntl_strerror,pcntl_sigprocmask,pcntl_sigwaitinfo,pcntl_sigtimedwait,pcntl_exec,pcntl_getpriority,pcntl_setpriority,pcntl_async_signals,pcntl_unshare,
Upload Files
File: /var/www/heifetz/heifetz-app/jobs/SendMessageJob.php
<?php

declare(strict_types=1);

namespace Jobs;

use App\Exceptions\CrmException;
use Core\Models\Message;
use Core\Models\MessageService;
use Core\Models\User;
use Models\Notification;
use Models\Repositories\NotificationRepository;
use Models\TelegramMessageQueue;
use Models\ViberQueue;

class SendMessageJob extends AbstractJob
{

    const MESSAGE_TYPE_DEFAULT = 0;
    const MESSAGE_TYPE_EXTERNAL = 1;

    private ?int $factoryId;
    private bool $forKing = false;
    private Message $message;
    private int $authorId;
    private array $recipientsIds;

    public function setMessageData(MessageService $messageService, int $messageType = self::MESSAGE_TYPE_DEFAULT): self
    {
        $this->data = [
            'recipientsIds' => $messageService->recipientsIds,
            'messageText' => $messageService->message->getText(),
            'isImportant' => $messageService->message->isImportant(),
            'factoryId' => $messageService->factoryId,
            'authorId' => $messageService->authorId,
            'forKing' => $messageService->forKing,
            'messageType' => $messageType,
        ];

        return $this;
    }

    public function execute(): bool
    {
        $messageData = $this->data;

        $this->recipientsIds = $messageData['recipientsIds'];
        $this->message = Message::create($messageData['messageText'], $messageData['isImportant']);
        $this->factoryId = $messageData['factoryId'];
        $this->authorId = $messageData['authorId'];
        $this->forKing = $messageData['forKing'];

        if ($messageData['messageType'] == self::MESSAGE_TYPE_EXTERNAL) {
            $this->sendExternal();
        } else {
            $this->send();
        }

        return true;
    }

    private function sendExternalMessage(User $user): int|bool|array
    {
        $result = true;
        switch ($user->notification_service) {
            case NotificationRepository::NS_VIBER:
                if ($user->viberIsValid()) {
                    $result = ViberQueue::save($user->id, $this->message->getText(), $this->authorId);
                }
                break;
            case NotificationRepository::NS_TELEGRAM:
                if ($user->hasTelegram()) {
                    TelegramMessageQueue::save($user->telegram_id, $this->message->getText(), userId: $user->id, authorId: $this->authorId);
                }
                break;
            case NotificationRepository::NS_WHATSAPP:
                // Выключили потому что много денег тратиться и нужны шаблоны
                // if (isset($user->whats_app_phone) && Phone::whatsAppValidate($user->whats_app_phone)) {
                //     $result = WhatsAppQueue::save($user->whats_app_phone, $this->message->getText(), $this->authorId);
                // }
                break;
            case NotificationRepository::NS_NONE:
            default:
                // Выключили потому что много денег тратиться
                //if (SmsProfiModule::isActive()) {
                //    $sendId = Mailing::addSms('Внешнее сообщение', Mailing::TYPE_OTHER, json_encode(['userId' => $userId]), $this->message->toSms(), 0, 0, 0, 1);
                //    $phones = Phone::getUserPhonesList($userId);
                //
                //    foreach ($phones as $phone) {
                //        $result = Sms::save(
                //            [
                //                'send_id' => $sendId,
                //                'unit_id' => 0,
                //                'message' => $this->message->toSms(),
                //                'status' => AbstractMessageQueue::STATUS_NEW,
                //                'send_after' => date('Y-m-d H:i:s'),
                //                'phone' => $phone,
                //                'company_id' => CoreHelper::$companyId,
                //            ]
                //        );
                //    }
                //}
                break;
        }

        return $result;
    }

    private function send(): void
    {
        foreach ($this->recipientsIds as $userId) {
            $user = User::findOne($userId, withSystemRoles: true);
            if (empty($user)) {
                throw new CrmException('Пользователь с ID: ' . $userId . ' не существует');
            }

            if ($user->is_king && !$this->forKing) {
                continue;
            }

            Notification::add($userId, $this->message->toNotify(), $this->factoryId, $this->message->isImportant(), $this->authorId, $this->forKing);

            if (!$this->message->isImportant()) {
                continue;
            }

            $this->sendExternalMessage($user);
        }
    }

    private function sendExternal(): void
    {
        foreach ($this->recipientsIds as $userId) {
            $user = User::findOne($userId, withSystemRoles: true);
            if (empty($user)) {
                throw new CrmException('Пользователь с ID: ' . $userId . ' не существует');
            }

            $result = $this->sendExternalMessage($user);
            if (!$result) {
                return;
            }
        }

    }

}