Skip to content

Open-source event management and ticket selling platform — perfect for concerts, conferences, and everything in between 🎟️ If you find this project helpful, please consider giving us a star ⭐️

3.5 KB
Raw Blame
<?php

namespace HiEvents\Http\Actions\EmailTemplates;

use HiEvents\DomainObjects\Enums\EmailTemplateType;
use HiEvents\DomainObjects\EventDomainObject;
use HiEvents\Exceptions\AccountNotVerifiedException;
use HiEvents\Exceptions\EmailTemplateNotFoundException;
use HiEvents\Exceptions\EmailTemplateValidationException;
use HiEvents\Exceptions\InvalidEmailTemplateException;
use HiEvents\Http\Resources\EmailTemplateResource;
use HiEvents\Http\ResponseCodes;
use HiEvents\Repository\Interfaces\EmailTemplateRepositoryInterface;
use HiEvents\Services\Application\Handlers\EmailTemplate\DTO\UpsertEmailTemplateDTO;
use HiEvents\Services\Application\Handlers\EmailTemplate\UpdateEmailTemplateHandler;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Validation\ValidationException;
use Symfony\Component\HttpFoundation\Response;

class UpdateEventEmailTemplateAction extends BaseEmailTemplateAction
{
    public function __construct(
        private readonly UpdateEmailTemplateHandler $handler,
        private readonly EmailTemplateRepositoryInterface $emailTemplateRepository,
    ) {}

    /**
     * @throws ValidationException
     */
    public function __invoke(Request $request, int $eventId, int $templateId): JsonResponse
    {
        $this->isActionAuthorized($eventId, EventDomainObject::class);

        try {
            $this->verifyAccountCanModifyEmailTemplates();
        } catch (AccountNotVerifiedException $e) {
            return $this->errorResponse($e->getMessage(), Response::HTTP_UNAUTHORIZED);
        }

        $validated = $this->validateUpdateEmailTemplateRequest($request);

        try {
            $existingTemplate = $this->emailTemplateRepository->findFirstWhere([
                'id' => $templateId,
                'account_id' => $this->getAuthenticatedAccountId(),
                'event_id' => $eventId,
                'organizer_id' => null,
            ]);

            if ($existingTemplate === null) {
                throw new EmailTemplateNotFoundException(__('Email template not found'));
            }

            $templateType = EmailTemplateType::from($existingTemplate->getTemplateType());

            $cta = [
                'label' => $validated['ctaLabel'],
                'url_token' => $templateType->ctaUrlToken(),
            ];

            $template = $this->handler->handle(
                new UpsertEmailTemplateDTO(
                    account_id: $this->getAuthenticatedAccountId(),
                    template_type: $templateType,
                    subject: $validated['subject'],
                    body: $validated['body'],
                    organizer_id: null,
                    event_id: $eventId,
                    id: $templateId,
                    cta: $cta,
                    is_active: $validated['isActive'] ?? true,
                )
            );
        } catch (EmailTemplateValidationException $e) {
            throw ValidationException::withMessages($e->validationErrors ?: ['body' => $e->getMessage()]);
        } catch (InvalidEmailTemplateException $e) {
            throw ValidationException::withMessages([
                'id' => $e->getMessage(),
            ]);
        } catch (EmailTemplateNotFoundException $e) {
            return $this->errorResponse(
                message: $e->getMessage(),
                statusCode: ResponseCodes::HTTP_NOT_FOUND,
            );
        }

        return $this->resourceResponse(
            resource: EmailTemplateResource::class,
            data: $template,
        );
    }
}