Files
crewli/api/app/Http/Controllers/Api/V1/OrganisationEmailTemplateController.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

189 lines
6.1 KiB
PHP

<?php
declare(strict_types=1);
namespace App\Http\Controllers\Api\V1;
use App\Enums\EmailTemplateType;
use App\Http\Controllers\Controller;
use App\Http\Requests\Api\V1\UpdateEmailTemplateRequest;
use App\Models\Organisation;
use App\Models\OrganisationEmailTemplate;
use App\Services\EmailService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\View;
final class OrganisationEmailTemplateController extends Controller
{
public function __construct(
private readonly EmailService $emailService,
) {}
public function index(Organisation $organisation): JsonResponse
{
Gate::authorize('update', $organisation);
$templates = $this->emailService->getAllTemplates($organisation);
return $this->success($templates);
}
public function show(Organisation $organisation, string $type): JsonResponse
{
Gate::authorize('update', $organisation);
$templateType = $this->resolveType($type);
$template = $this->emailService->resolveTemplate($templateType, $organisation);
$template['type'] = $templateType->value;
$template['label'] = $templateType->label();
$template['defaults'] = $templateType->defaults();
return $this->success($template);
}
public function update(UpdateEmailTemplateRequest $request, Organisation $organisation, string $type): JsonResponse
{
Gate::authorize('update', $organisation);
$templateType = $this->resolveType($type);
$template = OrganisationEmailTemplate::updateOrCreate(
[
'organisation_id' => $organisation->id,
'type' => $templateType->value,
],
$request->validated(),
);
activity('email_template')
->performedOn($template)
->causedBy($request->user())
->withProperties(['type' => $templateType->value])
->log('email_template.updated');
$result = $this->emailService->resolveTemplate($templateType, $organisation);
$result['type'] = $templateType->value;
$result['label'] = $templateType->label();
$result['defaults'] = $templateType->defaults();
return $this->success($result);
}
public function destroy(Organisation $organisation, string $type): JsonResponse
{
Gate::authorize('update', $organisation);
$templateType = $this->resolveType($type);
OrganisationEmailTemplate::where('organisation_id', $organisation->id)
->where('type', $templateType->value)
->delete();
activity('email_template')
->causedBy(request()->user())
->withProperties(['type' => $templateType->value])
->log('email_template.reset_to_default');
return $this->success(message: 'Template reset naar standaard.');
}
public function preview(Organisation $organisation, string $type): JsonResponse
{
Gate::authorize('update', $organisation);
$templateType = $this->resolveType($type);
$sampleVariables = [
'organisation_name' => $organisation->name,
'event_name' => 'Voorbeeldevenement',
'shift_title' => 'Bar medewerker',
'shift_date' => '15 juni 2026',
'shift_start' => '14:00',
'shift_end' => '22:00',
'section_name' => 'Hoofdpodium Bar',
];
$template = $this->emailService->resolveTemplate($templateType, $organisation);
// Substitute sample variables
foreach ($template as $key => $value) {
if (is_string($value)) {
foreach ($sampleVariables as $var => $replacement) {
$value = str_replace('{' . $var . '}', $replacement, $value);
}
$template[$key] = $value;
}
}
$branding = $this->emailService->resolveBranding($organisation);
$html = View::make('emails.transactional', [
'heading' => $template['heading'],
'bodyText' => $template['body_text'],
'buttonText' => $template['button_text'],
'actionUrl' => 'https://crewli.app/example',
'logoUrl' => $branding['logo_url'],
'primaryColor' => $branding['primary_color'],
'secondaryColor' => $branding['secondary_color'],
'footerText' => $branding['footer_text'],
])->render();
return $this->success(['html' => $html]);
}
public function sendTest(Request $request, Organisation $organisation, string $type): JsonResponse
{
Gate::authorize('update', $organisation);
$request->validate([
'email' => ['required', 'email'],
]);
$templateType = $this->resolveType($type);
$sampleVariables = [
'organisation_name' => $organisation->name,
'event_name' => 'Voorbeeldevenement',
'shift_title' => 'Bar medewerker',
'shift_date' => '15 juni 2026',
'shift_start' => '14:00',
'shift_end' => '22:00',
'section_name' => 'Hoofdpodium Bar',
];
$this->emailService->send(
type: $templateType,
recipientEmail: $request->input('email'),
recipientName: 'Test Ontvanger',
variables: $sampleVariables,
actionUrl: 'https://crewli.app/example',
organisation: $organisation,
triggeredByUserId: $request->user()->id,
);
activity('email_template')
->causedBy($request->user())
->withProperties([
'type' => $templateType->value,
'test_email' => $request->input('email'),
])
->log('email.test_sent');
return $this->success(message: 'Testmail verzonden naar ' . $request->input('email') . '.');
}
private function resolveType(string $type): EmailTemplateType
{
$templateType = EmailTemplateType::tryFrom($type);
if (! $templateType) {
abort(404, 'Onbekend template type.');
}
return $templateType;
}
}