File: //home/marketing.cfbon.ru/public_html/app/Jobs/CreateSendTask.php
<?php
namespace App\Jobs;
use App\Enums\PushJobStatus;
use App\Enums\RecipientType;
use App\Models\Guest;
use App\Models\PushJob;
use Illuminate\Bus\Batch;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Bus;
use Throwable;
class CreateSendTask implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
protected array $pushData;
public function __construct(array $pushData)
{
$this->pushData = $pushData;
}
public function handle(): void
{
$batch = Bus::batch([])
->name("Push notifications for job #{$this->pushData['id']}")
->allowFailures()
->then(function (Batch $batch) {
PushJob::where('batch_id', $batch->id)->update(['status' => PushJobStatus::COMPLETED->value]);
})->catch(function (Batch $batch, Throwable $e) {
PushJob::where('batch_id', $batch->id)->update(['status' => PushJobStatus::FAILED->value]);
})->finally(function (Batch $batch) {
})->dispatch();
Guest::whereNotNull('push_token')
->select(['id', 'push_token'])
->when($this->pushData['recipient_type'] == RecipientType::SPECIFIC_USER->value, function ($query) {
$usersPhones = explode(';', $this->pushData['selected_users']);
$query->whereIn('phone', $usersPhones);
})
->chunkById(500, function ($users) use (&$batch) {
$tokensChunks = $users->pluck('push_token')->chunk(250);
$jobs = [];
foreach ($tokensChunks as $tokens) {
$jobs[] = new SendPushToNotificationJob([
'tokens' => $tokens->toArray(),
'title' => $this->pushData['title'],
'body' => $this->pushData['text'] ?? null,
'img' => $this->pushData['img'] ?? null,
]);
}
$batch->add($jobs);
});
PushJob::where('id', $this->pushData['id'])->update([
'batch_id' => $batch->id,
'status' => PushJobStatus::PROCESSING->value
]);
}
}