File: /var/www/quadcode-site/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 $statusId;
public function __construct(string $leadId, string $email, string $statusId)
{
$this->leadId = $leadId;
$this->email = $email;
$this->statusId = $statusId;
}
public function handle(BitrixHelper $bitrixHelper): void
{
$logData = [
'email' => $this->email,
'statusId' => $this->statusId,
'leads' => [],
];
$logger = Log::channel(self::LOG_CHANNEL);
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);
}
$filter = [
'EMAIL' => $this->email,
'STATUS_ID' => $notFinalStatuses,
'!ID' => $this->leadId,
];
$leads = $bitrixHelper->leadList($filter);
if (!empty($leads)) {
$logData['leads'] = array_column($leads, 'ID');
$response = $bitrixHelper->updateLeadStatus($this->leadId, ['STATUS_ID' => $this->statusId]);
$logData[$this->leadId] = $response['result'] ?? false;
}
$logger->info('Done', $logData);
}
}