feat: allow question type definitions in multiple groups via group_ids
Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
parent
527ee238dd
commit
fd4397dcd9
|
|
@ -0,0 +1,19 @@
|
|||
ALTER TABLE question_type_definitions
|
||||
ADD COLUMN IF NOT EXISTS group_id BIGINT NULL
|
||||
REFERENCES question_type_definition_groups(id) ON DELETE SET NULL;
|
||||
|
||||
UPDATE question_type_definitions d
|
||||
SET group_id = m.group_id
|
||||
FROM (
|
||||
SELECT DISTINCT ON (definition_id) definition_id, group_id
|
||||
FROM question_type_definition_group_members
|
||||
ORDER BY definition_id, group_id
|
||||
) m
|
||||
WHERE d.id = m.definition_id;
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_question_type_definitions_group_id
|
||||
ON question_type_definitions(group_id);
|
||||
|
||||
DROP INDEX IF EXISTS idx_question_type_definition_group_members_group_id;
|
||||
|
||||
DROP TABLE IF EXISTS question_type_definition_group_members;
|
||||
|
|
@ -0,0 +1,22 @@
|
|||
CREATE TABLE IF NOT EXISTS question_type_definition_group_members (
|
||||
definition_id BIGINT NOT NULL
|
||||
REFERENCES question_type_definitions(id) ON DELETE CASCADE,
|
||||
group_id BIGINT NOT NULL
|
||||
REFERENCES question_type_definition_groups(id) ON DELETE CASCADE,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
PRIMARY KEY (definition_id, group_id)
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_question_type_definition_group_members_group_id
|
||||
ON question_type_definition_group_members(group_id);
|
||||
|
||||
INSERT INTO question_type_definition_group_members (definition_id, group_id)
|
||||
SELECT id, group_id
|
||||
FROM question_type_definitions
|
||||
WHERE group_id IS NOT NULL
|
||||
ON CONFLICT DO NOTHING;
|
||||
|
||||
DROP INDEX IF EXISTS idx_question_type_definitions_group_id;
|
||||
|
||||
ALTER TABLE question_type_definitions
|
||||
DROP COLUMN IF EXISTS group_id;
|
||||
|
|
@ -1,12 +1,12 @@
|
|||
# Question Type Definition Groups — Admin Panel Integration Guide
|
||||
|
||||
This guide explains how the admin panel should integrate **grouping for dynamic question type definitions**. Groups are named containers; each definition may optionally reference one group via nullable `group_id`.
|
||||
This guide explains how the admin panel should integrate **grouping for dynamic question type definitions**. Groups are named containers; each definition may belong to **zero or more** groups via nullable `group_ids`.
|
||||
|
||||
> **Scope:** LMS dynamic question-type builder (`/api/v1/questions/type-definitions` and `/api/v1/questions/type-definition-groups`).
|
||||
>
|
||||
> **Backend migration:** `000090_question_type_definition_groups` (run before using these APIs in an environment).
|
||||
> **Backend migrations:** `000090_question_type_definition_groups`, then `000091_question_type_definition_group_members` (many-to-many junction table).
|
||||
>
|
||||
> **Related:** Existing type-definition create/list/update flows are unchanged except for the new optional `group_id` field and `group_id` list filter.
|
||||
> **Related:** Existing type-definition create/list/update flows are unchanged except for the optional `group_ids` field and `group_id` list filter.
|
||||
|
||||
---
|
||||
|
||||
|
|
@ -35,13 +35,13 @@ This guide explains how the admin panel should integrate **grouping for dynamic
|
|||
| Topic | Behavior |
|
||||
|-------|----------|
|
||||
| Group entity | Named bucket with optional description, `display_order`, `status` |
|
||||
| Definition → group link | Nullable `group_id` on each question type definition |
|
||||
| Unlinked definition | `group_id` is JSON **`null`** (not `0`, not omitted in responses) |
|
||||
| Assign on create | Optional `group_id` in `POST /questions/type-definitions` |
|
||||
| Reassign / detach on update | `PUT /questions/type-definitions/:id` with `group_id` number or `null` |
|
||||
| List definitions in a group | `GET /questions/type-definitions?group_id=<id>` |
|
||||
| Definition → group link | Many-to-many via `question_type_definition_group_members` |
|
||||
| Response field | `group_ids` — JSON **`null`** when ungrouped, or `[1, 2, …]` when linked |
|
||||
| Assign on create | Optional `group_ids` array in `POST /questions/type-definitions` |
|
||||
| Replace memberships on update | `PUT /questions/type-definitions/:id` with `group_ids` array or `null` |
|
||||
| List definitions in a group | `GET /questions/type-definitions?group_id=<id>` (definitions in **any** matching membership) |
|
||||
| Group detail with definitions | `GET /questions/type-definition-groups/:id` → embeds `definitions[]` |
|
||||
| Delete group | Definitions are **not** deleted; their `group_id` becomes `null` |
|
||||
| Delete group | Definitions are **not** deleted; only that group's memberships are removed |
|
||||
| Permissions | Reuses existing `questions.*` permissions (no new RBAC keys) |
|
||||
|
||||
Groups help the admin panel organize the type-definition catalog (e.g. “Speaking”, “Reading”, “Grammar”) without changing how questions reference definitions (`question_type_definition_id` on questions is unchanged).
|
||||
|
|
@ -52,49 +52,33 @@ Groups help the admin panel organize the type-definition catalog (e.g. “Speaki
|
|||
|
||||
```mermaid
|
||||
erDiagram
|
||||
question_type_definition_groups ||--o{ question_type_definitions : "group_id (nullable FK)"
|
||||
question_type_definition_groups ||--o{ question_type_definition_group_members : has
|
||||
question_type_definitions ||--o{ question_type_definition_group_members : has
|
||||
question_type_definition_groups {
|
||||
bigint id PK
|
||||
varchar name
|
||||
text description
|
||||
int display_order
|
||||
varchar status
|
||||
timestamptz created_at
|
||||
timestamptz updated_at
|
||||
}
|
||||
question_type_definition_group_members {
|
||||
bigint definition_id PK,FK
|
||||
bigint group_id PK,FK
|
||||
}
|
||||
question_type_definitions {
|
||||
bigint id PK
|
||||
varchar key UK
|
||||
varchar display_name
|
||||
bigint group_id FK "nullable"
|
||||
text_array stimulus_component_kinds
|
||||
text_array response_component_kinds
|
||||
jsonb stimulus_schema
|
||||
jsonb response_schema
|
||||
boolean is_system
|
||||
varchar status
|
||||
}
|
||||
```
|
||||
|
||||
### Group (`question_type_definition_groups`)
|
||||
|
||||
| Field | Type | Notes |
|
||||
|-------|------|-------|
|
||||
| `id` | int64 | Primary key |
|
||||
| `name` | string | Required on create; shown in admin navigation |
|
||||
| `description` | string \| null | Optional |
|
||||
| `display_order` | int32 | Default `0`; list sorted by `display_order ASC`, then `name ASC` |
|
||||
| `status` | `"ACTIVE"` \| `"INACTIVE"` | Default `ACTIVE` |
|
||||
| `created_at` | ISO timestamp | |
|
||||
| `updated_at` | ISO timestamp \| omitted when null | |
|
||||
|
||||
### Definition link
|
||||
### Definition group memberships
|
||||
|
||||
| Field | On create | On update | In responses |
|
||||
|-------|-----------|-----------|----------------|
|
||||
| `group_id` | Optional; omit or `null` = ungrouped | Omit = no change; `null` = detach; positive int = assign | Always present as `group_id`; `null` when ungrouped |
|
||||
| `group_ids` | Optional array; omit or `[]` or `null` = ungrouped | Omit = no change; `null` or `[]` = detach from all groups; `[1,2]` = **replace** all memberships | Always `group_ids`; `null` when none, else sorted unique ids |
|
||||
|
||||
**Cardinality:** Each definition belongs to **at most one** group. To “move” a definition, update its `group_id`.
|
||||
**Cardinality:** Each definition can belong to **many** groups. The same definition may appear when listing multiple groups. Updating `group_ids` **replaces** the full membership set (same pattern as practice `parents`).
|
||||
|
||||
---
|
||||
|
||||
|
|
@ -102,13 +86,15 @@ erDiagram
|
|||
|
||||
| Scenario | Approach |
|
||||
|----------|----------|
|
||||
| Organize builder catalog by subject/skill | Create groups; assign definitions on create or edit |
|
||||
| “Ungrouped” / legacy definitions | Leave `group_id` null (system seeded types start ungrouped) |
|
||||
| Organize builder catalog by subject/skill | Create groups; assign one or more `group_ids` on create or edit |
|
||||
| “Ungrouped” definitions | Omit `group_ids`, send `null`, or `[]` |
|
||||
| Definition in multiple sections | `group_ids: [1, 3, 5]` on create/update |
|
||||
| Group management screen | CRUD on `/questions/type-definition-groups` |
|
||||
| Group detail / drill-down | `GET /questions/type-definition-groups/:id` (includes definitions) |
|
||||
| Filtered definition picker | `GET /questions/type-definitions?group_id=:id` |
|
||||
| Move definition to another group | `PUT /questions/type-definitions/:id` `{ "group_id": 2 }` |
|
||||
| Remove from group without deleting definition | `PUT /questions/type-definitions/:id` `{ "group_id": null }` |
|
||||
| Add to another group without removing others | Read current ids, append, `PUT` with merged array |
|
||||
| Remove from one group only | Read current ids, filter out, `PUT` with remaining array |
|
||||
| Remove from all groups | `PUT` with `"group_ids": null` or `[]` |
|
||||
| Retire a group label | `DELETE /questions/type-definition-groups/:id` or set `status: INACTIVE` |
|
||||
|
||||
---
|
||||
|
|
@ -125,25 +111,25 @@ sequenceDiagram
|
|||
UI->>API: POST /questions/type-definition-groups { name }
|
||||
API-->>UI: 201 { id: 1, name, ... }
|
||||
|
||||
UI->>API: POST /questions/type-definitions { key, display_name, group_id: 1, ... }
|
||||
API-->>UI: 201 { ID, group_id: 1, ... }
|
||||
UI->>API: POST /questions/type-definitions { key, display_name, group_ids: [1, 3], ... }
|
||||
API-->>UI: 201 { ID, group_ids: [1, 3], ... }
|
||||
|
||||
UI->>API: GET /questions/type-definition-groups/1
|
||||
API-->>UI: 200 { id, name, definitions: [...] }
|
||||
```
|
||||
|
||||
### Flow B — Assign existing ungrouped definition to a group
|
||||
### Flow B — Add existing definition to more groups
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant UI as Admin panel
|
||||
participant API as Yimaru API
|
||||
|
||||
UI->>API: GET /questions/type-definitions?group_id=1
|
||||
API-->>UI: 200 { question_type_definitions: [...] }
|
||||
UI->>API: GET /questions/type-definitions/42
|
||||
API-->>UI: 200 { ID: 42, group_ids: [1], ... }
|
||||
|
||||
Note over UI,API: User picks ungrouped definition id 42
|
||||
UI->>API: PUT /questions/type-definitions/42 { group_id: 1 }
|
||||
Note over UI,API: User selects groups 1 and 3
|
||||
UI->>API: PUT /questions/type-definitions/42 { group_ids: [1, 3] }
|
||||
API-->>UI: 200 { id: 42 }
|
||||
```
|
||||
|
||||
|
|
@ -151,7 +137,7 @@ sequenceDiagram
|
|||
|
||||
1. `GET /questions/type-definition-groups?status=ACTIVE&limit=200`
|
||||
2. For each group: `GET /questions/type-definitions?group_id=<id>&include_system=true`
|
||||
3. Optionally one call `GET /questions/type-definitions` without `group_id` and partition client-side where `group_id === null` → “Ungrouped”
|
||||
3. Optionally one call `GET /questions/type-definitions` without `group_id` and partition client-side where `group_ids == null` → “Ungrouped”
|
||||
|
||||
**Prefer Flow A’s group detail endpoint** when you need group metadata + definitions in one round trip.
|
||||
|
||||
|
|
@ -174,8 +160,8 @@ Content-Type: application/json
|
|||
| Update group | `questions.update` | `PUT /api/v1/questions/type-definition-groups/:id` |
|
||||
| Delete group | `questions.delete` | `DELETE /api/v1/questions/type-definition-groups/:id` |
|
||||
| List definitions (incl. by group) | `questions.list` | `GET /api/v1/questions/type-definitions` |
|
||||
| Create definition (with `group_id`) | `questions.create` | `POST /api/v1/questions/type-definitions` |
|
||||
| Update definition `group_id` | `questions.update` | `PUT /api/v1/questions/type-definitions/:id` |
|
||||
| Create definition (with `group_ids`) | `questions.create` | `POST /api/v1/questions/type-definitions` |
|
||||
| Update definition `group_ids` | `questions.update` | `PUT /api/v1/questions/type-definitions/:id` |
|
||||
|
||||
---
|
||||
|
||||
|
|
@ -276,7 +262,7 @@ GET /api/v1/questions/type-definition-groups?status=ACTIVE&limit=20&offset=0
|
|||
GET /api/v1/questions/type-definition-groups/1
|
||||
```
|
||||
|
||||
Returns the group row plus all definitions where `group_id = 1` (includes system definitions in that group). Definitions are ordered like the global list: system types first, then by display name.
|
||||
Returns the group row plus all definitions linked via the junction table (includes system definitions in that group). Definitions are ordered like the global list: system types first, then by display name.
|
||||
|
||||
**Success — `200 OK`**
|
||||
|
||||
|
|
@ -298,7 +284,7 @@ Returns the group row plus all definitions where `group_id = 1` (includes system
|
|||
"Key": "timed_speaking",
|
||||
"DisplayName": "Timed Speaking",
|
||||
"Description": null,
|
||||
"group_id": 1,
|
||||
"group_ids": [1, 3],
|
||||
"StimulusComponentKinds": ["AUDIO_PROMPT"],
|
||||
"ResponseComponentKinds": ["ANSWER_TIMER", "AUDIO_RESPONSE"],
|
||||
"StimulusSchema": [],
|
||||
|
|
@ -359,9 +345,8 @@ Partial update — only sent fields change.
|
|||
DELETE /api/v1/questions/type-definition-groups/1
|
||||
```
|
||||
|
||||
- Deletes the group row only.
|
||||
- All definitions that referenced this group get `group_id = null` (database `ON DELETE SET NULL`).
|
||||
- Does **not** delete definitions or questions using those definitions.
|
||||
- Deletes the group row and its junction-table memberships only.
|
||||
- Definitions are **not** deleted.
|
||||
|
||||
**Success — `200 OK`**
|
||||
|
||||
|
|
@ -380,19 +365,19 @@ DELETE /api/v1/questions/type-definition-groups/1
|
|||
|
||||
Existing type-definition endpoints are extended; all prior fields and validation rules still apply (including optional empty stimulus/response shells and `ANSWER_TIMER`-only response configs).
|
||||
|
||||
### Create definition with group
|
||||
### Create definition with groups
|
||||
|
||||
```http
|
||||
POST /api/v1/questions/type-definitions
|
||||
```
|
||||
|
||||
Add optional `group_id`:
|
||||
Add optional `group_ids`:
|
||||
|
||||
```json
|
||||
{
|
||||
"key": "timed_speaking",
|
||||
"display_name": "Timed Speaking",
|
||||
"group_id": 1,
|
||||
"group_ids": [1, 3],
|
||||
"stimulus_component_kinds": ["AUDIO_PROMPT"],
|
||||
"response_component_kinds": ["ANSWER_TIMER", "AUDIO_RESPONSE"],
|
||||
"stimulus_schema": [],
|
||||
|
|
@ -401,46 +386,51 @@ Add optional `group_id`:
|
|||
}
|
||||
```
|
||||
|
||||
| `group_id` value | Effect |
|
||||
|------------------|--------|
|
||||
| Omitted | Ungrouped (`group_id: null` in response) |
|
||||
| `null` | Ungrouped |
|
||||
| Positive integer | Must reference an existing group; else `404` |
|
||||
| `group_ids` value | Effect |
|
||||
|-------------------|--------|
|
||||
| Omitted, `null`, or `[]` | Ungrouped (`group_ids: null` in response) |
|
||||
| `[1, 3]` | Linked to groups 1 and 3 (all ids must exist; duplicates deduped) |
|
||||
|
||||
---
|
||||
|
||||
### Update definition group membership
|
||||
### Update definition group memberships
|
||||
|
||||
```http
|
||||
PUT /api/v1/questions/type-definitions/42
|
||||
```
|
||||
|
||||
`group_id` uses **three-state** semantics on update:
|
||||
`group_ids` uses **replace** semantics on update:
|
||||
|
||||
| Request body | Effect |
|
||||
|--------------|--------|
|
||||
| Field **omitted** | Keep current `group_id` |
|
||||
| `"group_id": null` | Detach from any group |
|
||||
| `"group_id": 0` or invalid | Treated as detach (`null`) |
|
||||
| `"group_id": 1` | Assign to group `1` (must exist) |
|
||||
| Field **omitted** | Keep current memberships |
|
||||
| `"group_ids": null` or `[]` | Detach from all groups |
|
||||
| `"group_ids": [1, 3]` | Replace memberships with groups 1 and 3 |
|
||||
|
||||
**Detach example**
|
||||
**Clear all groups**
|
||||
|
||||
```json
|
||||
{
|
||||
"group_id": null
|
||||
"group_ids": null
|
||||
}
|
||||
```
|
||||
|
||||
**Move example**
|
||||
**Set multiple groups**
|
||||
|
||||
```json
|
||||
{
|
||||
"group_id": 2
|
||||
"group_ids": [1, 2, 5]
|
||||
}
|
||||
```
|
||||
|
||||
**Metadata-only update (group unchanged)**
|
||||
**Add one group without removing others (client-side merge)**
|
||||
|
||||
```typescript
|
||||
const current = definition.group_ids ?? [];
|
||||
await api.update(definition.id, { group_ids: [...new Set([...current, newGroupId])] });
|
||||
```
|
||||
|
||||
**Metadata-only update (memberships unchanged)**
|
||||
|
||||
```json
|
||||
{
|
||||
|
|
@ -481,7 +471,7 @@ GET /api/v1/questions/type-definitions?group_id=1&include_system=true&limit=50&o
|
|||
"ID": 42,
|
||||
"Key": "timed_speaking",
|
||||
"DisplayName": "Timed Speaking",
|
||||
"group_id": 1,
|
||||
"group_ids": [1, 3],
|
||||
"StimulusComponentKinds": ["AUDIO_PROMPT"],
|
||||
"ResponseComponentKinds": ["ANSWER_TIMER", "AUDIO_RESPONSE"],
|
||||
"IsSystem": false,
|
||||
|
|
@ -503,7 +493,7 @@ GET /api/v1/questions/type-definitions?group_id=1&include_system=true&limit=50&o
|
|||
|
||||
| Field | JSON key |
|
||||
|-------|----------|
|
||||
| Group link on definition | `group_id` (snake_case) |
|
||||
| Group memberships on definition | `group_ids` (snake_case) |
|
||||
| Schema elements | `id`, `kind`, `label`, `required`, `config` (snake_case via struct tags) |
|
||||
|
||||
Normalize in your API client if the UI prefers camelCase:
|
||||
|
|
@ -514,7 +504,7 @@ function normalizeDefinition(raw: ApiQuestionTypeDefinition): QuestionTypeDefini
|
|||
id: raw.ID,
|
||||
key: raw.Key,
|
||||
displayName: raw.DisplayName,
|
||||
groupId: raw.group_id ?? null,
|
||||
groupIds: raw.group_ids ?? null,
|
||||
stimulusComponentKinds: raw.StimulusComponentKinds ?? [],
|
||||
responseComponentKinds: raw.ResponseComponentKinds ?? [],
|
||||
// ...
|
||||
|
|
@ -522,7 +512,7 @@ function normalizeDefinition(raw: ApiQuestionTypeDefinition): QuestionTypeDefini
|
|||
}
|
||||
```
|
||||
|
||||
`group_id` in responses is **`null`** when ungrouped (not `undefined`).
|
||||
`group_ids` in responses is **`null`** when the definition has no group memberships (not `undefined`).
|
||||
|
||||
---
|
||||
|
||||
|
|
@ -547,7 +537,7 @@ flowchart LR
|
|||
### Group list page
|
||||
|
||||
- Table/cards: name, description snippet, definition count (from group detail or cached), `status`, `display_order`
|
||||
- Actions: Create, Edit, Delete (confirm: definitions become ungrouped)
|
||||
- Actions: Create, Edit, Delete (confirm: removes group memberships only; definitions remain)
|
||||
- Sort by `display_order`, then name (matches API)
|
||||
- Filter: `ACTIVE` / `INACTIVE` / all
|
||||
|
||||
|
|
@ -556,23 +546,23 @@ flowchart LR
|
|||
- Load: `GET /questions/type-definition-groups/:id`
|
||||
- Show group metadata + `definitions` table
|
||||
- Actions:
|
||||
- **Add definition** → definition create form with `group_id` pre-filled
|
||||
- **Move out** → `PUT` definition with `group_id: null`
|
||||
- **Move to another group** → `PUT` with new `group_id`
|
||||
- **Add definition** → definition create form with `group_ids` including current group
|
||||
- **Remove from this group** → `PUT` with `group_ids` filtered to exclude this group id
|
||||
- **Edit memberships** → multi-select groups on definition edit form
|
||||
|
||||
### Definition create / edit form
|
||||
|
||||
- Add **Group** dropdown:
|
||||
- Add **Groups** multi-select:
|
||||
1. Load groups: `GET /questions/type-definition-groups?status=ACTIVE&limit=200`
|
||||
2. Option “No group” → omit `group_id` or send `null` on create
|
||||
3. Selected group id → `group_id` on create; on edit use three-state update rules
|
||||
- When opened from group detail, pre-select that group
|
||||
2. Empty selection → omit `group_ids`, send `null`, or `[]` on create
|
||||
3. On edit, send full desired `group_ids` array to replace memberships
|
||||
- When opened from group detail, pre-select that group (and allow adding more)
|
||||
|
||||
### Definition picker (e.g. when authoring questions)
|
||||
|
||||
- Tabs or sidebar: one tab per group + “Ungrouped”
|
||||
- Per tab: `GET /questions/type-definitions?group_id=<id>&status=ACTIVE`
|
||||
- Ungrouped: full list client-side filter where `group_id == null`, or dedicated UX section
|
||||
- Ungrouped: full list client-side filter where `group_ids == null`, or dedicated UX section
|
||||
|
||||
### Delete group confirmation copy
|
||||
|
||||
|
|
@ -643,7 +633,7 @@ export interface ApiQuestionTypeDefinition {
|
|||
Key: string;
|
||||
DisplayName: string;
|
||||
Description?: string | null;
|
||||
group_id: number | null;
|
||||
group_ids: number[] | null;
|
||||
StimulusComponentKinds: string[];
|
||||
ResponseComponentKinds: string[];
|
||||
StimulusSchema?: DynamicElementDefinition[];
|
||||
|
|
@ -682,7 +672,7 @@ export function normalizeDefinition(raw: ApiQuestionTypeDefinition): QuestionTyp
|
|||
key: raw.Key,
|
||||
displayName: raw.DisplayName,
|
||||
description: raw.Description ?? null,
|
||||
groupId: raw.group_id ?? null,
|
||||
groupIds: raw.group_ids ?? null,
|
||||
stimulusComponentKinds: raw.StimulusComponentKinds ?? [],
|
||||
responseComponentKinds: raw.ResponseComponentKinds ?? [],
|
||||
isSystem: raw.IsSystem,
|
||||
|
|
@ -781,8 +771,8 @@ export const questionTypeDefinitionsApi = {
|
|||
});
|
||||
},
|
||||
|
||||
assignGroup(definitionId: number, groupId: number | null) {
|
||||
return this.update(definitionId, { group_id: groupId });
|
||||
assignGroups(definitionId: number, groupIds: number[] | null) {
|
||||
return this.update(definitionId, { group_ids: groupIds });
|
||||
},
|
||||
};
|
||||
```
|
||||
|
|
@ -910,7 +900,7 @@ async function createDefinitionInGroup(
|
|||
) {
|
||||
return questionTypeDefinitionsApi.create({
|
||||
...payload,
|
||||
group_id: groupId,
|
||||
group_ids: groupIds,
|
||||
status: "ACTIVE",
|
||||
});
|
||||
}
|
||||
|
|
@ -934,8 +924,8 @@ async function createDefinitionInGroup(
|
|||
|
||||
| HTTP | `message` | Typical cause |
|
||||
|------|-----------|---------------|
|
||||
| 400 | `Invalid group_id` | Non-numeric `group_id` query param |
|
||||
| 404 | `Question type definition group not found` | `group_id` on create/update/list filter points to missing group |
|
||||
| 400 | `Invalid group_ids` | Malformed `group_ids` array on update |
|
||||
| 404 | `Question type definition group not found` | Unknown id in `group_ids` or `group_id` list filter |
|
||||
| 400 | `Unable to create question type definition` | Validation error (kinds, schemas, etc.) — unchanged |
|
||||
| 400 | `Unable to update question type definition` | Same |
|
||||
|
||||
|
|
@ -952,32 +942,32 @@ async function createDefinitionInGroup(
|
|||
| Topic | Behavior |
|
||||
|-------|----------|
|
||||
| System definitions | Can be assigned to a group like any other definition (`include_system` affects list) |
|
||||
| Multiple groups per definition | Not supported — one `group_id` only |
|
||||
| Delete group | Definitions survive with `group_id: null` |
|
||||
| Multiple groups per definition | **Supported** — `group_ids: [1, 2, 3]` |
|
||||
| Delete group | Definitions survive; only memberships for that group are removed |
|
||||
| Delete definition | Unchanged; group unaffected |
|
||||
| Questions referencing definitions | Unaffected by grouping (FK is `question_type_definition_id`, not group) |
|
||||
| Empty group | Valid — group with zero definitions returns `"definitions": []` |
|
||||
| Inactive group | Definitions may still reference it; consider UI warning or blocking new assignments |
|
||||
| `display_order` ties | Secondary sort is `name` ASC |
|
||||
| Pagination | Use `total_count`, `limit`, `offset` on both list endpoints |
|
||||
| No `ungrouped_only` query param | Filter client-side: `group_id == null` from global definition list |
|
||||
| No `ungrouped_only` query param | Filter client-side: `group_ids == null` from global definition list |
|
||||
|
||||
---
|
||||
|
||||
## Integration checklist
|
||||
|
||||
- [ ] Run migration `000090_question_type_definition_groups` on target environments
|
||||
- [ ] Run migrations `000090` and `000091` on target environments
|
||||
- [ ] Add **Groups** section to question-type admin navigation
|
||||
- [ ] Implement group list (CRUD) against `/questions/type-definition-groups`
|
||||
- [ ] Implement group detail using `GET .../type-definition-groups/:id` (definitions embedded)
|
||||
- [ ] Add **Group** field to definition create/edit (`group_id`)
|
||||
- [ ] Support `group_id: null` on update to detach
|
||||
- [ ] Add optional `group_id` filter to definition list / picker
|
||||
- [ ] Add **Groups** multi-select to definition create/edit (`group_ids`)
|
||||
- [ ] Support `group_ids: null` / `[]` on update to clear all memberships
|
||||
- [ ] Add optional `group_id` query filter to definition list / picker
|
||||
- [ ] Handle `404` when group id is invalid on filtered list
|
||||
- [ ] Normalize PascalCase definition fields + snake_case `group_id` in API client
|
||||
- [ ] Show delete-group confirmation (definitions become ungrouped)
|
||||
- [ ] Normalize PascalCase definition fields + snake_case `group_ids` in API client
|
||||
- [ ] Show delete-group confirmation (memberships removed; definitions remain)
|
||||
- [ ] Verify permissions: `questions.list`, `.get`, `.create`, `.update`, `.delete`
|
||||
- [ ] QA: create group → create definition in group → list by `group_id` → move → detach → delete group
|
||||
- [ ] QA: create groups → assign multiple `group_ids` → list by `group_id` → partial remove → clear all → delete group
|
||||
|
||||
---
|
||||
|
||||
|
|
@ -993,33 +983,36 @@ async function createDefinitionInGroup(
|
|||
| `PUT` | `/api/v1/questions/type-definition-groups/:id` | Update group |
|
||||
| `DELETE` | `/api/v1/questions/type-definition-groups/:id` | Delete group |
|
||||
| `GET` | `/api/v1/questions/type-definitions?group_id=:id` | List definitions in group |
|
||||
| `POST` | `/api/v1/questions/type-definitions` | Create definition (`group_id` optional) |
|
||||
| `PUT` | `/api/v1/questions/type-definitions/:id` | Update definition (`group_id` optional / null) |
|
||||
| `POST` | `/api/v1/questions/type-definitions` | Create definition (`group_ids` optional) |
|
||||
| `PUT` | `/api/v1/questions/type-definitions/:id` | Update definition (`group_ids` replace / null) |
|
||||
|
||||
### `group_id` cheat sheet
|
||||
### `group_ids` cheat sheet
|
||||
|
||||
| Context | Value | Result |
|
||||
|---------|-------|--------|
|
||||
| Create | omitted / `null` | Ungrouped |
|
||||
| Create | `1` | Linked to group 1 |
|
||||
| Update | omitted | No change |
|
||||
| Update | `null` | Detach |
|
||||
| Update | `2` | Move to group 2 |
|
||||
| Create | omitted / `null` / `[]` | Ungrouped |
|
||||
| Create | `[1, 3]` | Member of groups 1 and 3 |
|
||||
| Update | omitted | No membership change |
|
||||
| Update | `null` / `[]` | Detach from all groups |
|
||||
| Update | `[1, 2]` | Replace memberships with groups 1 and 2 |
|
||||
| Response | `null` | Not in any group |
|
||||
| Response | `1` | Member of group 1 |
|
||||
| Response | `[1, 3]` | Member of groups 1 and 3 |
|
||||
|
||||
### Minimal happy path
|
||||
|
||||
```bash
|
||||
# 1. Create group
|
||||
# 1. Create groups
|
||||
POST /api/v1/questions/type-definition-groups
|
||||
{ "name": "Reading" }
|
||||
POST /api/v1/questions/type-definition-groups
|
||||
{ "name": "Exam prep" }
|
||||
|
||||
# 2. Create definition in group (use returned group id)
|
||||
# 2. Create definition in multiple groups
|
||||
POST /api/v1/questions/type-definitions
|
||||
{ "key": "passage_mcq", "display_name": "Passage MCQ", "group_id": 1, ... }
|
||||
{ "key": "passage_mcq", "display_name": "Passage MCQ", "group_ids": [1, 2], ... }
|
||||
|
||||
# 3. Verify
|
||||
GET /api/v1/questions/type-definition-groups/1
|
||||
GET /api/v1/questions/type-definitions?group_id=1
|
||||
GET /api/v1/questions/type-definitions?group_id=2
|
||||
```
|
||||
|
|
|
|||
|
|
@ -36,8 +36,33 @@ type UpdateQuestionTypeDefinitionGroupInput struct {
|
|||
Status *string
|
||||
}
|
||||
|
||||
// NullableIDPatch supports three-state updates: omit (Set=false), clear (Set=true, Value=nil), set (Set=true, Value!=nil).
|
||||
type NullableIDPatch struct {
|
||||
Set bool
|
||||
Value *int64
|
||||
// DefinitionGroupIDsPtr returns nil when there are no groups (JSON null); otherwise a pointer to the slice.
|
||||
func DefinitionGroupIDsPtr(groupIDs []int64) *[]int64 {
|
||||
if len(groupIDs) == 0 {
|
||||
return nil
|
||||
}
|
||||
return &groupIDs
|
||||
}
|
||||
|
||||
// DedupeGroupIDs removes duplicates and non-positive ids while preserving first-seen order.
|
||||
func DedupeGroupIDs(groupIDs []int64) []int64 {
|
||||
seen := make(map[int64]struct{}, len(groupIDs))
|
||||
out := make([]int64, 0, len(groupIDs))
|
||||
for _, id := range groupIDs {
|
||||
if id <= 0 {
|
||||
continue
|
||||
}
|
||||
if _, ok := seen[id]; ok {
|
||||
continue
|
||||
}
|
||||
seen[id] = struct{}{}
|
||||
out = append(out, id)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// NullableGroupIDsPatch supports three-state updates: omit (Set=false), clear (Set=true, empty Value), replace (Set=true, Value).
|
||||
type NullableGroupIDsPatch struct {
|
||||
Set bool
|
||||
Value []int64
|
||||
}
|
||||
|
|
|
|||
|
|
@ -7,7 +7,7 @@ type QuestionTypeDefinition struct {
|
|||
Key string
|
||||
DisplayName string
|
||||
Description *string
|
||||
GroupID *int64 `json:"group_id"`
|
||||
GroupIDs *[]int64 `json:"group_ids"`
|
||||
StimulusComponentKinds []string
|
||||
ResponseComponentKinds []string
|
||||
StimulusSchema []DynamicElementDefinition
|
||||
|
|
@ -22,7 +22,7 @@ type CreateQuestionTypeDefinitionInput struct {
|
|||
Key string
|
||||
DisplayName string
|
||||
Description *string
|
||||
GroupID *int64
|
||||
GroupIDs []int64
|
||||
StimulusComponentKinds []string
|
||||
ResponseComponentKinds []string
|
||||
StimulusSchema []DynamicElementDefinition
|
||||
|
|
@ -34,7 +34,7 @@ type CreateQuestionTypeDefinitionInput struct {
|
|||
type UpdateQuestionTypeDefinitionInput struct {
|
||||
DisplayName *string
|
||||
Description *string
|
||||
GroupID NullableIDPatch
|
||||
GroupIDs NullableGroupIDsPatch
|
||||
StimulusComponentKinds []string
|
||||
ResponseComponentKinds []string
|
||||
StimulusSchema []DynamicElementDefinition
|
||||
|
|
|
|||
|
|
@ -36,18 +36,93 @@ func questionTypeDefinitionGroupToDomain(
|
|||
}
|
||||
}
|
||||
|
||||
func (s *Store) validateQuestionTypeDefinitionGroupID(ctx context.Context, groupID *int64) error {
|
||||
if groupID == nil || *groupID <= 0 {
|
||||
return nil
|
||||
func (s *Store) validateQuestionTypeDefinitionGroupIDs(ctx context.Context, groupIDs []int64) error {
|
||||
for _, id := range domain.DedupeGroupIDs(groupIDs) {
|
||||
exists, err := s.QuestionTypeDefinitionGroupExists(ctx, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !exists {
|
||||
return domain.ErrQuestionTypeDefinitionGroupNotFound
|
||||
}
|
||||
}
|
||||
exists, err := s.QuestionTypeDefinitionGroupExists(ctx, *groupID)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Store) loadQuestionTypeDefinitionGroupIDs(ctx context.Context, definitionIDs []int64) (map[int64][]int64, error) {
|
||||
out := make(map[int64][]int64, len(definitionIDs))
|
||||
if len(definitionIDs) == 0 {
|
||||
return out, nil
|
||||
}
|
||||
|
||||
rows, err := s.conn.Query(ctx, `
|
||||
SELECT definition_id, group_id
|
||||
FROM question_type_definition_group_members
|
||||
WHERE definition_id = ANY($1::bigint[])
|
||||
ORDER BY definition_id, group_id
|
||||
`, definitionIDs)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
for rows.Next() {
|
||||
var definitionID, groupID int64
|
||||
if err := rows.Scan(&definitionID, &groupID); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out[definitionID] = append(out[definitionID], groupID)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
func (s *Store) attachGroupsToDefinitions(ctx context.Context, defs []domain.QuestionTypeDefinition) ([]domain.QuestionTypeDefinition, error) {
|
||||
if len(defs) == 0 {
|
||||
return defs, nil
|
||||
}
|
||||
ids := make([]int64, len(defs))
|
||||
for i, d := range defs {
|
||||
ids[i] = d.ID
|
||||
}
|
||||
byDef, err := s.loadQuestionTypeDefinitionGroupIDs(ctx, ids)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for i := range defs {
|
||||
defs[i].GroupIDs = domain.DefinitionGroupIDsPtr(byDef[defs[i].ID])
|
||||
}
|
||||
return defs, nil
|
||||
}
|
||||
|
||||
func (s *Store) replaceQuestionTypeDefinitionGroupIDs(ctx context.Context, definitionID int64, groupIDs []int64) error {
|
||||
groupIDs = domain.DedupeGroupIDs(groupIDs)
|
||||
if err := s.validateQuestionTypeDefinitionGroupIDs(ctx, groupIDs); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
tx, err := s.conn.Begin(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !exists {
|
||||
return domain.ErrQuestionTypeDefinitionGroupNotFound
|
||||
defer tx.Rollback(ctx)
|
||||
|
||||
if _, err := tx.Exec(ctx, `
|
||||
DELETE FROM question_type_definition_group_members
|
||||
WHERE definition_id = $1
|
||||
`, definitionID); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
|
||||
for _, groupID := range groupIDs {
|
||||
if _, err := tx.Exec(ctx, `
|
||||
INSERT INTO question_type_definition_group_members (definition_id, group_id)
|
||||
VALUES ($1, $2)
|
||||
`, definitionID, groupID); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return tx.Commit(ctx)
|
||||
}
|
||||
|
||||
func (s *Store) QuestionTypeDefinitionGroupExists(ctx context.Context, id int64) (bool, error) {
|
||||
|
|
|
|||
|
|
@ -180,7 +180,6 @@ func questionTypeDefinitionToDomain(
|
|||
key string,
|
||||
displayName string,
|
||||
description pgtype.Text,
|
||||
groupID pgtype.Int8,
|
||||
stimulusKinds []string,
|
||||
responseKinds []string,
|
||||
stimulusSchema []byte,
|
||||
|
|
@ -204,7 +203,6 @@ func questionTypeDefinitionToDomain(
|
|||
Key: key,
|
||||
DisplayName: displayName,
|
||||
Description: fromPgText(description),
|
||||
GroupID: fromPgInt8(groupID),
|
||||
StimulusComponentKinds: stimulusKinds,
|
||||
ResponseComponentKinds: responseKinds,
|
||||
StimulusSchema: stimulusSchemaDef,
|
||||
|
|
@ -306,20 +304,16 @@ func (s *Store) CreateQuestionTypeDefinition(ctx context.Context, input domain.C
|
|||
if err := domain.ValidatePersistableQuestionTypeDefinition(normalizedKey, responseKinds); err != nil {
|
||||
return domain.QuestionTypeDefinition{}, err
|
||||
}
|
||||
if err := s.validateQuestionTypeDefinitionGroupID(ctx, input.GroupID); err != nil {
|
||||
return domain.QuestionTypeDefinition{}, err
|
||||
}
|
||||
|
||||
row := s.conn.QueryRow(ctx, `
|
||||
INSERT INTO question_type_definitions
|
||||
(key, display_name, description, group_id, stimulus_component_kinds, response_component_kinds, stimulus_schema, response_schema, is_system, status)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7::jsonb, $8::jsonb, $9, $10)
|
||||
RETURNING id, key, display_name, description, group_id, stimulus_component_kinds, response_component_kinds, stimulus_schema, response_schema, is_system, status, created_at, updated_at
|
||||
(key, display_name, description, stimulus_component_kinds, response_component_kinds, stimulus_schema, response_schema, is_system, status)
|
||||
VALUES ($1, $2, $3, $4, $5, $6::jsonb, $7::jsonb, $8, $9)
|
||||
RETURNING id, key, display_name, description, stimulus_component_kinds, response_component_kinds, stimulus_schema, response_schema, is_system, status, created_at, updated_at
|
||||
`,
|
||||
normalizedKey,
|
||||
strings.TrimSpace(input.DisplayName),
|
||||
toPgText(input.Description),
|
||||
toPgInt8(input.GroupID),
|
||||
stimulusKinds,
|
||||
responseKinds,
|
||||
mustJSON(stimulusSchema),
|
||||
|
|
@ -333,7 +327,6 @@ func (s *Store) CreateQuestionTypeDefinition(ctx context.Context, input domain.C
|
|||
key string
|
||||
displayName string
|
||||
description pgtype.Text
|
||||
groupID pgtype.Int8
|
||||
stimulus []string
|
||||
response []string
|
||||
stimulusSch []byte
|
||||
|
|
@ -343,16 +336,27 @@ func (s *Store) CreateQuestionTypeDefinition(ctx context.Context, input domain.C
|
|||
createdAt time.Time
|
||||
updatedAt pgtype.Timestamptz
|
||||
)
|
||||
if err := row.Scan(&id, &key, &displayName, &description, &groupID, &stimulus, &response, &stimulusSch, &responseSch, &isSystem, &status, &createdAt, &updatedAt); err != nil {
|
||||
if err := row.Scan(&id, &key, &displayName, &description, &stimulus, &response, &stimulusSch, &responseSch, &isSystem, &status, &createdAt, &updatedAt); err != nil {
|
||||
return domain.QuestionTypeDefinition{}, err
|
||||
}
|
||||
|
||||
return questionTypeDefinitionToDomain(id, key, displayName, description, groupID, stimulus, response, stimulusSch, responseSch, isSystem, status, createdAt, updatedAt), nil
|
||||
if len(input.GroupIDs) > 0 {
|
||||
if err := s.replaceQuestionTypeDefinitionGroupIDs(ctx, id, input.GroupIDs); err != nil {
|
||||
return domain.QuestionTypeDefinition{}, err
|
||||
}
|
||||
}
|
||||
|
||||
def := questionTypeDefinitionToDomain(id, key, displayName, description, stimulus, response, stimulusSch, responseSch, isSystem, status, createdAt, updatedAt)
|
||||
attached, err := s.attachGroupsToDefinitions(ctx, []domain.QuestionTypeDefinition{def})
|
||||
if err != nil {
|
||||
return domain.QuestionTypeDefinition{}, err
|
||||
}
|
||||
return attached[0], nil
|
||||
}
|
||||
|
||||
func (s *Store) GetQuestionTypeDefinitionByID(ctx context.Context, id int64) (domain.QuestionTypeDefinition, error) {
|
||||
row := s.conn.QueryRow(ctx, `
|
||||
SELECT id, key, display_name, description, group_id, stimulus_component_kinds, response_component_kinds, stimulus_schema, response_schema, is_system, status, created_at, updated_at
|
||||
SELECT id, key, display_name, description, stimulus_component_kinds, response_component_kinds, stimulus_schema, response_schema, is_system, status, created_at, updated_at
|
||||
FROM question_type_definitions
|
||||
WHERE id = $1
|
||||
`, id)
|
||||
|
|
@ -361,7 +365,6 @@ func (s *Store) GetQuestionTypeDefinitionByID(ctx context.Context, id int64) (do
|
|||
key string
|
||||
displayName string
|
||||
description pgtype.Text
|
||||
groupID pgtype.Int8
|
||||
stimulus []string
|
||||
response []string
|
||||
stimulusSch []byte
|
||||
|
|
@ -371,18 +374,31 @@ func (s *Store) GetQuestionTypeDefinitionByID(ctx context.Context, id int64) (do
|
|||
createdAt time.Time
|
||||
updatedAt pgtype.Timestamptz
|
||||
)
|
||||
if err := row.Scan(&id, &key, &displayName, &description, &groupID, &stimulus, &response, &stimulusSch, &responseSch, &isSystem, &status, &createdAt, &updatedAt); err != nil {
|
||||
if err := row.Scan(&id, &key, &displayName, &description, &stimulus, &response, &stimulusSch, &responseSch, &isSystem, &status, &createdAt, &updatedAt); err != nil {
|
||||
return domain.QuestionTypeDefinition{}, err
|
||||
}
|
||||
return questionTypeDefinitionToDomain(id, key, displayName, description, groupID, stimulus, response, stimulusSch, responseSch, isSystem, status, createdAt, updatedAt), nil
|
||||
def := questionTypeDefinitionToDomain(id, key, displayName, description, stimulus, response, stimulusSch, responseSch, isSystem, status, createdAt, updatedAt)
|
||||
attached, err := s.attachGroupsToDefinitions(ctx, []domain.QuestionTypeDefinition{def})
|
||||
if err != nil {
|
||||
return domain.QuestionTypeDefinition{}, err
|
||||
}
|
||||
return attached[0], nil
|
||||
}
|
||||
|
||||
func (s *Store) ListQuestionTypeDefinitions(ctx context.Context, status *string, includeSystem bool, groupID *int64, limit, offset int32) ([]domain.QuestionTypeDefinition, int64, error) {
|
||||
const baseWhere = `
|
||||
FROM question_type_definitions
|
||||
WHERE ($1::VARCHAR IS NULL OR status = $1)
|
||||
AND ($2::BOOLEAN = TRUE OR is_system = FALSE)
|
||||
AND ($3::BIGINT IS NULL OR group_id = $3)`
|
||||
FROM question_type_definitions d
|
||||
WHERE ($1::VARCHAR IS NULL OR d.status = $1)
|
||||
AND ($2::BOOLEAN = TRUE OR d.is_system = FALSE)
|
||||
AND (
|
||||
$3::BIGINT IS NULL
|
||||
OR EXISTS (
|
||||
SELECT 1
|
||||
FROM question_type_definition_group_members m
|
||||
WHERE m.definition_id = d.id
|
||||
AND m.group_id = $3
|
||||
)
|
||||
)`
|
||||
|
||||
var total int64
|
||||
if err := s.conn.QueryRow(ctx, `SELECT COUNT(*)`+baseWhere, status, includeSystem, toPgInt8(groupID)).Scan(&total); err != nil {
|
||||
|
|
@ -390,8 +406,8 @@ func (s *Store) ListQuestionTypeDefinitions(ctx context.Context, status *string,
|
|||
}
|
||||
|
||||
listSQL := `
|
||||
SELECT id, key, display_name, description, group_id, stimulus_component_kinds, response_component_kinds, stimulus_schema, response_schema, is_system, status, created_at, updated_at` + baseWhere + `
|
||||
ORDER BY is_system DESC, display_name ASC`
|
||||
SELECT d.id, d.key, d.display_name, d.description, d.stimulus_component_kinds, d.response_component_kinds, d.stimulus_schema, d.response_schema, d.is_system, d.status, d.created_at, d.updated_at` + baseWhere + `
|
||||
ORDER BY d.is_system DESC, d.display_name ASC`
|
||||
|
||||
args := []interface{}{status, includeSystem, toPgInt8(groupID)}
|
||||
if limit > 0 {
|
||||
|
|
@ -412,7 +428,6 @@ func (s *Store) ListQuestionTypeDefinitions(ctx context.Context, status *string,
|
|||
key string
|
||||
displayName string
|
||||
description pgtype.Text
|
||||
groupID pgtype.Int8
|
||||
stimulus []string
|
||||
response []string
|
||||
stimulusSch []byte
|
||||
|
|
@ -422,13 +437,21 @@ func (s *Store) ListQuestionTypeDefinitions(ctx context.Context, status *string,
|
|||
createdAt time.Time
|
||||
updatedAt pgtype.Timestamptz
|
||||
)
|
||||
if err := rows.Scan(&id, &key, &displayName, &description, &groupID, &stimulus, &response, &stimulusSch, &responseSch, &isSystem, &defStatus, &createdAt, &updatedAt); err != nil {
|
||||
if err := rows.Scan(&id, &key, &displayName, &description, &stimulus, &response, &stimulusSch, &responseSch, &isSystem, &defStatus, &createdAt, &updatedAt); err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
out = append(out, questionTypeDefinitionToDomain(id, key, displayName, description, groupID, stimulus, response, stimulusSch, responseSch, isSystem, defStatus, createdAt, updatedAt))
|
||||
out = append(out, questionTypeDefinitionToDomain(id, key, displayName, description, stimulus, response, stimulusSch, responseSch, isSystem, defStatus, createdAt, updatedAt))
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
return out, total, rows.Err()
|
||||
out, err = s.attachGroupsToDefinitions(ctx, out)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
return out, total, nil
|
||||
}
|
||||
|
||||
func (s *Store) UpdateQuestionTypeDefinition(ctx context.Context, id int64, input domain.UpdateQuestionTypeDefinitionInput) error {
|
||||
|
|
@ -487,32 +510,26 @@ func (s *Store) UpdateQuestionTypeDefinition(ctx context.Context, id int64, inpu
|
|||
status = normalizeDefinitionStatus(input.Status)
|
||||
}
|
||||
|
||||
groupID := existing.GroupID
|
||||
if input.GroupID.Set {
|
||||
if input.GroupID.Value != nil && *input.GroupID.Value > 0 {
|
||||
if err := s.validateQuestionTypeDefinitionGroupID(ctx, input.GroupID.Value); err != nil {
|
||||
return err
|
||||
}
|
||||
groupID = input.GroupID.Value
|
||||
} else {
|
||||
groupID = nil
|
||||
}
|
||||
}
|
||||
|
||||
_, err = s.conn.Exec(ctx, `
|
||||
UPDATE question_type_definitions
|
||||
SET display_name = $2,
|
||||
description = $3,
|
||||
group_id = $4,
|
||||
stimulus_component_kinds = $5,
|
||||
response_component_kinds = $6,
|
||||
stimulus_schema = $7::jsonb,
|
||||
response_schema = $8::jsonb,
|
||||
status = $9,
|
||||
stimulus_component_kinds = $4,
|
||||
response_component_kinds = $5,
|
||||
stimulus_schema = $6::jsonb,
|
||||
response_schema = $7::jsonb,
|
||||
status = $8,
|
||||
updated_at = NOW()
|
||||
WHERE id = $1
|
||||
`, id, displayName, toPgText(description), toPgInt8(groupID), stimulusKinds, responseKinds, mustJSON(stimulusSchema), mustJSON(responseSchema), status)
|
||||
return err
|
||||
`, id, displayName, toPgText(description), stimulusKinds, responseKinds, mustJSON(stimulusSchema), mustJSON(responseSchema), status)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if input.GroupIDs.Set {
|
||||
return s.replaceQuestionTypeDefinitionGroupIDs(ctx, id, input.GroupIDs.Value)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Store) DeleteQuestionTypeDefinition(ctx context.Context, id int64) error {
|
||||
|
|
|
|||
|
|
@ -34,7 +34,7 @@ type createQuestionTypeDefinitionReq struct {
|
|||
Key string `json:"key" validate:"required"`
|
||||
DisplayName string `json:"display_name" validate:"required"`
|
||||
Description *string `json:"description"`
|
||||
GroupID *int64 `json:"group_id"`
|
||||
GroupIDs []int64 `json:"group_ids"`
|
||||
StimulusComponentKinds []string `json:"stimulus_component_kinds"`
|
||||
ResponseComponentKinds []string `json:"response_component_kinds"`
|
||||
StimulusSchema []domain.DynamicElementDefinition `json:"stimulus_schema"`
|
||||
|
|
@ -45,7 +45,7 @@ type createQuestionTypeDefinitionReq struct {
|
|||
type updateQuestionTypeDefinitionReq struct {
|
||||
DisplayName *string `json:"display_name"`
|
||||
Description *string `json:"description"`
|
||||
GroupID json.RawMessage `json:"group_id"`
|
||||
GroupIDs json.RawMessage `json:"group_ids"`
|
||||
StimulusComponentKinds []string `json:"stimulus_component_kinds"`
|
||||
ResponseComponentKinds []string `json:"response_component_kinds"`
|
||||
StimulusSchema []domain.DynamicElementDefinition `json:"stimulus_schema"`
|
||||
|
|
@ -74,21 +74,18 @@ type listQuestionTypeDefinitionGroupsData struct {
|
|||
Offset int `json:"offset"`
|
||||
}
|
||||
|
||||
func parseNullableIDPatch(raw json.RawMessage) (domain.NullableIDPatch, error) {
|
||||
func parseNullableGroupIDsPatch(raw json.RawMessage) (domain.NullableGroupIDsPatch, error) {
|
||||
if raw == nil {
|
||||
return domain.NullableIDPatch{}, nil
|
||||
return domain.NullableGroupIDsPatch{}, nil
|
||||
}
|
||||
if string(raw) == "null" {
|
||||
return domain.NullableIDPatch{Set: true, Value: nil}, nil
|
||||
return domain.NullableGroupIDsPatch{Set: true, Value: nil}, nil
|
||||
}
|
||||
var id int64
|
||||
if err := json.Unmarshal(raw, &id); err != nil {
|
||||
return domain.NullableIDPatch{}, err
|
||||
var ids []int64
|
||||
if err := json.Unmarshal(raw, &ids); err != nil {
|
||||
return domain.NullableGroupIDsPatch{}, err
|
||||
}
|
||||
if id <= 0 {
|
||||
return domain.NullableIDPatch{Set: true, Value: nil}, nil
|
||||
}
|
||||
return domain.NullableIDPatch{Set: true, Value: &id}, nil
|
||||
return domain.NullableGroupIDsPatch{Set: true, Value: domain.DedupeGroupIDs(ids)}, nil
|
||||
}
|
||||
|
||||
func parseOptionalGroupIDQuery(c *fiber.Ctx) (*int64, error) {
|
||||
|
|
@ -182,7 +179,7 @@ func (h *Handler) CreateQuestionTypeDefinition(c *fiber.Ctx) error {
|
|||
Key: strings.TrimSpace(req.Key),
|
||||
DisplayName: strings.TrimSpace(req.DisplayName),
|
||||
Description: req.Description,
|
||||
GroupID: req.GroupID,
|
||||
GroupIDs: domain.DedupeGroupIDs(req.GroupIDs),
|
||||
StimulusComponentKinds: req.StimulusComponentKinds,
|
||||
ResponseComponentKinds: req.ResponseComponentKinds,
|
||||
StimulusSchema: req.StimulusSchema,
|
||||
|
|
@ -425,10 +422,10 @@ func (h *Handler) UpdateQuestionTypeDefinition(c *fiber.Ctx) error {
|
|||
req.DisplayName = &displayName
|
||||
}
|
||||
|
||||
groupIDPatch, err := parseNullableIDPatch(req.GroupID)
|
||||
groupIDsPatch, err := parseNullableGroupIDsPatch(req.GroupIDs)
|
||||
if err != nil {
|
||||
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
|
||||
Message: "Invalid group_id",
|
||||
Message: "Invalid group_ids",
|
||||
Error: err.Error(),
|
||||
})
|
||||
}
|
||||
|
|
@ -436,7 +433,7 @@ func (h *Handler) UpdateQuestionTypeDefinition(c *fiber.Ctx) error {
|
|||
err = h.questionsSvc.UpdateQuestionTypeDefinition(c.Context(), id, domain.UpdateQuestionTypeDefinitionInput{
|
||||
DisplayName: req.DisplayName,
|
||||
Description: req.Description,
|
||||
GroupID: groupIDPatch,
|
||||
GroupIDs: groupIDsPatch,
|
||||
StimulusComponentKinds: req.StimulusComponentKinds,
|
||||
ResponseComponentKinds: req.ResponseComponentKinds,
|
||||
StimulusSchema: req.StimulusSchema,
|
||||
|
|
|
|||
Loading…
Reference in New Issue
Block a user