| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108 |
- <?php
- namespace App\Jobs;
- use App\Enums\PushNotificationTargetEnum;
- use App\Models\Provider;
- use App\Models\Schedule;
- use App\Models\User;
- use App\Services\CustomScheduleService;
- use Carbon\Carbon;
- 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 NotifyProvidersOfNewOpportunityJob implements ShouldQueue
- {
- use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
- public int $tries = 3;
- public int $timeout = 60;
- public array $backoff = [10, 60, 300];
- /**
- * @param int[] $scheduleIds
- */
- public function __construct(public readonly array $scheduleIds) {}
- public function handle(CustomScheduleService $customScheduleService): void
- {
- $scheduleId = $this->scheduleIds[0] ?? null;
- if (! $scheduleId) {
- return;
- }
- $schedule = Schedule::with(['customSchedule', 'address'])->find($scheduleId);
- if (! $this->shouldNotify($schedule)) {
- return;
- }
- $providerIds = $customScheduleService->getAvailableProvidersForOpportunity($schedule);
- if ($providerIds->isEmpty()) {
- Log::info('Nenhum prestador disponivel para a nova oportunidade', [
- 'schedule_id' => $schedule->id,
- ]);
- return;
- }
- $userIds = User::query()
- ->whereIn('id', Provider::whereIn('id', $providerIds)->pluck('user_id'))
- ->where('push_notifications_enabled', true)
- ->whereHas('deviceTokens', function ($query) {
- $query->where('app_type', PushNotificationTargetEnum::PRESTADOR->value)
- ->where('active', true);
- })
- ->pluck('id');
- if ($userIds->isEmpty()) {
- return;
- }
- $district = $schedule->address?->district;
- $dateLabel = Carbon::parse($schedule->date)->format('d/m');
- $quantity = count($this->scheduleIds);
- $userIds->chunk(50)->each(function ($chunk) use ($schedule, $district, $dateLabel, $quantity) {
- foreach ($chunk as $userId) {
- SendOpportunityPushJob::dispatch(
- $userId,
- $schedule->id,
- $district,
- $dateLabel,
- $quantity,
- );
- }
- });
- }
- public function failed(\Throwable $exception): void
- {
- Log::error('Falha ao notificar prestadores de nova oportunidade', [
- 'schedule_ids' => $this->scheduleIds,
- 'error' => $exception->getMessage(),
- ]);
- }
- private function shouldNotify(?Schedule $schedule): bool
- {
- if (! $schedule || ! $schedule->customSchedule) {
- return false;
- }
- if ($schedule->schedule_type !== 'custom' || $schedule->status !== 'pending') {
- return false;
- }
- if ($schedule->provider_id !== null) {
- return false;
- }
- return ! Carbon::parse($schedule->date)->lt(today());
- }
- }
|