Skip to content

Beautiful Open-Source Form Builder

23.6 KB
Raw Blame
<?php

use App\Exceptions\PdfNotSupportedException;
use App\Models\Forms\Form;
use App\Models\PdfTemplate;
use App\Models\User;
use App\Models\Workspace;
use App\Service\Pdf\PdfContentRenderer;
use App\Service\Pdf\PdfGeneratorService;
use App\Service\Pdf\PdfImageRenderer;
use App\Service\Pdf\PdfImageResolver;
use App\Service\Pdf\PdfRichTextRenderer;
use App\Service\Storage\FileUploadPathService;
use App\Service\Storage\FilenameUrlEncoder;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Storage;
use setasign\Fpdi\Fpdi;

beforeEach(function () {
    Storage::fake('local');
});

function createTestForm(array $attributes = []): Form
{
    $user = User::factory()->create();
    $workspace = Workspace::create(['name' => 'Test Workspace', 'icon' => '📝']);
    $user->workspaces()->attach($workspace->id, ['role' => 'admin']);

    $defaultProps = [
        ['id' => 'name', 'name' => 'Name', 'type' => 'text'],
        ['id' => 'email', 'name' => 'Email', 'type' => 'email'],
    ];

    return Form::factory()
        ->forWorkspace($workspace)
        ->createdBy($user)
        ->withProperties($attributes['properties'] ?? $defaultProps)
        ->create(array_diff_key($attributes, ['properties' => true]));
}

