diff --git a/docs/DataStructure.md b/docs/DataStructure.md index da790fbbf..f31f904fc 100644 --- a/docs/DataStructure.md +++ b/docs/DataStructure.md @@ -274,7 +274,7 @@ Optional extra settings for some [Question Types](#question-types) | `questionType` | `linearscale` | String | `rating`, `promoter` | Sub type, fixed at creation; `rating` is a 1 to N scale drawn as icons, `promoter` is a 0 to 10 scale whose results show the promoter score; absent for a plain scale | | `ratingIcon` | `linearscale` with `questionType` `rating` | string | `'star', 'heart', 'thumb'` | Set the icon of the rating, default: `'star'` | | `goTo` | `dropdown, linearscale, multiple_unique` | Array | see [Jumps](#jumps) | Where to go next for an answer | -| `next` | `color, date, file, grid, long, multiple, ranking, short, time` | Integer / string | question id, `'submit'` | Where to go after the question, see [Jumps](#jumps) | +| `next` | `color, date, file, grid, long, multiple, ranking, section, short, time` | Integer / string | question id, `'submit'` | Where to go after the question or, on a section, after the section, see [Jumps](#jumps) | ### Jumps @@ -291,6 +291,7 @@ An answer can lead to a later question or to the end of the form, as in Microsof - Only the deprecated `datetime` accepts 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. +- `next` on a section is where respondents go after the section, as "After this section go to" in Microsoft Forms: the id of a later section or `"submit"`; other targets are removed like other disallowed jumps. It applies when the path leaves the section towards the following section or the end of the form, so a jump of an answer out of the section wins over it, while a jump within the section still ends at it. 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. diff --git a/lib/Constants.php b/lib/Constants.php index a2cfbf46c..625637706 100644 --- a/lib/Constants.php +++ b/lib/Constants.php @@ -287,6 +287,10 @@ class Constants { 'next' => ['integer', 'string'], ]; + public const EXTRA_SETTINGS_SECTION = [ + 'next' => ['integer', 'string'], + ]; + public const EXTRA_SETTINGS_GRID_QUESTION_TYPE = [ self::ANSWER_GRID_TYPE_CHECKBOX, self::ANSWER_GRID_TYPE_NUMBER, diff --git a/lib/Service/FormsService.php b/lib/Service/FormsService.php index c0a88d8c9..9ff30125c 100644 --- a/lib/Service/FormsService.php +++ b/lib/Service/FormsService.php @@ -908,6 +908,7 @@ public static function getAllowedExtraSettings(string $questionType): array { Constants::ANSWER_TYPE_COLOR => Constants::EXTRA_SETTINGS_COLOR, Constants::ANSWER_TYPE_TIME => Constants::EXTRA_SETTINGS_TIME, Constants::ANSWER_TYPE_LINEARSCALE => Constants::EXTRA_SETTINGS_LINEARSCALE, + Constants::ANSWER_TYPE_SECTION => Constants::EXTRA_SETTINGS_SECTION, default => [], }; } @@ -1296,7 +1297,7 @@ public static function mapJumpsOfCopies(array $questions, array $questionIdMap, } /** - * Remove the jumps that go to the question itself, to an earlier question or into the middle of another section, keeping the jumps to the end of the form, to later questions of the same section, to later sections and to questions that are not in the list + * Remove the jumps that go to the question itself, to an earlier question or into the middle of another section, and the jumps of a section to anything but a later section, keeping the jumps to the end of the form, to later questions of the same section, to later sections and to questions that are not in the list * * @param list $questions the questions of the form in their order * @return list the questions whose jumps were removed, with their new extra settings set @@ -1316,7 +1317,8 @@ public static function removeDisallowedJumps(array $questions): array { foreach ($questions as $position => $question) { $isDisallowed = static fn (mixed $target): bool => is_int($target) && isset($positions[$target]) && ($positions[$target] <= $position - || ($questions[$positions[$target]]->getType() !== Constants::ANSWER_TYPE_SECTION && $sections[$positions[$target]] !== $sections[$position])); + || ($questions[$positions[$target]]->getType() !== Constants::ANSWER_TYPE_SECTION + && ($question->getType() === Constants::ANSWER_TYPE_SECTION || $sections[$positions[$target]] !== $sections[$position]))); $extraSettings = $question->getExtraSettings(); $newSettings = $extraSettings; diff --git a/lib/Service/SubmissionService.php b/lib/Service/SubmissionService.php index e8541fc4f..3af0ac31f 100644 --- a/lib/Service/SubmissionService.php +++ b/lib/Service/SubmissionService.php @@ -854,6 +854,7 @@ 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. + * Leaving a section towards the following question or the end of the form goes to the `next` target of the section instead, if it has one. * 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 @@ -864,12 +865,18 @@ public static function getVisibleQuestions(array $questions, array $answers): ar $questions = array_values($questions); $positions = array_flip(array_column($questions, 'id')); $visibleQuestions = []; + $sectionNext = null; $position = 0; while ($position < count($questions)) { $question = $questions[$position]; $visibleQuestions[] = $question; + $toPosition = static fn (mixed $target): ?int => is_int($target) && isset($positions[$target]) && $positions[$target] > $position ? $positions[$target] : null; + if (($question['type'] ?? null) === Constants::ANSWER_TYPE_SECTION) { + $next = $question['extraSettings']['next'] ?? null; + $sectionNext = is_int($next) || is_string($next) ? $next : null; + } $answer = $answers[$question['id']] ?? []; if (self::awaitsAnswer($question, $answer, $position, $positions, count($questions))) { break; @@ -878,8 +885,15 @@ public static function getVisibleQuestions(array $questions, array $answers): ar 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; + $targetPosition = $toPosition($target); + if ($targetPosition === null && $sectionNext !== null + && ($position + 1 === count($questions) || ($questions[$position + 1]['type'] ?? null) === Constants::ANSWER_TYPE_SECTION)) { + if ($sectionNext === Constants::JUMP_TARGET_SUBMIT) { + break; + } + $targetPosition = $toPosition($sectionNext); + } + $position = $targetPosition ?? $position + 1; } return $visibleQuestions; @@ -953,7 +967,7 @@ private static function awaitsAnswer(array $question, mixed $answer, int $positi } /** - * 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` + * 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` other than sections * * @param array $question the question * @param mixed $answer the values of the answer to the question @@ -974,7 +988,8 @@ private static function getJumpTarget(array $question, mixed $answer): string|in } } - $next = isset(FormsService::getAllowedExtraSettings((string)($question['type'] ?? ''))['next']) ? ($extraSettings['next'] ?? null) : null; + $type = (string)($question['type'] ?? ''); + $next = $type !== Constants::ANSWER_TYPE_SECTION && isset(FormsService::getAllowedExtraSettings($type)['next']) ? ($extraSettings['next'] ?? null) : null; return is_int($next) || is_string($next) ? $next : null; } diff --git a/playwright/e2e/jump-issues.spec.ts b/playwright/e2e/jump-issues.spec.ts index 35a43d770..5b1cc1f68 100644 --- a/playwright/e2e/jump-issues.spec.ts +++ b/playwright/e2e/jump-issues.spec.ts @@ -319,6 +319,73 @@ test('jumps: in a form with sections, a jump into the middle of another section ]) }) +test('jumps: a section jumps only to a later section or the end of the form', () => { + const section = ( + id: number, + extraSettings: FormsQuestion['extraSettings'] = {}, + ): FormsQuestion => ({ ...short(id, extraSettings), type: 'section' }) + const allowed = withoutDisallowedJumps([ + section(1, { next: 2 }), + short(2), + section(3, { next: 5 }), + short(4), + section(5, { next: 'submit' }), + short(6), + ]) + expect(allowed.map((question) => question.extraSettings)).toEqual([ + {}, + {}, + { next: 5 }, + {}, + { next: 'submit' }, + {}, + ]) +}) + +test('jumps: questions skipped by the next target of a section are unreachable', () => { + const section = ( + id: number, + extraSettings: FormsQuestion['extraSettings'] = {}, + ): FormsQuestion => ({ ...short(id, extraSettings), type: 'section' }) + expect([ + ...getJumpIssues([ + section(1, { next: 5 }), + short(2), + section(3), + short(4), + section(5), + short(6), + ]).unreachable, + ]).toEqual([3, 4]) +}) + +test('jump issues: two questions of a section that jump out of it are both named', () => { + const section = (id: number): FormsQuestion => ({ + ...short(id), + type: 'section', + }) + expect([ + ...getJumpIssues([ + section(1), + radio(2, { goTo: [{ optionId: 11, target: 6 }] }), + short(3, { next: 'submit' }), + short(4, { next: 5 }), + short(5), + section(6), + short(7), + ]).leavingSection, + ]).toEqual([2, 3]) + expect([ + ...getJumpIssues([ + section(1), + radio(2, { goTo: [{ optionId: 11, target: 4 }] }), + short(3), + section(4), + short(5), + ]).leavingSection, + ]).toEqual([]) +}) + test('jumps: only the jumps a reorder removed are removed from newer extra settings', () => { const before = { goTo: [ diff --git a/playwright/e2e/sections.spec.ts b/playwright/e2e/sections.spec.ts index 4e50e3ae0..32f731311 100644 --- a/playwright/e2e/sections.spec.ts +++ b/playwright/e2e/sections.spec.ts @@ -461,6 +461,115 @@ test.describe('Sections', () => { expect(stored.extraSettings.goTo).toEqual([]) }) + test('After a section, respondents go to the section it names', async ({ + page, + submitView, + }) => { + const form = await api(page.request, 'POST', '/forms') + for (const [type, text] of [ + ['section', 'Part one'], + ['short', 'First'], + ['section', 'Part two'], + ['short', 'Second'], + ['section', 'Part three'], + ['short', 'Third'], + ]) { + await api(page.request, 'POST', `/forms/${form.id}/questions`, { + type, + text, + }) + } + await page.goto(`apps/forms/${form.hash}/edit`) + + const select = page + .getByRole('listitem', { name: 'Section number 1' }) + .getByRole('combobox', { name: 'After section 1 go to' }) + await select.click() + await expect(page.getByRole('option')).toHaveText([ + 'Next section', + 'Section 2: Part two', + 'Section 3: Part three', + 'End of the form', + ]) + const saved = page.waitForResponse( + (response) => + response.request().method() === 'PATCH' + && response.url().includes(`/forms/${form.id}/questions/`), + ) + await page.getByRole('option', { name: 'Section 3: Part three' }).click() + expect((await saved).ok()).toBeTruthy() + await expect( + page + .getByRole('listitem', { name: 'Section number 3' }) + .getByRole('combobox', { name: 'After section 3 go to' }), + ).toBeVisible() + + await page.goto(`apps/forms/${form.hash}/submit`) + await submitView.fillText('First', 'one') + await submitView.nextButton.click() + await expect(submitView.getQuestion('Part three')).toBeVisible() + await expect(submitView.nextButton).toHaveCount(0) + await submitView.fillText('Third', 'three') + const response = await submitView.submit() + expect(Object.keys(response.request().postDataJSON().answers)).toHaveLength( + 2, + ) + await expect(submitView.successMessage).toBeVisible() + }) + + test('A section that goes to a deleted section is named as a section and shows where respondents go', async ({ + page, + }) => { + const form = await api(page.request, 'POST', '/forms') + const ids: number[] = [] + for (const [type, text] of [ + ['section', 'Part one'], + ['short', 'First'], + ['section', 'Part two'], + ['short', 'Second'], + ['section', 'Part three'], + ]) { + ids.push( + ( + await api(page.request, 'POST', `/forms/${form.id}/questions`, { + type, + text, + }) + ).id, + ) + } + await api(page.request, 'PATCH', `/forms/${form.id}/questions/${ids[0]}`, { + keyValuePairs: { extraSettings: { next: ids[4] } }, + }) + await api(page.request, 'PATCH', `/forms/${form.id}/questions/${ids[2]}`, { + keyValuePairs: { extraSettings: { next: 'submit' } }, + }) + await page.goto(`apps/forms/${form.hash}/edit`) + + await page + .getByRole('listitem', { name: 'Section number 3' }) + .getByRole('button', { name: 'Actions', exact: true }) + .click() + await page + .getByRole('menuitem', { name: /^Delete (question|section)$/ }) + .click() + await expect( + page + .getByRole('status') + .getByText( + 'Section 1 went to a section that was deleted, so respondents now go to the next section instead.', + ), + ).toBeVisible() + const label = (number: number) => + page + .getByRole('listitem', { name: `Section number ${number}` }) + .locator('.jump-target-select__label') + await expect(label(1)).toHaveText( + 'Next section (the chosen section was deleted or moved up)', + ) + await expect(label(2)).toHaveText('End of the form') + }) + test('Each page checks its required questions, an empty section is an info page', async ({ page, submitView, @@ -555,4 +664,58 @@ test.describe('Sections', () => { await submitView.backButton.click() await expect(submitView.getQuestion('Your name')).toBeVisible() }) + + test('An empty section sends respondents on to its target without a page of its own', async ({ + page, + submitView, + }) => { + const form = await api(page.request, 'POST', '/forms') + const ids: Record = {} + for (const [type, text] of [ + ['section', 'Start'], + ['short', 'First'], + ['section', 'Jump'], + ['section', 'Skipped'], + ['short', 'Second'], + ['section', 'End'], + ['short', 'Third'], + ['section', 'Finish'], + ['section', 'Not reached'], + ['short', 'Never'], + ]) { + ids[text] = ( + await api(page.request, 'POST', `/forms/${form.id}/questions`, { + type, + text: ['Jump', 'Finish'].includes(text) ? '' : text, + }) + ).id + } + for (const [section, next] of [ + ['Jump', ids.End], + ['End', ids.Finish], + ['Finish', 'submit'], + ] as const) { + await api( + page.request, + 'PATCH', + `/forms/${form.id}/questions/${ids[section]}`, + { keyValuePairs: { extraSettings: { next } } }, + ) + } + await page.goto(`apps/forms/${form.hash}/submit`) + + await submitView.fillText('First', 'one') + await submitView.nextButton.click() + await expect(submitView.getQuestion('End')).toBeVisible() + await expect(submitView.getQuestion('Skipped')).toBeHidden() + await expect(submitView.nextButton).toHaveCount(0) + await submitView.fillText('Third', 'three') + const response = await submitView.submit() + expect( + Object.keys(response.request().postDataJSON().answers) + .map(Number) + .sort((a, b) => a - b), + ).toEqual([ids.First, ids.Third]) + await expect(submitView.successMessage).toBeVisible() + }) }) diff --git a/src/components/Questions/JumpTargetSelect.vue b/src/components/Questions/JumpTargetSelect.vue index 0f9a70303..9a5ac3ba3 100644 --- a/src/components/Questions/JumpTargetSelect.vue +++ b/src/components/Questions/JumpTargetSelect.vue @@ -71,6 +71,18 @@ export default defineComponent({ type: String, default: null, }, + + /** + * Label of a target that is not offered any more, by default going to the next question + */ + fallbackLabel: { + type: String, + default: () => + t( + 'forms', + 'Next question (the chosen question was deleted or moved up)', + ), + }, }, emits: ['update:modelValue'], @@ -80,10 +92,7 @@ export default defineComponent({ return ( this.options.find((option) => option.id === this.modelValue) ?? { id: this.modelValue, - label: t( - 'forms', - 'Next question (the chosen question was deleted or moved up)', - ), + label: this.fallbackLabel, } ) }, diff --git a/src/components/Questions/Question.vue b/src/components/Questions/Question.vue index c28a73238..64cc147b6 100644 --- a/src/components/Questions/Question.vue +++ b/src/components/Questions/Question.vue @@ -130,7 +130,11 @@ {{ t('forms', 'Required') }} {{ @@ -233,6 +237,7 @@ :modelValue="jumps.next" :options="jumps.targetOptions" :inputLabel="jumps.nextLabel" + :fallbackLabel="jumps.fallbackLabel" @update:modelValue="jumps.setNext" /> diff --git a/src/composables/useJumps.ts b/src/composables/useJumps.ts index 531c30aae..2bc368070 100644 --- a/src/composables/useJumps.ts +++ b/src/composables/useJumps.ts @@ -75,8 +75,10 @@ export function useJumps( const canGoTo = computed(() => QUESTION_TYPES_WITH_GOTO.includes(String(props.type)), ) - const canNext = computed(() => - QUESTION_TYPES_WITH_NEXT.includes(String(props.type)), + const isSection = computed(() => props.type === QUESTION_TYPE_SECTION) + const canNext = computed( + () => + isSection.value || QUESTION_TYPES_WITH_NEXT.includes(String(props.type)), ) watch( @@ -97,7 +99,7 @@ export function useJumps( () => !props.readOnly && canGoTo.value && enabled.value, ) const showNext = computed( - () => !props.readOnly && canNext.value && enabled.value, + () => !props.readOnly && canNext.value && (enabled.value || isSection.value), ) const position = computed(() => @@ -107,12 +109,47 @@ export function useJumps( const sections = computed(() => getSectionIndexes(formQuestions.value)) const number = computed(() => numbers.value.get(props.id) ?? position.value + 1) const nextLabel = computed(() => - t('forms', 'After question {number}', { number: number.value }), + isSection.value + ? t('forms', 'After section {number} go to', { number: number.value }) + : t('forms', 'After question {number}', { number: number.value }), + ) + const hasLaterSection = computed(() => + formQuestions.value + .slice(position.value + 1) + .some((question) => question.type === QUESTION_TYPE_SECTION), + ) + const endsForm = computed(() => isSection.value && !hasLaterSection.value) + const shownNext = computed(() => + endsForm.value && next.value === JUMP_TARGET_SUBMIT ? null : next.value, + ) + const fallbackLabel = computed(() => + !isSection.value + ? undefined + : endsForm.value + ? t( + 'forms', + 'End of the form (the chosen section was deleted or moved up)', + ) + : t( + 'forms', + 'Next section (the chosen section was deleted or moved up)', + ), ) const targetOptions = computed((previous) => { + const submitOption: JumpTargetOption = { + id: JUMP_TARGET_SUBMIT, + label: t('forms', 'End of the form'), + } const options: JumpTargetOption[] = [ - { id: null, label: t('forms', 'Next question') }, + { + id: null, + label: !isSection.value + ? t('forms', 'Next question') + : endsForm.value + ? t('forms', 'End of the form') + : t('forms', 'Next section'), + }, ...formQuestions.value .filter((question, targetPosition) => isAllowedTarget( @@ -153,7 +190,7 @@ export function useJumps( ), } }), - { id: JUMP_TARGET_SUBMIT, label: t('forms', 'End of the form') }, + ...(endsForm.value ? [] : [submitOption]), ] return previous?.length === options.length && previous.every( @@ -264,6 +301,14 @@ export function useJumps( ), ] : []), + ...(issues.leavingSection.has(props.id) + ? [ + t( + 'forms', + 'Other questions of this section jump out of it as well. Respondents follow the first of these jumps on their path.', + ), + ] + : []), ...(issues.unreachable.has(props.id) ? [ props.type === QUESTION_TYPE_SECTION @@ -316,7 +361,8 @@ export function useJumps( nextLabel, warnings, hint, - next, + next: shownNext, + fallbackLabel, targetOptions, getTarget, getTargetLabel, diff --git a/src/utils/Jumps.ts b/src/utils/Jumps.ts index b8abe511a..aff5f2051 100644 --- a/src/utils/Jumps.ts +++ b/src/utils/Jumps.ts @@ -11,7 +11,11 @@ import type { } from '../types/Entities.d.ts' import { QUESTION_EXTRASETTINGS_OTHER_PREFIX } from '../models/Constants.ts' -import { getSectionIndexes, isAllowedTarget } from './Sections.ts' +import { + getSectionIndexes, + isAllowedTarget, + QUESTION_TYPE_SECTION, +} from './Sections.ts' export const JUMP_TARGET_SUBMIT = 'submit' @@ -179,6 +183,7 @@ function awaitsAnswer( /** * 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. + * Leaving a section towards the following question or the end of the form goes to the `next` target of the section instead, if it has one. * The path ends at a question that has no answer yet and a jump per answer past the following question. * Mirrors `SubmissionService::getVisibleQuestions()`. * @@ -193,12 +198,25 @@ export function getVisibleQuestions( questions.map((question, position) => [question.id, position]), ) const visibleQuestions: T[] = [] + let sectionNext: unknown = null let position = 0 while (position < questions.length) { const question = questions[position] visibleQuestions.push(question) + const toPosition = (target: unknown): number | undefined => { + const targetPosition = + typeof target === 'number' ? positions.get(target) : undefined + return targetPosition !== undefined && targetPosition > position + ? targetPosition + : undefined + } + if (question.type === QUESTION_TYPE_SECTION) { + const next = question.extraSettings?.next + sectionNext = + typeof next === 'number' || typeof next === 'string' ? next : null + } const answer = answers[question.id] if (awaitsAnswer(question, answer, position, positions, questions.length)) { break @@ -207,12 +225,19 @@ export function getVisibleQuestions( if (target === JUMP_TARGET_SUBMIT) { break } - const targetPosition = - typeof target === 'number' ? positions.get(target) : undefined - position = - targetPosition !== undefined && targetPosition > position - ? targetPosition - : position + 1 + let targetPosition = toPosition(target) + if ( + targetPosition === undefined + && sectionNext !== null + && (position + 1 === questions.length + || questions[position + 1].type === QUESTION_TYPE_SECTION) + ) { + if (sectionNext === JUMP_TARGET_SUBMIT) { + break + } + targetPosition = toPosition(sectionNext) + } + position = targetPosition ?? position + 1 } return visibleQuestions @@ -228,6 +253,8 @@ export interface JumpIssues { unreachable: Set /** Ids of the reachable questions that a jump of an earlier question can skip */ skippable: Set + /** Ids of the questions with jumps out of their section, where other questions of the section have such jumps as well */ + leavingSection: Set } /** @@ -281,11 +308,13 @@ export function canDecideByAnswer(question: FormsQuestion): boolean { * @param questions the questions of the form in their order * @param position the position of the question * @param positions the positions by question id + * @param following the position that leaving the question without a jump leads to */ function getTargetPositions( questions: FormsQuestion[], position: number, positions: Map, + following: number, ): { targets: Set; brokenJumps: string[] } { const question = questions[position] const extraSettings = question.extraSettings ?? {} @@ -307,7 +336,7 @@ function getTargetPositions( if (target !== null && target !== undefined) { brokenJumps.push(`${question.id}:${jump}`) } - return position + 1 + return following } const possibleAnswers = getPossibleAnswers(question) @@ -358,16 +387,44 @@ export function getJumpIssues(questions: FormsQuestion[]): JumpIssues { brokenJumps: new Set(), unreachable: new Set(), skippable: new Set(), + leavingSection: new Set(), } + const sections = getSectionIndexes(questions) const reached = new Set(questions.length > 0 ? [0] : []) let farthestTarget = 0 + let sectionNext: number | undefined for (let position = 0; position < questions.length; position++) { const question = questions[position] + if (question.type === QUESTION_TYPE_SECTION) { + const next = question.extraSettings?.next + const nextPosition = + typeof next === 'number' ? positions.get(next) : undefined + sectionNext = + next === JUMP_TARGET_SUBMIT + ? questions.length + : nextPosition !== undefined + && isAllowedTarget( + questions, + sections, + position, + nextPosition, + ) + ? nextPosition + : undefined + if (next !== undefined && next !== null && sectionNext === undefined) { + issues.broken.add(question.id) + issues.brokenJumps.add(`${question.id}:next`) + } + } + const leavesSection = + position + 1 === questions.length + || questions[position + 1].type === QUESTION_TYPE_SECTION const { targets, brokenJumps } = getTargetPositions( questions, position, positions, + leavesSection && sectionNext !== undefined ? sectionNext : position + 1, ) if (brokenJumps.length > 0) { issues.broken.add(question.id) @@ -386,6 +443,36 @@ export function getJumpIssues(questions: FormsQuestion[]): JumpIssues { } } + const leaving = new Map() + questions.forEach((question, position) => { + const extraSettings = question.extraSettings ?? {} + const leaves = [ + ...getJumps(extraSettings).map((jump) => jump.target), + QUESTION_TYPES_WITH_NEXT.includes(question.type) + ? extraSettings.next + : undefined, + ].some((target) => { + const targetPosition = + typeof target === 'number' ? positions.get(target) : undefined + return ( + target === JUMP_TARGET_SUBMIT + || (targetPosition !== undefined + && sections[targetPosition] !== sections[position]) + ) + }) + if (leaves && sections[position] > 0) { + leaving.set(sections[position], [ + ...(leaving.get(sections[position]) ?? []), + question.id, + ]) + } + }) + for (const ids of leaving.values()) { + if (ids.length > 1) { + ids.forEach((id) => issues.leavingSection.add(id)) + } + } + return issues } diff --git a/src/utils/Sections.ts b/src/utils/Sections.ts index 14a5d36e7..382d116f8 100644 --- a/src/utils/Sections.ts +++ b/src/utils/Sections.ts @@ -101,7 +101,7 @@ export function getSectionIndexes(questions: Array<{ type: string }>): number[] } /** - * Whether a question may jump to a target: a later question of its own section, or a later section + * Whether a question may jump to a target: a later question of its own section, or a later section; a section only to a later section * * @param questions the questions and sections in their order * @param sections the section of each question by position, see `getSectionIndexes()` @@ -117,7 +117,8 @@ export function isAllowedTarget( return ( targetPosition > position && (questions[targetPosition].type === QUESTION_TYPE_SECTION - || sections[targetPosition] === sections[position]) + || (questions[position].type !== QUESTION_TYPE_SECTION + && sections[targetPosition] === sections[position])) ) } diff --git a/src/views/Create.vue b/src/views/Create.vue index 8eda6e71e..fd197a988 100644 --- a/src/views/Create.vue +++ b/src/views/Create.vue @@ -583,10 +583,10 @@ export default defineComponent({ } /** - * The numbers of the questions, as a list + * The numbers of questions or of sections, as a list; questions and sections are numbered apart * * @param questions the questions of the form in their order - * @param ids the ids of the questions + * @param ids the ids of the questions or of the sections */ const numbersOf = (questions: FormsQuestion[], ids: number[]): string => { const numbers = getNumbers(questions) @@ -600,6 +600,21 @@ export default defineComponent({ ) } + /** + * The ids of the sections among some ids + * + * @param questions the questions of the form in their order + * @param ids the ids of questions and sections + */ + const sectionIdsOf = (questions: FormsQuestion[], ids: number[]): number[] => + questions + .filter( + (question) => + question.type === QUESTION_TYPE_SECTION + && ids.includes(question.id), + ) + .map((question) => question.id) + /** * Show a warning when a change breaks jumps, makes questions unreachable or lets jumps skip more questions * @@ -620,9 +635,9 @@ export default defineComponent({ .map((question) => question.id), ) - const broken = getNewlyBrokenQuestions(before, after).filter((id) => - questionIds.has(id), - ) + const newlyBroken = getNewlyBrokenQuestions(before, after) + const broken = newlyBroken.filter((id) => questionIds.has(id)) + const brokenSections = newlyBroken.filter((id) => !questionIds.has(id)) const unreachable = [...after.unreachable].filter( (id) => !before.unreachable.has(id) && questionIds.has(id), ) @@ -639,6 +654,14 @@ export default defineComponent({ && !newIds.has(question.id), ) const messages = [ + brokenSections.length > 0 + && n( + 'forms', + 'Section {sections} went to a section that was deleted, so respondents now go to the next section instead.', + 'Sections {sections} went to sections that were deleted, so respondents now go to the next section instead.', + brokenSections.length, + { sections: numbersOf(newQuestions, brokenSections) }, + ), broken.length > 0 && (deletedSection ? n( @@ -797,18 +820,41 @@ export default defineComponent({ severity: 'warning', }) } + const sectionIds = sectionIdsOf(questions, ids) + const questionIds = ids.filter((id) => !sectionIds.includes(id)) + const sectionsText = + sectionIds.length === 0 + ? '' + : questionIds.length === 0 + ? n( + 'forms', + 'After this move, section {sections} would go to an earlier section.', + 'After this move, sections {sections} would go to earlier sections.', + sectionIds.length, + { sections: numbersOf(questions, sectionIds) }, + ) + : n( + 'forms', + 'Section {sections} would go to an earlier section as well.', + 'Sections {sections} would go to earlier sections as well.', + sectionIds.length, + { sections: numbersOf(questions, sectionIds) }, + ) + const questionsText = + questionIds.length === 0 + ? '' + : n( + 'forms', + 'After this move, question {questions} would jump to an earlier question.', + 'After this move, questions {questions} would jump to earlier questions.', + questionIds.length, + { questions: numbersOf(questions, questionIds) }, + ) return await showConfirmation({ name: t('forms', 'Jumps cannot go back'), - text: [ - n( - 'forms', - 'After this move, question {questions} would jump to an earlier question.', - 'After this move, questions {questions} would jump to earlier questions.', - ids.length, - { questions: numbersOf(questions, ids) }, - ), - moveBackText(moved), - ].join(' '), + text: [questionsText, sectionsText, moveBackText(moved)] + .filter(Boolean) + .join(' '), labelConfirm: t('forms', 'Remove jumps'), labelReject: t('forms', 'Move back'), severity: 'warning', diff --git a/tests/Unit/Service/FormsServiceTest.php b/tests/Unit/Service/FormsServiceTest.php index fe720fdf4..4c2ac9bdb 100644 --- a/tests/Unit/Service/FormsServiceTest.php +++ b/tests/Unit/Service/FormsServiceTest.php @@ -2476,6 +2476,30 @@ public function testRemoveDisallowedJumpsIntoTheMiddleOfAnotherSection(): void { $this->assertSame([], $questions[3]->getExtraSettings()); } + public function testRemoveDisallowedJumpsOfASectionToAQuestion(): void { + $questions = array_map(static function (array $data): Question { + $question = new Question(); + $question->setId($data[0]); + $question->setType($data[1]); + $question->setExtraSettings($data[2]); + return $question; + }, [ + [1, Constants::ANSWER_TYPE_SECTION, ['next' => 2]], + [2, Constants::ANSWER_TYPE_SHORT, []], + [3, Constants::ANSWER_TYPE_SECTION, ['next' => 5]], + [4, Constants::ANSWER_TYPE_SHORT, []], + [5, Constants::ANSWER_TYPE_SECTION, ['next' => 'submit']], + [6, Constants::ANSWER_TYPE_SHORT, []], + ]); + + $changed = FormsService::removeDisallowedJumps($questions); + + $this->assertSame([$questions[0]], $changed); + $this->assertSame([], $questions[0]->getExtraSettings()); + $this->assertSame(['next' => 5], $questions[2]->getExtraSettings()); + $this->assertSame(['next' => 'submit'], $questions[4]->getExtraSettings()); + } + public function testMapJumpsOfCopies(): void { $questions = array_map(static function (array $data): Question { $question = new Question(); diff --git a/tests/fixtures/jump-paths.json b/tests/fixtures/jump-paths.json index 527933439..4604b1047 100644 --- a/tests/fixtures/jump-paths.json +++ b/tests/fixtures/jump-paths.json @@ -431,5 +431,70 @@ ], "answers": {}, "visible": [1] + }, + { + "name": "leaving a section goes to the next target of the section", + "questions": [ + { "id": 1, "type": "section", "extraSettings": { "next": 5 } }, + { "id": 2, "type": "short", "extraSettings": {} }, + { "id": 3, "type": "section", "extraSettings": {} }, + { "id": 4, "type": "short", "extraSettings": {} }, + { "id": 5, "type": "section", "extraSettings": {} }, + { "id": 6, "type": "short", "extraSettings": {} } + ], + "answers": {}, + "visible": [1, 2, 5, 6] + }, + { + "name": "an answer that jumps out of the section wins over the next target of the section", + "questions": [ + { "id": 1, "type": "section", "extraSettings": { "next": 5 } }, + { "id": 2, "type": "multiple_unique", "extraSettings": { "goTo": [{ "optionId": 21, "target": 3 }] } }, + { "id": 3, "type": "section", "extraSettings": {} }, + { "id": 4, "type": "short", "extraSettings": {} }, + { "id": 5, "type": "section", "extraSettings": {} }, + { "id": 6, "type": "short", "extraSettings": {} } + ], + "answers": { "2": ["21"] }, + "visible": [1, 2, 3, 4, 5, 6] + }, + { + "name": "a jump inside a section still leaves it through the next target of the section", + "questions": [ + { "id": 1, "type": "section", "extraSettings": { "next": 7 } }, + { "id": 2, "type": "multiple_unique", "extraSettings": { "goTo": [{ "optionId": 21, "target": 4 }] } }, + { "id": 3, "type": "short", "extraSettings": {} }, + { "id": 4, "type": "short", "extraSettings": {} }, + { "id": 5, "type": "section", "extraSettings": {} }, + { "id": 6, "type": "short", "extraSettings": {} }, + { "id": 7, "type": "section", "extraSettings": {} }, + { "id": 8, "type": "short", "extraSettings": {} } + ], + "answers": { "2": ["21"] }, + "visible": [1, 2, 4, 7, 8] + }, + { + "name": "the next target of a section can end the form", + "questions": [ + { "id": 1, "type": "section", "extraSettings": { "next": "submit" } }, + { "id": 2, "type": "short", "extraSettings": {} }, + { "id": 3, "type": "section", "extraSettings": {} }, + { "id": 4, "type": "short", "extraSettings": {} } + ], + "answers": {}, + "visible": [1, 2] + }, + { + "name": "an empty section goes to its next target", + "questions": [ + { "id": 1, "type": "short", "extraSettings": {} }, + { "id": 2, "type": "section", "extraSettings": { "next": 5 } }, + { "id": 3, "type": "section", "extraSettings": {} }, + { "id": 4, "type": "short", "extraSettings": {} }, + { "id": 5, "type": "section", "extraSettings": {} }, + { "id": 6, "type": "short", "extraSettings": {} } + ], + "answers": {}, + "visible": [1, 2, 5, 6] } ]