From e10afe6675b9c0663140028deae99f2ca48e8511 Mon Sep 17 00:00:00 2001 From: Andy Scherzinger Date: Tue, 17 Nov 2026 14:28:21 +0100 Subject: [PATCH 1/7] fix(submission): count the same titles as blank as the submit view A question title made only of U+0085 (next line) or U+180E (Mongolian vowel separator) counted as blank on the server, as \s matches them in Unicode mode, while the submit view shows such a question, as JavaScript's trim() keeps both. The server now counts exactly the characters as blank that trim() removes, so a required question with such a title needs an answer, as in the submit view. Assisted-by: Claude Code:claude-opus-5-5 Signed-off-by: Andy Scherzinger --- lib/Service/SubmissionService.php | 2 +- tests/Unit/Service/SubmissionServiceTest.php | 7 +++++++ 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/lib/Service/SubmissionService.php b/lib/Service/SubmissionService.php index 237abbf74..503dfe94b 100644 --- a/lib/Service/SubmissionService.php +++ b/lib/Service/SubmissionService.php @@ -600,7 +600,7 @@ private function escapeCSV(string $value): string { * @param array $question the question with its options */ private static function isShownToRespondents(array $question): bool { - if (preg_match('/^[\s\p{Z}\x{FEFF}]*$/u', (string)($question['text'] ?? '')) === 1) { + if (preg_match('/^[\t\n\x0B\f\r\p{Z}\x{FEFF}]*$/u', (string)($question['text'] ?? '')) === 1) { return false; } diff --git a/tests/Unit/Service/SubmissionServiceTest.php b/tests/Unit/Service/SubmissionServiceTest.php index dffeb0d44..fa3430b82 100644 --- a/tests/Unit/Service/SubmissionServiceTest.php +++ b/tests/Unit/Service/SubmissionServiceTest.php @@ -939,6 +939,13 @@ public static function dataValidateSubmission() { [], null, ], + 'required-with-next-line-title-is-shown' => [ + [ + ['id' => 1, 'type' => 'short', 'text' => "\u{0085}\u{180E}", 'isRequired' => true] + ], + [], + "Question \"\u{0085}\u{180E}\" is required.", + ], 'required-choice-without-options-is-not-shown' => [ [ ['id' => 1, 'type' => 'multiple_unique', 'text' => 'q1', 'isRequired' => true, 'options' => []] From 316c636f338fb4b9135158674e6dfcb150538944 Mon Sep 17 00:00:00 2001 From: Andy Scherzinger Date: Tue, 17 Nov 2026 14:27:53 +0100 Subject: [PATCH 2/7] fix(submit): leave deleted options out of a restored draft A draft restored from the local storage of a logged in respondent keeps only those values of radio, checkbox and dropdown questions that are options of the question, or an answer "Other" while the question allows it. An option the owner deleted after the draft was saved no longer stays in the answer invisibly, where the server rejects it on every submit until the form is cleared. Assisted-by: Claude Code:claude-opus-5-5 Signed-off-by: Andy Scherzinger --- playwright/e2e/submit-form.spec.ts | 31 ++++++++++++++++++++++++++++++ src/views/Submit.vue | 30 ++++++++++++++++++++++++----- 2 files changed, 56 insertions(+), 5 deletions(-) diff --git a/playwright/e2e/submit-form.spec.ts b/playwright/e2e/submit-form.spec.ts index aa0b666a9..23e9af759 100644 --- a/playwright/e2e/submit-form.spec.ts +++ b/playwright/e2e/submit-form.spec.ts @@ -9,6 +9,7 @@ import { test as appNavigationTest } from '../support/fixtures/navigation.ts' import { test as randomUserTest } from '../support/fixtures/random-user.ts' import { test as submitTest } from '../support/fixtures/submit.ts' import { test as topBarTest } from '../support/fixtures/topBar.ts' +import { waitForApiResponse } from '../support/helpers.ts' import { QuestionType } from '../support/sections/QuestionType.ts' import { FormsView } from '../support/sections/TopBarSection.ts' @@ -79,4 +80,34 @@ test.describe('Form submission', () => { await submitView.submit() await expect(submitView.successMessage).toBeVisible() }) + + test('A restored draft leaves out deleted options', async ({ + page, + form, + topBar, + submitView, + }) => { + const editUrl = page.url() + await topBar.toggleView(FormsView.View) + await submitView.checkOption('Favorite fruits', 'Apple') + await submitView.checkOption('Favorite fruits', 'Cherry') + + page.once('dialog', (dialog) => dialog.accept()) + await page.goto(editUrl) + await expect( + page.getByRole('listitem', { name: /Question number \d+/ }), + ).toHaveCount(4) + const questions = await form.getQuestions() + const deleted = waitForApiResponse(page, 'DELETE') + await questions[1].section + .getByRole('button', { name: 'Delete answer' }) + .nth(2) + .click() + await deleted + + await topBar.toggleView(FormsView.View) + const response = await submitView.submit() + expect(response.status()).toBe(201) + await expect(submitView.successMessage).toBeVisible() + }) }) diff --git a/src/views/Submit.vue b/src/views/Submit.vue index 4dc324669..ad23a1307 100644 --- a/src/views/Submit.vue +++ b/src/views/Submit.vue @@ -640,10 +640,14 @@ export default defineComponent({ return } + const questions = new Map( + validQuestions.value.map((question) => [question.id, question]), + ) const localAnswers: AnswersMap = {} for (const [questionId, answer] of Object.entries(savedState)) { + const question = questions.get(parseInt(questionId, 10)) // Clean up answers for questions that do not exist anymore - if (!validQuestionsIds.value.has(parseInt(questionId, 10))) { + if (!question) { showClearFormDueToChangeDialog.value = true logger.debug('Question does not exist anymore', { questionId, @@ -651,12 +655,28 @@ export default defineComponent({ continue } - localAnswers[parseInt(questionId, 10)] = [ - 'QuestionMultiple', - 'QuestionRanking', - ].includes(answer.type) + const value = ['QuestionMultiple', 'QuestionRanking'].includes( + answer.type, + ) ? (answer.value as string[]).map(String) : answer.value + localAnswers[question.id] = + Array.isArray(value) + && ['dropdown', 'multiple', 'multiple_unique'].includes( + question.type, + ) + ? value.filter( + (choice) => + (question.options ?? []).some( + (option) => + String(option.id) === String(choice), + ) + || (!!question.extraSettings?.allowOtherAnswer + && String(choice).startsWith( + QUESTION_EXTRASETTINGS_OTHER_PREFIX, + )), + ) + : value } answers.value = localAnswers } From c7a2a056398d470fbf1657904cc5ba3a3af76d17 Mon Sep 17 00:00:00 2001 From: Andy Scherzinger Date: Tue, 17 Nov 2026 14:32:37 +0100 Subject: [PATCH 3/7] fix(editor): save the changes of a question one after another The editor sent each change of a question without waiting for the earlier request for the same question. When the server finished an earlier request last, for example for two changes of the extra settings, which are saved as a whole, the older value stayed in the database while the editor showed the newer one. The changes of a question are now saved one after another. Assisted-by: Claude Code:claude-opus-5-5 Signed-off-by: Andy Scherzinger --- src/composables/useQuestion.ts | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/src/composables/useQuestion.ts b/src/composables/useQuestion.ts index e82281264..221fe8519 100644 --- a/src/composables/useQuestion.ts +++ b/src/composables/useQuestion.ts @@ -286,13 +286,26 @@ export function useQuestion(props: QuestionPropsLike, options: UseQuestionOption return shuffled } + let saving: Promise = Promise.resolve() + + /** + * Persist a single question field to the backend once the earlier changes of the question are saved. + * + * @param key Question property name. + * @param value Question property value. + */ + function saveQuestionProperty(key: string, value: unknown): Promise { + saving = saving.then(() => patchQuestionProperty(key, value)) + return saving + } + /** * Persist a single question field to the backend. * * @param key Question property name. * @param value Question property value. */ - async function saveQuestionProperty( + async function patchQuestionProperty( key: string, value: | string From 5fcb0aee60e45a22603089ef932780f17d6bb315 Mon Sep 17 00:00:00 2001 From: Andy Scherzinger Date: Wed, 4 Nov 2026 16:50:33 +0100 Subject: [PATCH 4/7] fix(submission): only accept question and option ids as they are The check for answers to unknown questions compares the question ids strictly, as the validation of each question already does, and names the id as it was sent. Option ids are compared as canonical integers with the ids of the options of the question. Answers to questions that allow the answer "Other" are an option id of the question or an answer "Other", and storing an answer uses the same check for the answer "Other" as the validation. Assisted-by: Claude Code:claude-opus-5-5 Signed-off-by: Andy Scherzinger --- docs/API_v3.md | 2 +- lib/Controller/ApiController.php | 2 +- lib/Service/SubmissionService.php | 31 ++++++++------ tests/Unit/Service/SubmissionServiceTest.php | 44 ++++++++++++++++++++ 4 files changed, 64 insertions(+), 15 deletions(-) diff --git a/docs/API_v3.md b/docs/API_v3.md index 0cb4a5b2e..df9d76748 100644 --- a/docs/API_v3.md +++ b/docs/API_v3.md @@ -949,7 +949,7 @@ Store Submission to Database - Restrictions: The array of answers has the following structure: - QuestionID as key - An **array** of values as value --> Even for short Text Answers, wrapped into Array. - - For Question-Types with pre-defined answers (`multiple`, `multiple_unique`, `dropdown`), the array contains the corresponding option-IDs. + - For Question-Types with pre-defined answers (`multiple`, `multiple_unique`, `dropdown`), the array contains the corresponding option-IDs, each as a number or as a string of exactly its digits, e.g. `12` or `"12"`, but not `"012"` or `" 12"`. - For File-Uploads, the array contains objects with `uploadedFileId` and `uploadToken` (both from the [Upload a file] endpoint for the same `questionId`). ``` diff --git a/lib/Controller/ApiController.php b/lib/Controller/ApiController.php index 8162e70f0..5afc157c9 100644 --- a/lib/Controller/ApiController.php +++ b/lib/Controller/ApiController.php @@ -1910,7 +1910,7 @@ private function storeAnswersForQuestion(Form $form, $submissionId, array $quest $optionIndex = array_search($answer, array_column($question['options'], 'id')); if ($optionIndex !== false) { $answerText = $question['options'][$optionIndex]['text']; - } elseif (!empty($question['extraSettings']['allowOtherAnswer']) && str_starts_with($answer, Constants::QUESTION_EXTRASETTINGS_OTHER_PREFIX)) { + } elseif (SubmissionService::isOtherAnswer($question, $answer)) { $answerText = substr($answer, strlen(Constants::QUESTION_EXTRASETTINGS_OTHER_PREFIX)); } } elseif ($question['type'] === Constants::ANSWER_TYPE_FILE) { diff --git a/lib/Service/SubmissionService.php b/lib/Service/SubmissionService.php index 503dfe94b..0678b7ad8 100644 --- a/lib/Service/SubmissionService.php +++ b/lib/Service/SubmissionService.php @@ -699,7 +699,7 @@ public function validateSubmission(array $questions, array $answers, string $for } // Check if all answers are within the possible options - if (in_array($question['type'], Constants::ANSWER_TYPES_PREDEFINED) && empty($question['extraSettings']['allowOtherAnswer'])) { + if (in_array($question['type'], Constants::ANSWER_TYPES_PREDEFINED)) { // Normalize option IDs once for consistent comparison (DB may return ints, request may send strings) $optionIds = $this->normalizeOptionIds($question['options'] ?? []); @@ -717,18 +717,11 @@ public function validateSubmission(array $questions, array $answers, string $for $this->validateGridQuestion($question, $answers[$questionId]); } // Search corresponding option, return false if non-existent - else { - // Accept numeric strings like "46" from JSON payloads reliably (e.g. with hardening extensions enabled) - $answerId = is_int($answer) ? $answer : (is_string($answer) ? intval(trim($answer)) : null); - - // Reject non-numeric / malformed values early - if ($answerId === null || (string)$answerId !== (string)intval($answerId)) { + elseif (!self::isOtherAnswer($question, $answer)) { + $answerId = $this->normalizeNumericOptionId($answer); + if ($answerId === null || !in_array($answerId, $optionIds, true)) { throw new \InvalidArgumentException(sprintf('Answer "%s" for question "%s" is not a valid option.', is_scalar($answer) ? (string)$answer : gettype($answer), $question['text'])); } - - if (!in_array($answerId, $optionIds, true)) { - throw new \InvalidArgumentException(sprintf('Answer "%s" for question "%s" is not a valid option.', $answer, $question['text'])); - } } } } @@ -792,8 +785,8 @@ public function validateSubmission(array $questions, array $answers, string $for // Check for excess answers foreach ($answers as $id => $answerArray) { // Search corresponding question, return false if not found - if (!in_array($id, array_column($questions, 'id'))) { - throw new \InvalidArgumentException(sprintf('Answer for non-existent question with ID %d.', $id)); + if (!in_array($id, array_column($questions, 'id'), true)) { + throw new \InvalidArgumentException(sprintf('Answer for non-existent question with ID %s.', $id)); } } } @@ -934,6 +927,18 @@ private function validateGridQuestion(array $question, array $answers): void { } } + /** + * Whether the value is the answer "Other" of a question that allows it + * + * @param array $question the question + * @param mixed $answer a value of the answer + */ + public static function isOtherAnswer(array $question, mixed $answer): bool { + return !empty($question['extraSettings']['allowOtherAnswer']) + && is_string($answer) + && str_starts_with($answer, Constants::QUESTION_EXTRASETTINGS_OTHER_PREFIX); + } + /** * Whether the answer is a list of values: texts or numbers, uploaded files for file questions, or an object with the values by row for grid questions * diff --git a/tests/Unit/Service/SubmissionServiceTest.php b/tests/Unit/Service/SubmissionServiceTest.php index fa3430b82..8771f47bf 100644 --- a/tests/Unit/Service/SubmissionServiceTest.php +++ b/tests/Unit/Service/SubmissionServiceTest.php @@ -1065,6 +1065,50 @@ public static function dataValidateSubmission() { // Expected Result 'Answer for non-existent question with ID 2.', ], + 'question-id-in-other-notation' => [ + [ + ['id' => 1, 'type' => 'short', 'text' => 'q1', 'isRequired' => false, 'extraSettings' => ['validationType' => 'email']] + ], + [ + '1.0' => ['not an email'] + ], + 'Answer for non-existent question with ID 1.0.', + ], + 'option-id-in-other-notation' => [ + [ + ['id' => 1, 'type' => 'multiple_unique', 'text' => 'q1', 'isRequired' => false, 'options' => [ + ['id' => 3], + ['id' => 5] + ]], + ], + [ + '1' => ['03'] + ], + 'Answer "03" for question "q1" is not a valid option.', + ], + 'option-id-in-other-notation-with-other-answer' => [ + [ + ['id' => 1, 'type' => 'multiple_unique', 'text' => 'q1', 'isRequired' => false, 'extraSettings' => ['allowOtherAnswer' => true], 'options' => [ + ['id' => 3], + ['id' => 5] + ]], + ], + [ + '1' => ['05'] + ], + 'Answer "05" for question "q1" is not a valid option.', + ], + 'unknown-option-with-other-answer' => [ + [ + ['id' => 1, 'type' => 'multiple_unique', 'text' => 'q1', 'isRequired' => true, 'extraSettings' => ['allowOtherAnswer' => true], 'options' => [ + ['id' => 3] + ]], + ], + [ + '1' => ['not an option'] + ], + 'Answer "not an option" for question "q1" is not a valid option.', + ], 'invalid-multiple-too-many-answers' => [ // Questions [ From c0194fe7fef3974aa6c4180b4f3c390699aee74e Mon Sep 17 00:00:00 2001 From: Andy Scherzinger Date: Tue, 10 Nov 2026 23:13:28 +0100 Subject: [PATCH 5/7] feat(conditional): jump to a later question based on the answer As in Microsoft Forms, an answer can lead to a later question or to the end of the form, while the form stays a flat list of questions. Radio and dropdown questions store a target per option, and radio questions one for the answer "Other", in extraSettings.goTo. The other question types with jumps (short and long text, file, color, ranking, grid) store one target after the question in extraSettings.next. A question type has either goTo or next, never both: sending the other one is rejected as invalid extraSettings, and an answer without a jump leads to the following question. A target is the id of a question of the same form or "submit", and an option id belongs to the question; ids of questions of other forms are rejected, while ids of deleted questions of the form are accepted. Updating a question removes its jumps for options that are not options of the question, reported as removed-jumps. The path of a respondent starts at the first question and follows these targets. As in Microsoft Forms, it ends at a question with jumps per answer that has no answer yet: the questions after it appear once it is answered, and an optional one left empty lets the form be submitted without them. Only the first value of an answer decides, which keeps the walk linear in the size of a submission, and answers to questions the submit view does not show, such as questions without a title, do not count and their jumps per answer do not end the path, so they cannot skip required questions. A target that is not a later question of the form, for example after deleting it, counts as the following question. Answers to the questions off the path are ignored, also when a form changed while it was answered, and required only applies on the path. An answer "Other" needs a text, as it decides the path. Jumps never go back. Updating, reordering and copying a question remove the jumps to the question itself or to an earlier question; the request still succeeds with its usual status and a payload of the same shape, and the response header X-Forms-Adjusted lists the questions concerned as removed-jumps. A reorder returns the new extraSettings of these questions in its own response type QuestionOrder. Copying or importing a form maps the targets and option ids and drops such jumps as well, without the header, together with jumps whose target or option was not copied, jumps per answer with an invalid structure, and goTo or next on a question type without it. Exports keep the option ids for that. tests/fixtures/jump-paths.json holds the path cases, shared with the frontend. Based on the conditional questions of #3123 by Micke Nordin and TimedIn. Co-Authored-By: Micke Nordin Co-Authored-By: TimedIn Assisted-by: Claude Code:claude-opus-5-5 Signed-off-by: Andy Scherzinger --- REUSE.toml | 6 + docs/API_v3.md | 27 +- docs/DataStructure.md | 19 + lib/Constants.php | 22 ++ lib/Controller/ApiController.php | 102 ++++- lib/FormsMigrator.php | 6 + lib/ResponseDefinitions.php | 7 + lib/Service/FormsService.php | 264 ++++++++++++- lib/Service/SubmissionService.php | 169 ++++++++- openapi.json | 123 +++++- tests/Unit/Controller/ApiControllerTest.php | 371 +++++++++++++++++++ tests/Unit/FormsMigratorTest.php | 30 ++ tests/Unit/Service/FormsServiceTest.php | 269 ++++++++++++++ tests/Unit/Service/SubmissionServiceTest.php | 118 ++++++ tests/fixtures/jump-paths.json | 312 ++++++++++++++++ 15 files changed, 1798 insertions(+), 47 deletions(-) create mode 100644 tests/fixtures/jump-paths.json diff --git a/REUSE.toml b/REUSE.toml index 249413bd9..60bfea4ed 100644 --- a/REUSE.toml +++ b/REUSE.toml @@ -47,6 +47,12 @@ precedence = "aggregate" SPDX-FileCopyrightText = "2019 Nextcloud GmbH and Nextcloud contributors" SPDX-License-Identifier = "AGPL-3.0-or-later" +[[annotations]] +path = ["tests/fixtures/jump-paths.json"] +precedence = "aggregate" +SPDX-FileCopyrightText = "2026 Nextcloud GmbH and Nextcloud contributors" +SPDX-License-Identifier = "AGPL-3.0-or-later" + [[annotations]] path = ["img/*"] precedence = "aggregate" diff --git a/docs/API_v3.md b/docs/API_v3.md index df9d76748..dd5f92213 100644 --- a/docs/API_v3.md +++ b/docs/API_v3.md @@ -18,6 +18,7 @@ This file contains the API-Documentation. For more information on the returned D - The OCS-Endpoint _always returns_ an object called `ocs`. This contains an object `meta` holding some meta-data, as well as an object `data` holding the actual data. In this document, the response-blocks only show the `data`, if not explicitely stated different. - OpenAPI spec: a machine-readable OpenAPI description is available at `/openapi.json` in the repository root. Prefer it as source-of-truth for exact request/response shapes. +- When the server changes data beyond what a request asked for, it reports this in the response header `X-Forms-Adjusted`, see [Adjustments by the server](#adjustments-by-the-server). ``` "ocs": { @@ -30,6 +31,18 @@ This file contains the API-Documentation. For more information on the returned D } ``` +### Adjustments by the server + +Some requests succeed with their usual status, and their payload keeps its shape, but the server changes data beyond what the request asked for. The response header `X-Forms-Adjusted` then reports this as a [structured field dictionary (RFC 8941)](https://www.rfc-editor.org/rfc/rfc8941#name-dictionaries); the header is absent when nothing was adjusted. `Access-Control-Expose-Headers` makes it readable for cross-origin clients. Clients should ignore keys they do not know, as more keys may follow. + +| Key | Value | Set by | Meaning | +|-----|-------|--------|---------| +| `removed-jumps` | Inner list of question ids, e.g. `(3 7)` | Updating, reordering and copying questions; deleting options | Jumps to the question itself or to an earlier question, or jumps of the deleted option or of options that are not options of the question, were removed from the `extraSettings` of these questions, see [Jumps](DataStructure.md#jumps) | + +``` +X-Forms-Adjusted: removed-jumps=(3 7) +``` + ## API changes ### Deprecation info @@ -49,6 +62,7 @@ This file contains the API-Documentation. For more information on the returned D ### 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 and radio 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, and deleting an option removes its jumps. 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. - 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 @@ -260,7 +274,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) +- 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)). ``` See section 'Request full data of a form'. @@ -452,7 +466,7 @@ Update a single or multiple properties of a question-object. |-----------|---------|-------------| | _keyValuePairs_ | Array | Array of key-value pairs to update | - Restrictions: It is **not allowed** to update one of the following key-value pairs: _id, formId, order, type_. -- Response: **Status-Code OK**, as well as the id of the updated question. +- 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 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 @@ -473,7 +487,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. +- 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)` (see [Adjustments by the server](#adjustments-by-the-server)). ``` "data": { @@ -519,7 +533,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. +- 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)). ``` See section 'Create a new question'. @@ -590,7 +604,7 @@ Update a single or all properties of an option-object | _formId_ | Integer | ID of the form containing the question and option | | _questionId_ | Integer | ID of the question, the new option will belong to | | _optionId_ | Integer | ID of the option to delete | -- Response: **Status-Code OK**, as well as the id of the deleted option. +- Response: **Status-Code OK**, as well as the id of the deleted option. The jumps of the question for this option are removed (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)). ``` "data": 7 @@ -951,6 +965,8 @@ Store Submission to Database - An **array** of values as value --> Even for short Text Answers, wrapped into Array. - For Question-Types with pre-defined answers (`multiple`, `multiple_unique`, `dropdown`), the array contains the corresponding option-IDs, each as a number or as a string of exactly its digits, e.g. `12` or `"12"`, but not `"012"` or `" 12"`. - For File-Uploads, the array contains objects with `uploadedFileId` and `uploadToken` (both from the [Upload a file] endpoint for the same `questionId`). + - Answers to questions that the [jumps](DataStructure.md#jumps) of the answers skip are ignored, and a skipped required question needs no answer. The path ends at a question that has no answer and a jump per answer past the following question, so the questions after an optional one left empty need no answer either. + - An answer "Other" is `system-other-answer:` followed by its text, and the text must not be empty. ``` { @@ -984,6 +1000,7 @@ Update an existing submission (only allowed when `allowEditSubmissions` is set o - The form must have `allowEditSubmissions` enabled. - Only the user who created the submission may update it. - Answers are validated the same way as on submit. + - The answers replace all stored answers of the submission; answers to questions the [jumps](DataStructure.md#jumps) skip are not stored. - Response: **Status-Code OK**, as well as the id of the updated submission. ``` diff --git a/docs/DataStructure.md b/docs/DataStructure.md index d0e9acfa3..a650025c0 100644 --- a/docs/DataStructure.md +++ b/docs/DataStructure.md @@ -270,6 +270,25 @@ Optional extra settings for some [Question Types](#question-types) | `columns` | `grid` | Array | - | Array of column identifiers / labels for grid questions | | `rows` | `grid` | Array | - | Array of row identifiers / labels for grid questions | | `questionType` | `grid` | String | `checkbox`, `number`, `radio` | Type of cell for grid questions (checkbox, numeric input, or radio) | +| `goTo` | `dropdown, multiple_unique` | Array | see [Jumps](#jumps) | Where to go next for an answer | +| `next` | `color, file, grid, long, ranking, short` | Integer / string | question id, `'submit'` | Where to go after the question, see [Jumps](#jumps) | + +### Jumps + +An answer can lead to a later question or to the end of the form, as in Microsoft Forms. The form stays a flat list of questions. + +- `goTo` is a list of jumps per answer: `{"optionId": 12, "target": 34}` for an option, `{"other": true, "target": "submit"}` for the answer "Other". There is at most one jump per answer. +- `next` is one target after the whole question. +- A question has either jumps per answer or one jump after the question, depending on its type: `goTo` only on `dropdown` 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). +- 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. +- Question types in neither list, such as `datetime`, accept neither `goTo` nor `next` (400). +- A jump of the answer "Other" is for `multiple_unique` questions, as dropdowns have no answer "Other", and only matches while `allowOtherAnswer` is on. +- `next` also applies when the question is left unanswered. + +The respondent's path starts at the first question and follows these targets. It ends at a question that has no answer yet and a jump per answer past the following question, a jump of the answer "Other" only while `allowOtherAnswer` is on, and the questions after it appear once it is answered, as in Microsoft Forms. If such a question is optional and left empty, the form can be submitted without the questions after it. The first value of an answer decides, and answers to questions the submit view does not show, such as questions without a title, do not count. A target that is not a later question of the form, for example after the target was deleted, counts as the following question, and a jump of an option that no longer exists never matches. Questions off the path are skipped: answers to them are ignored, and their required flag does not apply. Editing a submission replaces all its stored answers, so answers to questions that are skipped now are removed. ### Option Types diff --git a/lib/Constants.php b/lib/Constants.php index 3e465cd0c..2acd28e5b 100644 --- a/lib/Constants.php +++ b/lib/Constants.php @@ -175,6 +175,7 @@ class Constants { public const EXTRA_SETTINGS_DROPDOWN = [ 'allowOtherAnswer' => ['boolean'], 'shuffleOptions' => ['boolean'], + 'goTo' => ['array'], ]; public const EXTRA_SETTINGS_MULTIPLE = [ @@ -184,9 +185,22 @@ class Constants { 'shuffleOptions' => ['boolean'], ]; + public const EXTRA_SETTINGS_MULTIPLEUNIQUE = [ + 'allowOtherAnswer' => ['boolean'], + 'optionsLimitMax' => ['integer'], + 'optionsLimitMin' => ['integer'], + 'shuffleOptions' => ['boolean'], + 'goTo' => ['array'], + ]; + public const EXTRA_SETTINGS_SHORT = [ 'validationType' => ['string'], 'validationRegex' => ['string'], + 'next' => ['integer', 'string'], + ]; + + public const EXTRA_SETTINGS_LONG = [ + 'next' => ['integer', 'string'], ]; public const EXTRA_SETTINGS_FILE = [ @@ -194,6 +208,7 @@ class Constants { 'allowedFileExtensions' => ['array'], 'maxAllowedFilesCount' => ['integer'], 'maxFileSize' => ['integer'], + 'next' => ['integer', 'string'], ]; public const EXTRA_SETTINGS_DATE = [ @@ -227,10 +242,16 @@ class Constants { 'columns' => ['array'], 'questionType' => ['string'], 'rows' => ['array'], + 'next' => ['integer', 'string'], ]; public const EXTRA_SETTINGS_RANKING = [ 'shuffleOptions' => ['boolean'], + 'next' => ['integer', 'string'], + ]; + + public const EXTRA_SETTINGS_COLOR = [ + 'next' => ['integer', 'string'], ]; public const EXTRA_SETTINGS_GRID_QUESTION_TYPE = [ @@ -281,6 +302,7 @@ class Constants { * Constants related to extra settings for questions */ public const QUESTION_EXTRASETTINGS_OTHER_PREFIX = 'system-other-answer:'; + public const JUMP_TARGET_SUBMIT = 'submit'; /** * Maximum number of submissions returned per paginated API request. diff --git a/lib/Controller/ApiController.php b/lib/Controller/ApiController.php index 5afc157c9..ed43de0ba 100644 --- a/lib/Controller/ApiController.php +++ b/lib/Controller/ApiController.php @@ -64,6 +64,7 @@ * @psalm-import-type FormsOrder from ResponseDefinitions * @psalm-import-type FormsPartialForm from ResponseDefinitions * @psalm-import-type FormsQuestion from ResponseDefinitions + * @psalm-import-type FormsQuestionOrder from ResponseDefinitions * @psalm-import-type FormsQuestionType from ResponseDefinitions * @psalm-import-type FormsQuestionGridCellType from ResponseDefinitions * @psalm-import-type FormsSubmission from ResponseDefinitions @@ -222,6 +223,9 @@ public function newForm(?int $fromId = null): DataResponse { // Get Questions, set new formId, reinsert $questions = $this->questionMapper->findByForm($oldForm->getId()); $oldConfirmationEmailQuestionId = $oldForm->getConfirmationEmailQuestionId(); + $questionIdMap = []; + $optionIdMap = []; + $newQuestions = []; foreach ($questions as $oldQuestion) { $questionData = $oldQuestion->read(); @@ -230,6 +234,8 @@ public function newForm(?int $fromId = null): DataResponse { $questionData['formId'] = $form->getId(); $newQuestion = Question::fromParams($questionData); $this->questionMapper->insert($newQuestion); + $questionIdMap[$oldQuestion->getId()] = $newQuestion->getId(); + $newQuestions[] = $newQuestion; if (isset($oldConfirmationEmailQuestionId) && $oldConfirmationEmailQuestionId === $oldQuestion->getId()) { $form->setConfirmationEmailQuestionId($newQuestion->getId()); @@ -244,9 +250,14 @@ public function newForm(?int $fromId = null): DataResponse { $optionData['questionId'] = $newQuestion->getId(); $newOption = Option::fromParams($optionData); $this->optionMapper->insert($newOption); + $optionIdMap[$oldOption->getId()] = $newOption->getId(); } } + foreach (FormsService::mapJumpsOfCopies($newQuestions, $questionIdMap, $optionIdMap) as $newQuestion) { + $this->questionMapper->update($newQuestion); + } + $this->formMapper->update($form); $this->auditLogger->log(Operation::FormCreated, 'Form %s was created by "%s" as a copy of form %s', [ 'formId' => $form->getId(), @@ -525,13 +536,15 @@ 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 + * * @param int $formId the form id * @param FormsQuestionType $type the new question type * @param FormsQuestionGridCellType $subtype the new question subtype * @param string $text the new question title * @param ?int $fromId (optional) id of the question that should be cloned * @param ?int $position (optional) the position of the new question - * @return DataResponse + * @return DataResponse * @throws OCSBadRequestException Invalid type * @throws OCSBadRequestException Datetime question type no longer supported * @throws OCSForbiddenException User has no permissions to get this form @@ -554,6 +567,7 @@ public function newQuestion(int $formId, ?string $type = null, ?string $subtype throw new OCSForbiddenException('This form is archived and can not be modified'); } + $headers = []; if ($fromId === null) { $this->logger->debug('Adding new question: formId: {formId}, type: {type}, text: {text}', [ 'formId' => $formId, @@ -644,6 +658,7 @@ public function newQuestion(int $formId, ?string $type = null, ?string $subtype $response = $newQuestion->read(); $response['options'] = []; $response['accept'] = []; + $optionIdMap = []; foreach ($sourceOptions as $sourceOption) { $optionData = $sourceOption->read(); @@ -652,9 +667,24 @@ public function newQuestion(int $formId, ?string $type = null, ?string $subtype $optionData['questionId'] = $newQuestion->getId(); $newOption = Option::fromParams($optionData); $insertedOption = $this->optionMapper->insert($newOption); + $optionIdMap[$sourceOption->getId()] = $insertedOption->getId(); $response['options'][] = $insertedOption->read(); } + + $extraSettings = $newQuestion->getExtraSettings(); + if (array_key_exists('goTo', $extraSettings) || array_key_exists('next', $extraSettings)) { + $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)) { + $headers = self::getRemovedJumpsHeaders([$newQuestion->getId()]); + } + if ($newQuestion->getExtraSettings() !== $extraSettings) { + $this->questionMapper->update($newQuestion); + $response['extraSettings'] = $newQuestion->getExtraSettings(); + } + } } $this->formMapper->update($form); @@ -663,17 +693,20 @@ public function newQuestion(int $formId, ?string $type = null, ?string $subtype $response['extraSettings'] = new \stdClass(); } - return new DataResponse($response, Http::STATUS_CREATED); + return new DataResponse($response, Http::STATUS_CREATED, $headers); } /** * 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 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 * @param int $questionId id of question to update * @param array $keyValuePairs Array of key=>value pairs to update. - * @return DataResponse + * @return DataResponse * @throws OCSBadRequestException Question doesn\'t belong to given Form * @throws OCSBadRequestException Invalid extraSettings, will not update. * @throws OCSForbiddenException Empty keyValuePairs, will not update @@ -740,6 +773,23 @@ public function updateQuestion(int $formId, int $questionId, array $keyValuePair throw new OCSBadRequestException('Invalid extraSettings, will not update.'); } + $removedJumps = false; + if (is_array($keyValuePairs['extraSettings'] ?? null) + && (array_key_exists('goTo', $keyValuePairs['extraSettings']) || array_key_exists('next', $keyValuePairs['extraSettings']))) { + $allQuestions = $this->questionMapper->findByForm($formId, true); + if (!$this->formsService->areJumpsOfForm($keyValuePairs['extraSettings'], $allQuestions)) { + throw new OCSBadRequestException('Invalid extraSettings, will not update.'); + } + $updatedQuestion = clone $question; + $updatedQuestion->setExtraSettings($keyValuePairs['extraSettings']); + $removedJumps = $this->formsService->removeJumpsOfMissingOptions($updatedQuestion); + $formQuestions = array_values(array_map(static fn (Question $formQuestion): Question => $formQuestion->getId() === $questionId ? $updatedQuestion : $formQuestion, array_filter($allQuestions, static fn (Question $formQuestion): bool => $formQuestion->getOrder() !== 0))); + if (in_array($updatedQuestion, FormsService::removeBackwardJumps($formQuestions), true)) { + $removedJumps = true; + } + $keyValuePairs['extraSettings'] = $updatedQuestion->getExtraSettings(); + } + if ($form->getConfirmationEmailQuestionId() === $question->getId() && !$question->isEmailType($keyValuePairs['type'] ?? null, $keyValuePairs['extraSettings'] ?? null)) { $form->setConfirmationEmailQuestionId(null); @@ -753,7 +803,7 @@ public function updateQuestion(int $formId, int $questionId, array $keyValuePair $this->questionMapper->update($question); $this->formMapper->update($form); - return new DataResponse($question->getId()); + return new DataResponse($question->getId(), Http::STATUS_OK, $removedJumps ? self::getRemovedJumpsHeaders([$questionId]) : []); } /** @@ -839,9 +889,11 @@ 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 + * * @param int $formId Id of the form to reorder * @param list $newOrder Array of Question-Ids in new order. - * @return DataResponse, array{}> + * @return DataResponse, array{X-Forms-Adjusted?: string, Access-Control-Expose-Headers?: string}> * @throws OCSBadRequestException The given array contains duplicates * @throws OCSBadRequestException The length of the given array does not match the number of stored questions * @throws OCSBadRequestException Question doesn't belong to given Form @@ -851,7 +903,7 @@ public function deleteQuestion(int $formId, int $questionId): DataResponse { * @throws OCSNotFoundException Could not find form * @throws OCSNotFoundException Could not find question * - * 200: the question ids of the given form in the new order + * 200: the question ids of the given form in the new order, with the new extra settings of the questions whose jumps were removed */ #[CORS()] #[NoAdminRequired()] @@ -922,6 +974,8 @@ public function reorderQuestions(int $formId, array $newOrder): DataResponse { } } + $changedQuestions = FormsService::removeBackwardJumps($questions); + // Write to Database foreach ($questions as $question) { $this->questionMapper->update($question); @@ -929,11 +983,14 @@ public function reorderQuestions(int $formId, array $newOrder): DataResponse { $response[(string)$question->getId()] = [ 'order' => $question->getOrder() ]; + if (in_array($question, $changedQuestions, true)) { + $response[(string)$question->getId()]['extraSettings'] = $question->getExtraSettings() ?: new \stdClass(); + } } $this->formMapper->update($form); - return new DataResponse($response); + return new DataResponse($response, Http::STATUS_OK, self::getRemovedJumpsHeaders(array_map(static fn (Question $question): int => $question->getId(), $changedQuestions))); } // Options @@ -1099,10 +1156,12 @@ public function updateOption(int $formId, int $questionId, int $optionId, array /** * Delete an option * + * The jumps of the question for this option are removed as well, and the header `X-Forms-Adjusted` then holds `removed-jumps` with the id of the question. + * * @param int $formId id of form * @param int $questionId id of question * @param int $optionId id of option to update - * @return DataResponse Returns the id of the deleted option + * @return DataResponse Returns the id of the deleted option * @throws OCSBadRequestException The given option id doesn't match the question or form * @throws OCSForbiddenException This form is archived and can not be modified * @throws OCSForbiddenException Current user has no permission to edit @@ -1143,6 +1202,12 @@ public function deleteOption(int $formId, int $questionId, int $optionId): DataR $this->optionMapper->delete($option); + $headers = []; + if ($this->formsService->removeJumpsOfMissingOptions($question)) { + $this->questionMapper->update($question); + $headers = self::getRemovedJumpsHeaders([$questionId]); + } + // Reorder the remaining options $options = array_values($this->optionMapper->findByQuestion($questionId)); foreach ($options as $order => $option) { @@ -1153,7 +1218,7 @@ public function deleteOption(int $formId, int $questionId, int $optionId): DataR $this->formMapper->update($form); - return new DataResponse($optionId); + return new DataResponse($optionId, Http::STATUS_OK, $headers); } /** @@ -1482,6 +1547,7 @@ public function newSubmission(int $formId, array $answers, string $shareHash = ' } catch (\InvalidArgumentException $e) { throw new OCSBadRequestException($e->getMessage()); } + $answers = SubmissionService::getAnswersOnPath($questions, $answers); // Create Submission $submission = new Submission(); @@ -1577,6 +1643,7 @@ public function updateSubmission(int $formId, int $submissionId, array $answers) } catch (\InvalidArgumentException $e) { throw new OCSBadRequestException($e->getMessage()); } + $answers = SubmissionService::getAnswersOnPath($questions, $answers); try { $submission = $this->submissionMapper->findById($submissionId); @@ -1872,6 +1939,23 @@ public function uploadFiles(int $formId, int $questionId, string $shareHash = '' // private functions + /** + * The response headers reporting what the server changed beyond the request, readable by cross-origin clients as well: + * `X-Forms-Adjusted` is a structured field dictionary (RFC 8941), here with `removed-jumps` listing the questions whose jumps were removed + * + * @param list $questionIds the ids of the questions whose jumps were removed + * @return array{X-Forms-Adjusted?: string, Access-Control-Expose-Headers?: string} no headers when nothing was adjusted + */ + private static function getRemovedJumpsHeaders(array $questionIds): array { + if ($questionIds === []) { + return []; + } + return [ + 'X-Forms-Adjusted' => 'removed-jumps=(' . implode(' ', $questionIds) . ')', + 'Access-Control-Expose-Headers' => 'X-Forms-Adjusted', + ]; + } + /** * Insert answers for a question * diff --git a/lib/FormsMigrator.php b/lib/FormsMigrator.php index d0f63216d..9158f69bb 100644 --- a/lib/FormsMigrator.php +++ b/lib/FormsMigrator.php @@ -165,6 +165,7 @@ public function import(IUser $user, IImportSource $importSource, OutputInterface $questionIdMap = []; $questionTypeMap = []; $optionIdMap = []; + $questions = []; foreach ($formData['questions'] as $questionData) { $question = new Question(); $question->setFormId($form->getId()); @@ -180,6 +181,7 @@ public function import(IUser $user, IImportSource $importSource, OutputInterface // Store QuestionId to map Answers. $questionIdMap[$questionData['id']] = $question->getId(); $questionTypeMap[$questionData['id']] = $questionData['type']; + $questions[] = $question; foreach ($questionData['options'] as $optionData) { $option = new Option(); @@ -196,6 +198,10 @@ public function import(IUser $user, IImportSource $importSource, OutputInterface } } + foreach (FormsService::mapJumpsOfCopies($questions, $questionIdMap, $optionIdMap) as $question) { + $this->questionMapper->update($question); + } + if (($formData['confirmationEmailQuestionId'] ?? null) !== null && isset($questionIdMap[$formData['confirmationEmailQuestionId']])) { $form->setConfirmationEmailQuestionId($questionIdMap[$formData['confirmationEmailQuestionId']]); diff --git a/lib/ResponseDefinitions.php b/lib/ResponseDefinitions.php index 15ed97324..74950b4bd 100644 --- a/lib/ResponseDefinitions.php +++ b/lib/ResponseDefinitions.php @@ -27,8 +27,10 @@ * dateMax?: string|int, * dateMin?: string|int, * dateRange?: bool, + * goTo?: list, * maxAllowedFilesCount?: int, * maxFileSize?: int, + * next?: int|string, * optionsHighest?: 2|3|4|5|6|7|8|9|10, * optionsLabelHighest?: string, * optionsLabelLowest?: string, @@ -44,6 +46,11 @@ * questionType?: string, * } * + * @psalm-type FormsQuestionOrder = array{ + * order: int, + * extraSettings?: FormsQuestionExtraSettings|\stdClass, + * } + * * @psalm-type FormsQuestionType = "dropdown"|"multiple"|"multiple_unique"|"date"|"time"|"short"|"long"|"file"|"datetime"|"grid" * @psalm-type FormsQuestionGridCellType = "checkbox"|"number"|"radio" * diff --git a/lib/Service/FormsService.php b/lib/Service/FormsService.php index 197ababbc..06c3c049a 100644 --- a/lib/Service/FormsService.php +++ b/lib/Service/FormsService.php @@ -888,31 +888,44 @@ private function getSharesWithUser(int $formId, string $userId): array { }); } - /* - * Validates the extraSettings + /** + * The extra settings a question type allows, with the allowed types of their values * - * @param array $extraSettings input extra settings * @param string $questionType the question type - * @return bool if the settings are valid + * @return array> the allowed value types by extra setting */ - public function areExtraSettingsValid(array $extraSettings, string $questionType): bool { - if (count($extraSettings) === 0) { - return true; - } - - // Ensure only allowed keys are set - $allowed = match ($questionType) { + public static function getAllowedExtraSettings(string $questionType): array { + return match ($questionType) { Constants::ANSWER_TYPE_DROPDOWN => Constants::EXTRA_SETTINGS_DROPDOWN, - Constants::ANSWER_TYPE_MULTIPLE, Constants::ANSWER_TYPE_MULTIPLEUNIQUE => Constants::EXTRA_SETTINGS_MULTIPLE, + Constants::ANSWER_TYPE_MULTIPLE => Constants::EXTRA_SETTINGS_MULTIPLE, + Constants::ANSWER_TYPE_MULTIPLEUNIQUE => Constants::EXTRA_SETTINGS_MULTIPLEUNIQUE, Constants::ANSWER_TYPE_SHORT => Constants::EXTRA_SETTINGS_SHORT, + Constants::ANSWER_TYPE_LONG => Constants::EXTRA_SETTINGS_LONG, Constants::ANSWER_TYPE_FILE => Constants::EXTRA_SETTINGS_FILE, Constants::ANSWER_TYPE_DATE => Constants::EXTRA_SETTINGS_DATE, Constants::ANSWER_TYPE_GRID => Constants::EXTRA_SETTINGS_GRID, Constants::ANSWER_TYPE_RANKING => Constants::EXTRA_SETTINGS_RANKING, + Constants::ANSWER_TYPE_COLOR => Constants::EXTRA_SETTINGS_COLOR, Constants::ANSWER_TYPE_TIME => Constants::EXTRA_SETTINGS_TIME, Constants::ANSWER_TYPE_LINEARSCALE => Constants::EXTRA_SETTINGS_LINEARSCALE, default => [], }; + } + + /* + * Validates the extraSettings + * + * @param array $extraSettings input extra settings + * @param string $questionType the question type + * @return bool if the settings are valid + */ + public function areExtraSettingsValid(array $extraSettings, string $questionType): bool { + if (count($extraSettings) === 0) { + return true; + } + + // Ensure only allowed keys are set + $allowed = self::getAllowedExtraSettings($questionType); // Number of keys in extraSettings but not in allowed (but not the other way round) $diff = array_diff(array_keys($extraSettings), array_keys($allowed)); if (count($diff) > 0) { @@ -927,6 +940,13 @@ public function areExtraSettingsValid(array $extraSettings, string $questionType } } + if (array_key_exists('next', $extraSettings) && !self::isJumpTarget($extraSettings['next'])) { + return false; + } + if (array_key_exists('goTo', $extraSettings) && !self::isGoToValid($extraSettings['goTo'], $questionType)) { + return false; + } + // Validate extraSettings for specific question types if ($questionType === Constants::ANSWER_TYPE_DATE) { $format = Constants::ANSWER_PHPDATETIME_FORMAT['date']; @@ -1055,6 +1075,226 @@ public function areExtraSettingsValid(array $extraSettings, string $questionType return true; } + /** + * Whether the value is a jump target: the id of a question or the end of the form + * + * @param mixed $target the value + */ + private static function isJumpTarget(mixed $target): bool { + return (is_int($target) && $target > 0) || $target === Constants::JUMP_TARGET_SUBMIT; + } + + /** + * Whether the value is a list of jumps per answer, at most one per answer + * + * @param mixed $goTo the value of `goTo` + * @param string $questionType the question type + */ + private static function isGoToValid(mixed $goTo, string $questionType): bool { + if (!is_array($goTo) || !array_is_list($goTo)) { + return false; + } + + $answers = []; + foreach ($goTo as $jump) { + $answer = self::getJumpAnswer($jump, $questionType); + if ($answer === null || isset($answers[$answer])) { + return false; + } + $answers[$answer] = true; + } + + return true; + } + + /** + * The answer of a jump per answer with one answer key and a target: `option:` for an option, `other` for the answer "Other" of a radio question + * + * @param mixed $jump the jump + * @param string $questionType the question type + * @return ?string the answer, `null` for a jump with an invalid structure + */ + private static function getJumpAnswer(mixed $jump, string $questionType): ?string { + if (!is_array($jump) || count($jump) !== 2 || !self::isJumpTarget($jump['target'] ?? null)) { + return null; + } + if (is_int($jump['optionId'] ?? null) && $jump['optionId'] > 0) { + return 'option:' . $jump['optionId']; + } + if (($jump['other'] ?? null) === true && $questionType === Constants::ANSWER_TYPE_MULTIPLEUNIQUE) { + return 'other'; + } + return null; + } + + /** + * Whether the jump targets are questions of the form, deleted ones included + * + * @param array $extraSettings the extra settings of the question, with a valid structure + * @param list $formQuestions the questions of the form, deleted ones included + */ + public function areJumpsOfForm(array $extraSettings, array $formQuestions): bool { + $goTo = is_array($extraSettings['goTo'] ?? null) ? $extraSettings['goTo'] : []; + $questionIds = array_map(static fn (Question $question): int => $question->getId(), $formQuestions); + foreach ([$extraSettings['next'] ?? null, ...array_column($goTo, 'target')] as $target) { + if (is_int($target) && !in_array($target, $questionIds, true)) { + return false; + } + } + return true; + } + + /** + * Remove the jumps for options that are not options of the question + * + * @param Question $question the question, with extra settings of a valid structure + * @return bool whether jumps were removed, with the new extra settings set + */ + public function removeJumpsOfMissingOptions(Question $question): bool { + $extraSettings = $question->getExtraSettings(); + $goTo = is_array($extraSettings['goTo'] ?? null) ? $extraSettings['goTo'] : []; + if (array_column($goTo, 'optionId') === []) { + return false; + } + + $optionIds = array_map(static fn (Option $option): int => $option->getId(), $this->optionMapper->findByQuestion($question->getId())); + $kept = array_values(array_filter($goTo, static fn (array $jump): bool => !isset($jump['optionId']) || in_array($jump['optionId'], $optionIds, true))); + if (count($kept) === count($goTo)) { + return false; + } + + $extraSettings['goTo'] = $kept; + $question->setExtraSettings($extraSettings); + return true; + } + + /** + * The extra settings of a copied question, with its jumps pointing at the copied questions and options. + * Jumps whose target or option has no copy are removed. + * + * @param array $extraSettings the extra settings of the original question + * @param ?array $questionIdMap the ids of the copied questions by original id, `null` keeps the targets + * @param array $optionIdMap the ids of the copied options by original id + * @return array the extra settings of the copy + */ + public static function mapJumps(array $extraSettings, ?array $questionIdMap, array $optionIdMap): array { + $mapTarget = static function (mixed $target) use ($questionIdMap): string|int|null { + if (!is_int($target)) { + return $target === Constants::JUMP_TARGET_SUBMIT ? $target : null; + } + return $questionIdMap === null ? $target : ($questionIdMap[$target] ?? null); + }; + + if (array_key_exists('next', $extraSettings)) { + $next = $mapTarget($extraSettings['next']); + if ($next === null) { + unset($extraSettings['next']); + } else { + $extraSettings['next'] = $next; + } + } + + if (array_key_exists('goTo', $extraSettings)) { + $goTo = []; + foreach (is_array($extraSettings['goTo']) ? $extraSettings['goTo'] : [] as $jump) { + if (!is_array($jump)) { + continue; + } + $jump['target'] = $mapTarget($jump['target'] ?? null); + if (array_key_exists('optionId', $jump)) { + $jump['optionId'] = is_int($jump['optionId']) ? ($optionIdMap[$jump['optionId']] ?? null) : null; + if ($jump['optionId'] === null) { + continue; + } + } + if ($jump['target'] !== null) { + $goTo[] = $jump; + } + } + $extraSettings['goTo'] = $goTo; + } + + return $extraSettings; + } + + /** + * 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 + * + * @param list $questions the copied questions + * @param array $questionIdMap the ids of the copied questions by original id + * @param array $optionIdMap the ids of the copied options by original id + * @return list the copied questions with jumps, with their new extra settings set + */ + public static function mapJumpsOfCopies(array $questions, array $questionIdMap, array $optionIdMap): array { + $copiesWithJumps = []; + foreach ($questions as $question) { + $extraSettings = $question->getExtraSettings(); + if (array_key_exists('goTo', $extraSettings) || array_key_exists('next', $extraSettings)) { + $allowed = self::getAllowedExtraSettings($question->getType()); + if (!isset($allowed['goTo'])) { + unset($extraSettings['goTo']); + } + if (!isset($allowed['next'])) { + unset($extraSettings['next']); + } + $extraSettings = self::mapJumps($extraSettings, $questionIdMap, $optionIdMap); + if (array_key_exists('goTo', $extraSettings)) { + $goTo = []; + foreach ($extraSettings['goTo'] as $jump) { + $answer = self::getJumpAnswer($jump, $question->getType()); + if ($answer !== null && !isset($goTo[$answer])) { + $goTo[$answer] = $jump; + } + } + $extraSettings['goTo'] = array_values($goTo); + } + $question->setExtraSettings($extraSettings); + $copiesWithJumps[] = $question; + } + } + + if ($copiesWithJumps !== []) { + usort($questions, static fn (Question $a, Question $b): int => $a->getOrder() <=> $b->getOrder()); + self::removeBackwardJumps($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 + * + * @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 { + $positions = array_flip(array_map(static fn (Question $question): int => $question->getId(), $questions)); + $changed = []; + + foreach ($questions as $position => $question) { + $isBackward = static fn (mixed $target): bool => is_int($target) && isset($positions[$target]) && $positions[$target] <= $position; + $extraSettings = $question->getExtraSettings(); + $newSettings = $extraSettings; + + if ($isBackward($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))); + if (count($goTo) !== count($extraSettings['goTo'])) { + $newSettings['goTo'] = $goTo; + } + } + + if ($newSettings !== $extraSettings) { + $question->setExtraSettings($newSettings); + $changed[] = $question; + } + } + + return $changed; + } + /** * Get list of forms * diff --git a/lib/Service/SubmissionService.php b/lib/Service/SubmissionService.php index 0678b7ad8..2e888f0d2 100644 --- a/lib/Service/SubmissionService.php +++ b/lib/Service/SubmissionService.php @@ -612,9 +612,29 @@ private static function isShownToRespondents(array $question): bool { }; } + /** + * Whether the values of an answer hold anything: a non-empty text, an uploaded file with its token, or a grid row with a value + * + * @param array $values the values of the answer + */ + private static function hasValues(array $values): bool { + return array_filter($values, static function (mixed $value): bool { + if (is_array($value)) { + if (isset($value['uploadedFileId'])) { + return !empty($value['uploadedFileId']) && !empty($value['uploadToken']); + } + + return !empty(array_filter($value, static fn ($subValue): bool => is_array($subValue) ? !empty(array_filter($subValue)) : $subValue !== '')); + } + + return is_scalar($value) && (string)$value !== ''; + }) !== []; + } + /** * Validate all answers against the questions * Required questions the submit view does not show to respondents need no answer + * Only the questions on the path of the respondent are checked, answers to skipped questions are ignored * * @param array $questions Array of the questions of the form * @param array $answers Array of the submitted answers @@ -623,8 +643,10 @@ private static function isShownToRespondents(array $question): bool { * @throw \InvalidArgumentException if validation failed */ public function validateSubmission(array $questions, array $answers, string $formOwnerId, int $formId): void { + $visibleQuestions = self::getQuestionsOnPath($questions, $answers); + // Check by questions - foreach ($questions as $question) { + foreach ($visibleQuestions as $question) { $questionId = $question['id']; $questionAnswered = array_key_exists($questionId, $answers) && $answers[$questionId] !== []; @@ -633,22 +655,10 @@ public function validateSubmission(array $questions, array $answers, string $for } // Check if all required questions have an answer - if ($question['isRequired'] + if (!empty($question['isRequired']) && self::isShownToRespondents($question) && (!$questionAnswered - || !array_filter($answers[$questionId], static function (string|array $value): bool { - if (is_array($value)) { - // file type - if (isset($value['uploadedFileId'])) { - return !empty($value['uploadedFileId']) && !empty($value['uploadToken']); - } - - // Grid questions - return !empty(array_filter($value, static fn ($subValue): bool => is_array($subValue) ? !empty(array_filter($subValue)) : $subValue !== '')); - } - - return $value !== ''; - }) + || !self::hasValues($answers[$questionId]) || (!empty($question['extraSettings']['allowOtherAnswer']) && !array_filter($answers[$questionId], fn ($value) => $value !== Constants::QUESTION_EXTRASETTINGS_OTHER_PREFIX))) ) { throw new \InvalidArgumentException(sprintf('Question "%s" is required.', $question['text'])); @@ -715,6 +725,8 @@ public function validateSubmission(array $questions, array $answers, string $for // Check if all grid rows, columns and values match the configured grid subtype elseif ($question['type'] === Constants::ANSWER_TYPE_GRID) { $this->validateGridQuestion($question, $answers[$questionId]); + } elseif ($answer === Constants::QUESTION_EXTRASETTINGS_OTHER_PREFIX && self::isOtherAnswer($question, $answer)) { + throw new \InvalidArgumentException(sprintf('The answer "Other" for question "%s" needs a text.', $question['text'])); } // Search corresponding option, return false if non-existent elseif (!self::isOtherAnswer($question, $answer)) { @@ -791,6 +803,133 @@ public function validateSubmission(array $questions, array $answers, string $for } } + /** + * The questions on the path of the respondent: from the first question, each question leads to the target of its + * answer in `goTo`, else to its `next` target, else to the following question, until the end of the form. + * A target that is not a later question of the form counts as the following question. + * The path ends at a question that has no answer yet and a jump per answer past the following question. + * + * @param array $questions the questions of the form in their order + * @param array $answers the answers by question id + * @return list the questions on the path, in their order + */ + public static function getVisibleQuestions(array $questions, array $answers): array { + $questions = array_values($questions); + $positions = array_flip(array_column($questions, 'id')); + $visibleQuestions = []; + + $position = 0; + while ($position < count($questions)) { + $question = $questions[$position]; + $visibleQuestions[] = $question; + + $answer = $answers[$question['id']] ?? []; + if (self::awaitsAnswer($question, $answer, $position, $positions, count($questions))) { + break; + } + $target = self::getJumpTarget($question, $answer); + if ($target === Constants::JUMP_TARGET_SUBMIT) { + break; + } + $targetPosition = is_int($target) && isset($positions[$target]) ? $positions[$target] : null; + $position = $targetPosition !== null && $targetPosition > $position ? $targetPosition : $position + 1; + } + + return $visibleQuestions; + } + + /** + * The answers to the questions on the path of the respondent + * + * @param array $questions the questions of the form in their order + * @param array $answers the answers by question id + * @return array the answers by question id, without the answers to skipped questions + */ + public static function getAnswersOnPath(array $questions, array $answers): array { + return array_intersect_key($answers, array_flip(array_column(self::getQuestionsOnPath($questions, $answers), 'id'))); + } + + /** + * The questions on the path of the respondent, see getVisibleQuestions(), where questions the submit view does not show neither decide nor end the path with their jumps per answer + * + * @param array $questions the questions of the form in their order + * @param array $answers the answers by question id + * @return list the questions on the path, in their order + */ + private static function getQuestionsOnPath(array $questions, array $answers): array { + foreach ($questions as $key => $question) { + if (!self::isShownToRespondents($question)) { + unset($questions[$key]['extraSettings']['goTo']); + } + } + return self::getVisibleQuestions($questions, $answers); + } + + /** + * Whether the path waits for the answer to a question: the question has a jump per answer past the following question and no answer yet. + * A jump of the answer "Other" only counts while the question allows the answer "Other". + * + * @param array $question the question + * @param mixed $answer the values of the answer to the question + * @param int $position the position of the question + * @param array $positions the positions by question id + * @param int $count the number of questions + */ + private static function awaitsAnswer(array $question, mixed $answer, int $position, array $positions, int $count): bool { + $goTo = $question['extraSettings']['goTo'] ?? null; + if (!is_array($goTo) || !isset(FormsService::getAllowedExtraSettings((string)($question['type'] ?? ''))['goTo'])) { + return false; + } + $jumpsPastFollowingQuestion = false; + foreach ($goTo as $jump) { + if (is_array($jump) && ($jump['other'] ?? false) === true && empty($question['extraSettings']['allowOtherAnswer'])) { + continue; + } + $target = is_array($jump) ? ($jump['target'] ?? null) : null; + if ($target === Constants::JUMP_TARGET_SUBMIT) { + $targetPosition = $count; + } elseif (is_int($target) && isset($positions[$target])) { + $targetPosition = $positions[$target]; + } else { + continue; + } + if ($targetPosition > $position + 1) { + $jumpsPastFollowingQuestion = true; + break; + } + } + if (!$jumpsPastFollowingQuestion) { + return false; + } + $value = is_array($answer) && array_is_list($answer) ? ($answer[0] ?? null) : null; + return !(is_int($value) || is_float($value) || is_string($value)) || (string)$value === ''; + } + + /** + * The jump target of a question for its answer: the target of the `goTo` entry matching the first value of the answer, else `next` on question types with `next` + * + * @param array $question the question + * @param mixed $answer the values of the answer to the question + * @return string|int|null the target, `null` for the following question + */ + private static function getJumpTarget(array $question, mixed $answer): string|int|null { + $extraSettings = $question['extraSettings'] ?? []; + $value = is_array($answer) && array_is_list($answer) ? ($answer[0] ?? null) : null; + + if (is_int($value) || is_float($value) || is_string($value)) { + foreach (is_array($extraSettings['goTo'] ?? null) ? $extraSettings['goTo'] : [] as $jump) { + if ((isset($jump['optionId']) && (string)$jump['optionId'] === (string)$value) + || (($jump['other'] ?? false) === true && self::isOtherAnswer($question, $value))) { + $target = $jump['target'] ?? null; + return is_int($target) || is_string($target) ? $target : null; + } + } + } + + $next = isset(FormsService::getAllowedExtraSettings((string)($question['type'] ?? ''))['next']) ? ($extraSettings['next'] ?? null) : null; + return is_int($next) || is_string($next) ? $next : null; + } + /** * Validate correct date/time formats * @param array $answers Array with date from answer diff --git a/openapi.json b/openapi.json index 4336a8c92..3437019a3 100644 --- a/openapi.json +++ b/openapi.json @@ -530,6 +530,35 @@ "dateRange": { "type": "boolean" }, + "goTo": { + "type": "array", + "items": { + "type": "object", + "required": [ + "target" + ], + "properties": { + "optionId": { + "type": "integer", + "format": "int64" + }, + "other": { + "type": "boolean" + }, + "target": { + "oneOf": [ + { + "type": "integer", + "format": "int64" + }, + { + "type": "string" + } + ] + } + } + } + }, "maxAllowedFilesCount": { "type": "integer", "format": "int64" @@ -538,6 +567,17 @@ "type": "integer", "format": "int64" }, + "next": { + "oneOf": [ + { + "type": "integer", + "format": "int64" + }, + { + "type": "string" + } + ] + }, "optionsHighest": { "type": "integer", "format": "int64", @@ -606,6 +646,29 @@ "radio" ] }, + "QuestionOrder": { + "type": "object", + "required": [ + "order" + ], + "properties": { + "order": { + "type": "integer", + "format": "int64" + }, + "extraSettings": { + "anyOf": [ + { + "$ref": "#/components/schemas/QuestionExtraSettings" + }, + { + "type": "object", + "additionalProperties": true + } + ] + } + } + }, "QuestionType": { "type": "string", "enum": [ @@ -1675,7 +1738,7 @@ "post": { "operationId": "api-new-question", "summary": "Add a new question", - "description": "This endpoint allows CORS requests", + "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", "tags": [ "api" ], @@ -1750,6 +1813,18 @@ "responses": { "201": { "description": "the created question", + "headers": { + "X-Forms-Adjusted": { + "schema": { + "type": "string" + } + }, + "Access-Control-Expose-Headers": { + "schema": { + "type": "string" + } + } + }, "content": { "application/json": { "schema": { @@ -1895,7 +1970,7 @@ "patch": { "operationId": "api-reorder-questions", "summary": "Updates the Order of all Questions of a Form", - "description": "This endpoint allows CORS requests", + "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\nThis endpoint allows CORS requests", "tags": [ "api" ], @@ -1951,7 +2026,19 @@ ], "responses": { "200": { - "description": "the question ids of the given form in the new order", + "description": "the question ids of the given form in the new order, with the new extra settings of the questions whose jumps were removed", + "headers": { + "X-Forms-Adjusted": { + "schema": { + "type": "string" + } + }, + "Access-Control-Expose-Headers": { + "schema": { + "type": "string" + } + } + }, "content": { "application/json": { "schema": { @@ -1973,7 +2060,7 @@ "data": { "type": "object", "additionalProperties": { - "$ref": "#/components/schemas/Order" + "$ref": "#/components/schemas/QuestionOrder" } } } @@ -2291,7 +2378,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": "This endpoint allows CORS requests", + "description": "Jumps to the question itself or to an earlier question 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" ], @@ -2357,6 +2444,18 @@ "responses": { "200": { "description": "the id of the updated question", + "headers": { + "X-Forms-Adjusted": { + "schema": { + "type": "string" + } + }, + "Access-Control-Expose-Headers": { + "schema": { + "type": "string" + } + } + }, "content": { "application/json": { "schema": { @@ -3360,7 +3459,7 @@ "delete": { "operationId": "api-delete-option", "summary": "Delete an option", - "description": "Returns the id of the deleted option\nThis endpoint allows CORS requests", + "description": "The jumps of the question for this option are removed as well, and the header `X-Forms-Adjusted` then holds `removed-jumps` with the id of the question.\nReturns the id of the deleted option\nThis endpoint allows CORS requests", "tags": [ "api" ], @@ -3414,6 +3513,18 @@ "responses": { "200": { "description": "the id of the deleted option", + "headers": { + "X-Forms-Adjusted": { + "schema": { + "type": "string" + } + }, + "Access-Control-Expose-Headers": { + "schema": { + "type": "string" + } + } + }, "content": { "application/json": { "schema": { diff --git a/tests/Unit/Controller/ApiControllerTest.php b/tests/Unit/Controller/ApiControllerTest.php index c2f0355f7..bc65cbdd6 100644 --- a/tests/Unit/Controller/ApiControllerTest.php +++ b/tests/Unit/Controller/ApiControllerTest.php @@ -37,6 +37,7 @@ function is_uploaded_file(string|bool|null $filename) { use OCA\Forms\Db\AnswerMapper; use OCA\Forms\Db\Form; use OCA\Forms\Db\FormMapper; +use OCA\Forms\Db\Option; use OCA\Forms\Db\OptionMapper; use OCA\Forms\Db\Question; use OCA\Forms\Db\QuestionMapper; @@ -965,6 +966,26 @@ public function testNewSubmission_answers() { $this->apiController->newSubmission(1, $answers, ''); } + public function testNewSubmission_storesNoAnswersWhenAnOptionalQuestionWithJumpsIsLeftEmpty() { + $form = new Form(); + $form->setId(1); + $form->setHash('hash'); + $form->setOwnerId('admin'); + + $this->formsService->method('loadFormForSubmission')->willReturn($form); + $this->formsService->method('getQuestions')->willReturn([ + ['id' => 1, 'type' => Constants::ANSWER_TYPE_MULTIPLEUNIQUE, 'text' => 'q1', 'isRequired' => false, 'options' => [['id' => 10, 'text' => 'A'], ['id' => 11, 'text' => 'B']], 'extraSettings' => ['goTo' => [['optionId' => 10, 'target' => 3], ['optionId' => 11, 'target' => 'submit']]]], + ['id' => 2, 'type' => Constants::ANSWER_TYPE_SHORT, 'text' => 'q2', 'isRequired' => true, 'options' => [], 'extraSettings' => []], + ['id' => 3, 'type' => Constants::ANSWER_TYPE_SHORT, 'text' => 'q3', 'isRequired' => true, 'options' => [], 'extraSettings' => []], + ]); + $this->formAccess(); + $this->submissionMapper->expects($this->once())->method('insert'); + $this->answerMapper->expects($this->never())->method('insert'); + + $response = $this->apiController->newSubmission(1, [2 => ['Rex']], ''); + $this->assertSame(201, $response->getStatus()); + } + public function testNewSubmission_formNotFound() { $this->formsService->expects($this->once()) ->method('loadFormForSubmission') @@ -1398,6 +1419,238 @@ public function testUpdateQuestionRejectsTypeChange(): void { $this->apiController->updateQuestion(1, 7, ['type' => Constants::ANSWER_TYPE_LONG]); } + public function testUpdateQuestionRemovesJumpsToTheQuestionItselfOrAnEarlierQuestion(): void { + $form = new Form(); + $form->setId(1); + $form->setOwnerId('currentUser'); + + $first = new Question(); + $first->setId(6); + $first->setFormId(1); + $first->setOrder(1); + $first->setType(Constants::ANSWER_TYPE_SHORT); + + $question = new Question(); + $question->setId(7); + $question->setFormId(1); + $question->setOrder(2); + $question->setType(Constants::ANSWER_TYPE_MULTIPLEUNIQUE); + + $deleted = new Question(); + $deleted->setId(5); + $deleted->setFormId(1); + $deleted->setOrder(0); + $deleted->setType(Constants::ANSWER_TYPE_SHORT); + + $extraSettings = ['goTo' => [['optionId' => 1, 'target' => 'submit'], ['optionId' => 2, 'target' => 7], ['optionId' => 3, 'target' => 6], ['optionId' => 4, 'target' => 5]]]; + $this->formsService->method('getFormIfAllowed')->with(1, Constants::PERMISSION_EDIT)->willReturn($form); + $this->formsService->method('isFormArchived')->with($form)->willReturn(false); + $this->formsService->method('areExtraSettingsValid')->willReturn(true); + $this->formsService->expects($this->once())->method('areJumpsOfForm')->with($extraSettings, [$deleted, $first, $question])->willReturn(true); + $this->questionMapper->method('findById')->with(7)->willReturn($question); + $this->questionMapper->method('findByForm')->with(1, true)->willReturn([$deleted, $first, $question]); + $this->questionMapper->expects($this->once()) + ->method('update') + ->with($this->callback(fn (Question $updatedQuestion): bool => $updatedQuestion->getId() === 7 + && $updatedQuestion->getExtraSettings() === ['goTo' => [['optionId' => 1, 'target' => 'submit'], ['optionId' => 4, 'target' => 5]]])); + + $response = $this->apiController->updateQuestion(1, 7, ['extraSettings' => $extraSettings]); + + $this->assertSame(7, $response->getData()); + $this->assertSame('removed-jumps=(7)', $response->getHeaders()['X-Forms-Adjusted']); + } + + public function testDeleteOptionRemovesItsJumps(): void { + $form = new Form(); + $form->setId(1); + $form->setOwnerId('currentUser'); + + $question = new Question(); + $question->setId(7); + $question->setFormId(1); + $question->setType(Constants::ANSWER_TYPE_MULTIPLEUNIQUE); + $question->setExtraSettings(['goTo' => [['optionId' => 3, 'target' => 'submit'], ['optionId' => 4, 'target' => 9]]]); + + $option = new Option(); + $option->setId(3); + $option->setQuestionId(7); + + $this->formsService->method('getFormIfAllowed')->with(1, Constants::PERMISSION_EDIT)->willReturn($form); + $this->formsService->method('isFormArchived')->with($form)->willReturn(false); + $this->optionMapper->method('findById')->with(3)->willReturn($option); + $this->optionMapper->method('findByQuestion')->with(7)->willReturn([]); + $this->optionMapper->expects($this->once())->method('delete')->with($option); + $this->formsService->expects($this->once()) + ->method('removeJumpsOfMissingOptions') + ->with($question) + ->willReturnCallback(function (Question $question): bool { + $question->setExtraSettings(['goTo' => [['optionId' => 4, 'target' => 9]]]); + return true; + }); + $this->questionMapper->method('findById')->with(7)->willReturn($question); + $this->questionMapper->expects($this->once()) + ->method('update') + ->with($this->callback(fn (Question $updatedQuestion): bool => $updatedQuestion->getExtraSettings() === ['goTo' => [['optionId' => 4, 'target' => 9]]])); + + $response = $this->apiController->deleteOption(1, 7, 3); + + $this->assertSame(3, $response->getData()); + $this->assertSame('removed-jumps=(7)', $response->getHeaders()['X-Forms-Adjusted']); + $this->assertSame('X-Forms-Adjusted', $response->getHeaders()['Access-Control-Expose-Headers']); + } + + public function testDeleteOptionWithoutJumpsKeepsTheQuestion(): void { + $form = new Form(); + $form->setId(1); + $form->setOwnerId('currentUser'); + + $question = new Question(); + $question->setId(7); + $question->setFormId(1); + $question->setType(Constants::ANSWER_TYPE_MULTIPLEUNIQUE); + $question->setExtraSettings(['goTo' => [['optionId' => 4, 'target' => 9]]]); + + $option = new Option(); + $option->setId(3); + $option->setQuestionId(7); + + $this->formsService->method('getFormIfAllowed')->with(1, Constants::PERMISSION_EDIT)->willReturn($form); + $this->formsService->method('isFormArchived')->with($form)->willReturn(false); + $this->optionMapper->method('findById')->with(3)->willReturn($option); + $this->optionMapper->method('findByQuestion')->with(7)->willReturn([]); + $this->formsService->expects($this->once())->method('removeJumpsOfMissingOptions')->with($question)->willReturn(false); + $this->questionMapper->method('findById')->with(7)->willReturn($question); + $this->questionMapper->expects($this->never())->method('update'); + + $response = $this->apiController->deleteOption(1, 7, 3); + + $this->assertArrayNotHasKey('X-Forms-Adjusted', $response->getHeaders()); + } + + public function testUpdateQuestionRejectsJumpsToQuestionsOfOtherForms(): void { + $form = new Form(); + $form->setId(1); + $form->setOwnerId('currentUser'); + + $question = new Question(); + $question->setId(7); + $question->setFormId(1); + $question->setOrder(1); + $question->setType(Constants::ANSWER_TYPE_SHORT); + + $this->formsService->method('getFormIfAllowed')->with(1, Constants::PERMISSION_EDIT)->willReturn($form); + $this->formsService->method('isFormArchived')->with($form)->willReturn(false); + $this->formsService->method('areExtraSettingsValid')->willReturn(true); + $this->formsService->method('areJumpsOfForm')->with(['next' => 99], [$question])->willReturn(false); + $this->questionMapper->method('findById')->with(7)->willReturn($question); + $this->questionMapper->method('findByForm')->with(1, true)->willReturn([$question]); + $this->questionMapper->expects($this->never())->method('update'); + + $this->expectException(OCSBadRequestException::class); + $this->apiController->updateQuestion(1, 7, ['extraSettings' => ['next' => 99]]); + } + + public function testUpdateQuestionRemovesJumpsOfMissingOptions(): void { + $form = new Form(); + $form->setId(1); + $form->setOwnerId('currentUser'); + + $question = new Question(); + $question->setId(7); + $question->setFormId(1); + $question->setOrder(1); + $question->setType(Constants::ANSWER_TYPE_MULTIPLEUNIQUE); + + $extraSettings = ['goTo' => [['optionId' => 1, 'target' => 'submit'], ['optionId' => 2, 'target' => 'submit']]]; + $this->formsService->method('getFormIfAllowed')->with(1, Constants::PERMISSION_EDIT)->willReturn($form); + $this->formsService->method('isFormArchived')->with($form)->willReturn(false); + $this->formsService->method('areExtraSettingsValid')->willReturn(true); + $this->formsService->method('areJumpsOfForm')->willReturn(true); + $this->formsService->expects($this->once()) + ->method('removeJumpsOfMissingOptions') + ->willReturnCallback(function (Question $updatedQuestion): bool { + $updatedQuestion->setExtraSettings(['goTo' => [['optionId' => 1, 'target' => 'submit']]]); + return true; + }); + $this->questionMapper->method('findById')->with(7)->willReturn($question); + $this->questionMapper->method('findByForm')->with(1, true)->willReturn([$question]); + $this->questionMapper->expects($this->once()) + ->method('update') + ->with($this->callback(fn (Question $updatedQuestion): bool => $updatedQuestion->getExtraSettings() === ['goTo' => [['optionId' => 1, 'target' => 'submit']]])); + + $response = $this->apiController->updateQuestion(1, 7, ['extraSettings' => $extraSettings]); + + $this->assertSame('removed-jumps=(7)', $response->getHeaders()['X-Forms-Adjusted']); + } + + public function testReorderQuestionsRemovesJumpsThatWouldGoBack(): void { + $form = new Form(); + $form->setId(1); + $form->setOwnerId('currentUser'); + + $questions = []; + foreach ([[6, 1, ['next' => 7]], [7, 2, []], [8, 3, ['next' => 'submit']]] as [$id, $order, $extraSettings]) { + $question = new Question(); + $question->setId($id); + $question->setFormId(1); + $question->setOrder($order); + $question->setExtraSettings($extraSettings); + $questions[$id] = $question; + } + + $this->formsService->method('getFormIfAllowed')->with(1, Constants::PERMISSION_EDIT)->willReturn($form); + $this->formsService->method('isFormArchived')->with($form)->willReturn(false); + $this->questionMapper->method('findByForm')->with(1)->willReturn(array_values($questions)); + $this->questionMapper->method('findById')->willReturnCallback(fn (int $id): Question => $questions[$id]); + + $response = $this->apiController->reorderQuestions(1, [7, 6, 8]); + + $this->assertEquals([ + '7' => ['order' => 1], + '6' => ['order' => 2, 'extraSettings' => new \stdClass()], + '8' => ['order' => 3], + ], $response->getData()); + $this->assertSame('removed-jumps=(6)', $response->getHeaders()['X-Forms-Adjusted']); + $this->assertSame('X-Forms-Adjusted', $response->getHeaders()['Access-Control-Expose-Headers']); + } + + public function testCloneQuestionAtTheEndRemovesJumpsThatWouldGoBack(): void { + $form = new Form(); + $form->setId(1); + $form->setOwnerId('currentUser'); + + $source = new Question(); + $source->setId(7); + $source->setFormId(1); + $source->setOrder(1); + $source->setType(Constants::ANSWER_TYPE_SHORT); + $source->setExtraSettings(['next' => 9]); + + $target = new Question(); + $target->setId(9); + $target->setFormId(1); + $target->setOrder(2); + $target->setType(Constants::ANSWER_TYPE_SHORT); + + $this->formsService->method('getFormIfAllowed')->with(1, Constants::PERMISSION_EDIT)->willReturn($form); + $this->formsService->method('isFormArchived')->with($form)->willReturn(false); + $this->questionMapper->method('findById')->with(7)->willReturn($source); + $this->optionMapper->method('findByQuestion')->with(7)->willReturn([]); + $this->questionMapper->method('insert')->willReturnCallback(function (Question $question) { + $question->setId(10); + return $question; + }); + $this->questionMapper->expects($this->once())->method('findByForm')->with(1)->willReturn([$source, $target]); + $this->questionMapper->expects($this->once()) + ->method('update') + ->with($this->callback(fn (Question $question): bool => $question->getId() === 10 && $question->getExtraSettings() === [])); + + $response = $this->apiController->newQuestion(1, null, null, '', 7); + + $this->assertEquals(new \stdClass(), $response->getData()['extraSettings']); + $this->assertSame('removed-jumps=(10)', $response->getHeaders()['X-Forms-Adjusted']); + } + public function testUpdateQuestionClearsConfirmationEmailQuestionIdWhenQuestionStopsBeingEmail(): void { $form = new Form(); $form->setId(1); @@ -1561,6 +1814,88 @@ public function testCloneFormWithConfirmationEmailQuestionId(): void { $this->assertEquals(11, $clonedForm->getConfirmationEmailQuestionId()); } + public function testCloneFormMapsJumps(): void { + $this->configService->method('canCreateForms')->willReturn(true); + + $oldForm = Form::fromParams(['id' => 7, 'title' => 'Old Form', 'ownerId' => 'currentUser']); + $this->formsService->method('getFormIfAllowed')->with(7)->willReturn($oldForm); + $this->formsService->method('generateFormHash')->willReturn('new hash'); + + $trigger = new Question(); + $trigger->setId(10); + $trigger->setFormId(7); + $trigger->setOrder(1); + $trigger->setType(Constants::ANSWER_TYPE_MULTIPLEUNIQUE); + $trigger->setExtraSettings(['goTo' => [['optionId' => 100, 'target' => 20]]]); + $target = new Question(); + $target->setId(20); + $target->setFormId(7); + $target->setOrder(2); + $target->setType(Constants::ANSWER_TYPE_SHORT); + $this->questionMapper->method('findByForm')->with(7)->willReturn([$trigger, $target]); + + $option = Option::fromParams(['id' => 100, 'questionId' => 10, 'text' => 'Yes']); + $this->optionMapper->method('findByQuestion')->willReturnCallback(fn (int $questionId) => $questionId === 10 ? [$option] : []); + + $this->formMapper->method('insert')->willReturnCallback(function (Form $form) { + $form->setId(14); + return $form; + }); + $newIds = [10 => 11, 20 => 21]; + $this->questionMapper->method('insert')->willReturnCallback(function (Question $question) use (&$newIds) { + $question->setId(array_shift($newIds)); + return $question; + }); + $this->optionMapper->method('insert')->willReturnCallback(function (Option $option) { + $option->setId(101); + return $option; + }); + + $this->questionMapper->expects($this->once()) + ->method('update') + ->with($this->callback(fn (Question $question) => $question->getId() === 11 + && $question->getExtraSettings() === ['goTo' => [['optionId' => 101, 'target' => 21]]])); + + $this->apiController->newForm(7); + } + + public function testCloneQuestionMapsOptionIdsOfJumps(): void { + $form = new Form(); + $form->setId(1); + $form->setOwnerId('currentUser'); + + $question = new Question(); + $question->setId(7); + $question->setFormId(1); + $question->setOrder(1); + $question->setType(Constants::ANSWER_TYPE_MULTIPLEUNIQUE); + $question->setExtraSettings(['goTo' => [['optionId' => 70, 'target' => 9]]]); + + $this->formsService->method('getFormIfAllowed')->with(1, Constants::PERMISSION_EDIT)->willReturn($form); + $this->formsService->method('isFormArchived')->with($form)->willReturn(false); + $this->questionMapper->method('findById')->with(7)->willReturn($question); + $this->questionMapper->method('findByForm')->with(1)->willReturn([$question]); + $this->optionMapper->method('findByQuestion')->with(7)->willReturn([Option::fromParams(['id' => 70, 'questionId' => 7, 'text' => 'Yes'])]); + $this->questionMapper->method('insert')->willReturnCallback(function (Question $question) { + $question->setId(8); + return $question; + }); + $this->optionMapper->method('insert')->willReturnCallback(function (Option $option) { + $option->setId(80); + return $option; + }); + + $this->questionMapper->expects($this->once()) + ->method('update') + ->with($this->callback(fn (Question $question) => $question->getId() === 8 + && $question->getExtraSettings() === ['goTo' => [['optionId' => 80, 'target' => 9]]])); + + $response = $this->apiController->newQuestion(1, null, null, '', 7); + + $this->assertSame(['goTo' => [['optionId' => 80, 'target' => 9]]], $response->getData()['extraSettings']); + $this->assertArrayNotHasKey('X-Forms-Adjusted', $response->getHeaders()); + } + public function testTransferOwnerNotOwner() { $form = new Form(); $form->setId(1); @@ -2146,6 +2481,42 @@ public function testUpdateSubmission_success() { ]); } + public function testUpdateSubmission_removesAnswersToSkippedQuestions() { + $form = new Form(); + $form->setId(1); + $form->setOwnerId('formOwner'); + $form->setAllowEditSubmissions(true); + + $submission = new Submission(); + $submission->setId(42); + $submission->setFormId(1); + $submission->setUserId('currentUser'); + + $this->formsService->method('loadFormForSubmission')->willReturn($form); + $this->formsService->method('canDeleteResults')->willReturn(true); + $this->formsService->method('getPermissions')->willReturn([]); + $this->formsService->method('getQuestions')->willReturn([ + ['id' => 1, 'type' => Constants::ANSWER_TYPE_MULTIPLEUNIQUE, 'text' => 'q1', 'options' => [['id' => 10, 'text' => 'Done']], 'extraSettings' => ['goTo' => [['optionId' => 10, 'target' => 3]]]], + ['id' => 2, 'type' => Constants::ANSWER_TYPE_SHORT, 'text' => 'q2', 'options' => [], 'extraSettings' => []], + ['id' => 3, 'type' => Constants::ANSWER_TYPE_SHORT, 'text' => 'q3', 'options' => [], 'extraSettings' => []], + ]); + $this->submissionMapper->method('findById')->willReturn($submission); + + $this->answerMapper->expects($this->once()) + ->method('deleteBySubmission') + ->with(42); + $inserted = []; + $this->answerMapper->expects($this->exactly(2)) + ->method('insert') + ->willReturnCallback(function ($answer) use (&$inserted) { + $inserted[] = $answer->getQuestionId(); + return $answer; + }); + + $this->apiController->updateSubmission(1, 42, ['1' => ['10'], '2' => ['skipped'], '3' => ['text']]); + $this->assertSame([1, 3], $inserted); + } + public function testUpdateSubmission_noPermission() { $formId = 1; $submissionId = 42; diff --git a/tests/Unit/FormsMigratorTest.php b/tests/Unit/FormsMigratorTest.php index 53affe486..a714d3431 100644 --- a/tests/Unit/FormsMigratorTest.php +++ b/tests/Unit/FormsMigratorTest.php @@ -416,6 +416,36 @@ public function testImportMapsOptionsOfGridAndRankingQuestions(array $options, a $this->assertSame($expectedAnswers, $insertedAnswers); } + public function testImportMapsJumps(): void { + $inputJson = '[{"title":"Link","description":"","created":1646251830,"access":{"permitAllUsers":false,"showToAllUsers":false},"expires":0,"state":0,"isAnonymous":false,"submitMultiple":false,"allowEditSubmissions":false,"showExpiration":false,"lastUpdated":123456789,' + . '"questions":[{"id":14,"order":1,"type":"multiple_unique","isRequired":false,"text":"Pet?","description":"","extraSettings":{"goTo":[{"optionId":35,"target":15},{"optionId":36,"target":15}],"next":"submit"},"options":[{"id":35,"text":"Yes"},{"text":"No"}]},' + . '{"id":15,"order":2,"type":"short","isRequired":false,"text":"Which?","description":"","extraSettings":{},"options":[]}],' + . '"submissions":[]}]'; + + $user = $this->createMock(IUser::class); + $user->method('getUID')->willReturn('someUser'); + $importSource = $this->createMock(IImportSource::class); + $importSource->method('getMigratorVersion')->willReturn(1); + $importSource->method('getFileContents')->willReturn($inputJson); + $questionIds = [100, 101]; + $this->questionMapper->method('insert')->willReturnCallback(function ($question) use (&$questionIds) { + $question->setId(array_shift($questionIds)); + return $question; + }); + $optionIds = [500, 501]; + $this->optionMapper->method('insert')->willReturnCallback(function ($option) use (&$optionIds) { + $option->setId(array_shift($optionIds)); + return $option; + }); + + $this->questionMapper->expects($this->once()) + ->method('update') + ->with($this->callback(fn ($question) => $question->getId() === 100 + && $question->getExtraSettings() === ['goTo' => [['optionId' => 500, 'target' => 101]]])); + + $this->formsMigrator->import($user, $importSource, $this->createMock(OutputInterface::class)); + } + public function testImport_NoVersion() { $user = $this->createMock(IUser::class); $importSource = $this->createMock(IImportSource::class); diff --git a/tests/Unit/Service/FormsServiceTest.php b/tests/Unit/Service/FormsServiceTest.php index 04185d43d..b4443ce38 100644 --- a/tests/Unit/Service/FormsServiceTest.php +++ b/tests/Unit/Service/FormsServiceTest.php @@ -1662,6 +1662,116 @@ public function testAreExtraSettingsValidNormalizesLegacyDateLimitsAsUtcDates(): public static function dataAreExtraSettingsValid() { return [ + 'jump: next to a question on a text question' => [ + 'extraSettings' => ['next' => 5], + 'questionType' => Constants::ANSWER_TYPE_SHORT, + 'expected' => true, + ], + 'jump: next to the end on a long text question' => [ + 'extraSettings' => ['next' => 'submit'], + 'questionType' => Constants::ANSWER_TYPE_LONG, + 'expected' => true, + ], + 'jump: next with an unknown word' => [ + 'extraSettings' => ['next' => 'end'], + 'questionType' => Constants::ANSWER_TYPE_SHORT, + 'expected' => false, + ], + 'jump: next with a negative id' => [ + 'extraSettings' => ['next' => -1], + 'questionType' => Constants::ANSWER_TYPE_SHORT, + 'expected' => false, + ], + 'jump: next as numeric string' => [ + 'extraSettings' => ['next' => '5'], + 'questionType' => Constants::ANSWER_TYPE_SHORT, + 'expected' => false, + ], + 'jump: next not offered on date questions' => [ + 'extraSettings' => ['next' => 5], + 'questionType' => Constants::ANSWER_TYPE_DATE, + 'expected' => false, + ], + 'jump: goTo per option and Other' => [ + 'extraSettings' => ['allowOtherAnswer' => true, 'goTo' => [['optionId' => 11, 'target' => 5], ['other' => true, 'target' => 'submit']]], + 'questionType' => Constants::ANSWER_TYPE_MULTIPLEUNIQUE, + 'expected' => true, + ], + 'jump: goTo on a dropdown' => [ + 'extraSettings' => ['goTo' => [['optionId' => 11, 'target' => 5]]], + 'questionType' => Constants::ANSWER_TYPE_DROPDOWN, + 'expected' => true, + ], + 'jump: goTo for Other on a dropdown' => [ + 'extraSettings' => ['allowOtherAnswer' => true, 'goTo' => [['other' => true, 'target' => 5]]], + 'questionType' => Constants::ANSWER_TYPE_DROPDOWN, + 'expected' => false, + ], + 'jump: next not offered on radio questions' => [ + 'extraSettings' => ['goTo' => [['optionId' => 11, 'target' => 5]], 'next' => 6], + 'questionType' => Constants::ANSWER_TYPE_MULTIPLEUNIQUE, + 'expected' => false, + ], + 'jump: next not offered on dropdowns' => [ + 'extraSettings' => ['next' => 6], + 'questionType' => Constants::ANSWER_TYPE_DROPDOWN, + 'expected' => false, + ], + 'jump: goTo not offered on text questions' => [ + 'extraSettings' => ['goTo' => [['optionId' => 11, 'target' => 5]]], + 'questionType' => Constants::ANSWER_TYPE_SHORT, + 'expected' => false, + ], + 'jump: goTo not offered on checkboxes' => [ + 'extraSettings' => ['goTo' => [['optionId' => 11, 'target' => 5]]], + 'questionType' => Constants::ANSWER_TYPE_MULTIPLE, + 'expected' => false, + ], + 'jump: goTo as object' => [ + 'extraSettings' => ['goTo' => ['a' => ['optionId' => 11, 'target' => 5]]], + 'questionType' => Constants::ANSWER_TYPE_MULTIPLEUNIQUE, + 'expected' => false, + ], + 'jump: goTo entry without target' => [ + 'extraSettings' => ['goTo' => [['optionId' => 11]]], + 'questionType' => Constants::ANSWER_TYPE_MULTIPLEUNIQUE, + 'expected' => false, + ], + 'jump: goTo entry with an extra key' => [ + 'extraSettings' => ['goTo' => [['optionId' => 11, 'target' => 5, 'foo' => 1]]], + 'questionType' => Constants::ANSWER_TYPE_MULTIPLEUNIQUE, + 'expected' => false, + ], + 'jump: goTo entry with option id as string' => [ + 'extraSettings' => ['goTo' => [['optionId' => '11', 'target' => 5]]], + 'questionType' => Constants::ANSWER_TYPE_MULTIPLEUNIQUE, + 'expected' => false, + ], + 'jump: goTo entry with other false' => [ + 'extraSettings' => ['goTo' => [['other' => false, 'target' => 5]]], + 'questionType' => Constants::ANSWER_TYPE_MULTIPLEUNIQUE, + 'expected' => false, + ], + 'jump: goTo with a scalar entry' => [ + 'extraSettings' => ['goTo' => [5]], + 'questionType' => Constants::ANSWER_TYPE_MULTIPLEUNIQUE, + 'expected' => false, + ], + 'jump: two jumps for one option' => [ + 'extraSettings' => ['goTo' => [['optionId' => 11, 'target' => 5], ['optionId' => 11, 'target' => 6]]], + 'questionType' => Constants::ANSWER_TYPE_MULTIPLEUNIQUE, + 'expected' => false, + ], + 'jump: two jumps for Other' => [ + 'extraSettings' => ['goTo' => [['other' => true, 'target' => 5], ['other' => true, 'target' => 6]]], + 'questionType' => Constants::ANSWER_TYPE_MULTIPLEUNIQUE, + 'expected' => false, + ], + 'jump: next on an empty regex short question' => [ + 'extraSettings' => ['validationType' => 'regex', 'validationRegex' => '', 'next' => 'end'], + 'questionType' => Constants::ANSWER_TYPE_SHORT, + 'expected' => false, + ], 'empty-extra-settings' => [ 'extraSettings' => [], 'questionType' => Constants::ANSWER_TYPE_LONG, @@ -2009,4 +2119,163 @@ private function createQuestionEntity(array $data): MockObject { return $questionEntity; } + public static function dataAreJumpsOfForm(): array { + return [ + 'targets of the form, a deleted one included' => [['next' => 2], true], + 'the end of the form' => [['goTo' => [['other' => true, 'target' => 'submit']]], true], + 'a question of another form' => [['next' => 9], false], + 'a goTo target of another form' => [['goTo' => [['optionId' => 11, 'target' => 9]]], false], + ]; + } + + #[DataProvider('dataAreJumpsOfForm')] + public function testAreJumpsOfForm(array $extraSettings, bool $expected): void { + $questions = []; + foreach ([[1, 1], [2, 0], [3, 2]] as [$id, $order]) { + $question = new Question(); + $question->setId($id); + $question->setOrder($order); + $questions[] = $question; + } + + $this->assertSame($expected, $this->formsService->areJumpsOfForm($extraSettings, $questions)); + } + + public static function dataRemoveJumpsOfMissingOptions(): array { + return [ + 'options of the question' => [['goTo' => [['optionId' => 11, 'target' => 3], ['other' => true, 'target' => 'submit']]], null], + 'no jumps per option' => [['next' => 3], null], + 'an option that no longer exists' => [ + ['allowOtherAnswer' => true, 'goTo' => [['optionId' => 13, 'target' => 3], ['optionId' => 11, 'target' => 'submit'], ['other' => true, 'target' => 3]]], + ['allowOtherAnswer' => true, 'goTo' => [['optionId' => 11, 'target' => 'submit'], ['other' => true, 'target' => 3]]], + ], + 'an option of another question' => [['goTo' => [['optionId' => 12, 'target' => 3]]], ['goTo' => []]], + ]; + } + + #[DataProvider('dataRemoveJumpsOfMissingOptions')] + public function testRemoveJumpsOfMissingOptions(array $extraSettings, ?array $expected): void { + $question = new Question(); + $question->setId(1); + $question->setExtraSettings($extraSettings); + $option = new Option(); + $option->setId(11); + $this->optionMapper->method('findByQuestion')->with(1)->willReturn([$option]); + + $this->assertSame($expected !== null, $this->formsService->removeJumpsOfMissingOptions($question)); + $this->assertSame($expected ?? $extraSettings, $question->getExtraSettings()); + } + + public function testMapJumps(): void { + $extraSettings = [ + 'allowOtherAnswer' => true, + 'next' => 3, + 'goTo' => [ + ['optionId' => 11, 'target' => 2], + ['optionId' => 12, 'target' => 'submit'], + ['optionId' => 13, 'target' => 2], + ['optionId' => 11, 'target' => 99], + ['other' => true, 'target' => 3], + ], + ]; + + $this->assertSame([ + 'allowOtherAnswer' => true, + 'next' => 30, + 'goTo' => [ + ['optionId' => 110, 'target' => 20], + ['optionId' => 120, 'target' => 'submit'], + ['other' => true, 'target' => 30], + ], + ], FormsService::mapJumps($extraSettings, [2 => 20, 3 => 30], [11 => 110, 12 => 120])); + } + + public function testMapJumpsKeepsTargetsWithoutQuestionMap(): void { + $this->assertSame( + ['next' => 3, 'goTo' => [['optionId' => 110, 'target' => 2]]], + FormsService::mapJumps(['next' => 3, 'goTo' => [['optionId' => 11, 'target' => 2]]], null, [11 => 110]), + ); + } + + public function testMapJumpsRemovesUnmappedNextAndMalformedJumps(): void { + $this->assertSame( + ['goTo' => []], + FormsService::mapJumps(['next' => 9, 'goTo' => [5, ['optionId' => '11', 'target' => 2], ['target' => [1]]]], [2 => 20], [11 => 110]), + ); + } + + public function testRemoveBackwardJumps(): void { + $questions = array_map(static function (array $data): Question { + $question = new Question(); + $question->setId($data[0]); + $question->setExtraSettings($data[1]); + return $question; + }, [ + [1, ['next' => 3, 'goTo' => [['optionId' => 11, 'target' => 1], ['optionId' => 12, 'target' => 'submit']]]], + [2, ['shuffleOptions' => true, 'goTo' => [['optionId' => 21, 'target' => 1], ['optionId' => 22, 'target' => 99]]]], + [3, ['next' => 2]], + [4, ['goTo' => []]], + ]); + + $changed = FormsService::removeBackwardJumps($questions); + + $this->assertSame([$questions[0], $questions[1], $questions[2]], $changed); + $this->assertSame(['next' => 3, 'goTo' => [['optionId' => 12, 'target' => 'submit']]], $questions[0]->getExtraSettings()); + $this->assertSame(['shuffleOptions' => true, 'goTo' => [['optionId' => 22, 'target' => 99]]], $questions[1]->getExtraSettings()); + $this->assertSame([], $questions[2]->getExtraSettings()); + $this->assertSame(['goTo' => []], $questions[3]->getExtraSettings()); + } + + public function testMapJumpsOfCopies(): void { + $questions = array_map(static function (array $data): Question { + $question = new Question(); + $question->setId($data[0]); + $question->setOrder($data[1]); + $question->setType($data[3]); + $question->setExtraSettings($data[2]); + return $question; + }, [ + [30, 3, ['next' => 1], Constants::ANSWER_TYPE_SHORT], + [10, 1, ['goTo' => [['optionId' => 7, 'target' => 3], ['other' => true, 'target' => 2]], 'next' => 3], Constants::ANSWER_TYPE_MULTIPLEUNIQUE], + [20, 2, ['shuffleOptions' => true], Constants::ANSWER_TYPE_MULTIPLEUNIQUE], + ]); + + $changed = FormsService::mapJumpsOfCopies($questions, [1 => 10, 2 => 20, 3 => 30], [7 => 70]); + + $this->assertSame([$questions[0], $questions[1]], $changed); + $this->assertSame([], $questions[0]->getExtraSettings()); + $this->assertSame(['goTo' => [['optionId' => 70, 'target' => 30], ['other' => true, 'target' => 20]]], $questions[1]->getExtraSettings()); + $this->assertSame(['shuffleOptions' => true], $questions[2]->getExtraSettings()); + } + + public function testMapJumpsOfCopiesWithoutJumpsLeavesTheCopiesAlone(): void { + $question = new Question(); + $question->setOrder(1); + $question->setExtraSettings(['shuffleOptions' => true]); + + $this->assertSame([], FormsService::mapJumpsOfCopies([$question], [], [])); + $this->assertSame(['shuffleOptions' => true], $question->getExtraSettings()); + } + + public function testMapJumpsOfCopiesDropsJumpsPerAnswerWithAnInvalidStructure(): void { + $question = new Question(); + $question->setId(10); + $question->setOrder(1); + $question->setType(Constants::ANSWER_TYPE_MULTIPLEUNIQUE); + $question->setExtraSettings(['goTo' => [ + ['optionId' => 7, 'target' => 2, 'label' => 'x'], + ['target' => 2], + ['optionId' => 7, 'target' => 'submit'], + ['optionId' => 7, 'target' => 2], + ['other' => true, 'target' => 2], + ]]); + $target = new Question(); + $target->setId(20); + $target->setOrder(2); + $target->setType(Constants::ANSWER_TYPE_SHORT); + + $this->assertSame([$question], FormsService::mapJumpsOfCopies([$question, $target], [2 => 20], [7 => 70])); + $this->assertSame(['goTo' => [['optionId' => 70, 'target' => 'submit'], ['other' => true, 'target' => 20]]], $question->getExtraSettings()); + } + } diff --git a/tests/Unit/Service/SubmissionServiceTest.php b/tests/Unit/Service/SubmissionServiceTest.php index 8771f47bf..9fed9a480 100644 --- a/tests/Unit/Service/SubmissionServiceTest.php +++ b/tests/Unit/Service/SubmissionServiceTest.php @@ -1796,4 +1796,122 @@ public function testValidateSubmission_rejectsForeignUploadToken(): void { $this->submissionService->validateSubmission($questions, $answers, 'alice', 7); } + + public static function dataJumpPaths(): array { + $cases = json_decode(file_get_contents(__DIR__ . '/../../fixtures/jump-paths.json'), true, 512, JSON_THROW_ON_ERROR); + return array_combine(array_column($cases, 'name'), array_map(static fn (array $case) => [$case['questions'], $case['answers'], $case['visible']], $cases)); + } + + /** + * Runs the cases of tests/fixtures/jump-paths.json, shared with playwright/e2e/jump-paths.spec.ts + */ + #[\PHPUnit\Framework\Attributes\DataProvider('dataJumpPaths')] + public function testJumpPaths(array $questions, array $answers, array $visible): void { + $visibleIds = array_column($this->submissionService->getVisibleQuestions($questions, $answers), 'id'); + + $this->assertSame($visible, $visibleIds); + } + + private static function getJumpQuestions(): array { + return [ + [ + 'id' => 1, + 'type' => Constants::ANSWER_TYPE_MULTIPLEUNIQUE, + 'text' => 'Do you have a pet?', + 'isRequired' => true, + 'extraSettings' => ['goTo' => [['optionId' => 12, 'target' => 3]]], + 'options' => [['id' => 11, 'text' => 'Yes'], ['id' => 12, 'text' => 'No']], + ], + [ + 'id' => 2, + 'type' => Constants::ANSWER_TYPE_SHORT, + 'text' => 'Which one?', + 'isRequired' => true, + 'extraSettings' => [], + ], + [ + 'id' => 3, + 'type' => Constants::ANSWER_TYPE_SHORT, + 'text' => 'Anything else?', + 'isRequired' => false, + 'extraSettings' => [], + ], + ]; + } + + public function testValidateSubmissionDoesNotRequireSkippedQuestions(): void { + $this->submissionService->validateSubmission(self::getJumpQuestions(), [1 => ['12']], 'alice', 7); + $this->addToAssertionCount(1); + } + + public function testValidateSubmissionRequiresNothingAfterAnOptionalQuestionWithJumpsLeftEmpty(): void { + $questions = self::getJumpQuestions(); + $questions[0]['isRequired'] = false; + $questions[0]['extraSettings'] = ['goTo' => [['optionId' => 11, 'target' => 3], ['optionId' => 12, 'target' => 3]]]; + $questions[2]['isRequired'] = true; + + $this->submissionService->validateSubmission($questions, [], 'alice', 7); + $this->assertSame([], SubmissionService::getAnswersOnPath($questions, [])); + } + + public function testValidateSubmissionRequiresAnUnansweredRequiredQuestionWithJumps(): void { + $this->expectException(\InvalidArgumentException::class); + $this->expectExceptionMessage('Question "Do you have a pet?" is required.'); + + $this->submissionService->validateSubmission(self::getJumpQuestions(), [], 'alice', 7); + } + + public function testValidateSubmissionRequiresQuestionsOnThePath(): void { + $this->expectException(\InvalidArgumentException::class); + $this->expectExceptionMessage('Question "Which one?" is required.'); + + $this->submissionService->validateSubmission(self::getJumpQuestions(), [1 => ['11']], 'alice', 7); + } + + public function testValidateSubmissionRejectsAnAnswerThatIsNoListToAQuestionWithJumps(): void { + $this->expectException(\InvalidArgumentException::class); + $this->expectExceptionMessage('Invalid answer for question "Do you have a pet?".'); + + $this->submissionService->validateSubmission(self::getJumpQuestions(), [1 => ['first' => '11']], 'alice', 7); + } + + public function testValidateSubmissionIgnoresAnswersToSkippedQuestions(): void { + $this->submissionService->validateSubmission(self::getJumpQuestions(), [1 => ['12'], 2 => ['Rex']], 'alice', 7); + $this->submissionService->validateSubmission(self::getJumpQuestions(), [1 => ['12'], 2 => ['']], 'alice', 7); + $this->submissionService->validateSubmission(self::getJumpQuestions(), [1 => ['12'], 2 => []], 'alice', 7); + $this->submissionService->validateSubmission(self::getJumpQuestions(), [1 => ['12'], 2 => [null]], 'alice', 7); + $this->addToAssertionCount(1); + } + + public function testGetAnswersOnPathDropsAnswersToSkippedQuestions(): void { + $this->assertSame( + [1 => ['12'], 3 => ['Thanks']], + SubmissionService::getAnswersOnPath(self::getJumpQuestions(), [1 => ['12'], 2 => ['Rex'], 3 => ['Thanks']]), + ); + } + + public function testAnswersToQuestionsTheSubmitViewDoesNotShowDoNotDecideThePath(): void { + $questions = self::getJumpQuestions(); + $questions[0]['text'] = ' '; + + $this->assertSame( + [1 => ['12'], 2 => ['Rex']], + SubmissionService::getAnswersOnPath($questions, [1 => ['12'], 2 => ['Rex']]), + ); + $this->expectException(\InvalidArgumentException::class); + $this->expectExceptionMessage('Question "Which one?" is required.'); + + $this->submissionService->validateSubmission($questions, [1 => ['12']], 'alice', 7); + } + + public function testValidateSubmissionRejectsOtherAnswerWithoutText(): void { + $questions = self::getJumpQuestions(); + $questions[0]['isRequired'] = false; + $questions[0]['extraSettings'] = ['allowOtherAnswer' => true, 'goTo' => [['other' => true, 'target' => 3]]]; + + $this->expectException(\InvalidArgumentException::class); + $this->expectExceptionMessage('The answer "Other" for question "Do you have a pet?" needs a text.'); + + $this->submissionService->validateSubmission($questions, [1 => [Constants::QUESTION_EXTRASETTINGS_OTHER_PREFIX]], 'alice', 7); + } }; diff --git a/tests/fixtures/jump-paths.json b/tests/fixtures/jump-paths.json new file mode 100644 index 000000000..a624dd264 --- /dev/null +++ b/tests/fixtures/jump-paths.json @@ -0,0 +1,312 @@ +[ + { + "name": "no jumps shows every question", + "questions": [ + { "id": 1, "type": "multiple_unique", "extraSettings": {} }, + { "id": 2, "type": "short", "extraSettings": {} }, + { "id": 3, "type": "short", "extraSettings": {} } + ], + "answers": { "1": ["11"] }, + "visible": [1, 2, 3] + }, + { + "name": "an option jumps over the questions in between", + "questions": [ + { "id": 1, "type": "multiple_unique", "extraSettings": { "goTo": [{ "optionId": 11, "target": 3 }] } }, + { "id": 2, "type": "short", "extraSettings": {} }, + { "id": 3, "type": "short", "extraSettings": {} } + ], + "answers": { "1": ["11"] }, + "visible": [1, 3] + }, + { + "name": "an option id sent as number matches", + "questions": [ + { "id": 1, "type": "dropdown", "extraSettings": { "goTo": [{ "optionId": 11, "target": 3 }] } }, + { "id": 2, "type": "short", "extraSettings": {} }, + { "id": 3, "type": "short", "extraSettings": {} } + ], + "answers": { "1": [11] }, + "visible": [1, 3] + }, + { + "name": "an option id in another notation does not match", + "questions": [ + { "id": 1, "type": "multiple_unique", "extraSettings": { "goTo": [{ "optionId": 11, "target": 3 }] } }, + { "id": 2, "type": "short", "extraSettings": {} }, + { "id": 3, "type": "short", "extraSettings": {} } + ], + "answers": { "1": ["011"] }, + "visible": [1, 2, 3] + }, + { + "name": "an option without a jump goes to the following question", + "questions": [ + { "id": 1, "type": "multiple_unique", "extraSettings": { "goTo": [{ "optionId": 11, "target": 3 }] } }, + { "id": 2, "type": "short", "extraSettings": {} }, + { "id": 3, "type": "short", "extraSettings": {} } + ], + "answers": { "1": ["12"] }, + "visible": [1, 2, 3] + }, + { + "name": "an unanswered question with jumps per answer ends the path", + "questions": [ + { "id": 1, "type": "multiple_unique", "extraSettings": { "goTo": [{ "optionId": 11, "target": 3 }] } }, + { "id": 2, "type": "short", "extraSettings": {} }, + { "id": 3, "type": "short", "extraSettings": {} } + ], + "answers": {}, + "visible": [1] + }, + { + "name": "an empty answer to a question with jumps per answer ends the path", + "questions": [ + { "id": 1, "type": "dropdown", "extraSettings": { "goTo": [{ "optionId": 11, "target": 3 }] } }, + { "id": 2, "type": "short", "extraSettings": {} }, + { "id": 3, "type": "short", "extraSettings": {} } + ], + "answers": { "1": [""] }, + "visible": [1] + }, + { + "name": "an optional question with jumps on all answers ends the path as well", + "questions": [ + { "id": 1, "type": "multiple_unique", "isRequired": false, "extraSettings": { "goTo": [{ "optionId": 11, "target": 3 }, { "optionId": 12, "target": "submit" }] } }, + { "id": 2, "type": "short", "isRequired": true, "extraSettings": {} }, + { "id": 3, "type": "short", "isRequired": true, "extraSettings": {} } + ], + "answers": {}, + "visible": [1] + }, + { + "name": "an unanswered question with jumps per answer ends the path where it is reached", + "questions": [ + { "id": 1, "type": "short", "extraSettings": {} }, + { "id": 2, "type": "multiple_unique", "extraSettings": { "goTo": [{ "optionId": 21, "target": 4 }] } }, + { "id": 3, "type": "short", "extraSettings": {} }, + { "id": 4, "type": "short", "extraSettings": {} } + ], + "answers": {}, + "visible": [1, 2] + }, + { + "name": "an unanswered question whose jumps all go to the following question does not end the path", + "questions": [ + { "id": 1, "type": "multiple_unique", "extraSettings": { "goTo": [{ "optionId": 11, "target": 2 }, { "optionId": 12, "target": 2 }] } }, + { "id": 2, "type": "short", "extraSettings": {} }, + { "id": 3, "type": "short", "extraSettings": {} } + ], + "answers": {}, + "visible": [1, 2, 3] + }, + { + "name": "an unanswered question whose jumps go to earlier or missing questions does not end the path", + "questions": [ + { "id": 1, "type": "short", "extraSettings": {} }, + { "id": 2, "type": "dropdown", "extraSettings": { "goTo": [{ "optionId": 21, "target": 1 }, { "optionId": 22, "target": 99 }, { "optionId": 23, "target": 2 }] } }, + { "id": 3, "type": "short", "extraSettings": {} } + ], + "answers": {}, + "visible": [1, 2, 3] + }, + { + "name": "an unanswered question with one jump past the following question ends the path", + "questions": [ + { "id": 1, "type": "multiple_unique", "extraSettings": { "goTo": [{ "optionId": 11, "target": 2 }, { "optionId": 12, "target": 3 }] } }, + { "id": 2, "type": "short", "extraSettings": {} }, + { "id": 3, "type": "short", "extraSettings": {} } + ], + "answers": {}, + "visible": [1] + }, + { + "name": "next is ignored on question types with goTo", + "questions": [ + { "id": 1, "type": "multiple_unique", "extraSettings": { "goTo": [{ "optionId": 11, "target": 3 }], "next": 3 } }, + { "id": 2, "type": "short", "extraSettings": {} }, + { "id": 3, "type": "short", "extraSettings": {} } + ], + "answers": { "1": ["12"] }, + "visible": [1, 2, 3] + }, + { + "name": "next of a text question jumps", + "questions": [ + { "id": 1, "type": "short", "extraSettings": { "next": 3 } }, + { "id": 2, "type": "short", "extraSettings": {} }, + { "id": 3, "type": "short", "extraSettings": {} } + ], + "answers": {}, + "visible": [1, 3] + }, + { + "name": "next jumps on every question type with next", + "questions": [ + { "id": 1, "type": "color", "extraSettings": { "next": 3 } }, + { "id": 2, "type": "short", "extraSettings": {} }, + { "id": 3, "type": "file", "extraSettings": { "next": 5 } }, + { "id": 4, "type": "short", "extraSettings": {} }, + { "id": 5, "type": "grid", "extraSettings": { "next": 7 } }, + { "id": 6, "type": "short", "extraSettings": {} }, + { "id": 7, "type": "long", "extraSettings": { "next": 9 } }, + { "id": 8, "type": "short", "extraSettings": {} }, + { "id": 9, "type": "ranking", "extraSettings": { "next": 11 } }, + { "id": 10, "type": "short", "extraSettings": {} }, + { "id": 11, "type": "short", "extraSettings": {} } + ], + "answers": {}, + "visible": [1, 3, 5, 7, 9, 11] + }, + { + "name": "only the first value of an answer decides", + "questions": [ + { "id": 1, "type": "multiple_unique", "extraSettings": { "goTo": [{ "optionId": 11, "target": 3 }] } }, + { "id": 2, "type": "short", "extraSettings": {} }, + { "id": 3, "type": "short", "extraSettings": {} } + ], + "answers": { "1": ["12", "11"] }, + "visible": [1, 2, 3] + }, + { + "name": "submit ends the form", + "questions": [ + { "id": 1, "type": "multiple_unique", "extraSettings": { "goTo": [{ "optionId": 11, "target": "submit" }] } }, + { "id": 2, "type": "short", "extraSettings": {} } + ], + "answers": { "1": ["11"] }, + "visible": [1] + }, + { + "name": "the answer Other jumps", + "questions": [ + { "id": 1, "type": "multiple_unique", "extraSettings": { "allowOtherAnswer": true, "goTo": [{ "other": true, "target": 3 }] } }, + { "id": 2, "type": "short", "extraSettings": {} }, + { "id": 3, "type": "short", "extraSettings": {} } + ], + "answers": { "1": ["system-other-answer:Rex"] }, + "visible": [1, 3] + }, + { + "name": "the answer Other does not jump when Other is off", + "questions": [ + { "id": 1, "type": "multiple_unique", "extraSettings": { "goTo": [{ "other": true, "target": 3 }] } }, + { "id": 2, "type": "short", "extraSettings": {} }, + { "id": 3, "type": "short", "extraSettings": {} } + ], + "answers": { "1": ["system-other-answer:Rex"] }, + "visible": [1, 2, 3] + }, + { + "name": "an unanswered question does not wait for the answer Other when Other is off", + "questions": [ + { "id": 1, "type": "multiple_unique", "extraSettings": { "goTo": [{ "other": true, "target": 3 }] } }, + { "id": 2, "type": "short", "extraSettings": {} }, + { "id": 3, "type": "short", "extraSettings": {} } + ], + "answers": {}, + "visible": [1, 2, 3] + }, + { + "name": "a target before the question counts as the following question", + "questions": [ + { "id": 1, "type": "short", "extraSettings": {} }, + { "id": 2, "type": "multiple_unique", "extraSettings": { "goTo": [{ "optionId": 21, "target": 1 }] } }, + { "id": 3, "type": "short", "extraSettings": {} } + ], + "answers": { "2": ["21"] }, + "visible": [1, 2, 3] + }, + { + "name": "a target that is the question itself counts as the following question", + "questions": [ + { "id": 1, "type": "short", "extraSettings": { "next": 1 } }, + { "id": 2, "type": "short", "extraSettings": {} } + ], + "answers": {}, + "visible": [1, 2] + }, + { + "name": "a missing target counts as the following question", + "questions": [ + { "id": 1, "type": "multiple_unique", "extraSettings": { "goTo": [{ "optionId": 11, "target": 99 }] } }, + { "id": 2, "type": "short", "extraSettings": {} } + ], + "answers": { "1": ["11"] }, + "visible": [1, 2] + }, + { + "name": "a malformed jump counts as no jump", + "questions": [ + { "id": 1, "type": "multiple_unique", "extraSettings": { "goTo": [null, "3", { "optionId": 11, "target": [3] }] } }, + { "id": 2, "type": "short", "extraSettings": {} }, + { "id": 3, "type": "short", "extraSettings": {} } + ], + "answers": { "1": ["11"] }, + "visible": [1, 2, 3] + }, + { + "name": "the first matching jump decides, even with a malformed target", + "questions": [ + { "id": 1, "type": "multiple_unique", "extraSettings": { "goTo": [{ "optionId": 11, "target": [3] }, { "optionId": 11, "target": 3 }] } }, + { "id": 2, "type": "short", "extraSettings": {} }, + { "id": 3, "type": "short", "extraSettings": {} } + ], + "answers": { "1": ["11"] }, + "visible": [1, 2, 3] + }, + { + "name": "next is ignored on question types without jumps", + "questions": [ + { "id": 1, "type": "datetime", "extraSettings": { "next": 3 } }, + { "id": 2, "type": "short", "extraSettings": {} }, + { "id": 3, "type": "short", "extraSettings": {} } + ], + "answers": { "1": ["2026-11-10 10:00"] }, + "visible": [1, 2, 3] + }, + { + "name": "jumps chain", + "questions": [ + { "id": 1, "type": "multiple_unique", "extraSettings": { "goTo": [{ "optionId": 11, "target": 3 }] } }, + { "id": 2, "type": "short", "extraSettings": {} }, + { "id": 3, "type": "dropdown", "extraSettings": { "goTo": [{ "optionId": 31, "target": 5 }] } }, + { "id": 4, "type": "short", "extraSettings": {} }, + { "id": 5, "type": "short", "extraSettings": {} } + ], + "answers": { "1": ["11"], "3": ["31"] }, + "visible": [1, 3, 5] + }, + { + "name": "each option has its own follow-up question, first option", + "questions": [ + { "id": 1, "type": "multiple_unique", "extraSettings": { "goTo": [{ "optionId": 11, "target": 2 }, { "optionId": 12, "target": 3 }] } }, + { "id": 2, "type": "short", "extraSettings": { "next": 4 } }, + { "id": 3, "type": "short", "extraSettings": {} }, + { "id": 4, "type": "short", "extraSettings": {} } + ], + "answers": { "1": ["11"] }, + "visible": [1, 2, 4] + }, + { + "name": "each option has its own follow-up question, second option", + "questions": [ + { "id": 1, "type": "multiple_unique", "extraSettings": { "goTo": [{ "optionId": 11, "target": 2 }, { "optionId": 12, "target": 3 }] } }, + { "id": 2, "type": "short", "extraSettings": { "next": 4 } }, + { "id": 3, "type": "short", "extraSettings": {} }, + { "id": 4, "type": "short", "extraSettings": {} } + ], + "answers": { "1": ["12"] }, + "visible": [1, 3, 4] + }, + { + "name": "the jumps of skipped questions do not count", + "questions": [ + { "id": 1, "type": "multiple_unique", "extraSettings": { "goTo": [{ "optionId": 11, "target": 3 }] } }, + { "id": 2, "type": "multiple_unique", "extraSettings": { "goTo": [{ "optionId": 21, "target": "submit" }] } }, + { "id": 3, "type": "short", "extraSettings": {} } + ], + "answers": { "1": ["11"], "2": ["21"] }, + "visible": [1, 3] + } +] From ba5eb5af146830e3475bdec9faa3a4ae42a9490b Mon Sep 17 00:00:00 2001 From: Andy Scherzinger Date: Tue, 10 Nov 2026 23:15:00 +0100 Subject: [PATCH 6/7] feat(conditional): choose where each answer goes in the editor "Go to based on answer" in the question menu shows a select at the end of each option row of radio and dropdown questions, and of the row "Other": the next question, a later question or the end of the form. The other question types with jumps get the select "After question N" below them instead. Each select of an answer has the visible label After "" go to, which is also its accessible name. Below a width of 480px the option text takes the first line and its select shares the second line with the move and delete buttons, so the keyboard focus follows the visual order. A target that was deleted or moved before the question is shown as going to the next question. Unchecking "Go to" closes the menu and asks before it removes the jumps of the question. The warnings let jumps of questions the submit view does not show lead nowhere, and count a jump of the answer "Other" as broken while "Other" is off, as a reorder removes it as well. A question with jumps per answer that is not required shows a hint to make it required, as respondents see the questions after it only once they answer it. Without an answer the path ends at such a question, so the editor no longer counts it as leading to the following question when it finds questions no respondent reaches. Changes are kept in the question and saved as complete lists. Extra settings the server adjusted replace the local ones unless they changed in the meantime, and deleting an option drops its jumps once the server confirms the deletion. playwright/e2e/jump-paths.spec.ts runs the path cases shared with the server against the frontend walk. Assisted-by: Claude Code:claude-opus-5-5 Signed-off-by: Andy Scherzinger --- playwright/e2e/jump-issues.spec.ts | 238 +++++++++++ playwright/e2e/jump-paths.spec.ts | 33 ++ src/components/Questions/AnswerInput.vue | 40 +- src/components/Questions/JumpTargetSelect.vue | 122 ++++++ src/components/Questions/Question.vue | 73 ++++ src/components/Questions/QuestionDropdown.vue | 16 +- src/components/Questions/QuestionMultiple.vue | 48 ++- src/composables/useJumps.ts | 288 +++++++++++++ src/composables/useQuestion.ts | 94 ++-- src/composables/useQuestionMultiple.ts | 13 + src/types/Entities.d.ts | 12 + src/utils/Jumps.ts | 401 ++++++++++++++++++ src/views/Create.vue | 254 ++++++++++- 13 files changed, 1586 insertions(+), 46 deletions(-) create mode 100644 playwright/e2e/jump-issues.spec.ts create mode 100644 playwright/e2e/jump-paths.spec.ts create mode 100644 src/components/Questions/JumpTargetSelect.vue create mode 100644 src/composables/useJumps.ts create mode 100644 src/utils/Jumps.ts diff --git a/playwright/e2e/jump-issues.spec.ts b/playwright/e2e/jump-issues.spec.ts new file mode 100644 index 000000000..0ee359188 --- /dev/null +++ b/playwright/e2e/jump-issues.spec.ts @@ -0,0 +1,238 @@ +/** + * SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors + * SPDX-License-Identifier: AGPL-3.0-or-later + */ + +import type { FormsQuestion } from '../../src/types/Entities.d.ts' + +import { expect, test } from '@playwright/test' +import { + formatList, + getJumpIssues, + getNewlyBrokenQuestions, +} from '../../src/utils/Jumps.ts' + +/** + * A radio question with the options "Yes" (id 11) and "No" (id 12) + * + * @param id the id of the question + * @param extraSettings the extra settings + * @param isRequired whether the question is required + */ +function radio( + id: number, + extraSettings: FormsQuestion['extraSettings'], + isRequired = false, +): FormsQuestion { + return { + id, + text: `Question ${id}`, + type: 'multiple_unique', + isRequired, + options: [ + { id: 11, questionId: id, text: 'Yes', order: 1 }, + { id: 12, questionId: id, text: 'No', order: 2 }, + ], + extraSettings, + } as FormsQuestion +} + +/** + * A short text question + * + * @param id the id of the question + * @param extraSettings the extra settings + * @param isRequired whether the question is required + */ +function short( + id: number, + extraSettings: FormsQuestion['extraSettings'] = {}, + isRequired = false, +): FormsQuestion { + return { id, text: `Question ${id}`, type: 'short', isRequired, extraSettings } +} + +/** + * The issues as plain values + * + * @param questions the questions of the form + */ +function issues(questions: FormsQuestion[]) { + const { broken, unreachable, skippable } = getJumpIssues(questions) + return { + broken: [...broken], + unreachable: [...unreachable], + skippable: [...skippable], + } +} + +test('jump lists: a language variant such as sr@latin lists as its base language', () => { + expect(formatList(['1', '2', '3'], 'sr@latin')).toBe('1, 2 i 3') + expect(formatList(['1', '2'], 'de-DE')).toBe('1 und 2') +}) + +test('jump issues: a jump over a question lets respondents skip it', () => { + expect( + issues([ + radio(1, { goTo: [{ optionId: 12, target: 3 }] }), + short(2), + short(3), + ]), + ).toEqual({ broken: [], unreachable: [], skippable: [2] }) +}) + +test('jump issues: "End of the form" lets respondents skip all later questions', () => { + expect( + issues([ + radio(1, { goTo: [{ optionId: 12, target: 'submit' }] }), + short(2), + short(3), + ]), + ).toEqual({ broken: [], unreachable: [], skippable: [2, 3] }) +}) + +test('jump issues: a required question whose answers all jump past a question makes it unreachable', () => { + expect( + issues([ + radio( + 1, + { + goTo: [ + { optionId: 11, target: 3 }, + { optionId: 12, target: 'submit' }, + ], + }, + true, + ), + short(2), + short(3), + ]), + ).toEqual({ broken: [], unreachable: [2], skippable: [3] }) +}) + +test('jump issues: an optional question whose answers all jump past a question makes it unreachable as well', () => { + expect( + issues([ + radio(1, { + goTo: [ + { optionId: 11, target: 3 }, + { optionId: 12, target: 3 }, + ], + }), + short(2), + short(3), + ]), + ).toEqual({ broken: [], unreachable: [2], skippable: [] }) +}) + +test('jump issues: "End of the form" after a question makes the later questions unreachable', () => { + expect(issues([short(1, { next: 'submit' }), short(2), short(3)])).toEqual({ + broken: [], + unreachable: [2, 3], + skippable: [], + }) +}) + +test('jump issues: a jump to an earlier or deleted question is broken', () => { + expect( + issues([ + short(1), + radio(2, { goTo: [{ optionId: 12, target: 1 }] }), + short(3, { next: 99 }), + short(4), + ]), + ).toEqual({ broken: [2, 3], unreachable: [], skippable: [] }) +}) + +test('jump issues: a jump that breaks is new even when its question has a broken jump already', () => { + const pet = radio(1, { + goTo: [ + { optionId: 11, target: 99 }, + { optionId: 12, target: 3 }, + ], + }) + const before = getJumpIssues([pet, short(2), short(3)]) + const after = getJumpIssues([short(3), pet, short(2)]) + + expect(getNewlyBrokenQuestions(before, after)).toEqual([1]) + expect(getNewlyBrokenQuestions(before, before)).toEqual([]) +}) + +test('jump issues: a malformed jump is ignored', () => { + expect( + issues([ + radio(1, { + goTo: [null, { optionId: 12, target: [3] }], + } as unknown as FormsQuestion['extraSettings']), + short(2), + short(3), + ]), + ).toEqual({ broken: [], unreachable: [], skippable: [] }) +}) + +test('jump issues: a jump of a deleted option is ignored', () => { + expect( + issues([ + radio(1, { goTo: [{ optionId: 99, target: 3 }] }), + short(2), + short(3), + ]), + ).toEqual({ broken: [], unreachable: [], skippable: [] }) +}) + +test('jump issues: with "Other" allowed, the answer "Other" needs a jump as well to make a question unreachable', () => { + const goTo = [ + { optionId: 11, target: 3 }, + { optionId: 12, target: 3 }, + ] + expect( + issues([ + radio(1, { goTo, allowOtherAnswer: true }, true), + short(2), + short(3), + ]).unreachable, + ).toEqual([]) + expect( + issues([ + radio( + 1, + { + goTo: [...goTo, { other: true, target: 3 }], + allowOtherAnswer: true, + }, + true, + ), + short(2), + short(3), + ]).unreachable, + ).toEqual([2]) +}) + +test('jump issues: the jumps of a question the submit view does not show lead nowhere', () => { + const other = radio( + 1, + { goTo: [{ other: true, target: 3 }], allowOtherAnswer: true }, + true, + ) + expect(issues([{ ...other, options: [] }, short(2), short(3)])).toEqual({ + broken: [], + unreachable: [], + skippable: [], + }) + const untitled = radio(1, { goTo: [{ optionId: 12, target: 3 }] }, true) + expect(issues([{ ...untitled, text: ' ' }, short(2), short(3)])).toEqual({ + broken: [], + unreachable: [], + skippable: [], + }) +}) + +test('jump issues: a jump of the answer "Other" breaks while "Other" is off', () => { + const pet = radio(2, { goTo: [{ other: true, target: 3 }] }) + expect( + getNewlyBrokenQuestions( + getJumpIssues([short(1), pet, short(3)]), + getJumpIssues([short(3), short(1), pet]), + ), + ).toEqual([2]) +}) diff --git a/playwright/e2e/jump-paths.spec.ts b/playwright/e2e/jump-paths.spec.ts new file mode 100644 index 000000000..d69cae596 --- /dev/null +++ b/playwright/e2e/jump-paths.spec.ts @@ -0,0 +1,33 @@ +/** + * SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors + * SPDX-License-Identifier: AGPL-3.0-or-later + */ + +import type { FormsQuestion } from '../../src/types/Entities.d.ts' + +import { expect, test } from '@playwright/test' +import { readFileSync } from 'node:fs' +import { getVisibleQuestions } from '../../src/utils/Jumps.ts' + +/** + * Runs the cases of tests/fixtures/jump-paths.json, shared with SubmissionServiceTest::testJumpPaths() + */ +const cases: Array<{ + name: string + questions: FormsQuestion[] + answers: Record + visible: number[] +}> = JSON.parse( + readFileSync( + new URL('../../tests/fixtures/jump-paths.json', import.meta.url), + 'utf-8', + ), +) + +for (const { name, questions, answers, visible } of cases) { + test(`jump path: ${name}`, () => { + expect( + getVisibleQuestions(questions, answers).map((question) => question.id), + ).toEqual(visible) + }) +} diff --git a/src/components/Questions/AnswerInput.vue b/src/components/Questions/AnswerInput.vue index 9181f22ff..23904f1b4 100644 --- a/src/components/Questions/AnswerInput.vue +++ b/src/components/Questions/AnswerInput.vue @@ -4,7 +4,10 @@ -->