Skip to content

A free open source IT asset/license management system

WIP: First pass at mail

Marcus Moore0f54a26f6e9b
diff --git a/app/Console/Commands/RegenerateAcceptances.php b/app/Console/Commands/RegenerateAcceptances.php
index 21cf808a74..7ff6f18dd6 100644
--- a/app/Console/Commands/RegenerateAcceptances.php
+++ b/app/Console/Commands/RegenerateAcceptances.php
@@ -3,6 +3,7 @@
namespace App\Console\Commands;
use App\Actions\Acceptances\CreateCheckoutAcceptanceAction;
+use App\Mail\AcceptanceReRequestMail;
use App\Models\Accessory;
use App\Models\AccessoryCheckout;
use App\Models\Asset;
@@ -16,6 +17,7 @@ use Illuminate\Console\Command;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection as EloquentCollection;
use Illuminate\Database\Eloquent\Model;
+use Illuminate\Support\Facades\Mail;
/**
* Re-requests EULA acceptance from users who currently hold items.
@@ -30,7 +32,8 @@ class RegenerateAcceptances extends Command
{--category=* : Limit to these category ids (default: all categories requiring acceptance)}
{--company=* : Limit to these company ids (default: all companies)}
{--dry-run : Print the report; create nothing}
- {--exclude-declined : Skip users whose latest response was a decline (default: re-ask them)}';
+ {--exclude-declined : Skip users whose latest response was a decline (default: re-ask them)}
+ {--notify : Also email each affected user}';
protected $description = 'Re-request EULA acceptance from users who currently hold items';
@@ -64,6 +67,24 @@ class RegenerateAcceptances extends Command
private bool $dryRun = false;
+ private bool $notify = false;
+
+ /**
+ * The holders this run created rows for, keyed by user id, each with how many rows
+ * they got. Keying by holder is what keeps a holder re-requested for three items to
+ * one email rather than three.
+ *
+ * @var array<int, array{user: User, count: int}>
+ */
+ private array $holdersToNotify = [];
+
+ /**
+ * Holders who got rows but could not be emailed, as ID/name table rows.
+ *
+ * @var array<int, array{0: int, 1: string}>
+ */
+ private array $holdersWithoutEmail = [];
+
/**
* The rows this run re-requested, in the order the builders found them. Under
* --dry-run they are the rows it would have created.
@@ -89,12 +110,15 @@ class RegenerateAcceptances extends Command
private int $created = 0;
+ private int $notified = 0;
+
public function handle(): int
{
$this->categoryIds = $this->option('category');
$this->companyIds = $this->option('company');
$this->excludeDeclined = (bool) $this->option('exclude-declined');
$this->dryRun = (bool) $this->option('dry-run');
+ $this->notify = (bool) $this->option('notify');
$this->findAssetCandidates();
$this->findLicenseSeatCandidates();
@@ -102,6 +126,8 @@ class RegenerateAcceptances extends Command
$this->findConsumableCandidates();
$this->findComponentCandidates();
+ $this->notifyHolders();
+
return $this->printReport();
}
@@ -408,6 +434,43 @@ class RegenerateAcceptances extends Command
);
$this->created++;
+
+ $holder = $pair['user'];
+ $this->holdersToNotify[$holder->id] = [
+ 'user' => $holder,
+ 'count' => ($this->holdersToNotify[$holder->id]['count'] ?? 0) + 1,
+ ];
+ }
+
+ /**
+ * Emails the holders this run created rows for, when --notify was passed.
+ *
+ * One message per holder, never one per row: a holder re-requested for three items
+ * is asked once, for three items. A holder with no email address still keeps their
+ * rows — they will see them on /account/accept at their next login, just without the
+ * nudge — and is reported instead.
+ */
+ private function notifyHolders(): void
+ {
+ if (! $this->notify) {
+ return;
+ }
+
+ foreach ($this->holdersToNotify as $holder) {
+ $user = $holder['user'];
+
+ if (! $user->email) {
+ $this->holdersWithoutEmail[] = [$user->id, $user->present()->fullName];
+
+ continue;
+ }
+
+ $mail = new AcceptanceReRequestMail($user, $holder['count']);
+
+ Mail::to($user->email)->send($user->locale ? $mail->locale($user->locale) : $mail);
+
+ $this->notified++;
+ }
}
/**
@@ -518,6 +581,15 @@ class RegenerateAcceptances extends Command
$this->info($this->dryRun ? 'Nothing was created.' : 'Created: '.$this->created.'.');
+ if ($this->notify) {
+ $this->info('Notified: '.$this->notified.'.');
+
+ if ($this->holdersWithoutEmail !== []) {
+ $this->info('The following users do not have an email address:');
+ $this->table(['ID', 'Name'], $this->holdersWithoutEmail);
+ }
+ }
+
return 0;
}
diff --git a/app/Mail/AcceptanceReRequestMail.php b/app/Mail/AcceptanceReRequestMail.php
new file mode 100644
index 0000000000..cde41f3d80
--- /dev/null
+++ b/app/Mail/AcceptanceReRequestMail.php
@@ -0,0 +1,64 @@
+<?php
+
+namespace App\Mail;
+
+use App\Models\User;
+use Illuminate\Bus\Queueable;
+use Illuminate\Mail\Mailables\Address;
+use Illuminate\Mail\Mailables\Attachment;
+use Illuminate\Mail\Mailables\Content;
+use Illuminate\Mail\Mailables\Envelope;
+use Illuminate\Queue\SerializesModels;
+
+/**
+ * Asks a holder to accept the terms again for items they already hold.
+ *
+ * Deliberately not the unaccepted-items reminder: a holder who accepted a year ago
+ * and is being asked again reads "Reminder: You have Unaccepted Items" as a bug, so
+ * this is framed as a fresh request rather than a nudge about something they ignored.
+ */
+class AcceptanceReRequestMail extends BaseMailable
+{
+ use Queueable, SerializesModels;
+
+ public function __construct(
+ public readonly User $holder,
+ public readonly int $itemCount,
+ ) {}
+
+ /**
+ * Get the message envelope.
+ */
+ public function envelope(): Envelope
+ {
+ return new Envelope(
+ from: new Address(config('mail.from.address'), config('mail.from.name')),
+ subject: trans('mail.acceptance_re_request'),
+ );
+ }
+
+ /**
+ * Get the message content definition.
+ */
+ public function content(): Content
+ {
+ return new Content(
+ markdown: 'notifications.markdown.acceptance-re-request',
+ with: [
+ 'assigned_to' => $this->holder->present()->fullName,
+ 'count' => $this->itemCount,
+ 'accept_url' => route('account.accept'),
+ ],
+ );
+ }
+
+ /**
+ * Get the attachments for the message.
+ *
+ * @return array<int, Attachment>
+ */
+ public function attachments(): array
+ {
+ return [];
+ }
+}
diff --git a/resources/lang/en-US/mail.php b/resources/lang/en-US/mail.php
index 0eca9b4c23..e471ecece8 100644
--- a/resources/lang/en-US/mail.php
+++ b/resources/lang/en-US/mail.php
@@ -38,6 +38,8 @@ return [
'acceptance_declined' => 'DECLINED: :user has declined :item',
'acceptance_accepted_greeting' => ':user has accepted an item:',
'acceptance_declined_greeting' => ':user has declined an item',
+ 'acceptance_re_request' => 'Action Required: Please Re-Accept Your Assigned Items',
+ 'acceptance_re_request_intro' => 'Please re-accept the terms for the :count item currently assigned to you. Click the link below to accept or decline it.|Please re-accept the terms for the :count items currently assigned to you. Click the link below to accept or decline them.',
'send_pdf_copy' => 'Send a copy of this acceptance to my email address',
'accessory_name' => 'Accessory Name',
'additional_notes' => 'Additional Notes',
diff --git a/resources/views/notifications/markdown/acceptance-re-request.blade.php b/resources/views/notifications/markdown/acceptance-re-request.blade.php
new file mode 100644
index 0000000000..b18b9ddd43
--- /dev/null
+++ b/resources/views/notifications/markdown/acceptance-re-request.blade.php
@@ -0,0 +1,11 @@
+@component('mail::message')
+# {{ trans('mail.hello') }} {{ $assigned_to }},
+
+{{ trans_choice('mail.acceptance_re_request_intro', $count, ['count' => $count]) }}
+[{{ trans('general.click_here') }}]({{ $accept_url }})
+
+{{ trans('mail.best_regards') }}
+
+{{ $snipeSettings->site_name }}
+
+@endcomponent
diff --git a/tests/Feature/Console/RegenerateAcceptancesTest.php b/tests/Feature/Console/RegenerateAcceptancesTest.php
index ac8f285d57..8ec5680922 100644
--- a/tests/Feature/Console/RegenerateAcceptancesTest.php
+++ b/tests/Feature/Console/RegenerateAcceptancesTest.php
@@ -2,6 +2,7 @@
namespace Tests\Feature\Console;
+use App\Mail\AcceptanceReRequestMail;
use App\Models\Accessory;
use App\Models\Asset;
use App\Models\AssetModel;
@@ -16,6 +17,7 @@ use App\Models\Location;
use App\Models\User;
use Database\Factories\CheckoutAcceptanceFactory;
use Illuminate\Database\Eloquent\Model;
+use Illuminate\Support\Facades\Mail;
use Tests\TestCase;
class RegenerateAcceptancesTest extends TestCase
@@ -706,6 +708,106 @@ class RegenerateAcceptancesTest extends TestCase
$this->assertNull($this->newestAcceptance()->alert_on_response_id);
}
+ public function test_notify_sends_one_email_per_holder_however_many_rows_they_got(): void
+ {
+ Mail::fake();
+ $company = Company::factory()->create();
+ $alice = User::factory()->create(['email' => '[email protected]']);
+ $bob = User::factory()->create(['email' => '[email protected]']);
+ $this->heldAsset($alice, $this->acceptanceCategory('asset'), $company, 'Alice laptop');
+ $this->heldAccessory($alice, $this->acceptanceCategory('accessory'), $company, 'Mouse');
+ $this->heldAsset($bob, $this->acceptanceCategory('asset'), $company, 'Bob laptop');
+
+ $this->artisan('snipeit:regenerate-acceptances', ['--notify' => true])
+ ->expectsOutput('Created: 3.')
+ ->expectsOutput('Notified: 2.')
+ ->assertExitCode(0);
+
+ Mail::assertSent(AcceptanceReRequestMail::class, function (AcceptanceReRequestMail $mail) {
+ return $mail->hasTo('[email protected]')
+ && $mail->itemCount === 2
+ && $mail->hasSubject(trans('mail.acceptance_re_request'))
+ && str_contains($mail->render(), trans_choice('mail.acceptance_re_request_intro', 2, ['count' => 2]));
+ });
+ Mail::assertSent(
+ AcceptanceReRequestMail::class,
+ fn (AcceptanceReRequestMail $mail) => $mail->hasTo('[email protected]') && $mail->itemCount === 1,
+ );
+ Mail::assertSent(AcceptanceReRequestMail::class, 2);
+ }
+
+ public function test_nothing_is_emailed_without_the_notify_flag(): void
+ {
+ Mail::fake();
+ $holder = User::factory()->create();
+ $this->assetIn($this->acceptanceCategory('asset'), [
+ 'assigned_to' => $holder->id,
+ 'assigned_type' => User::class,
+ ]);
+
+ $this->artisan('snipeit:regenerate-acceptances')
+ ->expectsOutput('Created: 1.')
+ ->doesntExpectOutput('Notified: 1.')
+ ->assertExitCode(0);
+
+ Mail::assertNothingSent();
+ }
+
+ public function test_dry_run_with_notify_emails_nobody(): void
+ {
+ Mail::fake();
+ $holder = User::factory()->create();
+ $this->assetIn($this->acceptanceCategory('asset'), [
+ 'assigned_to' => $holder->id,
+ 'assigned_type' => User::class,
+ ]);
+
+ $this->artisan('snipeit:regenerate-acceptances', ['--dry-run' => true, '--notify' => true])
+ ->expectsOutput('Nothing was created.')
+ ->expectsOutput('Notified: 0.')
+ ->assertExitCode(0);
+
+ Mail::assertNothingSent();
+ }
+
+ public function test_holder_without_an_email_still_gets_their_row_and_is_reported(): void
+ {
+ Mail::fake();
+ $holder = User::factory()->create(['email' => '']);
+ $asset = $this->assetIn($this->acceptanceCategory('asset'), [
+ 'assigned_to' => $holder->id,
+ 'assigned_type' => User::class,
+ ]);
+
+ $this->artisan('snipeit:regenerate-acceptances', ['--notify' => true])
+ ->expectsOutput('Created: 1.')
+ ->expectsOutput('Notified: 0.')
+ ->expectsOutput('The following users do not have an email address:')
+ ->expectsTable(['ID', 'Name'], [[$holder->id, $holder->present()->fullName]])
+ ->assertExitCode(0);
+
+ Mail::assertNothingSent();
+ $this->assertSame(
+ ['Asset #'.$asset->id.' -> user #'.$holder->id.' qty null'],
+ $this->acceptanceRows(),
+ );
+ }
+
+ public function test_the_no_email_table_is_not_printed_when_every_holder_has_an_email(): void
+ {
+ Mail::fake();
+ $holder = User::factory()->create(['email' => '[email protected]']);
+ $this->assetIn($this->acceptanceCategory('asset'), [
+ 'assigned_to' => $holder->id,
+ 'assigned_type' => User::class,
+ ]);
+
+ $this->artisan('snipeit:regenerate-acceptances', ['--notify' => true])
+ ->expectsOutput('Notified: 1.')
+ ->doesntExpectOutput('The following users do not have an email address:')
+ ->assertExitCode(0);
+ }
+
/**
* One realistic install, run for real.
*