-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathSendCertificateBatchJob.php
More file actions
88 lines (76 loc) · 2.97 KB
/
SendCertificateBatchJob.php
File metadata and controls
88 lines (76 loc) · 2.97 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
<?php
namespace App\Jobs;
use App\Excellence;
use App\Mail\NotifySuperOrganiser;
use App\Mail\NotifyWinner;
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\Cache;
use Illuminate\Support\Facades\Mail;
class SendCertificateBatchJob implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
public const BATCH_SIZE = 100;
public const CACHE_KEY_SEND_RUNNING = 'certificate_send_running_%s_%s';
public const CACHE_TTL = 86400;
public function __construct(
public int $edition,
public string $type,
public int $offset = 0
) {}
public function handle(): void
{
$runningKey = sprintf(self::CACHE_KEY_SEND_RUNNING, $this->edition, $this->type);
Cache::put($runningKey, time(), self::CACHE_TTL);
// Send to: all qualified recipients for this edition/type that are unsent or had send error.
// certificate_url may be null; email templates fall back to certificate pages where users generate themselves.
$query = Excellence::query()
->where('edition', $this->edition)
->where('type', $this->type)
->where(function ($q) {
$q->whereNull('notified_at')->orWhereNotNull('certificate_sent_error');
})
->with('user')
->orderBy('id');
$rows = $query->limit(self::BATCH_SIZE)->get();
foreach ($rows as $excellence) {
$user = $excellence->user;
if (! $user || ! $user->email) {
$excellence->update(['certificate_sent_error' => 'No user or email']);
continue;
}
try {
if ($this->type === 'SuperOrganiser') {
Mail::to($user->email)->queue(new NotifySuperOrganiser($user, $this->edition, $excellence->certificate_url));
} else {
Mail::to($user->email)->queue(new NotifyWinner($user, $this->edition, $excellence->certificate_url));
}
$excellence->update([
'notified_at' => Carbon::now(),
'certificate_sent_error' => null,
]);
} catch (\Throwable $e) {
$excellence->update([
'certificate_sent_error' => $e->getMessage(),
]);
}
}
$hasMore = Excellence::query()
->where('edition', $this->edition)
->where('type', $this->type)
->where(function ($q) {
$q->whereNull('notified_at')->orWhereNotNull('certificate_sent_error');
})
->limit(1)
->exists();
if ($hasMore) {
self::dispatch($this->edition, $this->type, 0);
} else {
Cache::forget($runningKey);
}
}
}