describe('PdfGeneratorService', function () {
    it('generates a pdf from template and submission data', function () {
        // Create valid PDF template
        $pdfContent = createTestPdf();
        $templatePath = 'pdf-templates/1/template.pdf';
        Storage::put($templatePath, $pdfContent);

        $form = createTestForm();
        // Zone mappings and filename_pattern are stored on the template
        $template = PdfTemplate::create([
            'form_id' => $form->id,
            'name' => 'Test Template',
            'filename' => 'template.pdf',
            'original_filename' => 'Template.pdf',
            'file_path' => $templatePath,
            'file_size' => strlen($pdfContent),
            'page_count' => 1,
            'zone_mappings' => [],
            'filename_pattern' => PdfTemplate::DEFAULT_FILENAME_PATTERN,
        ]);

        $submission = $form->submissions()->create([
            'data' => ['name' => 'Test User'],
        ]);

        $service = new PdfGeneratorService();
        $resultPath = $service->generateFromTemplate($form, $submission, $template);

        expect($resultPath)->toStartWith('tmp/pdf-output/');
        expect($resultPath)->toEndWith('.pdf');
        expect(Storage::exists($resultPath))->toBeTrue();

        // Verify it's a valid PDF
        $content = Storage::get($resultPath);
        expect($content)->toStartWith('%PDF');
    });

    it('generates pdf with zone mappings', function () {
        $pdfContent = createTestPdf();
        $templatePath = 'pdf-templates/1/template.pdf';
        Storage::put($templatePath, $pdfContent);

        $form = createTestForm([
            'properties' => [
                [
                    'id' => 'field_name',
                    'name' => 'Name',
                    'type' => 'text',
                ],
            ],
        ]);

        // Zone mappings are now stored on the template
        $template = PdfTemplate::create([
            'form_id' => $form->id,
            'name' => 'Test Template',
            'filename' => 'template.pdf',
            'original_filename' => 'Template.pdf',
            'file_path' => $templatePath,
            'file_size' => strlen($pdfContent),
            'page_count' => 1,
            'zone_mappings' => [
                [
                    'id' => 'zone_1',
                    'page' => 1,
                    'x' => 10,
                    'y' => 20,
                    'width' => 50,
                    'height' => 10,
                    'field_id' => 'field_name',
                    'font_size' => 12,
                    'font_color' => '#FF0000',
                ],
            ],
            'filename_pattern' => 'output',
        ]);

        $submission = $form->submissions()->create([
            'data' => ['field_name' => 'John Doe'],
        ]);

        $service = new PdfGeneratorService();
        $resultPath = $service->generateFromTemplate($form, $submission, $template);

        expect(Storage::exists($resultPath))->toBeTrue();

        $content = Storage::get($resultPath);
        expect($content)->toStartWith('%PDF');
    });

    it('handles special fields in zone mappings', function () {
        $pdfContent = createTestPdf();
        $templatePath = 'pdf-templates/1/template.pdf';
        Storage::put($templatePath, $pdfContent);

        $form = createTestForm(['title' => 'Contact Form']);

        // Zone mappings with special fields are stored on the template
        $template = PdfTemplate::create([
            'form_id' => $form->id,
            'name' => 'Test Template',
            'filename' => 'template.pdf',
            'original_filename' => 'Template.pdf',
            'file_path' => $templatePath,
            'file_size' => strlen($pdfContent),
            'page_count' => 1,
            'zone_mappings' => [
                [
                    'id' => 'zone_form_name',
                    'page' => 1,
                    'x' => 10,
                    'y' => 10,
                    'width' => 50,
                    'height' => 10,
                    'field_id' => 'form_name',
                    'font_size' => 12,
                    'font_color' => '#000000',
                ],
                [
                    'id' => 'zone_submission_id',
                    'page' => 1,
                    'x' => 10,
                    'y' => 20,
                    'width' => 50,
                    'height' => 10,
                    'field_id' => 'submission_id',
                    'font_size' => 12,
                    'font_color' => '#000000',
                ],
                [
                    'id' => 'zone_submission_date',
                    'page' => 1,
                    'x' => 10,
                    'y' => 30,
                    'width' => 50,
                    'height' => 10,
                    'field_id' => 'submission_date',
                    'font_size' => 12,
                    'font_color' => '#000000',
                ],
            ],
            'filename_pattern' => 'output',
        ]);

        $submission = $form->submissions()->create([
            'data' => [],
        ]);

        $service = new PdfGeneratorService();
        $resultPath = $service->generateFromTemplate($form, $submission, $template);

        expect(Storage::exists($resultPath))->toBeTrue();
    });

    it('resolves computed variables in zone mappings', function () {
        $pdfContent = createTestPdf();
        $templatePath = 'pdf-templates/1/template.pdf';
        Storage::put($templatePath, $pdfContent);

        $form = createTestForm([
            'properties' => [
                ['id' => 'agree', 'name' => 'Agree', 'type' => 'checkbox'],
                ['id' => 'score', 'name' => 'Score', 'type' => 'number'],
            ],
            'computed_variables' => [
                [
                    'id' => 'cv_bool',
                    'name' => 'Bool Result',
                    'formula' => 'IF({agree}, TRUE, FALSE)',
                ],
                [
                    'id' => 'cv_label',
                    'name' => 'String Label',
                    'formula' => 'IF({agree}, "yes", "no")',
                ],
                [
                    'id' => 'cv_double',
                    'name' => 'Double Score',
                    'formula' => '{score} * 2',
                ],
            ],
        ]);

        $template = PdfTemplate::create([
            'form_id' => $form->id,
            'name' => 'Computed Variable Template',
            'filename' => 'template.pdf',
            'original_filename' => 'Template.pdf',
            'file_path' => $templatePath,
            'file_size' => strlen($pdfContent),
            'page_count' => 1,
            'page_manifest' => [
                ['id' => 'page-1', 'type' => 'source', 'source_page' => 1],
            ],
            'zone_mappings' => [
                [
                    'id' => 'zone_bool',
                    'page_id' => 'page-1',
                    'x' => 10,
                    'y' => 10,
                    'width' => 40,
                    'height' => 8,
                    'field_id' => 'cv_bool',
                    'font_size' => 12,
                    'font_color' => '#000000',
                ],
                [
                    'id' => 'zone_double',
                    'page_id' => 'page-1',
                    'x' => 10,
                    'y' => 25,
                    'width' => 40,
                    'height' => 8,
                    'field_id' => 'cv_double',
                    'font_size' => 12,
                    'font_color' => '#000000',
                ],
            ],
            'filename_pattern' => 'output',
        ]);

        $submission = $form->submissions()->create([
            'data' => [
                'agree' => true,
                'score' => 21,
            ],
        ]);

        $service = new PdfGeneratorService();

        $method = new ReflectionMethod(PdfGeneratorService::class, 'getFormattedSubmissionData');
        $formattedData = $method->invoke($service, $form, $submission);

        // Booleans → Yes/No; explicit formula strings kept as written
        expect($formattedData['cv_bool'])->toBe('Yes')
            ->and($formattedData['cv_label'])->toBe('yes')
            ->and($formattedData['cv_double'])->toBe(42.0);

        $resultPath = $service->generateFromTemplate($form, $submission, $template);

        expect(Storage::exists($resultPath))->toBeTrue();
        expect(Storage::get($resultPath))->toStartWith('%PDF');
    });

    it('uses default filename pattern when not specified', function () {
        $pdfContent = createTestPdf();
        $templatePath = 'pdf-templates/1/template.pdf';
        Storage::put($templatePath, $pdfContent);

        $form = createTestForm(['title' => 'My Form']);

        // Template without explicit filename_pattern
        $template = PdfTemplate::create([
            'form_id' => $form->id,
            'name' => 'Test Template',
            'filename' => 'template.pdf',
            'original_filename' => 'Template.pdf',
            'file_path' => $templatePath,
            'file_size' => strlen($pdfContent),
            'page_count' => 1,
            'zone_mappings' => [],
            // No filename_pattern - should use default
        ]);

        $submission = $form->submissions()->create([
            'data' => [],
        ]);

        $service = new PdfGeneratorService();
        $resultPath = $service->generateFromTemplate($form, $submission, $template);

        expect(Storage::exists($resultPath))->toBeTrue();
    });

    it('generates pdf with static image from unsplash-like url', function () {
        Http::fake([
            'https://images.unsplash.com/*' => Http::response(
                tinyPngBytes(),
                200,
                ['Content-Type' => 'image/png']
            ),
        ]);

        $pdfContent = createTestPdf();
        $templatePath = 'pdf-templates/1/template.pdf';
        Storage::put($templatePath, $pdfContent);

        $form = createTestForm();

        $template = PdfTemplate::create([
            'form_id' => $form->id,
            'name' => 'Image URL Template',
            'filename' => 'template.pdf',
            'original_filename' => 'Template.pdf',
            'file_path' => $templatePath,
            'file_size' => strlen($pdfContent),
            'page_count' => 1,
            'page_manifest' => [
                ['id' => 'page-1', 'type' => 'source', 'source_page' => 1],
            ],
            'zone_mappings' => [
                [
                    'id' => 'zone_static_image',
                    'page_id' => 'page-1',
                    'x' => 10,
                    'y' => 10,
                    'width' => 20,
                    'height' => 20,
                    'static_image' => 'https://images.unsplash.com/photo-12345?auto=format&fit=crop&w=900&q=80',
                ],
            ],
            'filename_pattern' => 'output',
        ]);

        $submission = $form->submissions()->create([
            'data' => [],
        ]);

        $service = new PdfGeneratorService();
        $resultPath = $service->generateFromTemplate($form, $submission, $template);

        expect(Storage::exists($resultPath))->toBeTrue();
        expect(Storage::get($resultPath))->toStartWith('%PDF');
        Http::assertSentCount(1);
    });

    it('generates a PDF with both a legacy encoded upload and a signature', function () {
        $pdfContent = createTestPdf();
        $templatePath = 'pdf-templates/1/template.pdf';
        Storage::put($templatePath, $pdfContent);

        $form = createTestForm([
            'properties' => [
                ['id' => 'receipt', 'name' => 'Receipt', 'type' => 'files'],
                ['id' => 'signature', 'name' => 'Signature', 'type' => 'signature'],
            ],
        ]);
        $receiptFileName = 'receipt_550e8400-e29b-41d4-a716-446655440000.png';
        $signatureFileName = 'sign_550e8400-e29b-41d4-a716-446655440001.png';
        Storage::put(FileUploadPathService::getFileUploadPath($form->id, $receiptFileName), tinyPngBytes());
        Storage::put(FileUploadPathService::getFileUploadPath($form->id, $signatureFileName), tinyPngBytes());

        $template = PdfTemplate::create([
            'form_id' => $form->id,
            'name' => 'Upload and signature template',
            'filename' => 'template.pdf',
            'original_filename' => 'Template.pdf',
            'file_path' => $templatePath,
            'file_size' => strlen($pdfContent),
            'page_count' => 1,
            'page_manifest' => [
                ['id' => 'page-1', 'type' => 'source', 'source_page' => 1],
            ],
            'zone_mappings' => [
                ['id' => 'receipt-zone', 'page_id' => 'page-1', 'field_id' => 'receipt', 'x' => 10, 'y' => 10, 'width' => 30, 'height' => 20],
                ['id' => 'signature-zone', 'page_id' => 'page-1', 'field_id' => 'signature', 'x' => 50, 'y' => 10, 'width' => 30, 'height' => 20],
            ],
            'filename_pattern' => 'output',
        ]);

        $submission = $form->submissions()->create([
            'data' => [
                'receipt' => [FilenameUrlEncoder::encode($receiptFileName)],
                'signature' => $signatureFileName,
            ],
        ]);

        $resultPath = (new PdfGeneratorService())->generateFromTemplate($form, $submission, $template);
        $result = Storage::get($resultPath);

        expect($result)->toStartWith('%PDF')
            ->and(substr_count($result, '/Subtype /Image'))->toBeGreaterThanOrEqual(2);
    });
});

