diff --git a/docs/API_v3.md b/docs/API_v3.md index 90ead699e..72b0eb978 100644 --- a/docs/API_v3.md +++ b/docs/API_v3.md @@ -37,7 +37,7 @@ Some requests succeed with their usual status, and their payload keeps its shape | Key | Value | Set by | Meaning | |-----|-------|--------|---------| -| `removed-jumps` | Inner list of question ids, e.g. `(3 7)` | Updating, reordering and copying questions; deleting options; changing the bounds of a linear scale | Jumps to the question itself or to an earlier question, jumps of the deleted option or of options that are not options of the question, or jumps for values outside the scale, were removed from the `extraSettings` of these questions, see [Jumps](DataStructure.md#jumps) | +| `removed-jumps` | Inner list of question ids, e.g. `(3 7)` | Updating, reordering and copying questions; inserting a section; deleting options; changing the bounds of a linear scale | Jumps to the question itself, to an earlier question or into the middle of another section, jumps of the deleted option or of options that are not options of the question, or jumps for values outside the scale, were removed from the `extraSettings` of these questions, see [Jumps](DataStructure.md#jumps) | ``` X-Forms-Adjusted: removed-jumps=(3 7) @@ -64,7 +64,7 @@ When more than 100 questions lost jumps, which only a reorder can cause, `remove ### Other API changes -- Questions can jump to a later question or to the end of the form with the extra settings `goTo` (per answer, on dropdown, radio and linear scale questions) or `next` (after the question, on the other types with jumps), never both (see [Jumps](DataStructure.md#jumps)). Jumps to questions of other forms are rejected, jumps for options that are not options of the question are removed, deleting an option removes its jumps, and narrowing a linear scale removes the jumps of the values that are gone. Submissions and submission updates ignore answers to the questions the jumps skip and do not require them, the path ends at an unanswered question with a jump per answer past the following question, and an answer "Other" needs a text. Updating, reordering and copying questions removes jumps to the question itself or to an earlier question; the response header `X-Forms-Adjusted` then lists the questions concerned under `removed-jumps` (see [Adjustments by the server](#adjustments-by-the-server)). Copying or importing a form drops such jumps as well, without the header, as these create a new form. +- Questions can jump to a later question or to the end of the form with the extra settings `goTo` (per answer, on dropdown, radio and linear scale questions) or `next` (after the question, on the other types with jumps), never both (see [Jumps](DataStructure.md#jumps)). Jumps to questions of other forms are rejected, jumps for options that are not options of the question are removed, deleting an option removes its jumps, and narrowing a linear scale removes the jumps of the values that are gone. Submissions and submission updates ignore answers to the questions the jumps skip and do not require them, the path ends at an unanswered question with a jump per answer past the following question, and an answer "Other" needs a text. Updating, reordering and copying questions removes jumps to the question itself, to an earlier question or into the middle of another section; the response header `X-Forms-Adjusted` then lists the questions concerned under `removed-jumps` (see [Adjustments by the server](#adjustments-by-the-server)). Copying or importing a form drops such jumps as well, without the header, as these create a new form. - In API version 3.0 the following endpoints were introduced/changed: - `GET /api/v3/forms/{formId}/questions` to get all questions of a form - `GET /api/v3/forms/{formId}/questions/{questionId}` to get a single question @@ -276,7 +276,7 @@ Creates a clone of a form (without submissions). | Parameter | Type | Description | |-----------|---------|-------------| | _formId_ | Integer | ID of the form to clone | -- Response: Returns the full object of the new form. See [Request full data of a Form](#request-full-data-of-a-form). The jumps of the copied questions point at the copied questions and options; jumps whose target or option was not copied, jumps that would go to the question itself or to an earlier question, and `goTo` or `next` on a question type without it, are dropped, without the header `X-Forms-Adjusted` (see [Jumps](DataStructure.md#jumps)). +- Response: Returns the full object of the new form. See [Request full data of a Form](#request-full-data-of-a-form). The jumps of the copied questions point at the copied questions and options; jumps whose target or option was not copied, jumps that would go to the question itself, to an earlier question or into the middle of another section, and `goTo` or `next` on a question type without it, are dropped, without the header `X-Forms-Adjusted` (see [Jumps](DataStructure.md#jumps)). ``` See section 'Request full data of a form'. @@ -396,7 +396,7 @@ Returns the questions and options of the given form (without submissions). | _text_ | String | yes | _Optional_ The text of the new question. | | _position_ | Integer | yes | _(optional)_ 1-based position to insert the new question. When omitted the question is appended at the end. | - Restrictions: A `grid` question needs its cell type as _subtype_. A _subtype_ for a question type without sub types is rejected with **400 Bad Request**. -- Response: The new question object. +- Response: The new question object. A `section` inserted or cloned at a _position_ removes the jumps of other questions that would go into its middle (see [Jumps](DataStructure.md#jumps)), and the response header `X-Forms-Adjusted` then lists them under `removed-jumps` (see [Adjustments by the server](#adjustments-by-the-server)). ``` "data": { @@ -474,7 +474,7 @@ Update a single or multiple properties of a question-object. - It is **not allowed** to update one of the following key-value pairs: _id, formId, order, type_. - The sub type `extraSettings.questionType` is fixed when the question is created. An `extraSettings` value that adds, removes or changes `questionType` is rejected with **403 Forbidden**, so send the stored `questionType` with every `extraSettings` update. - A promoter score question (`questionType` `promoter`) keeps `optionsLowest` at `0` and `optionsHighest` at `10`; send both with every `extraSettings` update, or it is rejected with **400 Bad Request**. -- Response: **Status-Code OK**, as well as the id of the updated question. Jumps in `extraSettings` that go to the question itself or to an earlier question, and jumps of a linear scale for values outside its bounds, are removed before saving (see [Jumps](DataStructure.md#jumps)), and the response header `X-Forms-Adjusted` then holds `removed-jumps=()` (see [Adjustments by the server](#adjustments-by-the-server)). Jumps with an invalid structure, `goTo` or `next` on a question type without it, and ids of questions of other forms are rejected with **Status-Code Bad Request** "Invalid extraSettings, will not update." Jumps for options that are not options of the question are removed before saving, with the same header. +- Response: **Status-Code OK**, as well as the id of the updated question. Jumps in `extraSettings` that go to the question itself, to an earlier question or into the middle of another section, and jumps of a linear scale for values outside its bounds, are removed before saving (see [Jumps](DataStructure.md#jumps)), and the response header `X-Forms-Adjusted` then holds `removed-jumps=()` (see [Adjustments by the server](#adjustments-by-the-server)). Jumps with an invalid structure, `goTo` or `next` on a question type without it, and ids of questions of other forms are rejected with **Status-Code Bad Request** "Invalid extraSettings, will not update." Jumps for options that are not options of the question are removed before saving, with the same header. ``` "data": 1 @@ -495,7 +495,7 @@ Reorders all Questions of a single form |-----------|---------|-------------| | _newOrder_ | Array | Array of **all** Question-IDs, ordered in the desired order | - Restrictions: The Array **must** contain all Question-IDs corresponding to the specified form and **must not** contain any duplicates. -- Response: Array of questionIDs and their corresponding order. Jumps that would go to the question itself or to an earlier question are removed (see [Jumps](DataStructure.md#jumps)): the questions concerned also carry their new `extraSettings`, and the response header `X-Forms-Adjusted` then lists their ids, e.g. `X-Forms-Adjusted: removed-jumps=(3 7)`, or holds `removed-jumps` alone for more than 100 questions (see [Adjustments by the server](#adjustments-by-the-server)). +- Response: Array of questionIDs and their corresponding order. Jumps that would go to the question itself, to an earlier question or into the middle of another section are removed (see [Jumps](DataStructure.md#jumps)): the questions concerned also carry their new `extraSettings`, and the response header `X-Forms-Adjusted` then lists their ids, e.g. `X-Forms-Adjusted: removed-jumps=(3 7)`, or holds `removed-jumps` alone for more than 100 questions (see [Adjustments by the server](#adjustments-by-the-server)). An id of a deleted question gets a **Not Found** response. ``` @@ -542,7 +542,7 @@ Creates a clone of a question with all its options. | Parameter | Type | Optional | Description | |-----------|---------|----------|-------------| | _position_ | Integer | yes | _(optional)_ 1-based position to insert the cloned question. When omitted the clone is appended at the end. | -- Response: Returns cloned question object with the new ID set. Jumps that would go to the clone itself or to an earlier question, for example when it is appended at the end, are removed from its `extraSettings` (see [Jumps](DataStructure.md#jumps)), and the response header `X-Forms-Adjusted` then holds `removed-jumps=()` (see [Adjustments by the server](#adjustments-by-the-server)). +- Response: Returns cloned question object with the new ID set. Jumps that would go to the clone itself, to an earlier question or into the middle of another section, for example when it is appended at the end, are removed from its `extraSettings` (see [Jumps](DataStructure.md#jumps)), and the response header `X-Forms-Adjusted` then holds `removed-jumps=()` (see [Adjustments by the server](#adjustments-by-the-server)). ``` See section 'Create a new question'. diff --git a/docs/DataStructure.md b/docs/DataStructure.md index 321c8d824..da790fbbf 100644 --- a/docs/DataStructure.md +++ b/docs/DataStructure.md @@ -285,6 +285,7 @@ An answer can lead to a later question or to the end of the form, as in Microsof - A question has either jumps per answer or one jump after the question, depending on its type: `goTo` only on `dropdown`, `linearscale` and `multiple_unique`, `next` only on the other types listed above. Sending `next` on a question type with `goTo`, or `goTo` on a question type with `next`, is rejected with 400 "Invalid extraSettings". An answer without a `goTo` entry leads to the following question. - A target is the id of a later question of the same form or `"submit"` for the end of the form, and `optionId` is the id of an option of the question. Ids of questions of other forms are rejected as invalid `extraSettings`, while ids of deleted questions of the form are accepted. Updating a question removes its jumps for option ids that are not options of the question; the response header `X-Forms-Adjusted` then holds `removed-jumps` with the id of the question. - Jumps never go back: the server removes jumps to the question itself or to an earlier question when a question is updated, reordered or copied, and when a form is copied or imported; copying or importing a form also drops `goTo` or `next` on question types without it. Updating, reordering and copying a question still succeed with their usual status, and the payload keeps its shape: a reorder adds the new `extraSettings` of the questions concerned, and a copied question is returned with its reduced `extraSettings`. The response header `X-Forms-Adjusted` lists the questions that lost jumps, e.g. `removed-jumps=(3 7)`, see [Adjustments by the server](API_v3.md#adjustments-by-the-server). +- In a form with sections, a jump also never goes into the middle of another section: it goes to a later question of its own section, to a later section or to the end of the form. The server removes other jumps in the same cases as backward jumps, and inserting or cloning a section at a position removes the jumps of other questions that would go into its middle, with the header `X-Forms-Adjusted` listing them. - Deleting an option removes the jumps of the question for that option; the response header `X-Forms-Adjusted` then holds `removed-jumps` with the id of the question. - Saving a question rejects jumps with an invalid structure with 400, as any invalid `extraSettings`. Copying or importing a form keeps the jumps whose target and option it can map, and drops the others and jumps per answer with an invalid structure. The path walks ignore malformed entries. - Only the deprecated `datetime` accepts neither `goTo` nor `next` (400). diff --git a/lib/Controller/ApiController.php b/lib/Controller/ApiController.php index 261054fd1..c31cf436f 100644 --- a/lib/Controller/ApiController.php +++ b/lib/Controller/ApiController.php @@ -539,7 +539,8 @@ public function getQuestion(int $formId, int $questionId): DataResponse { /** * Add a new question * - * A clone loses its jumps to itself or to an earlier question, and the header `X-Forms-Adjusted` then holds `removed-jumps` with its id + * A clone loses its jumps to itself, to an earlier question or into the middle of another section, and the header `X-Forms-Adjusted` then holds `removed-jumps` with its id. + * A section inserted or cloned at a position removes the jumps of other questions that would go into its middle, and the header then holds `removed-jumps` with their ids. * * @param int $formId the form id * @param FormsQuestionType $type the new question type @@ -690,7 +691,7 @@ public function newQuestion(int $formId, ?string $type = null, ?string $subtype $newQuestion->setExtraSettings(FormsService::mapJumps($extraSettings, null, $optionIdMap)); $formQuestions = [...$allQuestions, $newQuestion]; usort($formQuestions, static fn (Question $a, Question $b): int => $a->getOrder() <=> $b->getOrder()); - if (in_array($newQuestion, FormsService::removeBackwardJumps($formQuestions), true)) { + if (in_array($newQuestion, FormsService::removeDisallowedJumps($formQuestions), true)) { $headers = self::getRemovedJumpsHeaders([$newQuestion->getId()]); } if ($newQuestion->getExtraSettings() !== $extraSettings) { @@ -700,6 +701,16 @@ public function newQuestion(int $formId, ?string $type = null, ?string $subtype } } + if (($response['type'] ?? null) === Constants::ANSWER_TYPE_SECTION && $position !== null) { + $changedQuestions = FormsService::removeDisallowedJumps($this->questionMapper->findByForm($formId)); + foreach ($changedQuestions as $changedQuestion) { + $this->questionMapper->update($changedQuestion); + } + if ($changedQuestions !== []) { + $headers = self::getRemovedJumpsHeaders(array_map(static fn (Question $changedQuestion): int => $changedQuestion->getId(), $changedQuestions)); + } + } + $this->formMapper->update($form); if (empty($response['extraSettings'])) { @@ -713,7 +724,7 @@ public function newQuestion(int $formId, ?string $type = null, ?string $subtype * Writes the given key-value pairs into Database * Key `order` should only be changed by reorderQuestions() and is not allowed here * - * Jumps to the question itself or to an earlier question, and jumps of a linear scale for values outside its bounds, are removed before saving, and the header `X-Forms-Adjusted` then holds `removed-jumps` with the id of the question. + * Jumps to the question itself, to an earlier question or into the middle of another section, and jumps of a linear scale for values outside its bounds, are removed before saving, and the header `X-Forms-Adjusted` then holds `removed-jumps` with the id of the question. * Jumps for options that are not options of the question are removed as well, with the same header. Jumps to questions of other forms are rejected as invalid `extraSettings`. * * @param int $formId the form id @@ -807,7 +818,7 @@ public function updateQuestion(int $formId, int $questionId, array $keyValuePair if (FormsService::removeJumpsOutsideScale($updatedQuestion)) { $removedJumps = true; } - if (in_array($updatedQuestion, FormsService::removeBackwardJumps($formQuestions), true)) { + if (in_array($updatedQuestion, FormsService::removeDisallowedJumps($formQuestions), true)) { $removedJumps = true; } $keyValuePairs['extraSettings'] = $updatedQuestion->getExtraSettings(); @@ -908,7 +919,7 @@ public function deleteQuestion(int $formId, int $questionId): DataResponse { /** * Updates the Order of all Questions of a Form * - * Jumps that would go to the question itself or to an earlier question are removed: the new extra settings of these questions are returned, and the header `X-Forms-Adjusted` holds `removed-jumps` with their ids, or alone for more than 100 questions + * Jumps that would go to the question itself, to an earlier question or into the middle of another section are removed: the new extra settings of these questions are returned, and the header `X-Forms-Adjusted` holds `removed-jumps` with their ids, or alone for more than 100 questions * * @param int $formId Id of the form to reorder * @param list $newOrder Array of Question-Ids in new order. @@ -984,7 +995,7 @@ public function reorderQuestions(int $formId, array $newOrder): DataResponse { } } - $changedQuestions = FormsService::removeBackwardJumps($questions); + $changedQuestions = FormsService::removeDisallowedJumps($questions); // Write to Database foreach ($questions as $question) { diff --git a/lib/Service/FormsService.php b/lib/Service/FormsService.php index 3108ecc62..c0a88d8c9 100644 --- a/lib/Service/FormsService.php +++ b/lib/Service/FormsService.php @@ -1251,7 +1251,7 @@ public static function mapJumps(array $extraSettings, ?array $questionIdMap, arr } /** - * Point the jumps of copied questions at the copied questions and options, and remove the jumps that go to the question itself or to an earlier question, jumps per answer with an invalid structure or for an answer with a jump already, and `goTo` or `next` on question types without it + * Point the jumps of copied questions at the copied questions and options, and remove the jumps that go to the question itself, to an earlier question or into the middle of another section, jumps per answer with an invalid structure or for an answer with a jump already, and `goTo` or `next` on question types without it * * @param list $questions the copied questions * @param array $questionIdMap the ids of the copied questions by original id @@ -1289,32 +1289,42 @@ public static function mapJumpsOfCopies(array $questions, array $questionIdMap, if ($copiesWithJumps !== []) { usort($questions, static fn (Question $a, Question $b): int => $a->getOrder() <=> $b->getOrder()); - self::removeBackwardJumps($questions); + self::removeDisallowedJumps($questions); } return $copiesWithJumps; } /** - * Remove the jumps that go to the question itself or to an earlier question, keeping the jumps to the end of the form, to later questions and to questions that are not in the list + * Remove the jumps that go to the question itself, to an earlier question or into the middle of another section, keeping the jumps to the end of the form, to later questions of the same section, to later sections and to questions that are not in the list * * @param list $questions the questions of the form in their order * @return list the questions whose jumps were removed, with their new extra settings set */ - public static function removeBackwardJumps(array $questions): array { + public static function removeDisallowedJumps(array $questions): array { $positions = array_flip(array_map(static fn (Question $question): int => $question->getId(), $questions)); + $sections = []; + $section = 0; + foreach ($questions as $position => $question) { + if ($question->getType() === Constants::ANSWER_TYPE_SECTION) { + $section++; + } + $sections[$position] = $section; + } $changed = []; foreach ($questions as $position => $question) { - $isBackward = static fn (mixed $target): bool => is_int($target) && isset($positions[$target]) && $positions[$target] <= $position; + $isDisallowed = static fn (mixed $target): bool => is_int($target) && isset($positions[$target]) + && ($positions[$target] <= $position + || ($questions[$positions[$target]]->getType() !== Constants::ANSWER_TYPE_SECTION && $sections[$positions[$target]] !== $sections[$position])); $extraSettings = $question->getExtraSettings(); $newSettings = $extraSettings; - if ($isBackward($extraSettings['next'] ?? null)) { + if ($isDisallowed($extraSettings['next'] ?? null)) { unset($newSettings['next']); } if (is_array($extraSettings['goTo'] ?? null)) { - $goTo = array_values(array_filter($extraSettings['goTo'], static fn (mixed $jump): bool => !$isBackward(is_array($jump) ? ($jump['target'] ?? null) : null))); + $goTo = array_values(array_filter($extraSettings['goTo'], static fn (mixed $jump): bool => !$isDisallowed(is_array($jump) ? ($jump['target'] ?? null) : null))); if (count($goTo) !== count($extraSettings['goTo'])) { $newSettings['goTo'] = $goTo; } diff --git a/openapi.json b/openapi.json index b0a6c2023..5f911b1e8 100644 --- a/openapi.json +++ b/openapi.json @@ -1758,7 +1758,7 @@ "post": { "operationId": "api-new-question", "summary": "Add a new question", - "description": "A clone loses its jumps to itself or to an earlier question, and the header `X-Forms-Adjusted` then holds `removed-jumps` with its id\nThis endpoint allows CORS requests", + "description": "A clone loses its jumps to itself, to an earlier question or into the middle of another section, and the header `X-Forms-Adjusted` then holds `removed-jumps` with its id. A section inserted or cloned at a position removes the jumps of other questions that would go into its middle, and the header then holds `removed-jumps` with their ids.\nThis endpoint allows CORS requests", "tags": [ "api" ], @@ -1990,7 +1990,7 @@ "patch": { "operationId": "api-reorder-questions", "summary": "Updates the Order of all Questions of a Form", - "description": "Jumps that would go to the question itself or to an earlier question are removed: the new extra settings of these questions are returned, and the header `X-Forms-Adjusted` holds `removed-jumps` with their ids, or alone for more than 100 questions\nThis endpoint allows CORS requests", + "description": "Jumps that would go to the question itself, to an earlier question or into the middle of another section are removed: the new extra settings of these questions are returned, and the header `X-Forms-Adjusted` holds `removed-jumps` with their ids, or alone for more than 100 questions\nThis endpoint allows CORS requests", "tags": [ "api" ], @@ -2398,7 +2398,7 @@ "patch": { "operationId": "api-update-question", "summary": "Writes the given key-value pairs into Database Key `order` should only be changed by reorderQuestions() and is not allowed here", - "description": "Jumps to the question itself or to an earlier question, and jumps of a linear scale for values outside its bounds, are removed before saving, and the header `X-Forms-Adjusted` then holds `removed-jumps` with the id of the question. Jumps for options that are not options of the question are removed as well, with the same header. Jumps to questions of other forms are rejected as invalid `extraSettings`.\nThis endpoint allows CORS requests", + "description": "Jumps to the question itself, to an earlier question or into the middle of another section, and jumps of a linear scale for values outside its bounds, are removed before saving, and the header `X-Forms-Adjusted` then holds `removed-jumps` with the id of the question. Jumps for options that are not options of the question are removed as well, with the same header. Jumps to questions of other forms are rejected as invalid `extraSettings`.\nThis endpoint allows CORS requests", "tags": [ "api" ], diff --git a/playwright/e2e/jump-issues.spec.ts b/playwright/e2e/jump-issues.spec.ts index 9aa23d286..35a43d770 100644 --- a/playwright/e2e/jump-issues.spec.ts +++ b/playwright/e2e/jump-issues.spec.ts @@ -11,7 +11,7 @@ import { formatList, getJumpIssues, getNewlyBrokenQuestions, - withoutBackwardJumps, + withoutDisallowedJumps, withoutRemovedJumps, } from '../../src/utils/Jumps.ts' @@ -258,7 +258,7 @@ test('jumps: only a question the submit view shows with answers to choose from c test('jumps: a new order loses only the jumps to the question itself or to an earlier question', () => { const unchanged = short(3, { next: 'submit' }) - const reordered = withoutBackwardJumps([ + const reordered = withoutDisallowedJumps([ short(2), radio(1, { goTo: [ @@ -280,6 +280,45 @@ test('jumps: a new order loses only the jumps to the question itself or to an ea expect(reordered[3]).toBe(unchanged) }) +test('jumps: in a form with sections, a jump into the middle of another section is removed', () => { + const section = (id: number): FormsQuestion => ({ + ...short(id), + type: 'section', + }) + const allowed = withoutDisallowedJumps([ + radio(1, { + goTo: [ + { optionId: 11, target: 2 }, + { optionId: 12, target: 3 }, + { optionId: 13, target: 4 }, + { optionId: 14, target: 6 }, + { optionId: 15, target: 5 }, + { optionId: 16, target: 'submit' }, + ], + }), + short(2, { next: 5 }), + section(3), + short(4, { next: 6 }), + section(5), + short(6), + ]) + expect(allowed.map((question) => question.extraSettings)).toEqual([ + { + goTo: [ + { optionId: 11, target: 2 }, + { optionId: 12, target: 3 }, + { optionId: 15, target: 5 }, + { optionId: 16, target: 'submit' }, + ], + }, + { next: 5 }, + {}, + {}, + {}, + {}, + ]) +}) + test('jumps: only the jumps a reorder removed are removed from newer extra settings', () => { const before = { goTo: [ diff --git a/playwright/e2e/sections.spec.ts b/playwright/e2e/sections.spec.ts index a561b8ef3..4e50e3ae0 100644 --- a/playwright/e2e/sections.spec.ts +++ b/playwright/e2e/sections.spec.ts @@ -71,7 +71,9 @@ test.describe('Sections', () => { ).toHaveCount(0) }) - test('A jump lists a later section by its own number', async ({ page }) => { + test('A jump lists the later sections, not the questions inside them', async ({ + page, + }) => { const { form } = await createSectionForm(page.request) await page.goto(`apps/forms/${form.hash}/edit`) @@ -86,8 +88,6 @@ test.describe('Sections', () => { await expect(page.getByRole('option')).toHaveText([ 'Next question', 'Section 1: About the pet', - 'Question 2: Which pet?', - 'Question 3: Comments', 'End of the form', ]) }) @@ -101,7 +101,7 @@ test.describe('Sections', () => { await api(page.request, 'PATCH', `/forms/${form.id}/questions/${pet.id}`, { keyValuePairs: { extraSettings: { - goTo: [{ optionId: options[1].id, target: comments.id }], + goTo: [{ optionId: options[1].id, target: 'submit' }], }, }, }) @@ -125,14 +125,13 @@ test.describe('Sections', () => { .getByRole('radio', { name: 'Yes' }), ).toBeChecked() await submitView.checkRadio('Do you have a pet?', 'No') - await expect(submitView.getQuestion('Comments')).toBeVisible() await expect(submitView.nextButton).toHaveCount(0) - await submitView.fillText('Comments', 'None') const response = await submitView.submit() const { answers } = response.request().postDataJSON() expect(answers).not.toHaveProperty(String(section.id)) expect(answers).not.toHaveProperty(String(which.id)) + expect(answers).not.toHaveProperty(String(comments.id)) await expect(submitView.successMessage).toBeVisible() }) @@ -237,6 +236,231 @@ test.describe('Sections', () => { ]) }) + test('The server removes jumps into the middle of another section', async ({ + page, + }) => { + const headers = { 'OCS-APIRequest': 'true', Accept: 'application/json' } + const { form, pet, options, which } = await createSectionForm(page.request) + const update = await page.request.patch( + `../ocs/v2.php/apps/forms/api/v3/forms/${form.id}/questions/${pet.id}`, + { + headers, + data: { + keyValuePairs: { + extraSettings: { + goTo: [ + { optionId: options[0].id, target: which.id }, + { optionId: options[1].id, target: 'submit' }, + ], + }, + }, + }, + }, + ) + expect(update.headers()['x-forms-adjusted']).toBe( + `removed-jumps=(${pet.id})`, + ) + const saved = await api(page.request, 'GET', `/forms/${form.id}`) + expect(saved.questions[0].extraSettings).toEqual({ + goTo: [{ optionId: options[1].id, target: 'submit' }], + }) + }) + + test('Inserting a section removes the jumps into its middle', async ({ + page, + }) => { + const headers = { 'OCS-APIRequest': 'true', Accept: 'application/json' } + const form = await api(page.request, 'POST', '/forms') + const question = await api( + page.request, + 'POST', + `/forms/${form.id}/questions`, + { + type: 'multiple_unique', + text: 'Continue?', + }, + ) + const options = await api( + page.request, + 'POST', + `/forms/${form.id}/questions/${question.id}/options`, + { optionTexts: ['Yes', 'No'] }, + ) + await api(page.request, 'POST', `/forms/${form.id}/questions`, { + type: 'short', + text: 'Why?', + }) + const last = await api(page.request, 'POST', `/forms/${form.id}/questions`, { + type: 'short', + text: 'Anything else?', + }) + await api( + page.request, + 'PATCH', + `/forms/${form.id}/questions/${question.id}`, + { + keyValuePairs: { + extraSettings: { + goTo: [{ optionId: options[0].id, target: last.id }], + }, + }, + }, + ) + + const insert = await page.request.post( + `../ocs/v2.php/apps/forms/api/v3/forms/${form.id}/questions`, + { headers, data: { type: 'section', text: 'More', position: 3 } }, + ) + expect(insert.headers()['x-forms-adjusted']).toBe( + `removed-jumps=(${question.id})`, + ) + const saved = await api(page.request, 'GET', `/forms/${form.id}`) + expect(saved.questions[0].extraSettings).toEqual({ goTo: [] }) + }) + + test('Cloning a section into the middle of a section removes the jumps into its middle', async ({ + page, + }) => { + const headers = { 'OCS-APIRequest': 'true', Accept: 'application/json' } + const form = await api(page.request, 'POST', '/forms') + const question = await api( + page.request, + 'POST', + `/forms/${form.id}/questions`, + { + type: 'multiple_unique', + text: 'Continue?', + }, + ) + const options = await api( + page.request, + 'POST', + `/forms/${form.id}/questions/${question.id}/options`, + { optionTexts: ['Yes', 'No'] }, + ) + await api(page.request, 'POST', `/forms/${form.id}/questions`, { + type: 'short', + text: 'Why?', + }) + const last = await api(page.request, 'POST', `/forms/${form.id}/questions`, { + type: 'short', + text: 'Anything else?', + }) + const section = await api( + page.request, + 'POST', + `/forms/${form.id}/questions`, + { + type: 'section', + text: 'More', + }, + ) + await api( + page.request, + 'PATCH', + `/forms/${form.id}/questions/${question.id}`, + { + keyValuePairs: { + extraSettings: { + goTo: [{ optionId: options[0].id, target: last.id }], + }, + }, + }, + ) + + const clone = await page.request.post( + `../ocs/v2.php/apps/forms/api/v3/forms/${form.id}/questions`, + { headers, data: { fromId: section.id, position: 3 } }, + ) + expect(clone.headers()['x-forms-adjusted']).toBe( + `removed-jumps=(${question.id})`, + ) + const saved = await api(page.request, 'GET', `/forms/${form.id}`) + expect(saved.questions[0].extraSettings).toEqual({ goTo: [] }) + }) + + test('Moving a question asks before it turns a jump into a jump into another section', async ({ + page, + }) => { + const form = await api(page.request, 'POST', '/forms') + await api(page.request, 'POST', `/forms/${form.id}/questions`, { + type: 'section', + text: 'Part one', + }) + const question = await api( + page.request, + 'POST', + `/forms/${form.id}/questions`, + { + type: 'multiple_unique', + text: 'Continue?', + }, + ) + const options = await api( + page.request, + 'POST', + `/forms/${form.id}/questions/${question.id}/options`, + { optionTexts: ['Yes', 'No'] }, + ) + const target = await api( + page.request, + 'POST', + `/forms/${form.id}/questions`, + { + type: 'short', + text: 'Anything else?', + }, + ) + for (const [type, text] of [ + ['section', 'Part two'], + ['short', 'Last'], + ]) { + await api(page.request, 'POST', `/forms/${form.id}/questions`, { + type, + text, + }) + } + await api( + page.request, + 'PATCH', + `/forms/${form.id}/questions/${question.id}`, + { + keyValuePairs: { + extraSettings: { + goTo: [{ optionId: options[0].id, target: target.id }], + }, + }, + }, + ) + await page.goto(`apps/forms/${form.hash}/edit`) + + await page + .getByRole('listitem', { name: 'Question number 2' }) + .getByRole('button', { name: 'Move question down' }) + .focus() + await page.keyboard.press('Enter') + const dialog = page.getByRole('dialog', { + name: 'Jumps go to the start of a section', + }) + await expect(dialog).toContainText( + 'After this move, question 1 would jump into the middle of another section. Move the question "Anything else?" back, or remove these jumps?', + ) + const order = page.waitForResponse( + (response) => + response.request().method() === 'PATCH' + && response.url().endsWith(`/forms/${form.id}/questions`), + ) + await dialog.getByRole('button', { name: 'Remove jumps' }).click() + await order + + const stored = await api( + page.request, + 'GET', + `/forms/${form.id}/questions/${question.id}`, + ) + expect(stored.extraSettings.goTo).toEqual([]) + }) + test('Each page checks its required questions, an empty section is an info page', async ({ page, submitView, diff --git a/src/composables/useJumps.ts b/src/composables/useJumps.ts index 982d8db3e..531c30aae 100644 --- a/src/composables/useJumps.ts +++ b/src/composables/useJumps.ts @@ -23,7 +23,12 @@ import { QUESTION_TYPES_WITH_GOTO, QUESTION_TYPES_WITH_NEXT, } from '../utils/Jumps.ts' -import { getNumbers, QUESTION_TYPE_SECTION } from '../utils/Sections.ts' +import { + getNumbers, + getSectionIndexes, + isAllowedTarget, + QUESTION_TYPE_SECTION, +} from '../utils/Sections.ts' /** The jump issues of the form, see `getJumpIssues()`, provided by the editor */ export const FORM_JUMP_ISSUES_KEY: InjectionKey> = @@ -99,6 +104,7 @@ export function useJumps( formQuestions.value.findIndex((question) => question.id === props.id), ) const numbers = computed(() => getNumbers(formQuestions.value)) + const sections = computed(() => getSectionIndexes(formQuestions.value)) const number = computed(() => numbers.value.get(props.id) ?? position.value + 1) const nextLabel = computed(() => t('forms', 'After question {number}', { number: number.value }), @@ -107,35 +113,46 @@ export function useJumps( const targetOptions = computed((previous) => { const options: JumpTargetOption[] = [ { id: null, label: t('forms', 'Next question') }, - ...formQuestions.value.slice(position.value + 1).map((question) => { - const number = numbers.value.get(question.id) - const title = question.text?.trim() - return { - id: question.id, - label: - question.type === QUESTION_TYPE_SECTION - ? t( - 'forms', - 'Section {number}: {title}', - { - number, - title: - title || t('forms', 'Untitled section'), - }, - { escape: false, sanitize: false }, - ) - : t( - 'forms', - 'Question {number}: {title}', - { - number, - title: - title || t('forms', 'Untitled question'), - }, - { escape: false, sanitize: false }, - ), - } - }), + ...formQuestions.value + .filter((question, targetPosition) => + isAllowedTarget( + formQuestions.value, + sections.value, + position.value, + targetPosition, + ), + ) + .map((question) => { + const number = numbers.value.get(question.id) + const title = question.text?.trim() + return { + id: question.id, + label: + question.type === QUESTION_TYPE_SECTION + ? t( + 'forms', + 'Section {number}: {title}', + { + number, + title: + title + || t('forms', 'Untitled section'), + }, + { escape: false, sanitize: false }, + ) + : t( + 'forms', + 'Question {number}: {title}', + { + number, + title: + title + || t('forms', 'Untitled question'), + }, + { escape: false, sanitize: false }, + ), + } + }), { id: JUMP_TARGET_SUBMIT, label: t('forms', 'End of the form') }, ] return previous?.length === options.length diff --git a/src/utils/Jumps.ts b/src/utils/Jumps.ts index e72456f28..b8abe511a 100644 --- a/src/utils/Jumps.ts +++ b/src/utils/Jumps.ts @@ -11,6 +11,7 @@ import type { } from '../types/Entities.d.ts' import { QUESTION_EXTRASETTINGS_OTHER_PREFIX } from '../models/Constants.ts' +import { getSectionIndexes, isAllowedTarget } from './Sections.ts' export const JUMP_TARGET_SUBMIT = 'submit' @@ -428,33 +429,41 @@ export function getJumps( } /** - * The questions without their jumps to the question itself or to an earlier question, as the server removes them when it saves an order. + * The questions without their jumps to the question itself, to an earlier question or into the middle of another section, as the server removes them when it saves an order. * Questions without such jumps stay the same objects. - * Mirrors `FormsService::removeBackwardJumps()`. + * Mirrors `FormsService::removeDisallowedJumps()`. * * @param questions the questions of the form in their order */ -export function withoutBackwardJumps(questions: T[]): T[] { +export function withoutDisallowedJumps( + questions: T[], +): T[] { const positions = new Map( questions.map((question, position) => [question.id, position]), ) + const sections = getSectionIndexes(questions) return questions.map((question, position) => { - const isBackward = (target: unknown): boolean => - typeof target === 'number' - && (positions.get(target) ?? Number.POSITIVE_INFINITY) <= position + const isDisallowed = (target: unknown): boolean => { + const targetPosition = + typeof target === 'number' ? positions.get(target) : undefined + return ( + targetPosition !== undefined + && !isAllowedTarget(questions, sections, position, targetPosition) + ) + } const { next, goTo, ...extraSettings }: FormsQuestionExtraSettings = question.extraSettings ?? {} const keptGoTo = Array.isArray(goTo) ? goTo.filter( (jump: unknown) => - !isBackward( + !isDisallowed( typeof jump === 'object' && jump !== null ? (jump as { target?: unknown }).target : undefined, ), ) : goTo - if (!isBackward(next) && keptGoTo?.length === goTo?.length) { + if (!isDisallowed(next) && keptGoTo?.length === goTo?.length) { return question } return { @@ -462,12 +471,26 @@ export function withoutBackwardJumps(questions: T[]): T extraSettings: { ...extraSettings, ...(goTo === undefined ? {} : { goTo: keptGoTo }), - ...(next === undefined || isBackward(next) ? {} : { next }), + ...(next === undefined || isDisallowed(next) ? {} : { next }), }, } }) } +/** + * The ids of the questions with jumps to the question itself, to an earlier question or into the middle of another section + * + * @param questions the questions of the form in their order + */ +export function getQuestionsWithDisallowedJumps( + questions: FormsQuestion[], +): number[] { + const allowed = withoutDisallowedJumps(questions) + return questions + .filter((question, position) => allowed[position] !== question) + .map((question) => question.id) +} + /** * Extra settings without the jumps that a change removed from other extra settings of the same question * diff --git a/src/utils/Sections.ts b/src/utils/Sections.ts index 5ce34e82b..14a5d36e7 100644 --- a/src/utils/Sections.ts +++ b/src/utils/Sections.ts @@ -88,6 +88,39 @@ export function getQuestionIdsInSections( ) } +/** + * The section of each question by position: 0 before the first section, then 1, 2, … from each section on, the section itself included + * + * @param questions the questions and sections in their order + */ +export function getSectionIndexes(questions: Array<{ type: string }>): number[] { + let section = 0 + return questions.map((question) => + question.type === QUESTION_TYPE_SECTION ? ++section : section, + ) +} + +/** + * Whether a question may jump to a target: a later question of its own section, or a later section + * + * @param questions the questions and sections in their order + * @param sections the section of each question by position, see `getSectionIndexes()` + * @param position the position of the question + * @param targetPosition the position of the target + */ +export function isAllowedTarget( + questions: Array<{ type: string }>, + sections: number[], + position: number, + targetPosition: number, +): boolean { + return ( + targetPosition > position + && (questions[targetPosition].type === QUESTION_TYPE_SECTION + || sections[targetPosition] === sections[position]) + ) +} + /** * The pages of the questions on a path: a page starts at each section, questions before the first section form the first page * diff --git a/src/views/Create.vue b/src/views/Create.vue index 6b73f1ef6..8eda6e71e 100644 --- a/src/views/Create.vue +++ b/src/views/Create.vue @@ -287,7 +287,8 @@ import { formatList, getJumpIssues, getNewlyBrokenQuestions, - withoutBackwardJumps, + getQuestionsWithDisallowedJumps, + withoutDisallowedJumps, withoutRemovedJumps, } from '../utils/Jumps.ts' import logger from '../utils/Logger.ts' @@ -741,33 +742,61 @@ export default defineComponent({ } /** - * The closing question of a move confirmation, naming the moved question + * The closing question of a move confirmation, naming the moved question or section * - * @param moved the moved question + * @param moved the moved question or section */ const moveBackText = (moved: FormsQuestion | undefined): string => - t( - 'forms', - 'Move the question "{title}" back, or remove these jumps?', - { title: moved?.text || t('forms', 'Untitled question') }, - undefined, - { escape: false, sanitize: false }, - ) + moved?.type === QUESTION_TYPE_SECTION + ? t( + 'forms', + 'Move the section "{title}" back, or remove these jumps?', + { title: moved.text || t('forms', 'Untitled section') }, + undefined, + { escape: false, sanitize: false }, + ) + : t( + 'forms', + 'Move the question "{title}" back, or remove these jumps?', + { title: moved?.text || t('forms', 'Untitled question') }, + undefined, + { escape: false, sanitize: false }, + ) /** - * Ask whether to remove the jumps that a new order of the questions would turn into jumps to an earlier question, or to move the moved question back + * Ask whether to remove the jumps that a new order of the questions would turn into jumps to an earlier question or into the middle of another section, or to move the moved question back * * @param questions the questions in the new order - * @param ids the ids of the questions with such jumps - * @param moved the moved question + * @param ids the ids of the questions with jumps to an earlier question + * @param intoSectionIds the ids of the other questions with jumps into the middle of another section + * @param moved the moved question or section * @return whether to remove the jumps */ const confirmRemovingBackwardJumps = async ( questions: FormsQuestion[], ids: number[], + intoSectionIds: number[], moved: FormsQuestion | undefined, ): Promise => { try { + if (ids.length === 0) { + return await showConfirmation({ + name: t('forms', 'Jumps go to the start of a section'), + text: [ + n( + 'forms', + 'After this move, question {questions} would jump into the middle of another section.', + 'After this move, questions {questions} would jump into the middle of other sections.', + intoSectionIds.length, + { questions: numbersOf(questions, intoSectionIds) }, + ), + moveBackText(moved), + ].join(' '), + labelConfirm: t('forms', 'Remove jumps'), + labelReject: t('forms', 'Move back'), + severity: 'warning', + }) + } return await showConfirmation({ name: t('forms', 'Jumps cannot go back'), text: [ @@ -806,11 +835,18 @@ export default defineComponent({ getJumpIssues(oldQuestions), getJumpIssues(questions), ) + const disallowedBefore = new Set( + getQuestionsWithDisallowedJumps(oldQuestions), + ) + const intoSection = getQuestionsWithDisallowedJumps(questions).filter( + (id) => !backward.includes(id) && !disallowedBefore.has(id), + ) let order = questions - if (backward.length > 0) { + if (backward.length > 0 || intoSection.length > 0) { const removeJumps = await confirmRemovingBackwardJumps( questions, backward, + intoSection, moved, ) if (!removeJumps) { @@ -857,7 +893,7 @@ export default defineComponent({ if (props.form.id !== formId) { return } - const adjustedOrder = withoutBackwardJumps(order) + const adjustedOrder = withoutDisallowedJumps(order) warnAboutJumpChanges(oldQuestions, adjustedOrder) const changes = new Map( order.flatMap((question, position) => @@ -1003,6 +1039,29 @@ export default defineComponent({ saveDescription() } + /** + * Remove the jumps into the middle of a section that a new section split off, as the server does when it inserts the section + */ + const removeJumpsIntoNewSection = (): void => { + const questions = withoutDisallowedJumps(props.form.questions) + const changed = props.form.questions + .filter((question, position) => questions[position] !== question) + .map((question) => question.id) + if (changed.length === 0) { + return + } + emit('update:form', { ...props.form, questions }) + showWarning( + n( + 'forms', + 'Question {questions} jumped into the part of a section that is now a new section, so its jumps there were removed. Please review the jumps.', + 'Questions {questions} jumped into the part of a section that is now a new section, so their jumps there were removed. Please review the jumps.', + changed.length, + { questions: numbersOf(questions, changed) }, + ), + ) + } + /** * Add a new question to the current form * @@ -1053,6 +1112,10 @@ export default defineComponent({ // Delegate insertion & focus handling to helper insertQuestion(question, { text, type, answers: [] }, position) + if (type === QUESTION_TYPE_SECTION) { + await nextTick() + removeJumpsIntoNewSection() + } } catch (error) { logger.error('Error while adding new question', { error }) showError( diff --git a/tests/Unit/Service/FormsServiceTest.php b/tests/Unit/Service/FormsServiceTest.php index a555e03c7..fe720fdf4 100644 --- a/tests/Unit/Service/FormsServiceTest.php +++ b/tests/Unit/Service/FormsServiceTest.php @@ -2418,7 +2418,7 @@ public function testMapJumpsRemovesUnmappedNextAndMalformedJumps(): void { ); } - public function testRemoveBackwardJumps(): void { + public function testRemoveDisallowedJumps(): void { $questions = array_map(static function (array $data): Question { $question = new Question(); $question->setId($data[0]); @@ -2431,7 +2431,7 @@ public function testRemoveBackwardJumps(): void { [4, ['goTo' => []]], ]); - $changed = FormsService::removeBackwardJumps($questions); + $changed = FormsService::removeDisallowedJumps($questions); $this->assertSame([$questions[0], $questions[1], $questions[2]], $changed); $this->assertSame(['next' => 3, 'goTo' => [['optionId' => 12, 'target' => 'submit']]], $questions[0]->getExtraSettings()); @@ -2440,6 +2440,42 @@ public function testRemoveBackwardJumps(): void { $this->assertSame(['goTo' => []], $questions[3]->getExtraSettings()); } + public function testRemoveDisallowedJumpsIntoTheMiddleOfAnotherSection(): void { + $questions = array_map(static function (array $data): Question { + $question = new Question(); + $question->setId($data[0]); + $question->setType($data[1]); + $question->setExtraSettings($data[2]); + return $question; + }, [ + [1, Constants::ANSWER_TYPE_MULTIPLEUNIQUE, ['goTo' => [ + ['optionId' => 11, 'target' => 2], + ['optionId' => 12, 'target' => 3], + ['optionId' => 13, 'target' => 4], + ['optionId' => 14, 'target' => 6], + ['optionId' => 15, 'target' => 5], + ['optionId' => 16, 'target' => 'submit'], + ]]], + [2, Constants::ANSWER_TYPE_SHORT, ['next' => 5]], + [3, Constants::ANSWER_TYPE_SECTION, []], + [4, Constants::ANSWER_TYPE_SHORT, ['next' => 6]], + [5, Constants::ANSWER_TYPE_SECTION, []], + [6, Constants::ANSWER_TYPE_SHORT, []], + ]); + + $changed = FormsService::removeDisallowedJumps($questions); + + $this->assertSame([$questions[0], $questions[3]], $changed); + $this->assertSame(['goTo' => [ + ['optionId' => 11, 'target' => 2], + ['optionId' => 12, 'target' => 3], + ['optionId' => 15, 'target' => 5], + ['optionId' => 16, 'target' => 'submit'], + ]], $questions[0]->getExtraSettings()); + $this->assertSame(['next' => 5], $questions[1]->getExtraSettings()); + $this->assertSame([], $questions[3]->getExtraSettings()); + } + public function testMapJumpsOfCopies(): void { $questions = array_map(static function (array $data): Question { $question = new Question();