diff --git a/docs/API_v3.md b/docs/API_v3.md index 7ad999c5f..645211cfd 100644 --- a/docs/API_v3.md +++ b/docs/API_v3.md @@ -547,7 +547,8 @@ Contains only manipulative question-endpoints. To retrieve options, request the | Parameter | Type | Optional | Description | |-----------|---------|----------|-------------| | _optionTexts_ | Array | | Array of strings containing the new options | - | _optionType_ | [Option Types](DataStructure.md#Option-Types) | yes | The option-type to assign to the new options (e.g. `row`). | + | _optionType_ | [Option Types](DataStructure.md#Option-Types) | yes | The option-type to assign to the new options (e.g. `row`). Defaults to `choice`. | +- Restrictions: Options can only be added to `dropdown`, `multiple`, `multiple_unique` and `ranking` questions, with option type `choice`, and to `grid` questions, with option type `row` or `column`. Any other question type or option type is rejected with **400 Bad Request**. - Response: The new array of option objects ``` diff --git a/docs/DataStructure.md b/docs/DataStructure.md index d0e9acfa3..7d861565d 100644 --- a/docs/DataStructure.md +++ b/docs/DataStructure.md @@ -277,7 +277,7 @@ Supported option types and their intended usage. | Type-ID | Description | | -------- | ------------------------------------------------------------------------------------------ | -| `choice` | Standard selectable option used by `dropdown`, `multiple` and `multiple_unique` questions. | +| `choice` | Standard selectable option used by `dropdown`, `multiple`, `multiple_unique` and `ranking` questions. | | `row` | Represents a row header when rendering options in a grid-style question. | | `column` | Represents a column header when rendering options in a grid-style question. | diff --git a/lib/Constants.php b/lib/Constants.php index 3e465cd0c..0766c108a 100644 --- a/lib/Constants.php +++ b/lib/Constants.php @@ -118,6 +118,22 @@ class Constants { public const ANSWER_GRID_TYPE_NUMBER = 'number'; public const ANSWER_GRID_TYPE_RADIO = 'radio'; + // Option types + public const OPTION_TYPE_CHOICE = 'choice'; + public const OPTION_TYPE_ROW = 'row'; + public const OPTION_TYPE_COLUMN = 'column'; + + /** + * The option types each question type takes; question types not listed take no options + */ + public const OPTION_TYPES_PER_ANSWER_TYPE = [ + self::ANSWER_TYPE_DROPDOWN => [self::OPTION_TYPE_CHOICE], + self::ANSWER_TYPE_MULTIPLE => [self::OPTION_TYPE_CHOICE], + self::ANSWER_TYPE_MULTIPLEUNIQUE => [self::OPTION_TYPE_CHOICE], + self::ANSWER_TYPE_RANKING => [self::OPTION_TYPE_CHOICE], + self::ANSWER_TYPE_GRID => [self::OPTION_TYPE_ROW, self::OPTION_TYPE_COLUMN], + ]; + // All AnswerTypes public const ANSWER_TYPES = [ self::ANSWER_TYPE_COLOR, diff --git a/lib/Controller/ApiController.php b/lib/Controller/ApiController.php index 8501a30bc..4c5258287 100644 --- a/lib/Controller/ApiController.php +++ b/lib/Controller/ApiController.php @@ -971,6 +971,8 @@ public function reorderQuestions(int $formId, array $newOrder): DataResponse { * @param string|null $optionType the new option type (e.g. 'row'), defaults to 'choice' * @return DataResponse, array{}> Returns a DataResponse containing the added options * @throws OCSBadRequestException This question is not part ot the given form + * @throws OCSBadRequestException This question type takes no options + * @throws OCSBadRequestException Invalid option type for this question * @throws OCSForbiddenException This form is archived and can not be modified * @throws OCSForbiddenException Current user has no permission to edit * @throws OCSNotFoundException Could not find form @@ -1016,6 +1018,18 @@ public function newOption(int $formId, int $questionId, array $optionTexts, ?str throw new OCSNotFoundException('Could not find question'); } + $allowedOptionTypes = Constants::OPTION_TYPES_PER_ANSWER_TYPE[$question->getType()] ?? []; + if ($allowedOptionTypes === []) { + $this->logger->debug('This question type takes no options'); + throw new OCSBadRequestException('This question type takes no options'); + } + + $optionType ??= Constants::OPTION_TYPE_CHOICE; + if (!in_array($optionType, $allowedOptionTypes, true)) { + $this->logger->debug('Invalid option type for this question'); + throw new OCSBadRequestException('Invalid option type for this question'); + } + // Retrieve all options sorted by 'order'. Takes the order of the last array-element and adds one. $options = $this->optionMapper->findByQuestion($questionId, $optionType); $lastOption = array_pop($options); diff --git a/lib/Db/Option.php b/lib/Db/Option.php index c36b04f76..ad6e2ba66 100644 --- a/lib/Db/Option.php +++ b/lib/Db/Option.php @@ -31,9 +31,6 @@ class Option extends Entity { protected ?int $order; protected ?string $optionType; - public const OPTION_TYPE_ROW = 'row'; - public const OPTION_TYPE_COLUMN = 'column'; - /** * Option constructor. */ diff --git a/lib/Service/SubmissionService.php b/lib/Service/SubmissionService.php index 78e4a6437..60fe14ae1 100644 --- a/lib/Service/SubmissionService.php +++ b/lib/Service/SubmissionService.php @@ -13,7 +13,6 @@ use OCA\Forms\Db\Answer; use OCA\Forms\Db\AnswerMapper; use OCA\Forms\Db\Form; -use OCA\Forms\Db\Option; use OCA\Forms\Db\OptionMapper; use OCA\Forms\Db\Question; use OCA\Forms\Db\QuestionMapper; @@ -301,10 +300,10 @@ public function getSubmissionsData(Form $form, string $fileFormat, ?File $file = foreach ($options as $option) { $optionPerOptionId[$option->getId()] = $option; - if ($option->getOptionType() === Option::OPTION_TYPE_ROW) { + if ($option->getOptionType() === Constants::OPTION_TYPE_ROW) { $gridRowsPerQuestionId[$question->getId()][] = $option->getId(); } - if ($option->getOptionType() === Option::OPTION_TYPE_COLUMN) { + if ($option->getOptionType() === Constants::OPTION_TYPE_COLUMN) { $gridColumnsPerQuestionId[$question->getId()][] = $option->getId(); } } @@ -607,7 +606,7 @@ private static function isShownToRespondents(array $question): bool { $optionTypes = array_map(static fn (mixed $option): mixed => is_array($option) ? ($option['optionType'] ?? null) : null, $question['options'] ?? []); return match ($question['type'] ?? null) { Constants::ANSWER_TYPE_MULTIPLE, Constants::ANSWER_TYPE_MULTIPLEUNIQUE, Constants::ANSWER_TYPE_DROPDOWN, Constants::ANSWER_TYPE_RANKING => $optionTypes !== [], - Constants::ANSWER_TYPE_GRID => in_array(Option::OPTION_TYPE_ROW, $optionTypes, true) && in_array(Option::OPTION_TYPE_COLUMN, $optionTypes, true), + Constants::ANSWER_TYPE_GRID => in_array(Constants::OPTION_TYPE_ROW, $optionTypes, true) && in_array(Constants::OPTION_TYPE_COLUMN, $optionTypes, true), default => true, }; } @@ -884,8 +883,8 @@ private function validateShortQuestion(array $question, string $data): bool { } private function validateGridQuestion(array $question, array $answers): void { - $rowIds = $this->normalizeOptionIds($question['options'] ?? [], Option::OPTION_TYPE_ROW); - $columnIds = $this->normalizeOptionIds($question['options'] ?? [], Option::OPTION_TYPE_COLUMN); + $rowIds = $this->normalizeOptionIds($question['options'] ?? [], Constants::OPTION_TYPE_ROW); + $columnIds = $this->normalizeOptionIds($question['options'] ?? [], Constants::OPTION_TYPE_COLUMN); $gridType = $question['extraSettings']['questionType'] ?? null; foreach ($answers as $rowId => $rowAnswer) { diff --git a/openapi.json b/openapi.json index 4e11633ce..45ef51791 100644 --- a/openapi.json +++ b/openapi.json @@ -2802,7 +2802,7 @@ } }, "400": { - "description": "This question is not part ot the given form", + "description": "Invalid option type for this question", "content": { "application/json": { "schema": { diff --git a/tests/Integration/Api/ApiV3Test.php b/tests/Integration/Api/ApiV3Test.php index dd8f87dc7..0a9483cb8 100644 --- a/tests/Integration/Api/ApiV3Test.php +++ b/tests/Integration/Api/ApiV3Test.php @@ -1127,6 +1127,22 @@ public function testCreateNewOption(array $expected): void { $this->assertEquals($expected, $data); } + public function testCreateNewOptionRejectsQuestionWithoutOptions(): void { + $formId = $this->testForms[0]['id']; + $questionId = $this->testForms[0]['questions'][0]['id']; + $resp = $this->http->request('POST', "api/v3/forms/{$formId}/questions/{$questionId}/options", [ + 'json' => [ + 'optionTexts' => ['Coffee', 'Tea'], + ], + 'http_errors' => false, + ]); + + $this->assertEquals(400, $resp->getStatusCode()); + + $question = $this->OcsResponse2Data($this->http->request('GET', "api/v3/forms/{$formId}/questions/{$questionId}")); + $this->assertSame([], $question['options']); + } + public static function dataUpdateOptionProperties() { $fullFormExpected = self::dataGetFullForm()['getFullForm']['expected']; $fullFormExpected['questions'][1]['options'][0]['text'] = 'New option Text.'; diff --git a/tests/Unit/Controller/ApiControllerTest.php b/tests/Unit/Controller/ApiControllerTest.php index 81fdf8bf0..62d1b381c 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; @@ -1418,6 +1419,59 @@ public function testChangeDeletedQuestion(string $method, array $arguments): voi $this->apiController->$method(...$arguments); } + public static function dataNewOptionOptionType(): array { + return [ + 'short text' => [Constants::ANSWER_TYPE_SHORT, 'choice', false], + 'long text' => [Constants::ANSWER_TYPE_LONG, 'choice', false], + 'date' => [Constants::ANSWER_TYPE_DATE, 'choice', false], + 'file' => [Constants::ANSWER_TYPE_FILE, 'choice', false], + 'linear scale' => [Constants::ANSWER_TYPE_LINEARSCALE, 'choice', false], + 'dropdown with a row' => [Constants::ANSWER_TYPE_DROPDOWN, 'row', false], + 'grid with a choice' => [Constants::ANSWER_TYPE_GRID, 'choice', false], + 'grid without option type' => [Constants::ANSWER_TYPE_GRID, null, false], + 'dropdown' => [Constants::ANSWER_TYPE_DROPDOWN, 'choice', true], + 'dropdown without option type' => [Constants::ANSWER_TYPE_DROPDOWN, null, true], + 'checkboxes' => [Constants::ANSWER_TYPE_MULTIPLE, 'choice', true], + 'radio buttons' => [Constants::ANSWER_TYPE_MULTIPLEUNIQUE, 'choice', true], + 'ranking' => [Constants::ANSWER_TYPE_RANKING, 'choice', true], + 'grid row' => [Constants::ANSWER_TYPE_GRID, 'row', true], + 'grid column' => [Constants::ANSWER_TYPE_GRID, 'column', true], + ]; + } + + /** + * @dataProvider dataNewOptionOptionType + */ + public function testNewOptionOptionType(string $questionType, ?string $optionType, bool $allowed): void { + $form = new Form(); + $form->setId(1); + $form->setOwnerId('currentUser'); + + $question = new Question(); + $question->setId(7); + $question->setFormId(1); + $question->setOrder(1); + $question->setType($questionType); + + $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->optionMapper->method('findByQuestion')->willReturn([]); + + if (!$allowed) { + $this->optionMapper->expects($this->never())->method('insert'); + $this->expectException(OCSBadRequestException::class); + } else { + $this->optionMapper->expects($this->once()) + ->method('insert') + ->with($this->callback(fn (Option $option): bool => $option->getOptionType() === ($optionType ?? Constants::OPTION_TYPE_CHOICE))) + ->willReturnArgument(0); + } + + $response = $this->apiController->newOption(1, 7, ['Coffee'], $optionType); + $this->assertSame(Http::STATUS_CREATED, $response->getStatus()); + } + public function testUpdateQuestionRejectsTypeChange(): void { $form = new Form(); $form->setId(1);