Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions playwright/e2e/question-editing.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ 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 { api } from '../support/helpers.ts'
import {
LinearScaleSubtype,
QuestionType,
Expand Down Expand Up @@ -144,3 +145,24 @@ test.describe('Question editing lifecycle', () => {
await expect(clone.answerInputs).toHaveCount(2)
})
})

test('The editor warns about changing questions once the form has responses', async ({
page,
}) => {
const form = await api(page.request, 'POST', '/forms')
const question = await api(page.request, 'POST', `/forms/${form.id}/questions`, {
type: 'short',
text: 'Name',
})
const warning = page.getByText('This form already has 1 response.')

await page.goto(`apps/forms/${form.hash}/edit`)
await expect(page.getByRole('textbox', { name: 'Form title' })).toBeVisible()
await expect(warning).toHaveCount(0)

await api(page.request, 'POST', `/forms/${form.id}/submissions`, {
answers: { [question.id]: ['Jane'] },
})
await page.reload()
await expect(warning).toBeVisible()
})
28 changes: 28 additions & 0 deletions playwright/e2e/submit-form.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,9 @@ test.describe('Form submission', () => {
await deleted

await topBar.toggleView(FormsView.View)
const dialog = page.getByRole('dialog', { name: 'Clear form' })
await expect(dialog.getByRole('listitem')).toHaveText(['Favorite fruits'])
await dialog.getByRole('button', { name: 'Abort' }).click()
const response = await submitView.submit()
expect(response.status()).toBe(201)
await expect(submitView.successMessage).toBeVisible()
Expand Down Expand Up @@ -209,6 +212,7 @@ test('A restored draft leaves out values the questions no longer offer', async (
},
type: 'QuestionGrid',
},
999999: { value: ['Friday'], type: 'QuestionShort' },
}),
],
)
Expand All @@ -224,6 +228,20 @@ test('A restored draft leaves out values the questions no longer offer', async (
)
await page.reload()

const dialog = page.getByRole('dialog', { name: 'Clear form' })
await expect(dialog).toContainText(
'Your answers to questions that no longer exist were removed.',
)
await expect(dialog).toContainText(
'Some of your answers are no longer offered and were removed from these questions:',
)
await expect(dialog.getByRole('listitem')).toHaveText([
'Rating',
'Order',
'Skills',
])
await dialog.getByRole('button', { name: 'Abort' }).click()

const response = await submitView.submit()
expect(response.status()).toBe(201)
const { answers } = response.request().postDataJSON()
Expand Down Expand Up @@ -251,6 +269,8 @@ test('A restored draft sends a linear scale answer as its plain number', async (
],
)
await page.reload()
await expect(submitView.getQuestion('Rating')).toBeVisible()
await expect(page.getByRole('dialog', { name: 'Clear form' })).toHaveCount(0)

const response = await submitView.submit()
expect(response.status()).toBe(201)
Expand Down Expand Up @@ -288,6 +308,14 @@ test('An edited submission leaves out values the questions no longer offer', asy
)
await page.goto(`apps/forms/${form.hash}/submit/${submissions[0].id}`)
await expect(submitView.getQuestion('Order')).toBeVisible()
const dialog = page.getByRole('dialog', { name: 'Clear form' })
await expect(dialog.getByRole('listitem')).toHaveText(['Rating', 'Order'])
await expect(
dialog.getByText(
'Your answers to questions that no longer exist were removed.',
),
).toHaveCount(0)
await dialog.getByRole('button', { name: 'Abort' }).click()

const response = await submitView.submit()
expect(response.status()).toBe(200)
Expand Down
13 changes: 12 additions & 1 deletion src/views/Create.vue
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,16 @@
<p v-if="infoMessage" class="info-message">
{{ infoMessage }}
</p>
<NcNoteCard v-if="form.submissionCount" type="warning">
{{
n(
'forms',
'This form already has %n response. Changing the options, rows or columns of a question, or the range of a linear scale, does not change it: answers that are no longer offered stay in the results.',
'This form already has %n responses. Changing the options, rows or columns of a question, or the range of a linear scale, does not change them: answers that are no longer offered stay in the results.',
form.submissionCount,
)
}}
</NcNoteCard>
</header>

<section>
Expand Down Expand Up @@ -233,7 +243,7 @@ import axios from '@nextcloud/axios'
import { showError } from '@nextcloud/dialogs'
import { emit as emitEvent } from '@nextcloud/event-bus'
import { loadState } from '@nextcloud/initial-state'
import { t } from '@nextcloud/l10n'
import { n, t } from '@nextcloud/l10n'
import moment from '@nextcloud/moment'
import { generateOcsUrl } from '@nextcloud/router'
import { useIsMobile } from '@nextcloud/vue'
Expand Down Expand Up @@ -856,6 +866,7 @@ export default defineComponent({
onQuestionOrderChange,
IconLock,
isMobile: useIsMobile(),
n,
t,
}
},
Expand Down
115 changes: 105 additions & 10 deletions src/views/Submit.vue
Comment thread
AndyScherzinger marked this conversation as resolved.
Resolved
Original file line number Diff line number Diff line change
Expand Up @@ -225,15 +225,40 @@
<NcDialog
v-model:open="showClearFormDueToChangeDialog"
:name="t('forms', 'Clear form')"
:message="
t(
'forms',
'The form has changed since your last visit. Do you want to clear all answers?',
)
"
:buttons="confirmClearFormButtons"
noClose
:closeOnClickOutside="false" />
:closeOnClickOutside="false">
<p>
{{ t('forms', 'The form has changed since your last visit.') }}
</p>
<p v-if="hasAnswersToDeletedQuestions">
{{
t(
'forms',
'Your answers to questions that no longer exist were removed.',
)
}}
</p>
<template v-if="questionsWithRemovedAnswers.length > 0">
<p>
{{
t(
'forms',
'Some of your answers are no longer offered and were removed from these questions:',
)
}}
</p>
<ul class="changed-questions">
<li
v-for="question in questionsWithRemovedAnswers"
:key="question.id"
dir="auto">
{{ question.text }}
</li>
</ul>
</template>
<p>{{ t('forms', 'Do you want to clear all answers?') }}</p>
</NcDialog>
</template>
</NcAppContent>
</template>
Expand Down Expand Up @@ -424,6 +449,8 @@ export default defineComponent({
const showConfirmLeaveDialog = ref(false)
const showClearFormDialog = ref(false)
const showClearFormDueToChangeDialog = ref(false)
const removedAnswerQuestionIds = ref<number[]>([])
const hasAnswersToDeletedQuestions = ref(false)
const confirmButtonCallback = ref<(val: boolean) => void>(() => {})

const validQuestions = computed<SubmitQuestion[]>(() => {
Expand Down Expand Up @@ -723,6 +750,62 @@ export default defineComponent({
)
}

/**
* Number of values in an answer, counting each cell of a grid
*
* @param value the values of the answer
*/
function countValues(value: AnswerValue): number {
if (Array.isArray(value)) {
return value.length
}
return Object.values(value).reduce<number>(
(count, rowValue) =>
count
+ (Array.isArray(rowValue)
? rowValue.length
: typeof rowValue === 'object' && rowValue !== null
? Object.keys(rowValue).length
: 1),
0,
)
}

/**
* Remember a question that lost an earlier answer because it is no longer offered
*
* @param questionId the id of the question
*/
function noteRemovedAnswer(questionId: number): void {
if (!removedAnswerQuestionIds.value.includes(questionId)) {
removedAnswerQuestionIds.value.push(questionId)
}
showClearFormDueToChangeDialog.value = true
}

/**
* The values of an earlier answer the question still offers, remembering the question if any were removed
*
* @param question the question
* @param value the values of the earlier answer
*/
function withOfferedEarlierValues(
question: SubmitQuestion,
value: AnswerValue,
): AnswerValue {
const offered = withOfferedValues(question, value)
if (countValues(offered) < countValues(value)) {
noteRemovedAnswer(question.id)
}
return offered
}

const questionsWithRemovedAnswers = computed(() =>
validQuestions.value.filter((question) =>
removedAnswerQuestionIds.value.includes(question.id),
),
)

/**
* Initialize answers from saved state in LocalStorage
*/
Expand All @@ -740,6 +823,7 @@ export default defineComponent({
const question = questions.get(parseInt(questionId, 10))
// Clean up answers for questions that do not exist anymore
if (!question) {
hasAnswersToDeletedQuestions.value = true
showClearFormDueToChangeDialog.value = true
logger.debug('Question does not exist anymore', {
questionId,
Expand All @@ -752,7 +836,7 @@ export default defineComponent({
)
? (answer.value as string[]).map(String)
: answer.value
localAnswers[question.id] = withOfferedValues(question, value)
localAnswers[question.id] = withOfferedEarlierValues(question, value)
}
answers.value = localAnswers
}
Expand Down Expand Up @@ -857,6 +941,7 @@ export default defineComponent({
logger.debug(`questionId: ${questionId}, answerId: ${answer.id}`)
// Clean up answers for questions that do not exist anymore
if (!validQuestionsIds.value.has(questionId)) {
hasAnswersToDeletedQuestions.value = true
showClearFormDueToChangeDialog.value = true
logger.debug('Question does not exist anymore', {
questionId,
Expand Down Expand Up @@ -910,7 +995,7 @@ export default defineComponent({
QUESTION_EXTRASETTINGS_OTHER_PREFIX + text,
)
} else {
// error handling
noteRemovedAnswer(questionId)
logger.debug(
`option ${text} could not be mapped to an option for question ${questionId}`,
)
Expand All @@ -930,7 +1015,7 @@ export default defineComponent({

for (const question of validQuestions.value) {
if (loaded[question.id] !== undefined) {
loaded[question.id] = withOfferedValues(
loaded[question.id] = withOfferedEarlierValues(
question,
loaded[question.id],
)
Expand Down Expand Up @@ -1228,6 +1313,8 @@ export default defineComponent({
showConfirmLeaveDialog.value = false
showClearFormDialog.value = false
showClearFormDueToChangeDialog.value = false
removedAnswerQuestionIds.value = []
hasAnswersToDeletedQuestions.value = false
success.value = false
submitForm.value = false
}
Expand Down Expand Up @@ -1342,6 +1429,8 @@ export default defineComponent({
...viewForm,
answerTypes,
answers,
questionsWithRemovedAnswers,
hasAnswersToDeletedQuestions,
confirmClearFormButtons,
confirmEmptyModalButtons,
confirmLeaveFormButtons,
Expand Down Expand Up @@ -1483,4 +1572,10 @@ export default defineComponent({
}
}
}

.changed-questions {
list-style: disc;
padding-inline-start: calc(var(--default-grid-baseline) * 5);
margin-block: var(--default-grid-baseline);
}
</style>
Loading