Skip to content
Open
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
3 changes: 2 additions & 1 deletion docs/API_v3.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

```
Expand Down
2 changes: 1 addition & 1 deletion docs/DataStructure.md
Original file line number Diff line number Diff line change
Expand Up @@ -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. |

Expand Down
16 changes: 16 additions & 0 deletions lib/Constants.php
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
14 changes: 14 additions & 0 deletions lib/Controller/ApiController.php
Original file line number Diff line number Diff line change
Expand Up @@ -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<Http::STATUS_CREATED, list<FormsOption>, 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
Expand Down Expand Up @@ -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);
Expand Down
3 changes: 0 additions & 3 deletions lib/Db/Option.php
Original file line number Diff line number Diff line change
Expand Up @@ -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.
*/
Expand Down
11 changes: 5 additions & 6 deletions lib/Service/SubmissionService.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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();
}
}
Expand Down Expand Up @@ -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,
};
}
Expand Down Expand Up @@ -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) {
Expand Down
2 changes: 1 addition & 1 deletion openapi.json
Original file line number Diff line number Diff line change
Expand Up @@ -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": {
Expand Down
16 changes: 16 additions & 0 deletions tests/Integration/Api/ApiV3Test.php
Original file line number Diff line number Diff line change
Expand Up @@ -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.';
Expand Down
54 changes: 54 additions & 0 deletions tests/Unit/Controller/ApiControllerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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);
Expand Down
Loading