Files
crewli/api/app/Services/EmailChangeService.php
bert.hausmans 65978104d8 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>
2026-04-15 20:12:21 +02:00

165 lines
5.4 KiB
PHP

<?php
declare(strict_types=1);
namespace App\Services;
use App\Enums\EmailChangeStatus;
use App\Enums\EmailTemplateType;
use App\Mail\EmailChangedConfirmationMail;
use App\Models\EmailChangeRequest;
use App\Models\Person;
use App\Models\User;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
final class EmailChangeService
{
public function __construct(
private readonly EmailService $emailService,
) {}
/**
* Request an email change. Sends verification to the NEW email.
*/
public function requestChange(
User $user,
string $newEmail,
User $requestedBy,
string $frontendUrl,
): EmailChangeRequest {
// Validate new email is not already in use
if (User::where('email', $newEmail)->where('id', '!=', $user->id)->exists()) {
throw ValidationException::withMessages([
'new_email' => ['Dit e-mailadres is al in gebruik door een ander account.'],
]);
}
// Cancel any existing pending requests for this user
EmailChangeRequest::where('user_id', $user->id)
->where('status', EmailChangeStatus::PENDING)
->update(['status' => EmailChangeStatus::CANCELLED->value]);
// Generate secure token
$plainToken = Str::random(64);
$request = EmailChangeRequest::create([
'user_id' => $user->id,
'current_email' => $user->email,
'new_email' => $newEmail,
'token' => hash('sha256', $plainToken),
'requested_by_user_id' => $requestedBy->id,
'status' => EmailChangeStatus::PENDING,
'expires_at' => now()->addHours(24),
]);
// Send verification email to the NEW address
$organisation = $user->organisations()->first();
$this->emailService->send(
type: EmailTemplateType::EMAIL_VERIFICATION,
recipientEmail: $newEmail,
recipientName: $user->first_name . ' ' . $user->last_name,
actionUrl: $frontendUrl . '/verify-email-change?token=' . $plainToken,
organisation: $organisation,
userId: $user->id,
triggeredByUserId: $requestedBy->id,
);
activity()
->causedBy($requestedBy)
->performedOn($user)
->withProperties([
'current_email' => $user->email,
'new_email' => $newEmail,
'is_self_change' => $user->id === $requestedBy->id,
])
->log('user.email_change_requested');
return $request;
}
/**
* Verify and execute the email change.
*/
public function verifyChange(string $plainToken): EmailChangeRequest
{
$hashedToken = hash('sha256', $plainToken);
$request = EmailChangeRequest::where('token', $hashedToken)
->where('status', EmailChangeStatus::PENDING)
->first();
if (! $request) {
throw ValidationException::withMessages([
'token' => ['Ongeldige of verlopen verificatielink.'],
]);
}
if ($request->isExpired()) {
$request->update(['status' => EmailChangeStatus::EXPIRED]);
throw ValidationException::withMessages([
'token' => ['Deze verificatielink is verlopen. Vraag opnieuw een e-mailwijziging aan.'],
]);
}
// Final check: new email still not in use
if (User::where('email', $request->new_email)
->where('id', '!=', $request->user_id)->exists()) {
$request->update(['status' => EmailChangeStatus::CANCELLED]);
throw ValidationException::withMessages([
'new_email' => ['Dit e-mailadres is inmiddels in gebruik door een ander account.'],
]);
}
$user = $request->user;
$oldEmail = $user->email;
DB::transaction(function () use ($request, $user) {
// Update user email
$user->update(['email' => $request->new_email]);
// Mark request as verified
$request->update([
'status' => EmailChangeStatus::VERIFIED,
'verified_at' => now(),
]);
});
// Send confirmation to the OLD email address
Mail::to($oldEmail)->send(new EmailChangedConfirmationMail(
user: $user,
oldEmail: $oldEmail,
newEmail: $request->new_email,
));
// Revoke all tokens (force re-login with new email)
$user->tokens()->delete();
// Log linked person email context
$persons = Person::where('user_id', $user->id)->get();
foreach ($persons as $person) {
activity()
->causedBy($user)
->performedOn($person)
->withProperties([
'old_user_email' => $oldEmail,
'new_user_email' => $request->new_email,
'person_email_unchanged' => $person->email,
])
->log('person.linked_user_email_changed');
}
activity()
->performedOn($user)
->withProperties([
'old_email' => $oldEmail,
'new_email' => $request->new_email,
])
->log('user.email_changed');
return $request;
}
}