From a6951db3e32177ed19168762aa730c8598997d74 Mon Sep 17 00:00:00 2001 From: Andy Scherzinger Date: Tue, 17 Nov 2026 14:27:53 +0100 Subject: [PATCH] fix(submit): leave removed values out of restored answers A draft restored from the local storage of a logged in respondent, and a submission opened for editing, keep only the values the question still offers: options of radio, checkbox, dropdown and ranking questions, or an answer "Other" while the question allows it, rows and columns of grid questions, and values of a linear scale within its bounds. A value the owner removed after the draft was saved or the submission was made 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 | 168 +++++++++++++++++++++++++++++ playwright/support/helpers.ts | 27 ++++- src/views/Submit.vue | 157 +++++++++++++++++---------- 3 files changed, 297 insertions(+), 55 deletions(-) diff --git a/playwright/e2e/submit-form.spec.ts b/playwright/e2e/submit-form.spec.ts index aa0b666a9f..81ffcf78d4 100644 --- a/playwright/e2e/submit-form.spec.ts +++ b/playwright/e2e/submit-form.spec.ts @@ -3,12 +3,15 @@ * SPDX-License-Identifier: AGPL-3.0-or-later */ +import type { APIRequestContext } from '@playwright/test' + import { expect, mergeTests } from '@playwright/test' import { test as formTest } from '../support/fixtures/form.ts' 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 { api, waitForApiResponse } from '../support/helpers.ts' import { QuestionType } from '../support/sections/QuestionType.ts' import { FormsView } from '../support/sections/TopBarSection.ts' @@ -79,4 +82,169 @@ 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() + }) +}) + +/** + * Create a form with a linear scale "Rating", a ranking question "Order" (First, Second, Third) and a checkbox grid "Skills" (rows Beginner, Expert; column Python) + * + * @param request the request context of the page + */ +async function createOfferedValuesForm(request: APIRequestContext) { + const form = await api(request, 'POST', '/forms') + const scale = await api(request, 'POST', `/forms/${form.id}/questions`, { + type: 'linearscale', + text: 'Rating', + }) + const ranking = await api(request, 'POST', `/forms/${form.id}/questions`, { + type: 'ranking', + text: 'Order', + }) + const options = await api( + request, + 'POST', + `/forms/${form.id}/questions/${ranking.id}/options`, + { optionTexts: ['First', 'Second', 'Third'] }, + ) + const grid = await api(request, 'POST', `/forms/${form.id}/questions`, { + type: 'grid', + subtype: 'checkbox', + text: 'Skills', + }) + const rows = await api( + request, + 'POST', + `/forms/${form.id}/questions/${grid.id}/options`, + { optionTexts: ['Beginner', 'Expert'], optionType: 'row' }, + ) + const columns = await api( + request, + 'POST', + `/forms/${form.id}/questions/${grid.id}/options`, + { optionTexts: ['Python'], optionType: 'column' }, + ) + return { form, scale, ranking, options, grid, rows, columns } +} + +test('A restored draft leaves out values the questions no longer offer', async ({ + page, + submitView, +}) => { + const { form, scale, ranking, options, grid, rows, columns } = + await createOfferedValuesForm(page.request) + await page.goto(`apps/forms/${form.hash}/submit`) + await page.evaluate( + ([key, draft]) => localStorage.setItem(key, draft), + [ + `nextcloud_forms_${form.hash}`, + JSON.stringify({ + [scale.id]: { value: ['8'], type: 'QuestionLinearScale' }, + [ranking.id]: { + value: options.map((option: { id: number }) => + String(option.id), + ), + type: 'QuestionRanking', + }, + [grid.id]: { + value: { + [rows[0].id]: [columns[0].id], + [rows[1].id]: [columns[0].id], + }, + type: 'QuestionGrid', + }, + }), + ], + ) + await api( + page.request, + 'DELETE', + `/forms/${form.id}/questions/${ranking.id}/options/${options[2].id}`, + ) + await api( + page.request, + 'DELETE', + `/forms/${form.id}/questions/${grid.id}/options/${rows[1].id}`, + ) + await page.reload() + + const response = await submitView.submit() + expect(response.status()).toBe(201) + const { answers } = response.request().postDataJSON() + expect(answers[scale.id] ?? []).toEqual([]) + expect(answers[ranking.id].map(String)).toEqual([ + String(options[0].id), + String(options[1].id), + ]) + expect(answers[grid.id]).toEqual({ [rows[0].id]: [columns[0].id] }) +}) + +test('An edited submission leaves out values the questions no longer offer', async ({ + page, + submitView, +}) => { + const { form, scale, ranking, options } = await createOfferedValuesForm( + page.request, + ) + await api(page.request, 'PATCH', `/forms/${form.id}/questions/${scale.id}`, { + keyValuePairs: { extraSettings: { optionsHighest: 10 } }, + }) + await api(page.request, 'POST', `/forms/${form.id}/submissions`, { + answers: { + [scale.id]: ['8'], + [ranking.id]: options.map((option: { id: number }) => String(option.id)), + }, + }) + const { submissions } = await api( + page.request, + 'GET', + `/forms/${form.id}/submissions`, + ) + await api(page.request, 'PATCH', `/forms/${form.id}/questions/${scale.id}`, { + keyValuePairs: { extraSettings: { optionsHighest: 5 } }, + }) + await api( + page.request, + 'DELETE', + `/forms/${form.id}/questions/${ranking.id}/options/${options[2].id}`, + ) + await page.goto(`apps/forms/${form.hash}/submit/${submissions[0].id}`) + await expect(submitView.getQuestion('Order')).toBeVisible() + + const response = await submitView.submit() + expect(response.status()).toBe(200) + const { answers } = response.request().postDataJSON() + expect(answers[scale.id] ?? []).toEqual([]) + expect(answers[ranking.id].map(String)).toEqual([ + String(options[0].id), + String(options[1].id), + ]) }) diff --git a/playwright/support/helpers.ts b/playwright/support/helpers.ts index 6a93d444c8..f108e6a291 100644 --- a/playwright/support/helpers.ts +++ b/playwright/support/helpers.ts @@ -3,7 +3,9 @@ * SPDX-License-Identifier: AGPL-3.0-or-later */ -import type { Page, Response } from '@playwright/test' +import type { APIRequestContext, Page, Response } from '@playwright/test' + +import { expect } from '@playwright/test' const FORMS_API_PATH = '/api/v3/forms/' @@ -21,3 +23,26 @@ export function waitForApiResponse(page: Page, method: string): Promise + new Set( + (question.options ?? []) + .filter((option) => option.optionType === optionType) + .map((option) => option.id), + ) + const rowIds = optionIdsByType(OptionType.Row) + const columnIds = optionIdsByType(OptionType.Column) + + const existingValues: GridQuestionValues = {} + for (const [rowId, rowValue] of Object.entries(gridValues)) { + if (!rowIds.has(Number(rowId))) { + continue + } + if (Array.isArray(rowValue)) { + const columns = rowValue.filter((columnId) => + columnIds.has(Number(columnId)), + ) + if (columns.length > 0) { + existingValues[Number(rowId)] = columns + } + } else if (typeof rowValue === 'object' && rowValue !== null) { + const cells = Object.fromEntries( + Object.entries(rowValue).filter(([columnId]) => + columnIds.has(Number(columnId)), + ), + ) + if (Object.keys(cells).length > 0) { + existingValues[Number(rowId)] = cells + } + } else if (columnIds.has(Number(rowValue))) { + existingValues[Number(rowId)] = rowValue + } + } + return existingValues + } + + /** + * The values of an answer the question still offers: its options or an answer "Other" while it allows one, the rows and columns of a grid, the values within the bounds of a linear scale + * + * @param question the question + * @param value the values of the answer + */ + function withOfferedValues( + question: SubmitQuestion, + value: AnswerValue, + ): AnswerValue { + if (!Array.isArray(value)) { + return question.type === 'grid' + ? withExistingGridCells(question, value) + : value + } + if (question.type === 'linearscale') { + const lowest = Number(question.extraSettings?.optionsLowest ?? 1) + const highest = Number(question.extraSettings?.optionsHighest ?? 5) + return value.filter( + (choice) => + Number(choice) >= lowest && Number(choice) <= highest, + ) + } + if (!answerTypes[question.type]?.predefined) { + return value + } + return value.filter( + (choice) => + (question.options ?? []).some( + (option) => String(option.id) === String(choice), + ) + || (!!question.extraSettings?.allowOtherAnswer + && String(choice).startsWith( + QUESTION_EXTRASETTINGS_OTHER_PREFIX, + )), + ) + } + /** * Initialize answers from saved state in LocalStorage */ @@ -601,10 +686,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, @@ -612,12 +701,12 @@ 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] = withOfferedValues(question, value) } answers.value = localAnswers } @@ -746,55 +835,7 @@ export default defineComponent({ } } else if (question.type === 'grid') { try { - const gridValues = JSON.parse(text) as GridQuestionValues - const optionIdsByType = (optionType: OptionType) => - new Set( - (question.options ?? []) - .filter( - (option) => - option.optionType === optionType, - ) - .map((option) => option.id), - ) - const rowIds = optionIdsByType(OptionType.Row) - const columnIds = optionIdsByType(OptionType.Column) - - // Drop answers for rows/columns that do not exist anymore - const restoredValues: GridQuestionValues = {} - for (const [rowId, rowValue] of Object.entries( - gridValues, - )) { - if (!rowIds.has(Number(rowId))) { - continue - } - if (Array.isArray(rowValue)) { - // Checkbox grid - const columns = rowValue.filter((columnId) => - columnIds.has(Number(columnId)), - ) - if (columns.length > 0) { - restoredValues[Number(rowId)] = columns - } - } else if ( - typeof rowValue === 'object' - && rowValue !== null - ) { - // Number/text grid - const cells = Object.fromEntries( - Object.entries(rowValue).filter( - ([columnId]) => - columnIds.has(Number(columnId)), - ), - ) - if (Object.keys(cells).length > 0) { - restoredValues[Number(rowId)] = cells - } - } else if (columnIds.has(Number(rowValue))) { - // Radio grid - restoredValues[Number(rowId)] = rowValue - } - } - loaded[questionId] = restoredValues + loaded[questionId] = JSON.parse(text) } catch (error) { logger.debug( `Could not parse grid answer ${text} for question ${questionId}`, @@ -841,6 +882,14 @@ export default defineComponent({ } } + for (const question of validQuestions.value) { + if (loaded[question.id] !== undefined) { + loaded[question.id] = withOfferedValues( + question, + loaded[question.id], + ) + } + } answers.value = loaded saveAllAnswersToLocalStorage() } catch (error) {