-
Notifications
You must be signed in to change notification settings - Fork 9
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. Weβll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[Feature] Ad hoc email command #12325
Open
petertgiles
wants to merge
9
commits into
main
Choose a base branch
from
11542-email-command
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
0087ba4
basic filtering
petertgiles fd70c76
fix json querying
petertgiles 48e30fd
extra validation
petertgiles c9b6086
new notification
petertgiles f26209c
template handling
petertgiles f5632f7
linting
petertgiles cbbaab7
fix function name typo
petertgiles 957001b
switch to InvalidArgumentException
petertgiles 57dafe8
use word queue in messages
petertgiles File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
148 changes: 148 additions & 0 deletions
148
api/app/Console/Commands/SendNotificationsAdHocEmail.php
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,148 @@ | ||
<?php | ||
|
||
namespace App\Console\Commands; | ||
|
||
use App\Enums\NotificationFamily; | ||
use App\Models\User; | ||
use App\Notifications\AdHocEmail; | ||
use Illuminate\Console\Command; | ||
use Illuminate\Contracts\Console\PromptsForMissingInput; | ||
use Illuminate\Database\Eloquent\Builder; | ||
use Illuminate\Database\Eloquent\Collection; | ||
|
||
class SendNotificationsAdHocEmail extends Command implements PromptsForMissingInput | ||
{ | ||
/** | ||
* The name and signature of the console command. | ||
* | ||
* @var string | ||
*/ | ||
protected $signature = 'send-notifications:ad-hoc-email | ||
{templateIdEn : The template ID for the English email message} | ||
{templateIdFr : The template ID for the French email message} | ||
{--emailAddress=* : The list of contact email addresses to send the notification to} | ||
{--notificationFamily=* : The list of notification families to send the notification to} | ||
{--notifyAllUsers : Send the notification to all users} | ||
'; | ||
|
||
/** | ||
* The console command description. | ||
* | ||
* @var string | ||
*/ | ||
protected $description = 'Send ad hoc email notifications from given GC Notify templates'; | ||
|
||
/** | ||
* Execute the console command. | ||
* | ||
* @return int | ||
*/ | ||
public function handle() | ||
{ | ||
$successCount = 0; | ||
$failureCount = 0; | ||
|
||
$users = $this->getUsersToSendNotificationTo(); | ||
$userCount = $users->count(); | ||
|
||
if ($this->confirm('Do you wish to send notifications to '.$userCount.' users?')) { | ||
$progressBar = $this->output->createProgressBar($userCount); | ||
$notification = new AdHocEmail($this->argument('templateIdEn'), $this->argument('templateIdFr')); | ||
|
||
$users->chunk(200, function (Collection $chunkOfUsers) use (&$successCount, &$failureCount, $progressBar, $notification) { | ||
/** @var \App\Models\User $user */ | ||
foreach ($chunkOfUsers as $user) { | ||
try { | ||
$user->notify($notification); | ||
$successCount++; | ||
} catch (\Throwable $e) { | ||
$this->error("Failed to queue notification for user $user->id: ".$e->getMessage()); | ||
$failureCount++; | ||
} finally { | ||
$progressBar->advance(); | ||
} | ||
} | ||
}); | ||
$this->newLine(); | ||
|
||
$this->info("Notifications queued. Success: $successCount Failure: $failureCount"); | ||
if ($failureCount > 0) { | ||
return Command::FAILURE; | ||
} else { | ||
return Command::SUCCESS; | ||
} | ||
} else { | ||
$this->info('Notification sending cancelled'); | ||
|
||
return Command::SUCCESS; | ||
} | ||
} | ||
|
||
private function getUsersToSendNotificationTo(): Builder | ||
{ | ||
$emailAddresses = $this->option('emailAddress'); | ||
$notificationFamilies = $this->option('notificationFamily'); | ||
$notifyAllUsers = $this->option('notifyAllUsers'); | ||
|
||
$options = $this->options(); | ||
|
||
// How many types of options were used? | ||
$optionTypesCount = | ||
(count($emailAddresses) > 0 ? 1 : 0) + | ||
(count($notificationFamilies) > 0 ? 1 : 0) + | ||
($notifyAllUsers ? 1 : 0); | ||
|
||
if ($optionTypesCount != 1) { | ||
throw new \InvalidArgumentException('Must filter users using exactly one of the option types'); | ||
} | ||
|
||
if (count($emailAddresses) > 0) { | ||
return $this->builderFromEmailAddresses($emailAddresses); | ||
} | ||
|
||
if (count($notificationFamilies) > 0) { | ||
return $this->builderFromNotificationFamilies($notificationFamilies); | ||
} | ||
|
||
if ($notifyAllUsers) { | ||
return User::query(); | ||
} | ||
|
||
throw new \InvalidArgumentException('Unexpected function end point for options: '.json_encode($options)); | ||
} | ||
|
||
private function builderFromEmailAddresses(array $requestedEmailAddresses): Builder | ||
{ | ||
$builder = User::whereIn('email', $requestedEmailAddresses); | ||
|
||
// Check for missing email addresses | ||
$dbEmailAddresses = $builder->pluck('email')->toArray(); | ||
$missingEmailAddresses = array_diff($requestedEmailAddresses, $dbEmailAddresses); | ||
if (count($missingEmailAddresses) > 0) { | ||
$this->alert('The following email addresses were not found:'); | ||
foreach ($missingEmailAddresses as $missingEmailAddress) { | ||
$this->warn($missingEmailAddress); | ||
} | ||
} | ||
|
||
return $builder; | ||
} | ||
|
||
private function builderFromNotificationFamilies(array $notificationFamilies): Builder | ||
{ | ||
// Check for bad notification families | ||
$allNotificationFamilies = array_column(NotificationFamily::cases(), 'name'); | ||
foreach ($notificationFamilies as $notificationFamily) { | ||
if (! in_array($notificationFamily, $allNotificationFamilies)) { | ||
throw new \InvalidArgumentException('Invalid notification family: '.$notificationFamily); | ||
} | ||
} | ||
|
||
$builder = User::whereJsonContains('enabled_email_notifications', $notificationFamilies[0]); | ||
for ($i = 1; $i < count($notificationFamilies); $i++) { | ||
$builder->orWhereJsonContains('enabled_email_notifications', $notificationFamilies[$i]); | ||
} | ||
|
||
return $builder; | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,56 @@ | ||
<?php | ||
|
||
namespace App\Notifications; | ||
|
||
use App\Enums\Language; | ||
use App\Models\User; | ||
use App\Notifications\Messages\GcNotifyEmailMessage; | ||
use Illuminate\Bus\Queueable; | ||
use Illuminate\Notifications\Notification; | ||
|
||
class AdHocEmail extends Notification implements CanBeSentViaGcNotifyEmail | ||
{ | ||
use Queueable; | ||
|
||
/** | ||
* Create a new notification instance. | ||
*/ | ||
public function __construct( | ||
public string $templateIdEn, | ||
public string $templateIdFr, | ||
) {} | ||
|
||
/** | ||
* Get the notification's delivery channels. | ||
* | ||
* @return array<int, string> | ||
*/ | ||
public function via(): array | ||
{ | ||
return [GcNotifyEmailChannel::class]; | ||
} | ||
|
||
/** | ||
* Get the GC Notify representation of the notification. | ||
*/ | ||
public function toGcNotifyEmail(User $notifiable): GcNotifyEmailMessage | ||
{ | ||
$locale = $this->locale ?? $notifiable->preferredLocale(); | ||
$templateId = match ($locale) { | ||
Language::EN->value => $this->templateIdEn, | ||
Language::FR->value => $this->templateIdFr, | ||
default => throw new \InvalidArgumentException("Unsupported locale: $locale"), | ||
}; | ||
|
||
$message = new GcNotifyEmailMessage( | ||
$templateId, | ||
$notifiable->email, | ||
[ | ||
'first_name' => $notifiable->first_name, | ||
'last_name' => $notifiable->last_name, | ||
] | ||
); | ||
|
||
return $message; | ||
} | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
oo.. progressbar!!!
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Trying out some of the new Laravel 11 features. π