feat: complete email infrastructure with queue, templates, logging, and API

Adds the full transactional email system:
- Redis queue (QUEUE_CONNECTION=redis), SES config in .env.example
- 3 migrations: organisation_email_settings, organisation_email_templates, email_logs
- EmailTemplateType and EmailLogStatus enums with Dutch defaults
- EmailService as central entry point for all email sending
- SendTransactionalEmail queued job with retries and idempotency
- TransactionalMail mailable with responsive HTML + plain text templates
- Organisation-level branding (colors, logo, footer, reply-to)
- Per-type template overrides with {variable} substitution
- Email log with filtering by status, type, date range, recipient
- Preview and send-test endpoints for template management
- API endpoints: email-settings, email-templates (CRUD), email-logs (read-only)
- Integrated into existing flows: invitations, password reset, email
  verification, registration approval/rejection
- 37 new tests across 4 test files, all existing tests updated

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-04-15 20:12:21 +02:00
parent c64875b6ef
commit 65978104d8
42 changed files with 2420 additions and 48 deletions

View File

@@ -5,13 +5,15 @@ declare(strict_types=1);
namespace Tests\Feature\Api\V1;
use App\Enums\EmailChangeStatus;
use App\Enums\EmailTemplateType;
use App\Jobs\SendTransactionalEmail;
use App\Mail\EmailChangedConfirmationMail;
use App\Mail\VerifyEmailChangeMail;
use App\Models\EmailChangeRequest;
use App\Models\Organisation;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Queue;
use Tests\TestCase;
class EmailChangeTest extends TestCase
@@ -22,7 +24,7 @@ class EmailChangeTest extends TestCase
public function test_user_can_request_email_change(): void
{
Mail::fake();
Queue::fake();
$user = User::factory()->create([
'email' => 'oud@voorbeeld.nl',
@@ -44,8 +46,9 @@ class EmailChangeTest extends TestCase
'status' => 'pending',
]);
Mail::assertQueued(VerifyEmailChangeMail::class, function ($mail) {
return $mail->hasTo('nieuw@voorbeeld.nl');
Queue::assertPushed(SendTransactionalEmail::class, function ($job) {
return $job->recipientEmail === 'nieuw@voorbeeld.nl'
&& $job->type === EmailTemplateType::EMAIL_VERIFICATION;
});
}
@@ -249,7 +252,7 @@ class EmailChangeTest extends TestCase
public function test_admin_can_change_member_email(): void
{
Mail::fake();
Queue::fake();
$organisation = Organisation::factory()->create();
$admin = User::factory()->create();
@@ -265,8 +268,9 @@ class EmailChangeTest extends TestCase
$response->assertOk();
Mail::assertQueued(VerifyEmailChangeMail::class, function ($mail) {
return $mail->hasTo('nieuw-lid@voorbeeld.nl');
Queue::assertPushed(SendTransactionalEmail::class, function ($job) {
return $job->recipientEmail === 'nieuw-lid@voorbeeld.nl'
&& $job->type === EmailTemplateType::EMAIL_VERIFICATION;
});
}

View File

@@ -4,12 +4,13 @@ declare(strict_types=1);
namespace Tests\Feature\Api\V1;
use App\Enums\EmailTemplateType;
use App\Jobs\SendTransactionalEmail;
use App\Models\User;
use App\Notifications\ResetPasswordNotification;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Notification;
use Illuminate\Support\Facades\Password;
use Illuminate\Support\Facades\Queue;
use Tests\TestCase;
class PasswordResetTest extends TestCase
@@ -20,7 +21,7 @@ class PasswordResetTest extends TestCase
public function test_forgot_password_returns_success_for_existing_email(): void
{
Notification::fake();
Queue::fake();
$user = User::factory()->create(['email' => 'jan@voorbeeld.nl']);
@@ -31,11 +32,16 @@ class PasswordResetTest extends TestCase
$response->assertOk();
Notification::assertSentTo($user, ResetPasswordNotification::class);
Queue::assertPushed(SendTransactionalEmail::class, function ($job) {
return $job->recipientEmail === 'jan@voorbeeld.nl'
&& $job->type === EmailTemplateType::PASSWORD_RESET;
});
}
public function test_forgot_password_returns_same_success_for_nonexisting_email(): void
{
Queue::fake();
$response = $this->postJson('/api/v1/auth/forgot-password', [
'email' => 'onbekend@voorbeeld.nl',
'app' => 'app',

View File

@@ -4,8 +4,8 @@ declare(strict_types=1);
namespace Tests\Feature\Api\V1;
use App\Mail\RegistrationApprovedMail;
use App\Mail\RegistrationRejectedMail;
use App\Jobs\SendTransactionalEmail;
use App\Enums\EmailTemplateType;
use App\Models\CrowdType;
use App\Models\Event;
use App\Models\Organisation;
@@ -13,7 +13,7 @@ use App\Models\Person;
use App\Models\User;
use Database\Seeders\RoleSeeder;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Queue;
use Laravel\Sanctum\Sanctum;
use Tests\TestCase;
@@ -46,7 +46,7 @@ class PersonApprovalEmailTest extends TestCase
public function test_approving_person_sends_approved_email(): void
{
Mail::fake();
Queue::fake();
$person = Person::factory()->create([
'event_id' => $this->event->id,
@@ -61,14 +61,20 @@ class PersonApprovalEmailTest extends TestCase
$response->assertOk();
Mail::assertQueued(RegistrationApprovedMail::class, function ($mail) {
return $mail->hasTo('volunteer@test.nl');
Queue::assertPushed(SendTransactionalEmail::class, function ($job) {
return $job->recipientEmail === 'volunteer@test.nl'
&& $job->type === EmailTemplateType::REGISTRATION_APPROVED;
});
$this->assertDatabaseHas('email_logs', [
'recipient_email' => 'volunteer@test.nl',
'template_type' => 'registration_approved',
]);
}
public function test_rejecting_person_sends_rejected_email_with_reason(): void
{
Mail::fake();
Queue::fake();
$person = Person::factory()->create([
'event_id' => $this->event->id,
@@ -90,15 +96,15 @@ class PersonApprovalEmailTest extends TestCase
'status' => 'rejected',
]);
Mail::assertQueued(RegistrationRejectedMail::class, function ($mail) {
return $mail->hasTo('volunteer@test.nl')
&& $mail->reason === 'Geen beschikbaarheid op de juiste momenten.';
Queue::assertPushed(SendTransactionalEmail::class, function ($job) {
return $job->recipientEmail === 'volunteer@test.nl'
&& $job->type === EmailTemplateType::REGISTRATION_REJECTED;
});
}
public function test_rejecting_person_sends_rejected_email_without_reason(): void
{
Mail::fake();
Queue::fake();
$person = Person::factory()->create([
'event_id' => $this->event->id,
@@ -113,9 +119,9 @@ class PersonApprovalEmailTest extends TestCase
$response->assertOk();
Mail::assertQueued(RegistrationRejectedMail::class, function ($mail) {
return $mail->hasTo('volunteer@test.nl')
&& $mail->reason === null;
Queue::assertPushed(SendTransactionalEmail::class, function ($job) {
return $job->recipientEmail === 'volunteer@test.nl'
&& $job->type === EmailTemplateType::REGISTRATION_REJECTED;
});
}

View File

@@ -0,0 +1,162 @@
<?php
declare(strict_types=1);
namespace Tests\Feature\Email;
use App\Enums\EmailLogStatus;
use App\Enums\EmailTemplateType;
use App\Models\EmailLog;
use App\Models\Event;
use App\Models\Organisation;
use App\Models\User;
use Database\Seeders\RoleSeeder;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Laravel\Sanctum\Sanctum;
use Tests\TestCase;
class EmailLogControllerTest extends TestCase
{
use RefreshDatabase;
private User $orgAdmin;
private User $outsider;
private Organisation $organisation;
private Organisation $otherOrganisation;
protected function setUp(): void
{
parent::setUp();
$this->seed(RoleSeeder::class);
$this->organisation = Organisation::factory()->create();
$this->otherOrganisation = Organisation::factory()->create();
$this->orgAdmin = User::factory()->create();
$this->organisation->users()->attach($this->orgAdmin, ['role' => 'org_admin']);
$this->outsider = User::factory()->create();
$this->otherOrganisation->users()->attach($this->outsider, ['role' => 'org_admin']);
}
public function test_index_returns_paginated_logs(): void
{
EmailLog::factory()->count(3)->create([
'organisation_id' => $this->organisation->id,
]);
Sanctum::actingAs($this->orgAdmin);
$response = $this->getJson("/api/v1/organisations/{$this->organisation->id}/email-logs");
$response->assertOk();
$this->assertCount(3, $response->json('data.data'));
}
public function test_filter_by_status(): void
{
EmailLog::factory()->sent()->create([
'organisation_id' => $this->organisation->id,
]);
EmailLog::factory()->failed()->create([
'organisation_id' => $this->organisation->id,
]);
Sanctum::actingAs($this->orgAdmin);
$response = $this->getJson("/api/v1/organisations/{$this->organisation->id}/email-logs?status=sent");
$response->assertOk();
$this->assertCount(1, $response->json('data.data'));
$this->assertEquals('sent', $response->json('data.data.0.status'));
}
public function test_filter_by_template_type(): void
{
EmailLog::factory()->create([
'organisation_id' => $this->organisation->id,
'template_type' => EmailTemplateType::INVITATION->value,
]);
EmailLog::factory()->create([
'organisation_id' => $this->organisation->id,
'template_type' => EmailTemplateType::PASSWORD_RESET->value,
]);
Sanctum::actingAs($this->orgAdmin);
$response = $this->getJson("/api/v1/organisations/{$this->organisation->id}/email-logs?template_type=invitation");
$response->assertOk();
$this->assertCount(1, $response->json('data.data'));
$this->assertEquals('invitation', $response->json('data.data.0.template_type'));
}
public function test_filter_by_date_range(): void
{
EmailLog::factory()->create([
'organisation_id' => $this->organisation->id,
'created_at' => '2026-04-10 12:00:00',
]);
EmailLog::factory()->create([
'organisation_id' => $this->organisation->id,
'created_at' => '2026-04-15 12:00:00',
]);
Sanctum::actingAs($this->orgAdmin);
$response = $this->getJson("/api/v1/organisations/{$this->organisation->id}/email-logs?from=2026-04-14&to=2026-04-16");
$response->assertOk();
$this->assertCount(1, $response->json('data.data'));
}
public function test_search_by_recipient_email(): void
{
EmailLog::factory()->create([
'organisation_id' => $this->organisation->id,
'recipient_email' => 'needle@example.com',
]);
EmailLog::factory()->create([
'organisation_id' => $this->organisation->id,
'recipient_email' => 'other@example.com',
]);
Sanctum::actingAs($this->orgAdmin);
$response = $this->getJson("/api/v1/organisations/{$this->organisation->id}/email-logs?search=needle");
$response->assertOk();
$this->assertCount(1, $response->json('data.data'));
$this->assertEquals('needle@example.com', $response->json('data.data.0.recipient_email'));
}
public function test_denied_for_non_org_admin(): void
{
Sanctum::actingAs($this->outsider);
$response = $this->getJson("/api/v1/organisations/{$this->organisation->id}/email-logs");
$response->assertForbidden();
}
public function test_cannot_see_other_org_logs(): void
{
EmailLog::factory()->count(2)->create([
'organisation_id' => $this->otherOrganisation->id,
]);
Sanctum::actingAs($this->orgAdmin);
$response = $this->getJson("/api/v1/organisations/{$this->organisation->id}/email-logs");
$response->assertOk();
$this->assertCount(0, $response->json('data.data'));
}
public function test_unauthenticated_returns_401(): void
{
$response = $this->getJson("/api/v1/organisations/{$this->organisation->id}/email-logs");
$response->assertUnauthorized();
}
}

View File

@@ -0,0 +1,173 @@
<?php
declare(strict_types=1);
namespace Tests\Feature\Email;
use App\Enums\EmailLogStatus;
use App\Enums\EmailTemplateType;
use App\Jobs\SendTransactionalEmail;
use App\Models\Organisation;
use App\Models\OrganisationEmailSettings;
use App\Models\OrganisationEmailTemplate;
use App\Services\EmailService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Queue;
use Tests\TestCase;
class EmailServiceTest extends TestCase
{
use RefreshDatabase;
private EmailService $service;
private Organisation $organisation;
protected function setUp(): void
{
parent::setUp();
$this->service = app(EmailService::class);
$this->organisation = Organisation::factory()->create(['name' => 'Test Org']);
}
public function test_send_creates_email_log_with_queued_status(): void
{
Queue::fake();
$log = $this->service->send(
type: EmailTemplateType::INVITATION,
recipientEmail: 'test@example.com',
recipientName: 'Test User',
variables: ['organisation_name' => 'Test Org'],
organisation: $this->organisation,
);
$this->assertDatabaseHas('email_logs', [
'id' => $log->id,
'recipient_email' => 'test@example.com',
'template_type' => 'invitation',
'status' => 'queued',
'organisation_id' => $this->organisation->id,
]);
}
public function test_send_dispatches_queued_job(): void
{
Queue::fake();
$this->service->send(
type: EmailTemplateType::INVITATION,
recipientEmail: 'test@example.com',
recipientName: 'Test User',
variables: ['organisation_name' => 'Test Org'],
organisation: $this->organisation,
);
Queue::assertPushed(SendTransactionalEmail::class, function ($job) {
return $job->recipientEmail === 'test@example.com'
&& $job->type === EmailTemplateType::INVITATION;
});
}
public function test_resolve_template_returns_defaults_without_org(): void
{
$template = $this->service->resolveTemplate(EmailTemplateType::INVITATION);
$this->assertFalse($template['is_custom']);
$this->assertStringContainsString('{organisation_name}', $template['subject']);
$this->assertEquals('Uitnodiging accepteren', $template['button_text']);
}
public function test_resolve_template_returns_org_override_when_exists(): void
{
OrganisationEmailTemplate::factory()->create([
'organisation_id' => $this->organisation->id,
'type' => EmailTemplateType::INVITATION->value,
'subject' => 'Aangepaste uitnodiging',
'heading' => 'Welkom!',
'body_text' => 'Aangepaste tekst',
'button_text' => 'Klik hier',
]);
$template = $this->service->resolveTemplate(EmailTemplateType::INVITATION, $this->organisation);
$this->assertTrue($template['is_custom']);
$this->assertEquals('Aangepaste uitnodiging', $template['subject']);
$this->assertEquals('Klik hier', $template['button_text']);
}
public function test_resolve_template_falls_back_to_defaults_without_override(): void
{
$template = $this->service->resolveTemplate(EmailTemplateType::PASSWORD_RESET, $this->organisation);
$this->assertFalse($template['is_custom']);
$this->assertEquals('Wachtwoord resetten', $template['subject']);
}
public function test_variable_substitution_replaces_placeholders(): void
{
Queue::fake();
$log = $this->service->send(
type: EmailTemplateType::INVITATION,
recipientEmail: 'test@example.com',
recipientName: 'Test User',
variables: ['organisation_name' => 'Feestfabriek'],
organisation: $this->organisation,
);
$this->assertDatabaseHas('email_logs', [
'id' => $log->id,
'subject' => 'Je bent uitgenodigd voor Feestfabriek',
]);
}
public function test_branding_uses_org_settings_when_available(): void
{
OrganisationEmailSettings::factory()->create([
'organisation_id' => $this->organisation->id,
'primary_color' => '#FF0000',
'secondary_color' => '#00FF00',
'footer_text' => 'Custom Footer',
'reply_to_email' => 'reply@example.com',
'reply_to_name' => 'Reply Name',
]);
$branding = $this->service->resolveBranding($this->organisation);
$this->assertEquals('#FF0000', $branding['primary_color']);
$this->assertEquals('#00FF00', $branding['secondary_color']);
$this->assertEquals('Custom Footer', $branding['footer_text']);
$this->assertEquals('reply@example.com', $branding['reply_to_email']);
$this->assertEquals('Reply Name', $branding['reply_to_name']);
}
public function test_branding_falls_back_to_defaults(): void
{
$branding = $this->service->resolveBranding($this->organisation);
$this->assertEquals('#6366F1', $branding['primary_color']);
$this->assertEquals('#4F46E5', $branding['secondary_color']);
$this->assertStringContainsString('Test Org', $branding['footer_text']);
$this->assertNull($branding['reply_to_email']);
}
public function test_branding_returns_system_defaults_without_org(): void
{
$branding = $this->service->resolveBranding(null);
$this->assertEquals('#6366F1', $branding['primary_color']);
$this->assertStringContainsString('Crewli', $branding['footer_text']);
}
public function test_get_all_templates_returns_all_types(): void
{
$templates = $this->service->getAllTemplates($this->organisation);
$this->assertCount(count(EmailTemplateType::cases()), $templates);
$types = array_column($templates, 'type');
foreach (EmailTemplateType::cases() as $case) {
$this->assertContains($case->value, $types);
}
}
}

View File

@@ -0,0 +1,235 @@
<?php
declare(strict_types=1);
namespace Tests\Feature\Email;
use App\Enums\EmailTemplateType;
use App\Models\Organisation;
use App\Models\OrganisationEmailSettings;
use App\Models\OrganisationEmailTemplate;
use App\Models\User;
use Database\Seeders\RoleSeeder;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Queue;
use Laravel\Sanctum\Sanctum;
use Tests\TestCase;
class EmailSettingsAndTemplateControllerTest extends TestCase
{
use RefreshDatabase;
private User $orgAdmin;
private User $outsider;
private Organisation $organisation;
private Organisation $otherOrganisation;
protected function setUp(): void
{
parent::setUp();
$this->seed(RoleSeeder::class);
$this->organisation = Organisation::factory()->create(['name' => 'Test Org']);
$this->otherOrganisation = Organisation::factory()->create();
$this->orgAdmin = User::factory()->create();
$this->organisation->users()->attach($this->orgAdmin, ['role' => 'org_admin']);
$this->outsider = User::factory()->create();
$this->otherOrganisation->users()->attach($this->outsider, ['role' => 'org_admin']);
}
// ── Email Settings ──
public function test_show_returns_defaults_when_no_settings(): void
{
Sanctum::actingAs($this->orgAdmin);
$response = $this->getJson("/api/v1/organisations/{$this->organisation->id}/email-settings");
$response->assertOk();
$response->assertJsonPath('data.primary_color', '#6366F1');
}
public function test_show_returns_custom_settings(): void
{
OrganisationEmailSettings::factory()->create([
'organisation_id' => $this->organisation->id,
'primary_color' => '#FF0000',
]);
Sanctum::actingAs($this->orgAdmin);
$response = $this->getJson("/api/v1/organisations/{$this->organisation->id}/email-settings");
$response->assertOk();
$response->assertJsonPath('data.primary_color', '#FF0000');
}
public function test_update_creates_settings_if_not_exists(): void
{
Sanctum::actingAs($this->orgAdmin);
$response = $this->putJson("/api/v1/organisations/{$this->organisation->id}/email-settings", [
'primary_color' => '#00FF00',
'footer_text' => 'Custom Footer',
]);
$response->assertOk();
$this->assertDatabaseHas('organisation_email_settings', [
'organisation_id' => $this->organisation->id,
'primary_color' => '#00FF00',
'footer_text' => 'Custom Footer',
]);
}
public function test_update_modifies_existing_settings(): void
{
OrganisationEmailSettings::factory()->create([
'organisation_id' => $this->organisation->id,
'primary_color' => '#FF0000',
]);
Sanctum::actingAs($this->orgAdmin);
$response = $this->putJson("/api/v1/organisations/{$this->organisation->id}/email-settings", [
'primary_color' => '#00FF00',
]);
$response->assertOk();
$response->assertJsonPath('data.primary_color', '#00FF00');
}
public function test_update_validates_hex_color(): void
{
Sanctum::actingAs($this->orgAdmin);
$response = $this->putJson("/api/v1/organisations/{$this->organisation->id}/email-settings", [
'primary_color' => 'invalid',
]);
$response->assertUnprocessable();
$response->assertJsonValidationErrors(['primary_color']);
}
public function test_settings_denied_for_non_org_admin(): void
{
Sanctum::actingAs($this->outsider);
$response = $this->getJson("/api/v1/organisations/{$this->organisation->id}/email-settings");
$response->assertForbidden();
}
// ── Email Templates ──
public function test_index_returns_all_template_types_with_content(): void
{
Sanctum::actingAs($this->orgAdmin);
$response = $this->getJson("/api/v1/organisations/{$this->organisation->id}/email-templates");
$response->assertOk();
$this->assertCount(count(EmailTemplateType::cases()), $response->json('data'));
}
public function test_show_returns_template_with_defaults(): void
{
Sanctum::actingAs($this->orgAdmin);
$response = $this->getJson("/api/v1/organisations/{$this->organisation->id}/email-templates/invitation");
$response->assertOk();
$response->assertJsonPath('data.type', 'invitation');
$response->assertJsonPath('data.is_custom', false);
$this->assertArrayHasKey('defaults', $response->json('data'));
}
public function test_update_creates_custom_override(): void
{
Sanctum::actingAs($this->orgAdmin);
$response = $this->putJson("/api/v1/organisations/{$this->organisation->id}/email-templates/invitation", [
'subject' => 'Aangepaste uitnodiging',
'body_text' => 'Aangepaste tekst voor de uitnodiging.',
]);
$response->assertOk();
$response->assertJsonPath('data.is_custom', true);
$response->assertJsonPath('data.subject', 'Aangepaste uitnodiging');
$this->assertDatabaseHas('organisation_email_templates', [
'organisation_id' => $this->organisation->id,
'type' => 'invitation',
'subject' => 'Aangepaste uitnodiging',
]);
}
public function test_destroy_resets_to_default(): void
{
OrganisationEmailTemplate::factory()->create([
'organisation_id' => $this->organisation->id,
'type' => EmailTemplateType::INVITATION->value,
]);
Sanctum::actingAs($this->orgAdmin);
$response = $this->deleteJson("/api/v1/organisations/{$this->organisation->id}/email-templates/invitation");
$response->assertOk();
$this->assertDatabaseMissing('organisation_email_templates', [
'organisation_id' => $this->organisation->id,
'type' => 'invitation',
]);
}
public function test_preview_returns_rendered_html(): void
{
Sanctum::actingAs($this->orgAdmin);
$response = $this->postJson("/api/v1/organisations/{$this->organisation->id}/email-templates/invitation/preview");
$response->assertOk();
$this->assertArrayHasKey('html', $response->json('data'));
$this->assertStringContainsString('<!DOCTYPE html>', $response->json('data.html'));
}
public function test_send_test_queues_email(): void
{
Queue::fake();
Sanctum::actingAs($this->orgAdmin);
$response = $this->postJson("/api/v1/organisations/{$this->organisation->id}/email-templates/invitation/send-test", [
'email' => 'test@example.com',
]);
$response->assertOk();
$this->assertDatabaseHas('email_logs', [
'organisation_id' => $this->organisation->id,
'recipient_email' => 'test@example.com',
'template_type' => 'invitation',
]);
}
public function test_templates_denied_for_non_org_admin(): void
{
Sanctum::actingAs($this->outsider);
$response = $this->getJson("/api/v1/organisations/{$this->organisation->id}/email-templates");
$response->assertForbidden();
}
public function test_show_returns_404_for_invalid_type(): void
{
Sanctum::actingAs($this->orgAdmin);
$response = $this->getJson("/api/v1/organisations/{$this->organisation->id}/email-templates/nonexistent");
$response->assertNotFound();
}
}

View File

@@ -0,0 +1,178 @@
<?php
declare(strict_types=1);
namespace Tests\Feature\Email;
use App\Enums\EmailLogStatus;
use App\Enums\EmailTemplateType;
use App\Jobs\SendTransactionalEmail;
use App\Mail\TransactionalMail;
use App\Models\EmailLog;
use App\Models\Organisation;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Mail;
use Tests\TestCase;
class SendTransactionalEmailJobTest extends TestCase
{
use RefreshDatabase;
private array $template;
private array $branding;
protected function setUp(): void
{
parent::setUp();
$this->template = [
'subject' => 'Test Subject',
'heading' => 'Test Heading',
'body_text' => 'Test body text',
'button_text' => 'Click me',
'is_custom' => false,
];
$this->branding = [
'logo_url' => null,
'primary_color' => '#6366F1',
'secondary_color' => '#4F46E5',
'footer_text' => '© 2026 Crewli',
'reply_to_email' => null,
'reply_to_name' => null,
];
}
public function test_job_sends_email_and_updates_log_to_sent(): void
{
Mail::fake();
$org = Organisation::factory()->create();
$log = EmailLog::factory()->create([
'organisation_id' => $org->id,
'status' => EmailLogStatus::QUEUED->value,
]);
$job = new SendTransactionalEmail(
emailLogId: $log->id,
type: EmailTemplateType::INVITATION,
recipientEmail: 'test@example.com',
recipientName: 'Test User',
template: $this->template,
branding: $this->branding,
actionUrl: 'https://example.com/action',
);
$job->handle();
Mail::assertSent(TransactionalMail::class, function ($mailable) {
return $mailable->template['subject'] === 'Test Subject';
});
$log->refresh();
$this->assertEquals(EmailLogStatus::SENT, $log->status);
$this->assertNotNull($log->sent_at);
}
public function test_job_skips_already_sent_emails(): void
{
Mail::fake();
$org = Organisation::factory()->create();
$log = EmailLog::factory()->sent()->create([
'organisation_id' => $org->id,
]);
$job = new SendTransactionalEmail(
emailLogId: $log->id,
type: EmailTemplateType::INVITATION,
recipientEmail: 'test@example.com',
recipientName: 'Test User',
template: $this->template,
branding: $this->branding,
);
$job->handle();
Mail::assertNothingSent();
}
public function test_job_updates_log_to_failed_on_exception(): void
{
Mail::fake();
Mail::shouldReceive('to')->andThrow(new \RuntimeException('SMTP error'));
$org = Organisation::factory()->create();
$log = EmailLog::factory()->create([
'organisation_id' => $org->id,
'status' => EmailLogStatus::QUEUED->value,
]);
$job = new SendTransactionalEmail(
emailLogId: $log->id,
type: EmailTemplateType::INVITATION,
recipientEmail: 'test@example.com',
recipientName: 'Test User',
template: $this->template,
branding: $this->branding,
);
try {
$job->handle();
} catch (\RuntimeException) {
// Expected
}
$log->refresh();
$this->assertEquals(EmailLogStatus::FAILED, $log->status);
$this->assertNotNull($log->failed_at);
$this->assertStringContainsString('SMTP error', $log->error_message);
}
public function test_job_retries_on_failure(): void
{
$job = new SendTransactionalEmail(
emailLogId: 'fake-id',
type: EmailTemplateType::INVITATION,
recipientEmail: 'test@example.com',
recipientName: 'Test User',
template: $this->template,
branding: $this->branding,
);
$this->assertEquals(3, $job->tries);
$this->assertEquals([30, 120, 300], $job->backoff);
$this->assertEquals('emails', $job->queue);
}
public function test_job_sets_reply_to_when_configured(): void
{
Mail::fake();
$org = Organisation::factory()->create();
$log = EmailLog::factory()->create([
'organisation_id' => $org->id,
'status' => EmailLogStatus::QUEUED->value,
]);
$brandingWithReplyTo = array_merge($this->branding, [
'reply_to_email' => 'reply@example.com',
'reply_to_name' => 'Reply User',
]);
$job = new SendTransactionalEmail(
emailLogId: $log->id,
type: EmailTemplateType::INVITATION,
recipientEmail: 'test@example.com',
recipientName: 'Test User',
template: $this->template,
branding: $brandingWithReplyTo,
);
$job->handle();
Mail::assertSent(TransactionalMail::class, function ($mailable) {
return $mailable->hasReplyTo('reply@example.com', 'Reply User');
});
}
}

View File

@@ -4,12 +4,15 @@ declare(strict_types=1);
namespace Tests\Feature\Invitation;
use App\Enums\EmailTemplateType;
use App\Jobs\SendTransactionalEmail;
use App\Models\Organisation;
use App\Models\User;
use App\Models\UserInvitation;
use Database\Seeders\RoleSeeder;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Queue;
use Laravel\Sanctum\Sanctum;
use Tests\TestCase;
@@ -34,7 +37,7 @@ class InvitationTest extends TestCase
public function test_org_admin_can_invite_user(): void
{
Mail::fake();
Queue::fake();
Sanctum::actingAs($this->orgAdmin);
$response = $this->postJson("/api/v1/organisations/{$this->org->id}/invite", [
@@ -48,7 +51,10 @@ class InvitationTest extends TestCase
'organisation_id' => $this->org->id,
'status' => 'pending',
]);
Mail::assertQueued(\App\Mail\InvitationMail::class);
Queue::assertPushed(SendTransactionalEmail::class, function ($job) {
return $job->recipientEmail === 'newuser@test.nl'
&& $job->type === EmailTemplateType::INVITATION;
});
}
public function test_org_member_cannot_invite_user(): void

View File

@@ -9,6 +9,7 @@ use Database\Seeders\RoleSeeder;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Password;
use Illuminate\Support\Facades\Queue;
use Laravel\Sanctum\Sanctum;
use Tests\TestCase;
@@ -98,6 +99,8 @@ final class AuthenticationSecurityTest extends TestCase
public function test_password_reset_returns_success_for_unknown_email(): void
{
Queue::fake();
$response = $this->postJson('/api/v1/auth/forgot-password', [
'email' => 'nonexistent@example.com',
'app' => 'app',
@@ -109,6 +112,8 @@ final class AuthenticationSecurityTest extends TestCase
public function test_password_reset_returns_success_for_known_email(): void
{
Queue::fake();
$user = User::factory()->create();
$response = $this->postJson('/api/v1/auth/forgot-password', [