Skip to content

Beautiful Open-Source Form Builder

Enhance PDF generation with computed variable support (#1233)

Chirag Chhatralaa580a1cf1d4b
diff --git a/api/app/Rules/PdfZoneMappingsRule.php b/api/app/Rules/PdfZoneMappingsRule.php
index 018bc87b6..f633756d3 100644
--- a/api/app/Rules/PdfZoneMappingsRule.php
+++ b/api/app/Rules/PdfZoneMappingsRule.php
@@ -30,14 +30,20 @@ class PdfZoneMappingsRule implements ValidationRule
return;
}
- // Get valid field IDs from form properties
+ // Get valid field IDs and computed variable IDs from the form
$validFieldIds = [];
- if ($this->form && is_array($this->form->properties)) {
- $validFieldIds = array_column($this->form->properties, 'id');
+ $validComputedVariableIds = [];
+ if ($this->form) {
+ if (is_array($this->form->properties)) {
+ $validFieldIds = array_column($this->form->properties, 'id');
+ }
+ if (is_array($this->form->computed_variables)) {
+ $validComputedVariableIds = array_column($this->form->computed_variables, 'id');
+ }
}
foreach ($value as $index => $zone) {
- $this->validateZone($zone, $index, $validFieldIds);
+ $this->validateZone($zone, $index, $validFieldIds, $validComputedVariableIds);
}
if (!empty($this->errors)) {
@@ -48,7 +54,7 @@ class PdfZoneMappingsRule implements ValidationRule
/**
* Validate a single zone.
*/
- private function validateZone(mixed $zone, int $index, array $validFieldIds): void
+ private function validateZone(mixed $zone, int $index, array $validFieldIds, array $validComputedVariableIds = []): void
{
if (!is_array($zone)) {
$this->errors[] = "Zone at index {$index} must be an array";
@@ -79,10 +85,15 @@ class PdfZoneMappingsRule implements ValidationRule
}
// Either field_id, static_text, or static_image must be present (key existence defines zone type)
- $hasFieldId = isset($zone['field_id']) && $zone['field_id'] !== '';
+ $fieldId = $zone['field_id'] ?? null;
+ $hasFieldId = is_string($fieldId) && trim($fieldId) !== '';
$hasStaticText = array_key_exists('static_text', $zone);
$hasStaticImage = array_key_exists('static_image', $zone);
+ if (array_key_exists('field_id', $zone) && $fieldId !== null && $fieldId !== '' && !$hasFieldId) {
+ $this->errors[] = "Zone {$index}: field_id must be a non-empty string";
+ }
+
if (!$hasFieldId && !$hasStaticText && !$hasStaticImage) {
$this->errors[] = "Zone {$index}: must have 'field_id', 'static_text', or 'static_image'";
}
@@ -98,12 +109,15 @@ class PdfZoneMappingsRule implements ValidationRule
$this->errors[] = "Static image should not be empty";
}
- // If field_id is set and we have valid IDs, validate it exists
- if ($hasFieldId && !empty($validFieldIds) && !in_array($zone['field_id'], $validFieldIds)) {
- // Allow special fields like submission_id, submission_date, form_name
+ // If field_id is set and we have a form context, validate it exists
+ if ($hasFieldId && $this->form !== null) {
$specialFields = ['submission_id', 'submission_date', 'form_name'];
- if (!in_array($zone['field_id'], $specialFields)) {
- $this->errors[] = "Zone {$index}: field_id '{$zone['field_id']}' does not exist in form";
+ $isValidField = in_array($fieldId, $validFieldIds, true);
+ $isSpecialField = in_array($fieldId, $specialFields, true);
+ $isComputedVariable = in_array($fieldId, $validComputedVariableIds, true);
+
+ if (!$isValidField && !$isSpecialField && !$isComputedVariable) {
+ $this->errors[] = "Zone {$index}: field_id '{$fieldId}' does not exist in form";
}
}
diff --git a/api/app/Service/Pdf/PdfCacheService.php b/api/app/Service/Pdf/PdfCacheService.php
index 2ad16c63c..4ee4d499d 100644
--- a/api/app/Service/Pdf/PdfCacheService.php
+++ b/api/app/Service/Pdf/PdfCacheService.php
@@ -58,7 +58,8 @@ class PdfCacheService
/**
* Generate a unique cache key for template-based PDF.
- * Includes template updated_at to automatically invalidate when template changes.
+ * Includes template updated_at and computed variable definitions so all inputs
+ * that affect the generated content invalidate the cached PDF.
*/
private function getTemplateCacheKey(
Form $form,
@@ -66,13 +67,15 @@ class PdfCacheService
PdfTemplate $template
): string {
$templateVersion = $template->updated_at->timestamp;
+ $computedVariablesVersion = hash('sha256', serialize($form->computed_variables ?? []));
return sprintf(
- 'pdf:%d:%d:%d:%d',
+ 'pdf:%d:%d:%d:%d:%s',
$form->id,
$submission->id,
$template->id,
- $templateVersion
+ $templateVersion,
+ $computedVariablesVersion
);
}
diff --git a/api/app/Service/Pdf/PdfGeneratorService.php b/api/app/Service/Pdf/PdfGeneratorService.php
index 005a5d990..53b7e1559 100644
--- a/api/app/Service/Pdf/PdfGeneratorService.php
+++ b/api/app/Service/Pdf/PdfGeneratorService.php
@@ -8,6 +8,7 @@ use App\Models\Forms\FormSubmission;
use App\Models\PdfTemplate;
use App\Service\Branding\BrandingPolicy;
use App\Service\Forms\FormSubmissionFormatter;
+use App\Service\Formulas\ComputedVariableEvaluator;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use setasign\Fpdi\Fpdi;
@@ -199,7 +200,7 @@ class PdfGeneratorService
$value = $this->getFieldValue($fieldId, $submissionData);
}
- if (empty($value)) {
+ if ($value === null || $value === '') {
return;
}
@@ -216,10 +217,14 @@ class PdfGeneratorService
/**
* Get field value from submission data.
*/
- private function getFieldValue(string $fieldId, array $submissionData): mixed
+ private function getFieldValue(?string $fieldId, array $submissionData): mixed
{
- // Check for direct field match
- if (isset($submissionData[$fieldId])) {
+ if ($fieldId === null || $fieldId === '') {
+ return null;
+ }
+
+ // Check for direct field / computed variable match
+ if (array_key_exists($fieldId, $submissionData)) {
return $submissionData[$fieldId];
}
@@ -241,7 +246,7 @@ class PdfGeneratorService
{
$formatter = new FormSubmissionFormatter($form, $submission->data);
$formatted = $formatter->outputStringsOnly()->showHiddenFields()->getFieldsWithValue();
- $rawData = $submission->data;
+ $rawData = $submission->data ?? [];
$data = [];
foreach ($formatted as $field) {
@@ -260,6 +265,37 @@ class PdfGeneratorService
$data['submission_date'] = $submission->created_at ? $submission->created_at->format('Y-m-d H:i:s') : now()->format('Y-m-d H:i:s');
$data['form_name'] = $form->title;
+ // Add computed variable values evaluated from raw submission data
+ foreach (ComputedVariableEvaluator::evaluateForSubmission($form, $rawData) as $variableId => $value) {
+ $data[$variableId] = $this->formatComputedValue($value);
+ }
+
return $data;
}
+
+ /**
+ * Format a computed variable value for PDF rendering.
+ *
+ * Booleans become Yes/No (same as mentions/summaries).
+ * Explicit formula string/number results are left unchanged — e.g.
+ * IF(..., "yes", "no") stays "yes", while IF(..., TRUE, FALSE) becomes "Yes".
+ */
+ private function formatComputedValue(mixed $value): mixed
+ {
+ if (is_bool($value)) {
+ return $value ? 'Yes' : 'No';
+ }
+
+ if (is_array($value)) {
+ return implode(', ', array_map(function ($item) {
+ if (is_bool($item)) {
+ return $item ? 'Yes' : 'No';
+ }
+
+ return is_scalar($item) ? (string) $item : '';
+ }, $value));
+ }
+
+ return $value;
+ }
}
diff --git a/api/tests/Feature/Integrations/Pdf/PdfCacheServiceTest.php b/api/tests/Feature/Integrations/Pdf/PdfCacheServiceTest.php
index eda5ef6cb..bc68ff2d5 100644
--- a/api/tests/Feature/Integrations/Pdf/PdfCacheServiceTest.php
+++ b/api/tests/Feature/Integrations/Pdf/PdfCacheServiceTest.php
@@ -185,6 +185,50 @@ describe('PdfCacheService', function () {
expect(Storage::exists($path1))->toBeTrue();
expect(Storage::exists($path2))->toBeTrue();
});
+
+ it('invalidates cache when computed variable definitions change', function () {
+ $pdfContent = createCacheTestPdf();
+ $templatePath = 'pdf-templates/1/template.pdf';
+ Storage::put($templatePath, $pdfContent);
+
+ $form = createCacheTestForm([
+ 'computed_variables' => [
+ ['id' => 'cv_total', 'name' => 'Total', 'formula' => '{amount} * 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,
+ 'zone_mappings' => [],
+ ]);
+
+ $submission = $form->submissions()->create([
+ 'data' => ['amount' => 10],
+ ]);
+
+ $cacheService = new PdfCacheService();
+ $generator = new PdfGeneratorService();
+
+ $path1 = $cacheService->getOrGenerateFromTemplate($form, $submission, $template, $generator);
+
+ $form->update([
+ 'computed_variables' => [
+ ['id' => 'cv_total', 'name' => 'Total', 'formula' => '{amount} * 3'],
+ ],
+ ]);
+
+ $path2 = $cacheService->getOrGenerateFromTemplate($form->refresh(), $submission, $template, $generator);
+
+ expect($path2)->not->toBe($path1)
+ ->and(Storage::exists($path1))->toBeTrue()
+ ->and(Storage::exists($path2))->toBeTrue();
+ });
});
/**
diff --git a/api/tests/Feature/Integrations/Pdf/PdfGeneratorServiceTest.php b/api/tests/Feature/Integrations/Pdf/PdfGeneratorServiceTest.php
index 3732a12ab..3933c84dc 100644
--- a/api/tests/Feature/Integrations/Pdf/PdfGeneratorServiceTest.php
+++ b/api/tests/Feature/Integrations/Pdf/PdfGeneratorServiceTest.php
@@ -192,6 +192,96 @@ describe('PdfGeneratorService', function () {
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';
diff --git a/api/tests/Feature/Integrations/Pdf/PdfTemplateTest.php b/api/tests/Feature/Integrations/Pdf/PdfTemplateTest.php
index 791ae33a6..940056636 100644
--- a/api/tests/Feature/Integrations/Pdf/PdfTemplateTest.php
+++ b/api/tests/Feature/Integrations/Pdf/PdfTemplateTest.php
@@ -705,6 +705,60 @@ describe('PDF From-Scratch Default Filename Pattern', function () {
});
describe('PDF Template Update - source_page renormalization', function () {
+ it('persists and reloads computed variable zone mappings', function () {
+ $user = $this->actingAsProUser();
+ $workspace = $this->createUserWorkspace($user);
+ $form = $this->createForm($user, $workspace, [
+ 'properties' => [
+ ['id' => 'amount', 'name' => 'Amount', 'type' => 'number'],
+ ],
+ 'computed_variables' => [
+ ['id' => 'cv_total', 'name' => 'Total', 'formula' => '{amount} * 2'],
+ ],
+ ]);
+
+ $pdfContent = createValidPdf();
+ $filePath = "pdf-templates/{$form->id}/template.pdf";
+ Storage::put($filePath, $pdfContent);
+
+ $template = PdfTemplate::create([
+ 'form_id' => $form->id,
+ 'name' => 'Computed Variable Template',
+ 'filename' => 'template.pdf',
+ 'original_filename' => 'template.pdf',
+ 'file_path' => $filePath,
+ 'file_size' => strlen($pdfContent),
+ 'page_count' => 1,
+ 'page_manifest' => [['id' => 'page-1', 'type' => 'source', 'source_page' => 1]],
+ 'zone_mappings' => [],
+ ]);
+
+ $zone = [
+ 'id' => 'zone-total',
+ 'page_id' => 'page-1',
+ 'x' => 10,
+ 'y' => 10,
+ 'width' => 30,
+ 'height' => 5,
+ 'field_id' => 'cv_total',
+ 'font_size' => 12,
+ 'font_color' => '#000000',
+ ];
+
+ $this->putJson(
+ route('open.forms.pdf-templates.update', [$form, $template]),
+ [
+ 'page_manifest' => $template->page_manifest,
+ 'zone_mappings' => [$zone],
+ ]
+ )->assertSuccessful()
+ ->assertJsonPath('data.zone_mappings.0.field_id', 'cv_total');
+
+ $this->getJson(route('open.forms.pdf-templates.show', [$form, $template]))
+ ->assertSuccessful()
+ ->assertJsonPath('data.zone_mappings.0.field_id', 'cv_total');
+ });
+
it('renormalizes source_page after removing pages from manifest', function () {
$user = $this->actingAsProUser();
$workspace = $this->createUserWorkspace($user);
diff --git a/api/tests/Unit/Rules/PdfZoneMappingsRuleTest.php b/api/tests/Unit/Rules/PdfZoneMappingsRuleTest.php
new file mode 100644
index 000000000..aed63fe83
--- /dev/null
+++ b/api/tests/Unit/Rules/PdfZoneMappingsRuleTest.php
@@ -0,0 +1,160 @@
+<?php
+
+use App\Models\Forms\Form;
+use App\Models\User;
+use App\Models\Workspace;
+use App\Rules\PdfZoneMappingsRule;
+use Illuminate\Support\Facades\Validator;
+use Tests\TestCase;
+
+uses(TestCase::class);
+
+function createPdfZoneForm(array $attributes = []): Form
+{
+ $user = User::factory()->create();
+ $workspace = Workspace::create(['name' => 'PDF Zone Workspace', 'icon' => '📝']);
+ $user->workspaces()->attach($workspace->id, ['role' => 'admin']);
+
+ return Form::factory()
+ ->forWorkspace($workspace)
+ ->createdBy($user)
+ ->withProperties($attributes['properties'] ?? [
+ ['id' => 'name', 'name' => 'Name', 'type' => 'text'],
+ ['id' => 'agree', 'name' => 'Agree', 'type' => 'checkbox'],
+ ])
+ ->create(array_diff_key($attributes, ['properties' => true]));
+}
+
+function validPdfZone(array $overrides = []): array
+{
+ return array_merge([
+ 'id' => 'zone_1',
+ 'page_id' => 'page-1',
+ 'x' => 10,
+ 'y' => 10,
+ 'width' => 30,
+ 'height' => 5,
+ 'field_id' => 'name',
+ 'font_size' => 12,
+ 'font_color' => '#000000',
+ ], $overrides);
+}
+
+describe('PdfZoneMappingsRule', function () {
+ it('accepts form field ids', function () {
+ $form = createPdfZoneForm();
+
+ $validator = Validator::make(
+ ['zone_mappings' => [validPdfZone(['field_id' => 'name'])]],
+ ['zone_mappings' => [new PdfZoneMappingsRule($form)]]
+ );
+
+ expect($validator->passes())->toBeTrue();
+ });
+
+ it('accepts special field ids', function () {
+ $form = createPdfZoneForm();
+
+ $validator = Validator::make(
+ ['zone_mappings' => [validPdfZone(['field_id' => 'submission_id'])]],
+ ['zone_mappings' => [new PdfZoneMappingsRule($form)]]
+ );
+
+ expect($validator->passes())->toBeTrue();
+ });
+
+ it('accepts computed variable ids', function () {
+ $form = createPdfZoneForm([
+ 'computed_variables' => [
+ [
+ 'id' => 'cv_yes_no',
+ 'name' => 'Yes No',
+ 'formula' => 'IF({agree}, "yes", "no")',
+ ],
+ ],
+ ]);
+
+ $validator = Validator::make(
+ ['zone_mappings' => [validPdfZone(['field_id' => 'cv_yes_no'])]],
+ ['zone_mappings' => [new PdfZoneMappingsRule($form)]]
+ );
+
+ expect($validator->passes())->toBeTrue();
+ });
+
+ it('rejects unknown field ids', function () {
+ $form = createPdfZoneForm([
+ 'computed_variables' => [
+ [
+ 'id' => 'cv_yes_no',
+ 'name' => 'Yes No',
+ 'formula' => 'IF({agree}, "yes", "no")',
+ ],
+ ],
+ ]);
+
+ $validator = Validator::make(
+ ['zone_mappings' => [validPdfZone(['field_id' => 'missing_field'])]],
+ ['zone_mappings' => [new PdfZoneMappingsRule($form)]]
+ );
+
+ expect($validator->fails())->toBeTrue();
+ expect($validator->errors()->first('zone_mappings'))->toContain("field_id 'missing_field' does not exist in form");
+ });
+
+ it('rejects unknown field ids when the form has no standard fields', function () {
+ $form = createPdfZoneForm(['properties' => []]);
+
+ $validator = Validator::make(
+ ['zone_mappings' => [validPdfZone(['field_id' => 'missing_field'])]],
+ ['zone_mappings' => [new PdfZoneMappingsRule($form)]]
+ );
+
+ expect($validator->fails())->toBeTrue();
+ expect($validator->errors()->first('zone_mappings'))->toContain("field_id 'missing_field' does not exist in form");
+ });
+
+ it('rejects non-string field ids', function () {
+ $form = createPdfZoneForm();
+
+ $validator = Validator::make(
+ ['zone_mappings' => [validPdfZone(['field_id' => ['name']])]],
+ ['zone_mappings' => [new PdfZoneMappingsRule($form)]]
+ );
+
+ expect($validator->fails())->toBeTrue();
+ expect($validator->errors()->first('zone_mappings'))->toContain('field_id must be a non-empty string');
+ });
+
+ it('still accepts static text and image zones', function () {
+ $form = createPdfZoneForm();
+
+ $zones = [
+ [
+ 'id' => 'zone_text',
+ 'page_id' => 'page-1',
+ 'x' => 10,
+ 'y' => 10,
+ 'width' => 30,
+ 'height' => 5,
+ 'static_text' => 'Hello',
+ ],
+ [
+ 'id' => 'zone_image',
+ 'page_id' => 'page-1',
+ 'x' => 10,
+ 'y' => 20,
+ 'width' => 30,
+ 'height' => 20,
+ 'static_image' => 'https://example.com/image.png',
+ ],
+ ];
+
+ $validator = Validator::make(
+ ['zone_mappings' => $zones],
+ ['zone_mappings' => [new PdfZoneMappingsRule($form)]]
+ );
+
+ expect($validator->passes())->toBeTrue();
+ });
+});
diff --git a/client/components/open/pdf-editor/PdfRightSidebar.vue b/client/components/open/pdf-editor/PdfRightSidebar.vue
index fa5f54d60..e219b32e5 100644
--- a/client/components/open/pdf-editor/PdfRightSidebar.vue
+++ b/client/components/open/pdf-editor/PdfRightSidebar.vue
@@ -10,7 +10,7 @@
>
<template #content-top>
<div
- v-if="formFields.length"
+ v-if="formFields.length || computedVariables.length"
class="p-2 border-b border-neutral-100 dark:border-neutral-700"
>
<UInput
@@ -18,7 +18,7 @@
v-model="formFieldsSearch"
variant="outline"
class="w-full"
- placeholder="Search form fields..."
+ placeholder="Search fields & variables..."
icon="i-heroicons-magnifying-glass-solid"
:ui="{ trailing: 'pe-1' }"
@click.stop
@@ -204,6 +204,7 @@ const {
selectedZone,
formFields,
specialFields,
+ computedVariables,
fieldOptions,
} = storeToRefs(pdfStore)
@@ -221,8 +222,15 @@ const filteredFormFields = computed(() => {
return formFields.value.filter((f) => f.name.toLowerCase().includes(q))
})
+const filteredComputedVariables = computed(() => {
+ const q = formFieldsSearch.value.trim().toLowerCase()
+ if (!q) return computedVariables.value
+ return computedVariables.value.filter((v) => v.name.toLowerCase().includes(q))
+})
+
const addZoneMenuItems = computed(() => {
const items = []
+ const hasSearchableItems = formFields.value.length || computedVariables.value.length
if (formFields.value.length) {
const formFieldItems = [
@@ -234,7 +242,7 @@ const addZoneMenuItems = computed(() => {
]
if (filteredFormFields.value.length) {
items.push(formFieldItems)
- } else {
+ } else if (formFieldsSearch.value.trim()) {
items.push([
{ type: 'label', label: 'Form Fields' },
{ type: 'label', label: `No fields match "${formFieldsSearch.value}"` },
@@ -242,23 +250,43 @@ const addZoneMenuItems = computed(() => {
}
}
- items.push([
- { type: 'label', label: 'Special Fields' },
- ...specialFields.value.map((field) => ({
- label: field.name,
- onSelect: () => addZoneWithField(field),
- })),
- ])
+ if (computedVariables.value.length) {
+ if (filteredComputedVariables.value.length) {
+ items.push([
+ { type: 'label', label: 'Computed Variables' },
+ ...filteredComputedVariables.value.map((variable) => ({
+ label: variable.name,
+ icon: 'i-heroicons-variable',
+ onSelect: () => addZoneWithField(variable),
+ })),
+ ])
+ } else if (formFieldsSearch.value.trim()) {
+ items.push([
+ { type: 'label', label: 'Computed Variables' },
+ { type: 'label', label: `No variables match "${formFieldsSearch.value}"` },
+ ])
+ }
+ }
- items.push([{
- label: 'Static Text',
- icon: 'i-heroicons-pencil',
- onSelect: () => addZoneWithField(null, 'static_text'),
- }, {
- label: 'Image',
- icon: 'i-heroicons-photo',
- onSelect: () => addZoneWithField(null, 'static_image'),
- }])
+ if (!hasSearchableItems || !formFieldsSearch.value.trim()) {
+ items.push([
+ { type: 'label', label: 'Special Fields' },
+ ...specialFields.value.map((field) => ({
+ label: field.name,
+ onSelect: () => addZoneWithField(field),
+ })),
+ ])
+
+ items.push([{
+ label: 'Static Text',
+ icon: 'i-heroicons-pencil',
+ onSelect: () => addZoneWithField(null, 'static_text'),
+ }, {
+ label: 'Image',
+ icon: 'i-heroicons-photo',
+ onSelect: () => addZoneWithField(null, 'static_image'),
+ }])
+ }
return items
})
@@ -303,6 +331,9 @@ const getZoneListLabel = (zone) => {
const getZoneIcon = (zone) => {
if (zone.static_text !== undefined) return 'i-heroicons-document-text'
if (zone.static_image !== undefined) return 'i-heroicons-photo'
+ if (zone.field_id && computedVariables.value.some((v) => v.id === zone.field_id)) {
+ return 'i-heroicons-variable'
+ }
return 'i-heroicons-at-symbol'
}
diff --git a/client/stores/working_pdf.js b/client/stores/working_pdf.js
index a0a6b2c10..5569911b6 100644
--- a/client/stores/working_pdf.js
+++ b/client/stores/working_pdf.js
@@ -87,10 +87,25 @@ export const useWorkingPdfStore = defineStore("working_pdf", {
]
},
+ computedVariables() {
+ if (!this.form?.computed_variables?.length) return []
+ return this.form.computed_variables
+ .filter(v => v?.id && v?.name)
+ .map(v => ({
+ id: v.id,
+ name: v.name,
+ type: 'computed',
+ }))
+ },
+
fieldOptions() {
const formOptions = this.formFields.map(f => ({ name: f.name, value: f.id }))
+ const computedOptions = this.computedVariables.map(v => ({
+ name: `${v.name} (Variable)`,
+ value: v.id,
+ }))
const specialOptions = this.specialFields.map(f => ({ name: f.name, value: f.id }))
- return [...formOptions, ...specialOptions]
+ return [...formOptions, ...computedOptions, ...specialOptions]
},
defaultFilenamePattern() {
@@ -210,7 +225,7 @@ export const useWorkingPdfStore = defineStore("working_pdf", {
getZoneLabel(zone) {
if (zone.static_text !== undefined) return 'Static Text'
if (zone.static_image !== undefined) return 'Image'
- const allFields = [...this.formFields, ...this.specialFields]
+ const allFields = [...this.formFields, ...this.computedVariables, ...this.specialFields]
const field = allFields.find(f => f.id === zone.field_id)
return field?.name || zone.field_id || 'Unmapped'
},
diff --git a/client/test/unit/working-pdf-store.test.ts b/client/test/unit/working-pdf-store.test.ts
index f895c9a7d..5afa917ac 100644
--- a/client/test/unit/working-pdf-store.test.ts
+++ b/client/test/unit/working-pdf-store.test.ts
@@ -110,3 +110,56 @@ describe('working_pdf store - page_manifest model', () => {
expect(store.getSourcePageNumber(2)).toBeNull()
})
})
+
+describe('working_pdf store - computed variables', () => {
+ beforeEach(() => {
+ setActivePinia(createPinia())
+ })
+
+ it('exposes computed variables in field options and zone labels', () => {
+ const store = useWorkingPdfStore()
+ store.set(createTemplateFixture({
+ page_manifest: [{ id: 'p1', type: 'source', source_page: 1 }],
+ page_count: 1,
+ }))
+ store.setForm({
+ properties: [
+ { id: 'agree', name: 'Agree', type: 'checkbox' },
+ ],
+ computed_variables: [
+ { id: 'cv_yes_no', name: 'Yes No', formula: 'IF({agree}, "yes", "no")' },
+ ],
+ })
+
+ expect(store.computedVariables).toEqual([
+ { id: 'cv_yes_no', name: 'Yes No', type: 'computed' },
+ ])
+ expect(store.fieldOptions).toContainEqual({
+ name: 'Yes No (Variable)',
+ value: 'cv_yes_no',
+ })
+
+ store.addZoneWithField({ id: 'cv_yes_no', name: 'Yes No' })
+
+ const zone = store.content.zone_mappings[0]
+ expect(zone.field_id).toBe('cv_yes_no')
+ expect(store.getZoneLabel(zone)).toBe('Yes No')
+
+ const savedTemplate = {
+ ...createTemplateFixture(),
+ ...store.getSaveData(),
+ }
+
+ store.reset()
+ store.set(savedTemplate)
+ store.setForm({
+ properties: [],
+ computed_variables: [
+ { id: 'cv_yes_no', name: 'Yes No', formula: 'IF({agree}, "yes", "no")' },
+ ],
+ })
+
+ expect(store.content.zone_mappings[0].field_id).toBe('cv_yes_no')
+ expect(store.getZoneLabel(store.content.zone_mappings[0])).toBe('Yes No')
+ })
+})