File: /var/www/quadcode/app/Jobs/ChangeBitrixStatusJob.php
<?php
namespace App\Jobs;
use App\Exceptions\JobException;
use App\Helpers\BitrixHelper;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;
class ChangeBitrixStatusJob implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
const LOG_CHANNEL = 'bitrixWebhookJob';
const STATUS_SUCCESS = 'success';
const STATUS_FAILURE = 'failure';
const STATUS_APOLOGY = 'apology';
private ?string $leadId;
private ?string $email;
private ?string $phone;
private string $statusId;
public function __construct(?string $leadId, ?string $email, ?string $phone, string $statusId)
{
$this->leadId = $leadId;
$this->email = $email;
$this->phone = $phone;
$this->statusId = $statusId;
}
public function handle(BitrixHelper $bitrixHelper)
{
$logData = [
'email' => $this->email,
'phone' => $this->phone,
'statusId' => $this->statusId,
'leads' => [],
];
$logger = Log::channel(self::LOG_CHANNEL);
if (empty($this->leadId)) {
$logger->info('Done lead Id is empty', $logData);
return;
}
if (empty($this->email) && empty($this->phone)) {
$error = 'Need email or phone';
$logger->error($error, $logData);
return;
}
if (!$bitrixHelper->check()) {
$error = 'Need to fill BITRIX24_HOST, BITRIX24_USER_ID or BITRIX24_TOKEN in .env';
$logger->error($error, $logData);
throw new JobException($error);
}
$filter = ['ENTITY_ID' => 'STATUS'];
$statusListData = $bitrixHelper->getStatusList($filter);
$hasStatus = false;
$notFinalStatuses = [];
foreach ($statusListData['result'] as $status) {
if ($status['STATUS_ID'] == $this->statusId) {
$hasStatus = true;
}
if (!in_array($status['EXTRA']['SEMANTICS'], [self::STATUS_SUCCESS, self::STATUS_FAILURE, self::STATUS_APOLOGY])) {
$notFinalStatuses[] = $status['STATUS_ID'];
}
}
if (!$hasStatus) {
$error = 'Bitrix status not found:' . $this->statusId;
$logger->error($error, $logData);
throw new JobException($error);
}
$leads = [];
if (!empty($this->email)) {
$filter = [
'EMAIL' => $this->email,
'STATUS_ID' => $notFinalStatuses,
'!ID' => $this->leadId,
];
$leads = array_merge($leads, $bitrixHelper->leadList($filter));
}
if (!empty($this->phone)) {
$filter = [
'PHONE' => $this->phone,
'STATUS_ID' => $notFinalStatuses,
'!ID' => $this->leadId,
];
$leads = array_merge($leads, $bitrixHelper->leadList($filter));
if ($this->phone[0] != '+') {
$filter = [
'PHONE' => '+' . $this->phone,
'STATUS_ID' => $notFinalStatuses,
'!ID' => $this->leadId,
];
$leads = array_merge($leads, $bitrixHelper->leadList($filter));
}
}
if (!empty($leads)) {
$logData['leads'] = array_unique(array_column($leads, 'ID'));
$response = $bitrixHelper->updateLeadStatus($this->leadId, ['STATUS_ID' => $this->statusId]);
$logData[$this->leadId] = $response['result'] ?? false;
}
$logger->info('Done', $logData);
}
}