From 9ab7bf3832b19268fe3f2453d60f1f73f4cd75a5 Mon Sep 17 00:00:00 2001 From: Andy Scherzinger Date: Sat, 21 Nov 2026 16:54:49 +0100 Subject: [PATCH 01/12] feat(linearscale): add a rating sub type A rating ("how would you rate this") is answered with one whole number from 1 to N, which a linear scale already stores, validates, counts in the results and exports. It therefore becomes a sub type of the linear scale rather than a question type of its own: fixed when the question is created and stored in extraSettings.questionType, the way grid questions store their cell type. The add-question menu lists "Numbers" and "Rating" under "Linear scale". The editor of a rating offers only the highest rating (2 to 10, default 5), since a rating always starts at 1. Answers, results and exports go through the existing linear scale paths; the results summary names a rating "Linear scale (Rating)". The server accepts no other sub type of a linear scale and keeps a rating starting at 1. Existing linear scale questions have no sub type and stay as they are. Assisted-by: ClaudeCode:claude-opus-5-5 Signed-off-by: Andy Scherzinger --- docs/API_v3.md | 1 + docs/DataStructure.md | 3 +- lib/Constants.php | 7 +++ lib/Controller/ApiController.php | 4 +- lib/ResponseDefinitions.php | 2 +- lib/Service/FormsService.php | 9 ++++ openapi.json | 7 +-- playwright/e2e/a11y-question-inputs.spec.ts | 8 +++- playwright/e2e/question-editing.spec.ts | 12 ++++- playwright/support/sections/FormSection.ts | 8 +++- playwright/support/sections/QuestionType.ts | 8 ++++ src/components/AddQuestionMenu.vue | 17 ++++--- .../Questions/QuestionLinearScale.vue | 17 ++++++- src/components/Results/ResultsSummary.vue | 10 +++- src/components/Results/Submission.vue | 1 - src/models/AnswerTypes.ts | 20 +++++++- src/models/Constants.ts | 4 ++ tests/Unit/Controller/ApiControllerTest.php | 48 +++++++++++++++++-- tests/Unit/Service/FormsServiceTest.php | 15 ++++++ 19 files changed, 172 insertions(+), 29 deletions(-) diff --git a/docs/API_v3.md b/docs/API_v3.md index 7c0b0fb82c..ad2786c7e7 100644 --- a/docs/API_v3.md +++ b/docs/API_v3.md @@ -377,6 +377,7 @@ Returns the questions and options of the given form (without submissions). |-----------|---------|----------|-------------| | _type_ | [QuestionType](DataStructure.md#question-types) | | The question-type of the new question | | _text_ | String | yes | _Optional_ The text of the new question. | + | _subtype_ | String | yes | _Optional_ The sub type, stored as `extraSettings.questionType`: `checkbox`, `number` or `radio` for `grid`, `rating` for `linearscale` (a 1 to N scale drawn as icons). Any other value is rejected. | | _position_ | Integer | yes | _(optional)_ 1-based position to insert the new question. When omitted the question is appended at the end. | - Response: The new question object. diff --git a/docs/DataStructure.md b/docs/DataStructure.md index d0e9acfa34..cfa6963401 100644 --- a/docs/DataStructure.md +++ b/docs/DataStructure.md @@ -263,13 +263,14 @@ Optional extra settings for some [Question Types](#question-types) | `timeMax` | `time` | string | - | Maximum allowed time to be chosen (as `HH:mm` string) | | `timeMin` | `time` | string | - | Minimum allowed time to be chosen (as `HH:mm` string) | | `timeRange` | `time` | Boolean | `true/false` | The time picker should query a time range | -| `optionsLowest` | `linearscale` | Integer | `0, 1` | Set the lowest value of the scale, default: `1` | +| `optionsLowest` | `linearscale` | Integer | `0, 1` | Set the lowest value of the scale, default: `1`; always `1` for the `rating` sub type | | `optionsHighest` | `linearscale` | Integer | `2, 3, 4, 5, 6, 7, 8, 9, 10` | Set the highest value of the scale, default: `5` | | `optionsLabelLowest` | `linearscale` | string | - | Set the label of the lowest value, default: `'Strongly disagree'` | | `optionsLabelHighest` | `linearscale` | string | - | Set the label of the highest value, default: `'Strongly agree'` | | `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) | +| `questionType` | `linearscale` | String | `rating` | Sub type, fixed at creation; `rating` is a 1 to N scale drawn as icons; absent for a plain scale | ### Option Types diff --git a/lib/Constants.php b/lib/Constants.php index 3e465cd0cd..307f1058d3 100644 --- a/lib/Constants.php +++ b/lib/Constants.php @@ -118,6 +118,8 @@ class Constants { public const ANSWER_GRID_TYPE_NUMBER = 'number'; public const ANSWER_GRID_TYPE_RADIO = 'radio'; + public const ANSWER_LINEARSCALE_TYPE_RATING = 'rating'; + // All AnswerTypes public const ANSWER_TYPES = [ self::ANSWER_TYPE_COLOR, @@ -221,6 +223,7 @@ class Constants { 'optionsHighest' => ['integer', 'NULL'], 'optionsLabelLowest' => ['string', 'NULL'], 'optionsLabelHighest' => ['string', 'NULL'], + 'questionType' => ['string'], ]; public const EXTRA_SETTINGS_GRID = [ @@ -239,6 +242,10 @@ class Constants { self::ANSWER_GRID_TYPE_RADIO, ]; + public const EXTRA_SETTINGS_LINEARSCALE_QUESTION_TYPE = [ + self::ANSWER_LINEARSCALE_TYPE_RATING, + ]; + /** * !! Keep in sync with src/mixins/ShareTypes.js !! */ diff --git a/lib/Controller/ApiController.php b/lib/Controller/ApiController.php index 97a203b04c..d098deec07 100644 --- a/lib/Controller/ApiController.php +++ b/lib/Controller/ApiController.php @@ -67,7 +67,7 @@ * @psalm-import-type FormsPartialForm from ResponseDefinitions * @psalm-import-type FormsQuestion from ResponseDefinitions * @psalm-import-type FormsQuestionType from ResponseDefinitions - * @psalm-import-type FormsQuestionGridCellType from ResponseDefinitions + * @psalm-import-type FormsQuestionSubtype from ResponseDefinitions * @psalm-import-type FormsSubmission from ResponseDefinitions * @psalm-import-type FormsSubmissions from ResponseDefinitions * @psalm-import-type FormsUploadedFile from ResponseDefinitions @@ -530,7 +530,7 @@ public function getQuestion(int $formId, int $questionId): DataResponse { * * @param int $formId the form id * @param FormsQuestionType $type the new question type - * @param FormsQuestionGridCellType $subtype the new question subtype + * @param FormsQuestionSubtype $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 diff --git a/lib/ResponseDefinitions.php b/lib/ResponseDefinitions.php index 17fac6599e..804dde2d8e 100644 --- a/lib/ResponseDefinitions.php +++ b/lib/ResponseDefinitions.php @@ -45,7 +45,7 @@ * } * * @psalm-type FormsQuestionType = "dropdown"|"multiple"|"multiple_unique"|"date"|"time"|"short"|"long"|"file"|"datetime"|"grid"|"linearscale"|"color"|"ranking" - * @psalm-type FormsQuestionGridCellType = "checkbox"|"number"|"radio" + * @psalm-type FormsQuestionSubtype = "checkbox"|"number"|"radio"|"rating" * * @psalm-type FormsQuestion = array{ * id: int, diff --git a/lib/Service/FormsService.php b/lib/Service/FormsService.php index ea64994141..b682707a34 100644 --- a/lib/Service/FormsService.php +++ b/lib/Service/FormsService.php @@ -1051,6 +1051,15 @@ public function areExtraSettingsValid(array $extraSettings, string $questionType || isset($extraSettings['optionsHighest']) && ($extraSettings['optionsHighest'] < 2 || $extraSettings['optionsHighest'] > 10)) { return false; } + + $subtype = $extraSettings['questionType'] ?? null; + if ($subtype !== null && !in_array($subtype, Constants::EXTRA_SETTINGS_LINEARSCALE_QUESTION_TYPE, true)) { + return false; + } + + if ($subtype === Constants::ANSWER_LINEARSCALE_TYPE_RATING && ($extraSettings['optionsLowest'] ?? 1) !== 1) { + return false; + } } elseif ($questionType === Constants::ANSWER_TYPE_GRID) { if (isset($extraSettings['questionType']) && !in_array($extraSettings['questionType'], Constants::EXTRA_SETTINGS_GRID_QUESTION_TYPE, true)) { diff --git a/openapi.json b/openapi.json index 4e11633cea..c67dff09fb 100644 --- a/openapi.json +++ b/openapi.json @@ -598,12 +598,13 @@ } } }, - "QuestionGridCellType": { + "QuestionSubtype": { "type": "string", "enum": [ "checkbox", "number", - "radio" + "radio", + "rating" ] }, "QuestionType": { @@ -1700,7 +1701,7 @@ "description": "the new question type" }, "subtype": { - "$ref": "#/components/schemas/QuestionGridCellType", + "$ref": "#/components/schemas/QuestionSubtype", "default": null, "description": "the new question subtype" }, diff --git a/playwright/e2e/a11y-question-inputs.spec.ts b/playwright/e2e/a11y-question-inputs.spec.ts index c32bc14f1c..4eeb6a9642 100644 --- a/playwright/e2e/a11y-question-inputs.spec.ts +++ b/playwright/e2e/a11y-question-inputs.spec.ts @@ -8,7 +8,11 @@ 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 topBarTest } from '../support/fixtures/topBar.ts' -import { GridSubtype, QuestionType } from '../support/sections/QuestionType.ts' +import { + GridSubtype, + LinearScaleSubtype, + QuestionType, +} from '../support/sections/QuestionType.ts' import { FormsView } from '../support/sections/TopBarSection.ts' const test = mergeTests(randomUserTest, appNavigationTest, formTest, topBarTest) @@ -196,7 +200,7 @@ test.describe('Accessibility: aria attributes on question inputs', () => { await appNavigation.clickNewForm() await form.fillTitle('Test form') - await form.addQuestion(QuestionType.LinearScale) + await form.addQuestion(QuestionType.LinearScale, LinearScaleSubtype.Numbers) const questions = await form.getQuestions() await questions[0].fillTitle('Rate your experience') await questions[0].fillDescription('From 1 to 5') diff --git a/playwright/e2e/question-editing.spec.ts b/playwright/e2e/question-editing.spec.ts index cfa6650ae7..fd052a8e7a 100644 --- a/playwright/e2e/question-editing.spec.ts +++ b/playwright/e2e/question-editing.spec.ts @@ -7,7 +7,10 @@ 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 { QuestionType } from '../support/sections/QuestionType.ts' +import { + LinearScaleSubtype, + QuestionType, +} from '../support/sections/QuestionType.ts' const test = mergeTests(randomUserTest, appNavigationTest, formTest) @@ -32,7 +35,12 @@ test.describe('Question editing lifecycle', () => { for (const type of questionTypes) { test(`Add a ${type} question`, async ({ form }) => { - await form.addQuestion(type) + await form.addQuestion( + type, + type === QuestionType.LinearScale + ? LinearScaleSubtype.Numbers + : undefined, + ) const questions = await form.getQuestions() expect(questions).toHaveLength(1) diff --git a/playwright/support/sections/FormSection.ts b/playwright/support/sections/FormSection.ts index ab7d3e8d0b..b2c3b8a93a 100644 --- a/playwright/support/sections/FormSection.ts +++ b/playwright/support/sections/FormSection.ts @@ -4,7 +4,11 @@ */ import type { Locator, Page } from '@playwright/test' -import type { GridSubtype, QuestionType } from './QuestionType.ts' +import type { + GridSubtype, + LinearScaleSubtype, + QuestionType, +} from './QuestionType.ts' import { waitForApiResponse } from '../helpers.ts' import { QuestionSection } from './QuestionSection.ts' @@ -43,7 +47,7 @@ export class FormSection { public async addQuestion( type: QuestionType, - subtype?: GridSubtype, + subtype?: GridSubtype | LinearScaleSubtype, ): Promise { const created = waitForApiResponse(this.page, 'POST') await this.newQuestionButton.click() diff --git a/playwright/support/sections/QuestionType.ts b/playwright/support/sections/QuestionType.ts index 1f51c8f709..5d8a57b742 100644 --- a/playwright/support/sections/QuestionType.ts +++ b/playwright/support/sections/QuestionType.ts @@ -26,3 +26,11 @@ export enum GridSubtype { Number = 'Number', RadioButtons = 'Radio buttons', } + +/** + * Labels of the entries in the linear scale subtype menu. + */ +export enum LinearScaleSubtype { + Numbers = 'Numbers', + Rating = 'Rating', +} diff --git a/src/components/AddQuestionMenu.vue b/src/components/AddQuestionMenu.vue index 854d2ef58c..0b565da640 100644 --- a/src/components/AddQuestionMenu.vue +++ b/src/components/AddQuestionMenu.vue @@ -41,18 +41,23 @@ - {{ t('forms', 'Grid') }} + {{ answerTypesFilter[activeQuestionType].label }} + @click=" + onSubtypeClick( + activeQuestionType, + answer.extraSettings.questionType ?? null, + position, + ) + "> @@ -68,7 +73,6 @@ import type { AnswerTypeConfig } from '../models/AnswerTypes.ts' import IconPlus from '@material-symbols/svg-400/outlined/add.svg?raw' import IconChevronLeft from '@material-symbols/svg-400/outlined/chevron_left.svg?raw' -import { t } from '@nextcloud/l10n' import { defineComponent, ref, watch } from 'vue' import NcActionButton from '@nextcloud/vue/components/NcActionButton' import NcActions from '@nextcloud/vue/components/NcActions' @@ -145,7 +149,7 @@ export default defineComponent({ const onSubtypeClick = ( type: string, - subtype: string | number, + subtype: string | null, position: number | null, ) => { emit('addQuestion', type, subtype, position) @@ -157,7 +161,6 @@ export default defineComponent({ openLocal, onPrimaryClick, onSubtypeClick, - t, IconChevronLeft, IconPlus, } diff --git a/src/components/Questions/QuestionLinearScale.vue b/src/components/Questions/QuestionLinearScale.vue index c08e67413e..0d1c983ab6 100644 --- a/src/components/Questions/QuestionLinearScale.vue +++ b/src/components/Questions/QuestionLinearScale.vue @@ -13,6 +13,7 @@ v-on="commonListeners"> +
+ +
import IconPencil from '@material-symbols/svg-400/outlined/edit.svg?raw' +import IconHeartFilled from '@material-symbols/svg-400/outlined/favorite-fill.svg?raw' +import IconHeart from '@material-symbols/svg-400/outlined/favorite.svg?raw' +import IconStarFilled from '@material-symbols/svg-400/outlined/star-fill.svg?raw' +import IconStar from '@material-symbols/svg-400/outlined/star.svg?raw' +import IconThumbFilled from '@material-symbols/svg-400/outlined/thumb_up-fill.svg?raw' +import IconThumb from '@material-symbols/svg-400/outlined/thumb_up.svg?raw' import { t } from '@nextcloud/l10n' import { computed, defineComponent, nextTick, onMounted, ref } from 'vue' +import NcActionCaption from '@nextcloud/vue/components/NcActionCaption' import NcActionInput from '@nextcloud/vue/components/NcActionInput' +import NcActionRadio from '@nextcloud/vue/components/NcActionRadio' import NcCheckboxRadioSwitch from '@nextcloud/vue/components/NcCheckboxRadioSwitch' import NcIconSvgWrapper from '@nextcloud/vue/components/NcIconSvgWrapper' import NcTextArea from '@nextcloud/vue/components/NcTextArea' @@ -156,14 +213,49 @@ type LinearScaleExtraSettings = { optionsLabelLowest?: string | null optionsLabelHighest?: string | null questionType?: string + ratingIcon?: string | null +} + +interface RatingIcon { + id: 'star' | 'heart' | 'thumb' + label: string + outline: string + filled: string + color: string } +const RATING_ICONS: RatingIcon[] = [ + { + id: 'star', + label: t('forms', 'Stars'), + outline: IconStar, + filled: IconStarFilled, + color: 'var(--color-element-warning)', + }, + { + id: 'heart', + label: t('forms', 'Hearts'), + outline: IconHeart, + filled: IconHeartFilled, + color: 'var(--color-element-error)', + }, + { + id: 'thumb', + label: t('forms', 'Thumbs up'), + outline: IconThumb, + filled: IconThumbFilled, + color: 'var(--color-element-info)', + }, +] + export default defineComponent({ name: 'QuestionLinearScale', components: { NcIconSvgWrapper, + NcActionCaption, NcActionInput, + NcActionRadio, NcCheckboxRadioSwitch, NcTextArea, Question, @@ -186,6 +278,15 @@ export default defineComponent({ const isRating = computed( () => extraSettings.value.questionType === LinearScaleType.Rating, ) + const ratingIcon = computed( + () => + RATING_ICONS.find( + (icon) => icon.id === extraSettings.value.ratingIcon, + ) ?? RATING_ICONS[0], + ) + const ratingValue = computed( + () => parseInt(values.value?.[0] ?? '') || 0, + ) const highestLabel = computed(() => isRating.value ? t('forms', 'Highest rating') @@ -279,7 +380,7 @@ export default defineComponent({ } onMounted(() => { - if (!props.readOnly) { + if (!props.readOnly && !isRating.value) { resizeLabel('lowest') resizeLabel('highest') } @@ -300,6 +401,15 @@ export default defineComponent({ const onChange = (option: string): void => { emit('update:values', [option]) + if (isRating.value) { + question.errorMessage.value = null + } + } + + const onRatingIconChange = (icon: RatingIcon['id']): void => { + question.onExtraSettingsChange({ + ratingIcon: icon === RATING_ICONS[0].id ? null : icon, + }) } const onOptionsLowestChange = (value: number): void => { @@ -355,6 +465,10 @@ export default defineComponent({ optionsLabelHighest, isRating, highestLabel, + ratingIcon, + ratingIcons: RATING_ICONS, + ratingValue, + onRatingIconChange, validate, onChange, onOptionsLowestChange, @@ -369,6 +483,64 @@ export default defineComponent({ From af8d27f0d9aa068d7aaccf04dc0dcf07d045fa3f Mon Sep 17 00:00:00 2001 From: global-prog Date: Sat, 21 Nov 2026 16:53:41 +0100 Subject: [PATCH 11/12] feat(results): show the promoter score for the promoter sub type A promoter score question splits respondents into promoters (9-10), passives (7-8) and detractors (0-6). The summary of such a question now adds the promoter score, the share of promoters minus the share of detractors, together with both shares. The score is rounded from the exact difference rather than computed from the rounded shares, which can be one point off (4 promoters and 2 detractors out of 7 give 29, not 28). Plain scales, including plain 0-10 scales, show no score. Based on the original implementation by global-prog, reworked by Andy Scherzinger. Signed-off-by: global-prog Assisted-by: ClaudeCode:claude-opus-5-5 Signed-off-by: Andy Scherzinger --- src/components/Results/ResultsSummary.vue | 62 +++++++++++++++++++++++ 1 file changed, 62 insertions(+) diff --git a/src/components/Results/ResultsSummary.vue b/src/components/Results/ResultsSummary.vue index a135319be9..93dae68d3a 100644 --- a/src/components/Results/ResultsSummary.vue +++ b/src/components/Results/ResultsSummary.vue @@ -36,6 +36,18 @@
{{ t('forms', 'Maximum') }}
{{ formatCount(numericStats.max) }}
+
+
{{ t('forms', 'Promoter score (promoters − detractors)') }}
+
{{ formatCount(promoterBreakdown.score) }}
+
+ {{ + formatPromoterShares( + promoterBreakdown.promoters, + promoterBreakdown.detractors, + ) + }} +
+
@@ -236,6 +248,20 @@ function formatPercent(percentage: number): string { return percent.format(percentage / 100) } +/** + * The shares of promoters and detractors as text, e.g. "50% promoters, 25% detractors" + * + * @param promoters the share of promoters in percent + * @param detractors the share of detractors in percent + */ +function formatPromoterShares(promoters: number, detractors: number): string { + // TRANSLATORS {promoters} and {detractors} are percentages, e.g. "50% promoters, 25% detractors" + return t('forms', '{promoters} promoters, {detractors} detractors', { + promoters: formatPercent(promoters), + detractors: formatPercent(detractors), + }) +} + export default defineComponent({ name: 'ResultsSummary', @@ -770,10 +796,39 @@ export default defineComponent({ } }) + /** + * Promoter and detractor shares in percent and the promoter score, the difference of + * the two, using the 9-10 / 7-8 / 0-6 split. Null unless the question has the promoter + * sub type and answers. + */ + const promoterBreakdown = computed(() => { + if ( + props.question.extraSettings?.questionType + !== LinearScaleType.Promoter + ) { + return null + } + const values = numericValues.value + if (values.length === 0) { + return null + } + const promoters = values.filter((value) => value >= 9).length + const detractors = values.filter((value) => value <= 6).length + const share = (count: number) => + Math.sign(count) + * Math.round((Math.abs(count) * 100) / values.length) || 0 + return { + promoters: share(promoters), + detractors: share(detractors), + score: share(promoters - detractors), + } + }) + return { IconFile, answerTypes, numericStats, + promoterBreakdown, questionTypeLabel, averageRating, questionOptions, @@ -785,6 +840,7 @@ export default defineComponent({ answers, formatCount, formatPercent, + formatPromoterShares, oneDecimal, t, } @@ -961,5 +1017,11 @@ export default defineComponent({ font-size: 1.2em; font-weight: bold; } + + dd.question-summary__figures-detail { + color: var(--color-text-maxcontrast); + font-size: 0.9em; + font-weight: normal; + } } From b920b9e637a8471e5bb320b644403df47e62aaee Mon Sep 17 00:00:00 2001 From: Andy Scherzinger Date: Sat, 21 Nov 2026 16:24:59 +0100 Subject: [PATCH 12/12] test(results): cover the scale figures and the promoter score The figures and the promoter score are computed in the frontend only, which has no unit tests, so end-to-end tests are their only coverage. They check the figures above the bars of a scale question, the promoter score of the promoter sub type, its absence on a plain 0-10 scale, the absence of the figures on a rating, and the questions the add-question menu creates for the "Promoter score" and "Numbers" entries, including the default labels of a promoter score question. Assisted-by: ClaudeCode:claude-opus-5-5 Signed-off-by: Andy Scherzinger --- playwright/e2e/results-scale-figures.spec.ts | 187 +++++++++++++++++++ 1 file changed, 187 insertions(+) create mode 100644 playwright/e2e/results-scale-figures.spec.ts diff --git a/playwright/e2e/results-scale-figures.spec.ts b/playwright/e2e/results-scale-figures.spec.ts new file mode 100644 index 0000000000..b6a386f525 --- /dev/null +++ b/playwright/e2e/results-scale-figures.spec.ts @@ -0,0 +1,187 @@ +/** + * SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors + * 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 resultsTest } from '../support/fixtures/results.ts' +import { api, waitForApiResponse } from '../support/helpers.ts' +import { + LinearScaleSubtype, + QuestionType, +} from '../support/sections/QuestionType.ts' + +const test = mergeTests(randomUserTest, appNavigationTest, formTest, resultsTest) + +/** + * Create a form with the linear scale "Recommend" and one submission per answer + * + * @param request the request context of the page + * @param subtype the sub type of the scale, or null for a plain scale + * @param extraSettings further extra settings of the scale + * @param answers the answers to submit, one submission each + */ +async function createScaleForm( + request: APIRequestContext, + subtype: string | null, + extraSettings: Record, + answers: string[] = [], +) { + const form = await api(request, 'POST', '/forms') + await api(request, 'PATCH', `/forms/${form.id}`, { + keyValuePairs: { submitMultiple: true }, + }) + const scale = await api(request, 'POST', `/forms/${form.id}/questions`, { + type: 'linearscale', + subtype, + text: 'Recommend', + }) + if (Object.keys(extraSettings).length > 0) { + await api(request, 'PATCH', `/forms/${form.id}/questions/${scale.id}`, { + keyValuePairs: { + extraSettings: { ...scale.extraSettings, ...extraSettings }, + }, + }) + } + for (const answer of answers) { + await api(request, 'POST', `/forms/${form.id}/submissions`, { + answers: { [scale.id]: [answer] }, + }) + } + return form +} + +test('Scale figures and the promoter score are shown above the bars', async ({ + page, + resultsView, +}) => { + const form = await createScaleForm(page.request, 'promoter', {}, [ + '10', + '9', + '7', + '3', + ]) + await page.goto(`apps/forms/${form.hash}/results`) + await page.waitForURL(/\/results\/summary$/) + + const summary = resultsView.getSummaryForQuestion('Recommend') + await expect( + summary.getByText( + 'Linear scale (0: Not at all likely, 10: Extremely likely)', + { exact: true }, + ), + ).toBeVisible() + const figure = (label: string) => summary.locator(`dt:text-is("${label}") + dd`) + await expect(figure('Answers')).toHaveText('4') + await expect(figure('Average')).toHaveText('7.3') + await expect(figure('Median')).toHaveText('8') + await expect(figure('Minimum')).toHaveText('3') + await expect(figure('Maximum')).toHaveText('10') + await expect(figure('Promoter score (promoters − detractors)')).toHaveText('25') + await expect(summary.getByText('50% promoters, 25% detractors')).toBeVisible() + await expect(summary.locator('dl + ol meter')).not.toHaveCount(0) +}) + +test('A plain 0 to 10 scale shows no promoter score', async ({ + page, + resultsView, +}) => { + const form = await createScaleForm( + page.request, + null, + { optionsLowest: 0, optionsHighest: 10 }, + ['10', '3'], + ) + await page.goto(`apps/forms/${form.hash}/results`) + await page.waitForURL(/\/results\/summary$/) + + const summary = resultsView.getSummaryForQuestion('Recommend') + await expect(summary.locator('dt:text-is("Average") + dd')).toHaveText('6.5') + await expect(summary.getByText(/Promoter score/)).toHaveCount(0) +}) + +test('A rating shows its average rating and no scale figures', async ({ + page, + resultsView, +}) => { + const form = await createScaleForm(page.request, 'rating', {}, ['5', '4']) + await page.goto(`apps/forms/${form.hash}/results`) + await page.waitForURL(/\/results\/summary$/) + + const summary = resultsView.getSummaryForQuestion('Recommend') + await expect( + summary.getByText('Average rating 4.5 of 5, from 2 ratings'), + ).toBeVisible() + await expect(summary.locator('dl')).toHaveCount(0) + await expect(summary.getByText(/Promoter score/)).toHaveCount(0) +}) + +test('A promoter score question from the menu is a fixed 0 to 10 scale', async ({ + page, + appNavigation, + form, +}) => { + await page.goto('apps/forms') + await appNavigation.clickNewForm() + await form.fillTitle('Promoter form') + + const created = waitForApiResponse(page, 'POST') + await form.addQuestion(QuestionType.LinearScale, LinearScaleSubtype.Promoter) + const response = await created + expect(response.request().postDataJSON()).toMatchObject({ + type: 'linearscale', + subtype: 'promoter', + }) + expect((await response.json()).ocs.data.extraSettings).toEqual({ + questionType: 'promoter', + optionsLowest: 0, + optionsHighest: 10, + }) + + const [question] = await form.getQuestions() + await expect(question.section.getByRole('radio')).toHaveCount(11) + await expect(question.section.getByRole('radio').first()).toHaveAccessibleName( + '0', + ) + await expect(question.section.getByRole('radio').last()).toHaveAccessibleName( + '10', + ) + await expect( + question.section.getByRole('textbox', { name: 'Label for lowest value' }), + ).toHaveValue('Not at all likely') + await expect( + question.section.getByRole('textbox', { name: 'Label for highest value' }), + ).toHaveValue('Extremely likely') + + await question.openActionsMenu() + await expect(page.getByRole('checkbox', { name: 'Required' })).toBeVisible() + await expect(page.getByRole('combobox', { name: 'Lowest value' })).toHaveCount(0) + await expect(page.getByRole('combobox', { name: 'Highest value' })).toHaveCount( + 0, + ) +}) + +test('A numbers question from the menu has no sub type', async ({ + page, + appNavigation, + form, +}) => { + await page.goto('apps/forms') + await appNavigation.clickNewForm() + await form.fillTitle('Numbers form') + + const created = waitForApiResponse(page, 'POST') + await form.addQuestion(QuestionType.LinearScale, LinearScaleSubtype.Numbers) + const response = await created + expect(response.request().postDataJSON().subtype).toBeNull() + expect((await response.json()).ocs.data.extraSettings).toEqual({}) + + const [question] = await form.getQuestions() + await question.openActionsMenu() + await expect(page.getByRole('combobox', { name: 'Lowest value' })).toBeVisible() +})