Skip to content

Beautiful Open-Source Form Builder

8.3 KB
Raw Blame
<?php

namespace App\Integrations\Handlers;

use App\Models\Integration\FormIntegration;
use App\Events\Forms\FormSubmitted;
use App\Models\Forms\Form;
use App\Models\Integration\FormIntegrationsEvent;
use App\Service\Forms\FormSubmissionFormatter;
use App\Service\Forms\FormLogicConditionChecker;
use App\Service\Forms\SubmissionUrlService;
use App\Service\Formulas\ComputedVariableEvaluator;
use App\Service\Security\PublicWebhookUrl;
use Illuminate\Http\Client\RequestException;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

abstract class AbstractIntegrationHandler
{
    protected $form = null;
    protected $submissionData = null;
    protected array $submissionMeta = [];
    protected $integrationData = null;
    protected $provider = null;
    protected ?array $computedValues = null;

    public function __construct(
        protected FormSubmitted $event,
        protected FormIntegration $formIntegration,
        protected array $integration
    ) {
        $this->form = $event->form;
        $this->submissionData = $event->data;
        $this->submissionMeta = $event->meta;
        $this->integrationData = $formIntegration->data;
        $this->provider = $formIntegration->provider;
    }

    /**
     * Get computed variable values for this submission
     */
    protected function getComputedValues(): array
    {
        if ($this->computedValues === null) {
            $this->computedValues = ComputedVariableEvaluator::evaluateForSubmission(
                $this->form,
                $this->submissionData
            );
        }
        return $this->computedValues;
    }

    protected function getProviderName(): string
    {
        return $this->integration['name'] ?? '';
    }

    protected function logicConditionsMet(): bool
    {
        if (!$this->formIntegration->logic || empty((array) $this->formIntegration->logic)) {
            return true;
        }
        return FormLogicConditionChecker::conditionsMetWithForm(
            json_decode(json_encode($this->formIntegration->logic), true),
            $this->submissionData,
            $this->form
        );
    }

    protected function shouldRun(): bool
    {
        return $this->logicConditionsMet();
    }

    protected function getWebhookUrl(): ?string
    {
        return '';
    }

    /**
     * Default webhook payload. Can be changed in child classes.
     */
    protected function getWebhookData(): array
    {
        return self::formatWebhookData($this->form, $this->submissionData, $this->submissionMeta);
    }

    public function run(?FormIntegrationsEvent $attempt = null): FormIntegrationsEvent
    {
        $eventMetadata = $this->getEventMetadata();

        try {
            if (!$this->shouldRun()) {
                $attributes = [
                    'status' => 'skipped',
                    'data' => array_merge($eventMetadata, ['message' => 'Integration conditions were not met. No request was sent.']),
                ];
            } else {
                $this->handle();
                $attributes = [
                    'status' => FormIntegrationsEvent::STATUS_SUCCESS,
                    'data' => $eventMetadata,
                ];
            }
        } catch (\Exception $e) {
            $attributes = [
                'status' => FormIntegrationsEvent::STATUS_ERROR,
                'data' => array_merge($eventMetadata, $this->extractEventDataFromException($e)),
            ];
            Log::error('Integration failed', array_merge([
                'form_id' => $this->form->id,
                'integration_id' => $this->formIntegration->id,
            ], $this->extractEventDataFromException($e)));
        }

        try {
            return $this->recordEvent($attributes, $attempt);
        } catch (\Exception $exception) {
            if ($attempt) {
                // Keep the durable retry reservation and never classify storage errors as delivery failures.
                throw $exception;
            }

            Log::error('Could not record integration outcome', [
                'form_id' => $this->form->id,
                'integration_id' => $this->formIntegration->id,
                'exception_type' => get_class($exception),
            ]);

            // A recoverable history write failure must not prevent the other integrations from running.
            return $this->recordEvent([
                'status' => 'unknown',
                'data' => array_merge($attributes['data'] ?? [], [
                    'message' => 'The integration outcome could not be recorded. Check the destination before sending again.',
                ]),
            ]);
        }
    }

    protected function recordEvent(array $attributes, ?FormIntegrationsEvent $attempt = null): FormIntegrationsEvent
    {
        if (!$attempt) {
            return $this->formIntegration->events()->create($attributes);
        }

        $attributes['data'] = array_merge((array) $attempt->data, $attributes['data'] ?? []);
        $attempt->update($attributes);
        if ($attempt->status === FormIntegrationsEvent::STATUS_ERROR) {
            \App\Events\Models\FormIntegrationsEventCreated::dispatch($attempt);
        }

        return $attempt;
    }

    public function created(): void
    {
        //
    }

    /**
     * Default handle. Can be changed in child classes.
     */
    public function handle(): void
    {
        if (!$this->shouldRun()) {
            return;
        }

        $url = $this->getWebhookUrl();

        Http::throw()
            ->withOptions(PublicWebhookUrl::requestOptions($url))
            ->post($url, $this->getWebhookData());
    }

    abstract public static function getValidationRules(?Form $form): array;

    public static function isOAuthRequired(): bool
    {
        return false;
    }

    public static function getValidationAttributes(): array
    {
        return [];
    }

    public static function formatWebhookData(Form $form, array $submissionData, array $submissionMeta = []): array
    {
        $formatter = (new FormSubmissionFormatter($form, $submissionData))
            ->useSignedUrlForFiles()
            ->showHiddenFields();

        // Old format - kept for retro-compatibility
        $oldFormatData = [];
        $formattedData = [];
        $fieldsWithValue = $formatter->getFieldsWithValue();

        foreach ($fieldsWithValue as $field) {
            $oldFormatData[$field['name']] = $field['value'];
            // New format using ID
            $formattedData[$field['id']] = [
                'value' => $field['value'],
                'name' => $field['name'],
                'type' => $field['type']
            ];
        }

        $data = [
            'form_id' => $form->id,
            'form_title' => $form->title,
            'form_slug' => $form->slug,
            'submission' => $oldFormatData,
            'data' => $formattedData,
            'message' => 'Please do not use the `submission` field. It is deprecated and will be removed in the future.'
        ];
        if (isset($submissionData['submission_id'])) {
            $data['submission_id'] = $submissionData['submission_id'];
        }
        if ($form->workspace?->hasFeature('editable_submissions') && $form->editable_submissions && isset($submissionData['submission_id'])) {
            $data['edit_link'] = SubmissionUrlService::buildEditUrl($form, $submissionData['submission_id']);
        }

        $attribution = $submissionMeta['attribution'] ?? null;
        if (is_array($attribution) && !empty($attribution)) {
            $data['meta'] = ['attribution' => $attribution];
        }

        return $data;
    }

    protected function getEventMetadata(): array
    {
        if (!isset($this->submissionData['submission_id'])) {
            return [];
        }

        return [
            'submission_id' => $this->submissionData['submission_id'],
        ];
    }

    public function extractEventDataFromException(\Exception $e): array
    {
        if ($e instanceof RequestException) {
            return [
                'message' => $e->getMessage(),
                'response' => $e->response->json(),
                'status' => $e->response->status(),
            ];
        }
        return [
            'message' => $e->getMessage()
        ];
    }

    /**
     * Used in FormIntegrationRequest to format integration
     */
    public static function formatData(array $data): array
    {
        return $data;
    }
}