Skip to content

Beautiful Open-Source Form Builder

Fix PDF template editing and add duplication across workspace forms (#1348)

Julien Nahum37670a948396
diff --git a/api/app/Http/Controllers/Pdf/PdfTemplateController.php b/api/app/Http/Controllers/Pdf/PdfTemplateController.php
index bb89ee7a6..18825687b 100644
--- a/api/app/Http/Controllers/Pdf/PdfTemplateController.php
+++ b/api/app/Http/Controllers/Pdf/PdfTemplateController.php
@@ -5,9 +5,11 @@ namespace App\Http\Controllers\Pdf;
use App\Exceptions\PdfNotSupportedException;
use App\Http\Controllers\Controller;
use App\Http\Requests\Pdf\CreatePdfTemplateRequest;
+use App\Http\Requests\Pdf\DuplicatePdfTemplateRequest;
use App\Http\Requests\Pdf\UpdatePdfTemplateRequest;
use App\Models\Forms\Form;
use App\Models\PdfTemplate;
+use App\Service\Pdf\DuplicatePdfTemplate;
use App\Service\Pdf\PdfFormFieldRenderer;
use App\Service\Pdf\PdfTemplateRebuildService;
use Illuminate\Support\Facades\Storage;
@@ -92,6 +94,21 @@ class PdfTemplateController extends Controller
], 201);
}
+ public function duplicate(DuplicatePdfTemplateRequest $request, Form $form, PdfTemplate $pdfTemplate, DuplicatePdfTemplate $duplicator)
+ {
+ $this->authorize('update', $form);
+ abort_unless($pdfTemplate->form_id === $form->id, 404);
+
+ $target = Form::where('workspace_id', $form->workspace_id)
+ ->findOrFail($request->validated('target_form_id'));
+ $this->authorize('update', $target);
+
+ return response()->json([
+ 'message' => 'PDF template duplicated successfully.',
+ 'data' => $duplicator->duplicate($pdfTemplate, $target, $request->validated()),
+ ], 201);
+ }
+
/**
* Get a specific PDF template.
*/
diff --git a/api/app/Http/Requests/Pdf/DuplicatePdfTemplateRequest.php b/api/app/Http/Requests/Pdf/DuplicatePdfTemplateRequest.php
new file mode 100644
index 000000000..50b58e761
--- /dev/null
+++ b/api/app/Http/Requests/Pdf/DuplicatePdfTemplateRequest.php
@@ -0,0 +1,18 @@
+<?php
+
+namespace App\Http\Requests\Pdf;
+
+use Illuminate\Foundation\Http\FormRequest;
+
+class DuplicatePdfTemplateRequest extends FormRequest
+{
+ public function rules(): array
+ {
+ return [
+ 'target_form_id' => 'required|integer',
+ 'name' => 'required|string|max:255',
+ 'field_mappings' => 'sometimes|array',
+ 'field_mappings.*' => 'nullable|string',
+ ];
+ }
+}
diff --git a/api/app/Service/Pdf/DuplicatePdfTemplate.php b/api/app/Service/Pdf/DuplicatePdfTemplate.php
new file mode 100644
index 000000000..e04142cad
--- /dev/null
+++ b/api/app/Service/Pdf/DuplicatePdfTemplate.php
@@ -0,0 +1,87 @@
+<?php
+
+namespace App\Service\Pdf;
+
+use App\Models\Forms\Form;
+use App\Models\PdfTemplate;
+use Illuminate\Support\Facades\DB;
+use Illuminate\Support\Facades\Storage;
+use Illuminate\Support\Str;
+use Illuminate\Validation\ValidationException;
+
+class DuplicatePdfTemplate
+{
+ private const SPECIAL_FIELDS = ['submission_id', 'submission_date', 'form_name'];
+
+ public function duplicate(PdfTemplate $source, Form $target, array $data): PdfTemplate
+ {
+ $zones = $source->zone_mappings ?? [];
+ if ($source->form_id !== $target->id) {
+ $zones = $this->mapFields($zones, $target, $data['field_mappings'] ?? []);
+ }
+
+ abort_unless(Storage::exists($source->file_path), 404, 'PDF template file not found.');
+ $filename = Str::uuid() . '.pdf';
+ $path = "pdf-templates/{$target->id}/{$filename}";
+
+ try {
+ if (!Storage::copy($source->file_path, $path)) {
+ throw new \RuntimeException('Failed to copy PDF template file.');
+ }
+
+ return DB::transaction(function () use ($source, $target, $data, $zones, $filename, $path) {
+ $copy = $source->replicate();
+ $copy->fill([
+ 'form_id' => $target->id,
+ 'name' => $data['name'],
+ 'filename' => $filename,
+ 'file_path' => $path,
+ 'zone_mappings' => $zones,
+ ]);
+ $copy->save();
+
+ return $copy;
+ });
+ } catch (\Throwable $exception) {
+ Storage::delete($path);
+ throw $exception;
+ }
+ }
+
+ private function mapFields(array $zones, Form $target, array $mappings): array
+ {
+ $fields = collect($target->properties ?? [])
+ ->reject(fn ($field) => str_starts_with($field['type'] ?? '', 'nf-'))
+ ->concat($target->computed_variables ?? [])
+ ->keyBy('id');
+
+ return collect($zones)->map(function ($zone) use ($fields, $mappings) {
+ $fieldId = $zone['field_id'] ?? null;
+ if (array_key_exists('static_text', $zone) || array_key_exists('static_image', $zone)
+ || !$fieldId || in_array($fieldId, self::SPECIAL_FIELDS, true)) {
+ return $zone;
+ }
+
+ // Missing mappings must never silently discard a customer's layout.
+ if (!array_key_exists($fieldId, $mappings)) {
+ throw ValidationException::withMessages([
+ 'field_mappings' => 'Choose a destination or explicitly skip each mapped field.',
+ ]);
+ }
+ $destination = $mappings[$fieldId];
+ if ($destination === null) {
+ return null;
+ }
+ if (!$fields->has($destination)) {
+ throw ValidationException::withMessages([
+ 'field_mappings' => 'Mapped fields must belong to the destination form.',
+ ]);
+ }
+
+ $zone['field_id'] = $destination;
+ $zone['field_name'] = $fields[$destination]['name'];
+
+ return $zone;
+ })->filter(fn ($zone) => $zone !== null)->values()->all();
+ }
+}
diff --git a/api/routes/api.php b/api/routes/api.php
index c6af0883a..f1841166e 100644
--- a/api/routes/api.php
+++ b/api/routes/api.php
@@ -334,6 +334,7 @@ Route::group(['middleware' => 'auth.multi'], function () {
Route::prefix('/{form}/pdf-templates')->name('pdf-templates.')->group(function () {
Route::get('/', [PdfTemplateController::class, 'index'])->name('index');
Route::post('/', [PdfTemplateController::class, 'store'])->name('store');
+ Route::post('/{pdfTemplate}/duplicate', [PdfTemplateController::class, 'duplicate'])->name('duplicate');
Route::get('/{pdfTemplate}', [PdfTemplateController::class, 'show'])->name('show');
Route::put('/{pdfTemplate}', [PdfTemplateController::class, 'update'])->name('update');
Route::delete('/{pdfTemplate}', [PdfTemplateController::class, 'destroy'])->name('destroy');
diff --git a/api/tests/Feature/Integrations/Pdf/DuplicatePdfTemplateTest.php b/api/tests/Feature/Integrations/Pdf/DuplicatePdfTemplateTest.php
new file mode 100644
index 000000000..225f753f0
--- /dev/null
+++ b/api/tests/Feature/Integrations/Pdf/DuplicatePdfTemplateTest.php
@@ -0,0 +1,158 @@
+<?php
+
+use App\Models\PdfTemplate;
+use App\Models\User;
+use Illuminate\Support\Facades\Storage;
+
+beforeEach(function () {
+ Storage::fake('local');
+ $this->owner = $this->actingAsProUser();
+ $this->workspace = $this->createUserWorkspace($this->owner);
+ $this->sourceForm = $this->createForm($this->owner, $this->workspace);
+ $this->targetForm = $this->createForm($this->owner, $this->workspace, [
+ 'properties' => [['id' => 'target-name', 'type' => 'text', 'name' => 'Destination name']],
+ 'computed_variables' => [['id' => 'target-total', 'name' => 'Total', 'formula' => '1']],
+ ]);
+ $this->sourceFieldId = $this->sourceForm->properties[0]['id'];
+ $zone = ['id' => 'field-zone', 'page_id' => 'page-one', 'page' => 1, 'x' => 5, 'y' => 5, 'width' => 40, 'height' => 10, 'font_size' => 12];
+ $this->sourceTemplate = PdfTemplate::create([
+ 'form_id' => $this->sourceForm->id,
+ 'name' => 'Original',
+ 'filename' => 'original.pdf',
+ 'original_filename' => 'uploaded.pdf',
+ 'file_path' => "pdf-templates/{$this->sourceForm->id}/original.pdf",
+ 'file_size' => 100,
+ 'page_count' => 1,
+ 'page_manifest' => [['id' => 'page-one', 'type' => 'source', 'source_page' => 1]],
+ 'zone_mappings' => [
+ [...$zone, 'field_id' => $this->sourceFieldId, 'field_name' => 'Source name'],
+ [...$zone, 'id' => 'label', 'static_text' => '<b>Name</b>'],
+ [...$zone, 'id' => 'image', 'static_image' => 'https://example.test/logo.png'],
+ [...$zone, 'id' => 'special', 'field_id' => 'submission_id'],
+ ],
+ 'filename_pattern' => 'custom-filename',
+ 'remove_branding' => true,
+ ]);
+ Storage::put($this->sourceTemplate->file_path, 'original PDF bytes');
+ $this->endpoint = route('open.forms.pdf-templates.duplicate', [$this->sourceForm, $this->sourceTemplate]);
+});
+
+it('duplicates all template settings into an independent file in the same form', function () {
+ $response = $this->postJson($this->endpoint, ['target_form_id' => $this->sourceForm->id, 'name' => 'Copy']);
+ $response->assertCreated();
+ $copy = PdfTemplate::findOrFail($response->json('data.id'));
+ expect($copy->id)->not->toBe($this->sourceTemplate->id);
+ expect($copy->file_path)->not->toBe($this->sourceTemplate->file_path);
+ expect($copy->zone_mappings)->toBe($this->sourceTemplate->zone_mappings);
+ expect($copy->page_manifest)->toBe($this->sourceTemplate->page_manifest);
+ expect($copy->filename_pattern)->toBe('custom-filename');
+ expect($copy->remove_branding)->toBeTrue();
+ expect($copy->original_filename)->toBe('uploaded.pdf');
+ expect(Storage::get($copy->file_path))->toBe('original PDF bytes');
+
+ Storage::put($copy->file_path, 'edited copy');
+ expect(Storage::get($this->sourceTemplate->file_path))->toBe('original PDF bytes');
+ $this->deleteJson(route('open.forms.pdf-templates.destroy', [$this->sourceForm, $copy]))->assertOk();
+ expect(Storage::exists($this->sourceTemplate->file_path))->toBeTrue();
+ expect($this->sourceTemplate->fresh()->name)->toBe('Original');
+});
+
+it('remaps fields to another form while preserving static zones and special fields', function () {
+ $this->postJson($this->endpoint, [
+ 'target_form_id' => $this->targetForm->id,
+ 'name' => 'Destination copy',
+ 'field_mappings' => [$this->sourceFieldId => 'target-name'],
+ ])->assertCreated()->assertJsonPath('data.form_id', $this->targetForm->id)
+ ->assertJsonPath('data.zone_mappings.0.field_id', 'target-name')
+ ->assertJsonPath('data.zone_mappings.0.field_name', 'Destination name')
+ ->assertJsonPath('data.zone_mappings.1.static_text', '<b>Name</b>')
+ ->assertJsonPath('data.zone_mappings.2.static_image', 'https://example.test/logo.png')
+ ->assertJsonPath('data.zone_mappings.3.field_id', 'submission_id');
+ expect($this->sourceTemplate->fresh()->zone_mappings[0]['field_id'])->toBe($this->sourceFieldId);
+});
+
+it('supports computed variable destinations and explicitly skipped fields', function () {
+ $this->postJson($this->endpoint, [
+ 'target_form_id' => $this->targetForm->id, 'name' => 'Variable copy',
+ 'field_mappings' => [$this->sourceFieldId => 'target-total'],
+ ])->assertCreated()->assertJsonPath('data.zone_mappings.0.field_id', 'target-total');
+
+ $response = $this->postJson($this->endpoint, [
+ 'target_form_id' => $this->targetForm->id, 'name' => 'Static copy',
+ 'field_mappings' => [$this->sourceFieldId => null],
+ ])->assertCreated();
+ expect($response->json('data.zone_mappings'))->toHaveCount(3);
+ expect($response->json('data.zone_mappings.0.static_text'))->toBe('<b>Name</b>');
+});
+
+it('requires explicit mappings and rejects fields outside the destination', function (array $mappings) {
+ $this->postJson($this->endpoint, [
+ 'target_form_id' => $this->targetForm->id, 'name' => 'Copy', 'field_mappings' => $mappings,
+ ])->assertUnprocessable()->assertJsonValidationErrors('field_mappings');
+ expect(PdfTemplate::count())->toBe(1);
+ expect(Storage::allFiles())->toHaveCount(1);
+})->with([
+ 'missing mappings' => [[]],
+ 'unknown source field' => [['unknown-source' => 'target-name']],
+]);
+
+it('rejects invalid mapped destination fields including layout blocks', function () {
+ $this->targetForm->update(['properties' => [['id' => 'heading', 'type' => 'nf-text', 'name' => 'Heading']]]);
+ foreach ([$this->sourceFieldId, 'heading', 'not-a-field', 'submission_id'] as $fieldId) {
+ $this->postJson($this->endpoint, [
+ 'target_form_id' => $this->targetForm->id, 'name' => 'Copy',
+ 'field_mappings' => [$this->sourceFieldId => $fieldId],
+ ])->assertUnprocessable()->assertJsonValidationErrors('field_mappings');
+ }
+ expect(PdfTemplate::count())->toBe(1);
+});
+
+it('rejects copying to another workspace even when the user owns both', function () {
+ $otherWorkspace = $this->createUserWorkspace($this->owner);
+ $otherForm = $this->createForm($this->owner, $otherWorkspace);
+ $this->postJson($this->endpoint, ['target_form_id' => $otherForm->id, 'name' => 'Copy'])->assertNotFound();
+ expect(PdfTemplate::count())->toBe(1);
+});
+
+it('requires authentication and edit access', function () {
+ $this->actingAsGuest();
+ $this->postJson($this->endpoint, ['target_form_id' => $this->sourceForm->id, 'name' => 'Copy'])->assertUnauthorized();
+ $this->actingAsUser();
+ $this->postJson($this->endpoint, ['target_form_id' => $this->sourceForm->id, 'name' => 'Copy'])->assertForbidden();
+});
+
+it('denies readonly workspace members', function () {
+ $reader = $this->createUser();
+ $this->workspace->users()->attach($reader, ['role' => User::ROLE_READONLY]);
+ $this->actingAsGuest();
+ $this->actingAsUser($reader);
+ $this->postJson($this->endpoint, ['target_form_id' => $this->sourceForm->id, 'name' => 'Copy'])->assertForbidden();
+});
+
+it('checks the source template belongs to the source form', function () {
+ $endpoint = route('open.forms.pdf-templates.duplicate', [$this->targetForm, $this->sourceTemplate]);
+ $this->postJson($endpoint, ['target_form_id' => $this->targetForm->id, 'name' => 'Copy'])->assertNotFound();
+});
+
+it('does not create a template when the source file is missing', function () {
+ Storage::delete($this->sourceTemplate->file_path);
+ $this->postJson($this->endpoint, ['target_form_id' => $this->sourceForm->id, 'name' => 'Copy'])->assertNotFound();
+ expect(PdfTemplate::count())->toBe(1);
+});
+
+it('cleans up the copied file when creating the database record fails', function () {
+ PdfTemplate::creating(function ($template) {
+ if ($template->name === 'Failed copy') {
+ throw new RuntimeException('Simulated database failure');
+ }
+ });
+ $this->postJson($this->endpoint, ['target_form_id' => $this->sourceForm->id, 'name' => 'Failed copy'])->assertStatus(500);
+ expect(PdfTemplate::count())->toBe(1);
+ expect(Storage::allFiles())->toBe([$this->sourceTemplate->file_path]);
+});
+
+it('validates the copy name and target form', function () {
+ $this->postJson($this->endpoint, [])->assertUnprocessable()->assertJsonValidationErrors(['name', 'target_form_id']);
+ $this->postJson($this->endpoint, ['target_form_id' => 999999999, 'name' => 'Copy'])->assertNotFound();
+ expect(PdfTemplate::count())->toBe(1);
+});
diff --git a/client/api/forms.js b/client/api/forms.js
index 6439a62a6..c1358de43 100644
--- a/client/api/forms.js
+++ b/client/api/forms.js
@@ -89,6 +89,7 @@ export const formsApi = {
pdfTemplates: {
list: (formId, options) => apiService.get(`/open/forms/${formId}/pdf-templates`, options),
upload: (formId, data, options) => apiService.post(`/open/forms/${formId}/pdf-templates`, data, options),
+ duplicate: (formId, templateId, data) => apiService.post(`/open/forms/${formId}/pdf-templates/${templateId}/duplicate`, data),
get: (formId, templateId, options) => apiService.get(`/open/forms/${formId}/pdf-templates/${templateId}`, options),
update: (formId, templateId, data) => apiService.put(`/open/forms/${formId}/pdf-templates/${templateId}`, data),
delete: (formId, templateId) => apiService.delete(`/open/forms/${formId}/pdf-templates/${templateId}`),
diff --git a/client/components/forms/heavy/components/QuillyEditor.vue b/client/components/forms/heavy/components/QuillyEditor.vue
index bb3a77396..cf098b1f3 100644
--- a/client/components/forms/heavy/components/QuillyEditor.vue
+++ b/client/components/forms/heavy/components/QuillyEditor.vue
@@ -38,21 +38,24 @@ const emit = defineEmits([
let quillInstance = null
const container = ref(null)
-const model = ref(props.modelValue)
+let model = props.modelValue
// Safely paste HTML content with handling for empty content
const pasteHTML = (instance) => {
- if (!props.modelValue) {
- instance.setContents([])
- return
- }
-
try {
- instance.clipboard.dangerouslyPasteHTML(0, props.modelValue, 'silent')
+ if (!props.modelValue) {
+ instance.setContents([], 'silent')
+ } else {
+ // Without an insertion index, Quill replaces the previous document.
+ instance.clipboard.dangerouslyPasteHTML(props.modelValue, 'silent')
+ }
} catch (error) {
console.error('Error pasting HTML:', error)
// Fallback to setting empty content
- instance.setContents([])
+ instance.setContents([], 'silent')
+ } finally {
+ // An external document must not inherit undo/redo entries from another zone.
+ instance.history?.clear()
}
}
@@ -86,7 +89,8 @@ const initializeQuill = () => {
quillInstance.on('text-change', (delta, oldContents, source) => {
// Update local model only on user input
- model.value = quillInstance.getSemanticHTML()
+ model = quillInstance.getSemanticHTML()
+ emit('update:modelValue', model)
emit('text-change', { delta, oldContents, source })
})
@@ -96,7 +100,7 @@ const initializeQuill = () => {
if (props.modelValue) {
pasteHTML(quillInstance)
- model.value = quillInstance.getSemanticHTML()
+ model = quillInstance.getSemanticHTML()
}
// Apply initial disabled state
@@ -117,26 +121,13 @@ watch(
() => props.modelValue,
(newValue) => {
if (!quillInstance) return
- if (newValue && newValue !== model.value) {
+ if (newValue !== model) {
pasteHTML(quillInstance)
- model.value = quillInstance.getSemanticHTML()
- } else if (!newValue) {
- quillInstance.setContents([])
- model.value = ''
+ model = quillInstance.getSemanticHTML()
}
}
)
-// Watch model and update modelValue if has changes
-watch(model, (newValue, oldValue) => {
- if (!quillInstance) return
- if (newValue && newValue !== oldValue) {
- emit('update:modelValue', newValue)
- } else if (!newValue) {
- quillInstance.setContents([])
- }
-})
-
watch(() => props.disabled, (newValue) => {
if (!quillInstance) return
if (newValue) {
@@ -166,4 +157,4 @@ onBeforeUnmount(() => {
}
quillInstance = null
})
-</script>
\ No newline at end of file
+</script>
diff --git a/client/components/open/pdf-editor/DuplicatePdfTemplateModal.vue b/client/components/open/pdf-editor/DuplicatePdfTemplateModal.vue
new file mode 100644
index 000000000..4280415ea
--- /dev/null
+++ b/client/components/open/pdf-editor/DuplicatePdfTemplateModal.vue
@@ -0,0 +1,125 @@
+<template>
+ <UModal v-model:open="open" :dismissible="!isPending" :close="!isPending" title="Duplicate PDF template" description="Create an independent copy in this form or another form in the same workspace.">
+ <template #body>
+ <form id="duplicate-pdf-template" class="space-y-4" @submit.prevent="submit">
+ <TextInput v-model="name" name="copy_name" label="Template name" :required="true" :max-char-limit="255" :disabled="isPending" />
+ <SelectInput
+ v-model="targetId"
+ name="target_form"
+ label="Destination form"
+ :options="formOptions"
+ :searchable="true"
+ :loading="formsLoading || fetchingMoreForms"
+ :clearable="false"
+ :required="true"
+ :disabled="isPending"
+ />
+ <UAlert v-if="formsError" color="error" title="Could not load destination forms." />
+ <template v-if="isOtherForm">
+ <p v-if="sourceFields.length" class="text-sm text-neutral-600">
+ Choose which destination field each PDF field should use. Text, images and page layouts are copied as they are.
+ </p>
+ <p v-if="targetLoading" class="text-sm text-neutral-500">Loading destination fields…</p>
+ <UAlert v-else-if="targetError" color="error" title="Could not load destination fields." />
+ <template v-else-if="destinationForm && sourceFields.length">
+ <SelectInput
+ v-for="field in sourceFields"
+ :key="field.id"
+ v-model="fieldMappings[field.id]"
+ :name="`mapping_${field.id}`"
+ :label="field.name"
+ :options="fieldOptions"
+ placeholder="Select a field or skip this field"
+ :searchable="true"
+ :clearable="false"
+ :disabled="isPending"
+ />
+ <UAlert
+ v-if="skippedCount"
+ color="warning"
+ :title="`${skippedCount} field${skippedCount === 1 ? '' : 's'} will be left out of the copy.`"
+ description="The text labels next to these fields will still be copied."
+ />
+ </template>
+ </template>
+ <UAlert v-if="submitError" color="error" :title="submitError" />
+ </form>
+ </template>
+ <template #footer>
+ <div class="flex justify-end gap-2 w-full">
+ <UButton color="neutral" variant="outline" :disabled="isPending" @click="open = false">Cancel</UButton>
+ <UButton type="submit" form="duplicate-pdf-template" :loading="isPending" :disabled="!canSubmit">Duplicate template</UButton>
+ </div>
+ </template>
+ </UModal>
+</template>
+
+<script setup>
+import { useFormsList } from '~/composables/query/forms/useFormsList'
+import { usePdfTemplates } from '~/composables/query/forms/usePdfTemplates'
+import { getPdfDestinationFields, getPdfTemplateFields, suggestPdfFieldMappings } from '~/lib/pdf-template-duplication'
+
+const props = defineProps({
+ form: { type: Object, required: true },
+ template: { type: Object, required: true },
+})
+const open = defineModel('open', { type: Boolean, default: false })
+const emit = defineEmits(['duplicated'])
+const SKIP_FIELD = '__skip__'
+const name = ref(`Copy of ${props.template.name}`.slice(0, 255))
+const targetId = ref(props.form.id)
+const fieldMappings = ref({})
+const submitError = ref('')
+const isOtherForm = computed(() => targetId.value !== props.form.id)
+const workspaceId = computed(() => props.form.workspace_id)
+const { forms, isLoading: formsLoading, isFetchingNextPage: fetchingMoreForms, error: formsError } = useFormsList(workspaceId, {
+ fetchAll: true,
+ enabled: open,
+})
+const formOptions = computed(() => [
+ { name: `${props.form.title} (this form)`, value: props.form.id },
+ ...forms.value.filter(form => form.id !== props.form.id).map(form => ({ name: form.title, value: form.id })),
+])
+const { detailById } = useForms()
+const { data: destinationForm, isLoading: targetLoading, error: targetError } = detailById(targetId, {
+ usePrivate: true,
+ enabled: computed(() => open.value && isOtherForm.value),
+})
+const sourceFields = computed(() => getPdfTemplateFields(props.template, props.form))
+const destinationFields = computed(() => getPdfDestinationFields(destinationForm.value))
+const fieldOptions = computed(() => [
+ { name: 'Skip this field', value: SKIP_FIELD },
+ ...destinationFields.value.map(field => ({
+ name: field.type === 'computed' ? `${field.name} (Variable)` : field.name,
+ value: field.id,
+ })),
+])
+
+watch([targetId, () => destinationForm.value?.id], () => {
+ fieldMappings.value = suggestPdfFieldMappings(sourceFields.value, destinationFields.value)
+ submitError.value = ''
+})
+
+const skippedCount = computed(() => Object.values(fieldMappings.value).filter(value => value === SKIP_FIELD).length)
+const canSubmit = computed(() => name.value.trim() && targetId.value && !isPending.value
+ && (!isOtherForm.value || (!targetLoading.value && !targetError.value && destinationForm.value?.id === targetId.value
+ && sourceFields.value.every(field => !!fieldMappings.value[field.id]))))
+const { duplicate } = usePdfTemplates()
+const { mutateAsync, isPending } = duplicate(() => props.form.id, () => props.template.id)
+
+function submit() {
+ if (!canSubmit.value) return
+ submitError.value = ''
+ const destination = isOtherForm.value ? destinationForm.value : props.form
+ const mappings = Object.fromEntries(Object.entries(fieldMappings.value)
+ .map(([id, value]) => [id, value === SKIP_FIELD ? null : value]))
+ mutateAsync({ target_form_id: targetId.value, name: name.value.trim(), field_mappings: mappings })
+ .then(response => {
+ open.value = false
+ emit('duplicated', { template: response.data, form: destination })
+ })
+ .catch(error => {
+ submitError.value = error?.data?.message || error?.message || 'Failed to duplicate PDF template.'
+ })
+}
+</script>
diff --git a/client/composables/query/forms/useForms.js b/client/composables/query/forms/useForms.js
index cd99e7372..a03e6cb70 100644
--- a/client/composables/query/forms/useForms.js
+++ b/client/composables/query/forms/useForms.js
@@ -48,9 +48,9 @@ export function useForms() {
queryKey: detailByIdKey(scope, id),
queryFn: () => {
if (usePrivate) {
- return formsApi.getById(id, queryOptions)
+ return formsApi.getById(toValue(id), queryOptions)
}
- return formsApi.publicGetById(id, queryOptions)
+ return formsApi.publicGetById(toValue(id), queryOptions)
},
enabled: isQueryEnabled(id, enabled, usePrivate),
onSuccess: (form) => {
diff --git a/client/composables/query/forms/usePdfTemplates.js b/client/composables/query/forms/usePdfTemplates.js
index a14c9f1ee..8f403dece 100644
--- a/client/composables/query/forms/usePdfTemplates.js
+++ b/client/composables/query/forms/usePdfTemplates.js
@@ -71,12 +71,21 @@ export function usePdfTemplates() {
})
}
+ const duplicate = (formId, templateId) => useMutation({
+ mutationFn: (data) => formsApi.pdfTemplates.duplicate(toValue(formId), toValue(templateId), data),
+ onSuccess: (response) => {
+ queryClient.setQueryData(detailKey(response.data.form_id, response.data.id), response)
+ invalidate(response.data.form_id)
+ },
+ })
+
return {
list,
detail,
upload,
update,
remove,
+ duplicate,
invalidate,
}
}
diff --git a/client/lib/pdf-template-duplication.js b/client/lib/pdf-template-duplication.js
new file mode 100644
index 000000000..1a1b50c3b
--- /dev/null
+++ b/client/lib/pdf-template-duplication.js
@@ -0,0 +1,33 @@
+const specialFields = new Set(['submission_id', 'submission_date', 'form_name'])
+
+export function getPdfDestinationFields(form) {
+ return [
+ ...(form?.properties || []).filter(field => !field.type?.startsWith('nf-')),
+ ...(form?.computed_variables || []).map(field => ({ ...field, type: 'computed' })),
+ ]
+}
+
+export function getPdfTemplateFields(template, form) {
+ const fields = getPdfDestinationFields(form)
+ const result = new Map()
+ for (const zone of template?.zone_mappings || []) {
+ if (zone.static_text !== undefined || zone.static_image !== undefined
+ || !zone.field_id || specialFields.has(zone.field_id)) continue
+ const field = fields.find(field => field.id === zone.field_id)
+ result.set(zone.field_id, {
+ id: zone.field_id,
+ name: field?.name || zone.field_name || 'Removed field',
+ type: field?.type,
+ })
+ }
+ return [...result.values()]
+}
+
+export function suggestPdfFieldMappings(sourceFields, destinationFields) {
+ return Object.fromEntries(sourceFields.map(source => {
+ const exact = destinationFields.find(field => field.id === source.id && field.type === source.type)
+ const matches = destinationFields.filter(field => field.type === source.type
+ && field.name.trim().toLowerCase() === source.name.trim().toLowerCase())
+ return [source.id, exact?.id || (matches.length === 1 ? matches[0].id : undefined)]
+ }))
+}
diff --git a/client/pages/forms/[slug]/show/pdf-templates.vue b/client/pages/forms/[slug]/show/pdf-templates.vue
index 5ac6de5b5..d17831987 100644
--- a/client/pages/forms/[slug]/show/pdf-templates.vue
+++ b/client/pages/forms/[slug]/show/pdf-templates.vue
@@ -1,5 +1,12 @@
<template>
<PageContainer spacing="md">
+ <DuplicatePdfTemplateModal
+ v-if="duplicateModalOpen && templateToDuplicate"
+ v-model:open="duplicateModalOpen"
+ :form="form"
+ :template="templateToDuplicate"
+ @duplicated="onDuplicated"
+ />
<PageSection
title="PDF Templates"
description="Create PDF documents from your form submissions."
@@ -133,6 +140,7 @@ import DashboardLoadingBlock from '~/components/dashboard/states/DashboardLoadin
import DashboardEmptyState from '~/components/dashboard/states/DashboardEmptyState.vue'
import { formsApi } from '~/api/forms'
import { usePdfTemplates } from '~/composables/query/forms/usePdfTemplates'
+import DuplicatePdfTemplateModal from '~/components/open/pdf-editor/DuplicatePdfTemplateModal.vue'
const props = defineProps({
form: { type: Object, required: true },
@@ -157,6 +165,8 @@ const fileInput = ref(null)
const uploading = ref(false)
const creatingFromScratch = ref(false)
const deletingId = ref(null)
+const templateToDuplicate = ref(null)
+const duplicateModalOpen = ref(false)
// Fetch templates
const { list, upload, remove } = usePdfTemplates()
@@ -255,6 +265,14 @@ const getTemplateMenuItems = (template) => {
icon: 'i-heroicons-eye',
onClick: () => previewTemplate(template)
},
+ {
+ label: 'Duplicate template',
+ icon: 'i-heroicons-document-duplicate',
+ onClick: () => {
+ templateToDuplicate.value = template
+ duplicateModalOpen.value = true
+ }
+ },
{
label: 'Edit',
icon: 'i-heroicons-pencil-square-20-solid',
@@ -273,6 +291,14 @@ const getTemplateMenuItems = (template) => {
]
}
+const onDuplicated = ({ template, form }) => {
+ alert.success('PDF template duplicated successfully.')
+ router.push({
+ name: 'forms-slug-pdf-editor-templateId',
+ params: { slug: form.slug, templateId: template.id }
+ })
+}
+
// Edit template
const editTemplate = (template) => {
router.push({
diff --git a/client/stores/working_pdf.js b/client/stores/working_pdf.js
index 8fe157059..e4cb2b9f1 100644
--- a/client/stores/working_pdf.js
+++ b/client/stores/working_pdf.js
@@ -230,7 +230,8 @@ export const useWorkingPdfStore = defineStore("working_pdf", {
page: this.currentPage,
page_id: currentEntry.id,
x: 10,
- y: 10 + (this.currentPageZones.length * 8),
+ // Start another stack before a new zone would extend past the page.
+ y: 10 + ((this.currentPageZones.length % 11) * 8),
width: 30,
height: 5,
font_size: 12,
diff --git a/client/test/nuxt/duplicate-pdf-template-modal.spec.ts b/client/test/nuxt/duplicate-pdf-template-modal.spec.ts
new file mode 100644
index 000000000..e3937d392
--- /dev/null
+++ b/client/test/nuxt/duplicate-pdf-template-modal.spec.ts
@@ -0,0 +1,78 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+import { flushPromises, mount } from '@vue/test-utils'
+import { ref } from 'vue'
+import { mockNuxtImport } from '@nuxt/test-utils/runtime'
+import DuplicatePdfTemplateModal from '~/components/open/pdf-editor/DuplicatePdfTemplateModal.vue'
+
+const state = vi.hoisted(() => ({
+ destination: null as any,
+ forms: null as any,
+ mutation: null as any,
+ mutateAsync: vi.fn(),
+}))
+vi.mock('~/composables/query/forms/useFormsList', () => ({ useFormsList: () => state.forms }))
+vi.mock('~/composables/query/forms/usePdfTemplates', () => ({
+ usePdfTemplates: () => ({ duplicate: () => state.mutation }),
+}))
+mockNuxtImport('useForms', () => () => ({ detailById: () => state.destination }))
+
+function mountModal() {
+ return mount(DuplicatePdfTemplateModal, {
+ props: {
+ open: true,
+ form: { id: 1, title: 'Source', workspace_id: 3, slug: 'source', properties: [] },
+ template: { id: 10, name: 'Static template', zone_mappings: [{ static_text: '<h1>Agreement</h1>' }] },
+ },
+ global: { stubs: {
+ UModal: { props: ['open'], template: '<section><slot name="body" /><slot name="footer" /></section>' },
+ UAlert: { props: ['title'], template: '<div role="alert">{{ title }}</div>' },
+ UButton: { props: ['disabled', 'loading'], template: '<button :disabled="disabled || loading"><slot /></button>' },
+ TextInput: { template: '<input />' },
+ SelectInput: {
+ props: ['modelValue', 'options'],
+ emits: ['update:modelValue'],
+ template: '<select :value="modelValue" @change="$emit(\'update:modelValue\', Number($event.target.value))"><option v-for="option in options" :key="option.value" :value="option.value">{{ option.name }}</option></select>',
+ },
+ } },
+ })
+}
+
+describe('static-only PDF template duplication', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ state.destination = { data: ref(undefined), isLoading: ref(true), error: ref(null) }
+ state.forms = { forms: ref([{ id: 2, title: 'Destination' }]), isLoading: ref(false), isFetchingNextPage: ref(false), error: ref(null) }
+ state.mutation = { mutateAsync: state.mutateAsync, isPending: ref(false) }
+ })
+
+ it('shows destination loading and failure even when there are no mapped fields', async () => {
+ const wrapper = mountModal()
+ await wrapper.get('select').setValue('2')
+ expect(wrapper.text()).toContain('Loading destination fields')
+ expect(wrapper.findAll('button').at(-1)!.attributes('disabled')).toBeDefined()
+
+ state.destination.isLoading.value = false
+ state.destination.error.value = new Error('Destination unavailable')
+ await flushPromises()
+ expect(wrapper.get('[role="alert"]').text()).toBe('Could not load destination fields.')
+ expect(wrapper.findAll('button').at(-1)!.attributes('disabled')).toBeDefined()
+ expect(state.mutateAsync).not.toHaveBeenCalled()
+ wrapper.unmount()
+ })
+
+ it('can copy a static-only template after the destination loads', async () => {
+ const wrapper = mountModal()
+ await wrapper.get('select').setValue('2')
+ const destination = { id: 2, slug: 'destination', title: 'Destination', properties: [] }
+ state.destination.data.value = destination
+ state.destination.isLoading.value = false
+ state.mutateAsync.mockResolvedValue({ data: { id: 20, form_id: 2 } })
+ await flushPromises()
+ expect(wrapper.findAll('button').at(-1)!.attributes('disabled')).toBeUndefined()
+ await wrapper.get('form').trigger('submit')
+ await flushPromises()
+ expect(state.mutateAsync).toHaveBeenCalledWith({ target_form_id: 2, name: 'Copy of Static template', field_mappings: {} })
+ expect(wrapper.emitted('duplicated')?.[0]).toEqual([{ template: { id: 20, form_id: 2 }, form: destination }])
+ wrapper.unmount()
+ })
+})
diff --git a/client/test/nuxt/form-detail-reactive-id.spec.ts b/client/test/nuxt/form-detail-reactive-id.spec.ts
new file mode 100644
index 000000000..8f8a0fe18
--- /dev/null
+++ b/client/test/nuxt/form-detail-reactive-id.spec.ts
@@ -0,0 +1,28 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+import { ref } from 'vue'
+import { useForms } from '~/composables/query/forms/useForms'
+import { formsApi } from '~/api/forms'
+
+vi.mock('@tanstack/vue-query', () => ({
+ useQuery: (options: any) => options,
+ useMutation: vi.fn(),
+ useQueryClient: () => ({}),
+}))
+vi.mock('~/api/forms', () => ({
+ formsApi: { getById: vi.fn(), publicGetById: vi.fn() },
+}))
+
+describe('form detail queries with a reactive destination id', () => {
+ beforeEach(() => vi.clearAllMocks())
+
+ it.each([true, false])('uses the current id for private=%s queries', usePrivate => {
+ const targetId = ref(10)
+ const query = useForms().detailById(targetId, { usePrivate }) as any
+ const fetch = usePrivate ? formsApi.getById : formsApi.publicGetById
+ query.queryFn()
+ expect(fetch).toHaveBeenLastCalledWith(10, {})
+ targetId.value = 20
+ query.queryFn()
+ expect(fetch).toHaveBeenLastCalledWith(20, {})
+ })
+})
diff --git a/client/test/nuxt/quilly-editor-content.spec.ts b/client/test/nuxt/quilly-editor-content.spec.ts
new file mode 100644
index 000000000..f19e482c1
--- /dev/null
+++ b/client/test/nuxt/quilly-editor-content.spec.ts
@@ -0,0 +1,75 @@
+import { describe, expect, it, vi } from 'vitest'
+import { mount } from '@vue/test-utils'
+import QuillyEditor from '~/components/forms/heavy/components/QuillyEditor.vue'
+
+describe('QuillyEditor external content changes', () => {
+ it('replaces the previous zone content and formatting without emitting edits', async () => {
+ const wrapper = mount(QuillyEditor, {
+ attachTo: document.body,
+ props: { modelValue: '<h1>Document title</h1>' },
+ })
+ await wrapper.setProps({ modelValue: '<p>Full name</p>' })
+
+ expect(wrapper.get('.ql-editor').text()).toBe('Full name')
+ expect(wrapper.find('.ql-editor h1').exists()).toBe(false)
+ expect(wrapper.emitted('update:modelValue')).toBeUndefined()
+
+ await wrapper.setProps({ modelValue: '<p>Email</p>' })
+ expect(wrapper.get('.ql-editor').text()).toBe('Email')
+ await wrapper.setProps({ modelValue: '' })
+ expect(wrapper.get('.ql-editor').text()).toBe('')
+ expect(wrapper.emitted('update:modelValue')).toBeUndefined()
+ wrapper.unmount()
+ })
+
+ it('emits user edits and clearing after switching content', async () => {
+ const wrapper = mount(QuillyEditor, {
+ attachTo: document.body,
+ props: { modelValue: '<p>Before</p>' },
+ })
+ await wrapper.setProps({ modelValue: '<p>After</p>' })
+ const quill = wrapper.emitted('ready')![0][0] as any
+ quill.insertText(5, ' edited', 'user')
+ expect(wrapper.emitted('update:modelValue')?.at(-1)?.[0]).toContain('After edited')
+ quill.deleteText(0, quill.getLength(), 'user')
+ expect(wrapper.emitted('update:modelValue')).toHaveLength(2)
+ expect(quill.getText().trim()).toBe('')
+ wrapper.unmount()
+ })
+
+ it('keeps undo and redo within the current zone after switching documents', async () => {
+ const wrapper = mount(QuillyEditor, {
+ attachTo: document.body,
+ props: { modelValue: '<h1>Zone A</h1>' },
+ })
+ const quill = wrapper.emitted('ready')![0][0] as any
+ // JSDOM has no range geometry; keep the real history and content operations.
+ vi.spyOn(quill, 'scrollSelectionIntoView').mockImplementation(() => {})
+ quill.history.undo()
+ expect(wrapper.get('.ql-editor').text()).toBe('Zone A')
+ expect(wrapper.emitted('update:modelValue')).toBeUndefined()
+
+ quill.insertText(6, ' edited', 'user')
+ quill.history.cutoff()
+ await wrapper.setProps({ modelValue: '<p>Zone B</p>' })
+ quill.history.undo()
+ quill.history.redo()
+ expect(wrapper.get('.ql-editor').text()).toBe('Zone B')
+ expect(wrapper.find('.ql-editor h1').exists()).toBe(false)
+ expect(wrapper.emitted('update:modelValue')).toHaveLength(1)
+
+ quill.insertText(6, ' edited', 'user')
+ quill.history.undo()
+ expect(wrapper.get('.ql-editor').text()).toBe('Zone B')
+ quill.history.redo()
+ expect(wrapper.get('.ql-editor').text()).toBe('Zone B edited')
+
+ await wrapper.setProps({ modelValue: '' })
+ const editCount = wrapper.emitted('update:modelValue')!.length
+ quill.history.undo()
+ quill.history.redo()
+ expect(wrapper.get('.ql-editor').text()).toBe('')
+ expect(wrapper.emitted('update:modelValue')).toHaveLength(editCount)
+ wrapper.unmount()
+ })
+})
diff --git a/client/test/unit/pdf-template-duplication.test.ts b/client/test/unit/pdf-template-duplication.test.ts
new file mode 100644
index 000000000..4fa838da8
--- /dev/null
+++ b/client/test/unit/pdf-template-duplication.test.ts
@@ -0,0 +1,37 @@
+import { describe, expect, it } from 'vitest'
+import { getPdfDestinationFields, getPdfTemplateFields, suggestPdfFieldMappings } from '../../lib/pdf-template-duplication'
+
+describe('PDF template field mappings', () => {
+ it('lists each mapped field once, preserving removed field labels and excluding static and special zones', () => {
+ const template = { zone_mappings: [
+ { field_id: 'name' }, { field_id: 'name' },
+ { field_id: 'removed', field_name: 'Old label' },
+ { field_id: 'submission_id' }, { static_text: 'Text' }, { static_image: 'image.png' },
+ { field_id: 'total' },
+ ] }
+ const form = { properties: [{ id: 'name', name: 'Name', type: 'text' }], computed_variables: [{ id: 'total', name: 'Total' }] }
+ expect(getPdfTemplateFields(template, form)).toEqual([
+ { id: 'name', name: 'Name', type: 'text' },
+ { id: 'removed', name: 'Old label', type: undefined },
+ { id: 'total', name: 'Total', type: 'computed' },
+ ])
+ })
+
+ it('suggests only unique name and type matches or identical field ids', () => {
+ const source = [
+ { id: 'same', name: 'Renamed', type: 'text' },
+ { id: 'new', name: ' EMAIL ', type: 'email' },
+ { id: 'ambiguous', name: 'Name', type: 'text' },
+ { id: 'missing', name: 'Age', type: 'number' },
+ ]
+ const target = getPdfDestinationFields({ properties: [
+ { id: 'same', name: 'Original', type: 'text' },
+ { id: 'email', name: 'Email', type: 'email' },
+ { id: 'one', name: 'Name', type: 'text' },
+ { id: 'two', name: 'Name', type: 'text' },
+ { id: 'section', name: 'Heading', type: 'nf-text' },
+ ] })
+ expect(target).toHaveLength(4)
+ expect(suggestPdfFieldMappings(source, target)).toEqual({ same: 'same', new: 'email', ambiguous: undefined, missing: undefined })
+ })
+})
diff --git a/client/test/unit/working-pdf-store.test.ts b/client/test/unit/working-pdf-store.test.ts
index 838e06336..6cb2ac210 100644
--- a/client/test/unit/working-pdf-store.test.ts
+++ b/client/test/unit/working-pdf-store.test.ts
@@ -20,6 +20,19 @@ describe('working_pdf store - page_manifest model', () => {
setActivePinia(createPinia())
})
+ it('keeps new zones inside a populated page across repeated additions', () => {
+ const store = useWorkingPdfStore()
+ store.set(createTemplateFixture())
+ for (let i = 0; i < 40; i++) {
+ store.addZoneWithField({ id: 'submission_id', name: 'Submission ID' })
+ const zone = store.selectedZone!
+ expect(zone.y).toBeGreaterThanOrEqual(0)
+ expect(zone.y + zone.height).toBeLessThanOrEqual(100)
+ expect(zone.x + zone.width).toBeLessThanOrEqual(100)
+ }
+ expect(store.getSaveData()!.zone_mappings).toHaveLength(40)
+ })
+
it('creates default source page manifest when missing', () => {
const store = useWorkingPdfStore()
store.set(createTemplateFixture({ page_count: 3 }))
diff --git a/docs/docs.json b/docs/docs.json
index 02a605694..90a53090c 100644
--- a/docs/docs.json
+++ b/docs/docs.json
@@ -23,7 +23,8 @@
{
"group": "Features",
"pages": [
- "features/computed-variables"
+ "features/computed-variables",
+ "features/pdf-templates"
]
},
{
diff --git a/docs/features/pdf-templates.mdx b/docs/features/pdf-templates.mdx
new file mode 100644
index 000000000..279d78e27
--- /dev/null
+++ b/docs/features/pdf-templates.mdx
@@ -0,0 +1,28 @@
+---
+title: 'PDF templates'
+description: 'Create reusable PDF layouts and duplicate them within your workspace.'
+---
+
+You can create PDF documents from submissions using **PDF Templates** on your form dashboard. Upload a PDF or choose **Add template → Create from scratch**, then position text, images and mapped fields in the editor.
+
+## Duplicate a template
+
+1. Open your form's **PDF Templates** tab.
+2. Open the template's menu and choose **Duplicate template**.
+3. Enter a name and select the destination form. You can choose the current form or another form in the same workspace.
+4. When copying to another form, review the field mappings. Unique matches with the same name and type are preselected. Choose a destination field or **Skip this field** for every remaining field. Computed variables can also be mapped.
+5. Select **Duplicate template** to open the new copy in the editor.
+
+<Note>
+You need edit access to both forms. Skipped field zones are excluded from the copy; their static text labels remain. Special fields such as the submission ID use the destination form's submission data automatically.
+</Note>
+
+The copy keeps the page order, text, images, filename pattern and branding setting. Its PDF file is independent, so editing or deleting either template does not affect the other. Duplicating a template does not change email attachments or the form's selected download template; select the copy separately where needed.
+
+## Edit pages and zones
+
+Use **Add Zone** to insert a form field, computed variable, static text or image. New zones always start inside the page. Drag and resize zones to adjust your layout.
+
+The **Duplicate page** control in the left sidebar copies a page inside the current template. Use **Duplicate template** from the template list when you need a separate document.
+
+Save your changes before opening **Preview**. The preview includes sample submission values when submissions are available.