describe('PdfNotSupportedException', function () {
    it('has correct default message', function () {
        $exception = new PdfNotSupportedException();

        expect($exception->getMessage())->toContain('PDF');
        expect($exception->getMessage())->toContain('compression');
    });

    it('accepts custom message', function () {
        $exception = new PdfNotSupportedException('Custom error message');

        expect($exception->getMessage())->toBe('Custom error message');
    });
});

describe('Image resolving', function () {
    it('resolves image content from storage for form uploads', function () {
        $form = createTestForm();
        $fileName = 'avatar-test.png';
        Storage::put("forms/{$form->id}/submissions/{$fileName}", 'img-bytes');

        $resolver = new PdfImageResolver($form);
        $content = $resolver->resolveContent($fileName);

        expect($content)->toBe('img-bytes');
    });

    it('does not fetch unsafe remote image urls', function () {
        Http::fake();

        $resolver = new PdfImageResolver();

        $content = $resolver->resolveContent('https://169.254.169.254/latest/meta-data/');

        expect($content)->toBeNull();
        Http::assertNothingSent();
    });

    it('resolves local asset urls from storage without remote fetch', function () {
        Http::fake();
        Storage::put('assets/forms/image.png', 'stored-image-bytes');

        $resolver = new PdfImageResolver();
        $content = $resolver->resolveContent(route('forms.assets.show', ['image.png']));

        expect($content)->toBe('stored-image-bytes');
        Http::assertNothingSent();
    });
});

describe('PdfContentRenderer scalar values', function () {
    it('renders numeric values without dropping them', function () {
        $renderer = PdfContentRenderer::forForm(null);
        $pdf = new Fpdi();
        $pdf->AddPage();

        $renderer->renderContent(
            $pdf,
            12345,
            10,
            10,
            80,
            20,
            ['font_size' => 12, 'font_color' => '#000000'],
            210
        );

        $content = $pdf->Output('S');
        expect($content)->toStartWith('%PDF');
    });

    it('does not render unresolved static image values as text', function () {
        $imageResolver = new class () extends PdfImageResolver {
            public function resolveContent(string $imageValue): ?string
            {
                return null;
            }
        };

        $richTextRenderer = new class () extends PdfRichTextRenderer {
            public bool $rendered = false;

            public function render(
                Fpdi $pdf,
                string $text,
                float $x,
                float $y,
                float $width,
                float $height,
                array $zone,
                float $pageWidth
            ): void {
                $this->rendered = true;
            }
        };

        $renderer = new PdfContentRenderer(
            null,
            $imageResolver,
            new PdfImageRenderer(),
            $richTextRenderer
        );
        $pdf = new Fpdi();
        $pdf->AddPage();

        $renderer->renderContent(
            $pdf,
            'https://example.com/image.png',
            10,
            10,
            80,
            20,
            ['static_image' => 'https://example.com/image.png'],
            210
        );

        expect($richTextRenderer->rendered)->toBeFalse();
    });

    it('renders encoded upload names as images instead of PDF text', function () {
        $imageResolver = new class () extends PdfImageResolver {
            public array $resolvedValues = [];

            public function resolveContent(string $imageValue): ?string
            {
                $this->resolvedValues[] = $imageValue;

                return tinyPngBytes();
            }
        };

        $imageRenderer = new class () extends PdfImageRenderer {
            public ?string $renderedContent = null;

            public function render(
                Fpdi $pdf,
                string $imageContent,
                float $x,
                float $y,
                float $width,
                float $height
            ): void {
                $this->renderedContent = $imageContent;
            }
        };

        $richTextRenderer = new class () extends PdfRichTextRenderer {
            public bool $rendered = false;

            public function render(
                Fpdi $pdf,
                string $text,
                float $x,
                float $y,
                float $width,
                float $height,
                array $zone,
                float $pageWidth
            ): void {
                $this->rendered = true;
            }
        };

        $renderer = new PdfContentRenderer(null, $imageResolver, $imageRenderer, $richTextRenderer);
        $pdf = new Fpdi();
        $pdf->AddPage();
        $encodedFileName = FilenameUrlEncoder::encode('receipt_550e8400-e29b-41d4-a716-446655440000.png');

        $renderer->renderContent(
            $pdf,
            $encodedFileName,
            10,
            10,
            80,
            20,
            ['font_size' => 12, 'font_color' => '#000000'],
            210
        );

        expect($imageResolver->resolvedValues)->toBe([$encodedFileName])
            ->and($imageRenderer->renderedContent)->toBe(tinyPngBytes())
            ->and($richTextRenderer->rendered)->toBeFalse();
    });

    it('renders inline rich text segments without dropping styled required marks', function () {
        $renderer = new PdfRichTextRenderer();
        $pdf = new class () extends Fpdi {
            public array $cells = [];
            private array $currentColor = [0, 0, 0];
            private string $currentStyle = '';

            public function SetTextColor($r, $g = null, $b = null)
            {
                $this->currentColor = [(int) $r, (int) $g, (int) $b];
                parent::SetTextColor($r, $g, $b);
            }

            public function SetFont($family, $style = '', $size = 0)
            {
                $this->currentStyle = $style;
                parent::SetFont($family, $style, $size);
            }

            public function Cell($w, $h = 0, $txt = '', $border = 0, $ln = 0, $align = '', $fill = false, $link = '')
            {
                $this->cells[] = [
                    'text' => $txt,
                    'x' => $this->GetX(),
                    'y' => $this->GetY(),
                    'color' => $this->currentColor,
                    'style' => $this->currentStyle,
                ];
                parent::Cell($w, $h, $txt, $border, $ln, $align, $fill, $link);
            }
        };
        $pdf->AddPage();

        $renderer->render(
            $pdf,
            'Name <strong style="color: #EF4444">*</strong>',
            10,
            10,
            80,
            8,
            ['font_size' => 10, 'font_color' => '#374151'],
            210
        );

        $nameCell = collect($pdf->cells)->firstWhere('text', 'Name');
        $starCell = collect($pdf->cells)->firstWhere('text', '*');

        expect($nameCell)->not->toBeNull();
        expect($starCell)->not->toBeNull();
        expect($starCell['y'])->toBe($nameCell['y']);
        expect($starCell['color'])->toBe([239, 68, 68]);
        expect($starCell['style'])->toContain('B');
    });

    it('encodes rich text cells as Windows-1252 for FPDF core fonts', function () {
        $renderer = new PdfRichTextRenderer();
        $pdf = new class () extends Fpdi {
            public array $cells = [];
            public array $widthTexts = [];

            public function GetStringWidth($s)
            {
                $this->widthTexts[] = $s;

                return parent::GetStringWidth($s);
            }

            public function Cell($w, $h = 0, $txt = '', $border = 0, $ln = 0, $align = '', $fill = false, $link = '')
            {
                $this->cells[] = $txt;

                parent::Cell($w, $h, $txt, $border, $ln, $align, $fill, $link);
            }
        };
        $pdf->AddPage();

        $renderer->render(
            $pdf,
            '<p>Délivrée&nbsp;été</p>',
            10,
            10,
            80,
            8,
            ['font_size' => 10, 'font_color' => '#374151'],
            210
        );

        $cellText = implode('', $pdf->cells);

        expect(bin2hex($cellText))->toBe('44e96c697672e965a0e974e9');
        expect(mb_convert_encoding($cellText, 'UTF-8', 'Windows-1252'))->toBe("Délivrée\u{00A0}été");
        expect($pdf->widthTexts)->toBe($pdf->cells);
    });
});

/**
 * Helper to create a valid test PDF.
 */
function createTestPdf(): string
{
    $pdf = new \setasign\Fpdi\Fpdi();
    $pdf->AddPage();
    $pdf->SetFont('Helvetica', '', 12);
    $pdf->Cell(0, 10, 'Test PDF');

    return $pdf->Output('S');
}

function tinyPngBytes(): string
{
    return base64_decode(
        'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/w8AAgMBAQEAAP8AAAAASUVORK5CYII=',
        true
    ) ?: '';
}