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
|
# 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`).
|
> **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 |
|
| Topic | Behavior |
|
||||||
|-------|----------|
|
|-------|----------|
|
||||||
| Group entity | Named bucket with optional description, `display_order`, `status` |
|
| Group entity | Named bucket with optional description, `display_order`, `status` |
|
||||||
| Definition → group link | Nullable `group_id` on each question type definition |
|
| Definition → group link | Many-to-many via `question_type_definition_group_members` |
|
||||||
| Unlinked definition | `group_id` is JSON **`null`** (not `0`, not omitted in responses) |
|
| Response field | `group_ids` — JSON **`null`** when ungrouped, or `[1, 2, …]` when linked |
|
||||||
| Assign on create | Optional `group_id` in `POST /questions/type-definitions` |
|
| Assign on create | Optional `group_ids` array in `POST /questions/type-definitions` |
|
||||||
| Reassign / detach on update | `PUT /questions/type-definitions/:id` with `group_id` number or `null` |
|
| 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>` |
|
| 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[]` |
|
| 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) |
|
| 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).
|
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
|
```mermaid
|
||||||
erDiagram
|
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 {
|
question_type_definition_groups {
|
||||||
bigint id PK
|
bigint id PK
|
||||||
varchar name
|
varchar name
|
||||||
text description
|
text description
|
||||||
int display_order
|
int display_order
|
||||||
varchar status
|
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 {
|
question_type_definitions {
|
||||||
bigint id PK
|
bigint id PK
|
||||||
varchar key UK
|
varchar key UK
|
||||||
varchar display_name
|
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`)
|
### Definition group memberships
|
||||||
|
|
||||||
| 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
|
|
||||||
|
|
||||||
| Field | On create | On update | In responses |
|
| 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 |
|
| Scenario | Approach |
|
||||||
|----------|----------|
|
|----------|----------|
|
||||||
| Organize builder catalog by subject/skill | Create groups; assign definitions on create or edit |
|
| Organize builder catalog by subject/skill | Create groups; assign one or more `group_ids` on create or edit |
|
||||||
| “Ungrouped” / legacy definitions | Leave `group_id` null (system seeded types start ungrouped) |
|
| “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 management screen | CRUD on `/questions/type-definition-groups` |
|
||||||
| Group detail / drill-down | `GET /questions/type-definition-groups/:id` (includes definitions) |
|
| Group detail / drill-down | `GET /questions/type-definition-groups/:id` (includes definitions) |
|
||||||
| Filtered definition picker | `GET /questions/type-definitions?group_id=:id` |
|
| Filtered definition picker | `GET /questions/type-definitions?group_id=:id` |
|
||||||
| Move definition to another group | `PUT /questions/type-definitions/:id` `{ "group_id": 2 }` |
|
| Add to another group without removing others | Read current ids, append, `PUT` with merged array |
|
||||||
| Remove from group without deleting definition | `PUT /questions/type-definitions/:id` `{ "group_id": null }` |
|
| 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` |
|
| 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 }
|
UI->>API: POST /questions/type-definition-groups { name }
|
||||||
API-->>UI: 201 { id: 1, name, ... }
|
API-->>UI: 201 { id: 1, name, ... }
|
||||||
|
|
||||||
UI->>API: POST /questions/type-definitions { key, display_name, group_id: 1, ... }
|
UI->>API: POST /questions/type-definitions { key, display_name, group_ids: [1, 3], ... }
|
||||||
API-->>UI: 201 { ID, group_id: 1, ... }
|
API-->>UI: 201 { ID, group_ids: [1, 3], ... }
|
||||||
|
|
||||||
UI->>API: GET /questions/type-definition-groups/1
|
UI->>API: GET /questions/type-definition-groups/1
|
||||||
API-->>UI: 200 { id, name, definitions: [...] }
|
API-->>UI: 200 { id, name, definitions: [...] }
|
||||||
```
|
```
|
||||||
|
|
||||||
### Flow B — Assign existing ungrouped definition to a group
|
### Flow B — Add existing definition to more groups
|
||||||
|
|
||||||
```mermaid
|
```mermaid
|
||||||
sequenceDiagram
|
sequenceDiagram
|
||||||
participant UI as Admin panel
|
participant UI as Admin panel
|
||||||
participant API as Yimaru API
|
participant API as Yimaru API
|
||||||
|
|
||||||
UI->>API: GET /questions/type-definitions?group_id=1
|
UI->>API: GET /questions/type-definitions/42
|
||||||
API-->>UI: 200 { question_type_definitions: [...] }
|
API-->>UI: 200 { ID: 42, group_ids: [1], ... }
|
||||||
|
|
||||||
Note over UI,API: User picks ungrouped definition id 42
|
Note over UI,API: User selects groups 1 and 3
|
||||||
UI->>API: PUT /questions/type-definitions/42 { group_id: 1 }
|
UI->>API: PUT /questions/type-definitions/42 { group_ids: [1, 3] }
|
||||||
API-->>UI: 200 { id: 42 }
|
API-->>UI: 200 { id: 42 }
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|
@ -151,7 +137,7 @@ sequenceDiagram
|
||||||
|
|
||||||
1. `GET /questions/type-definition-groups?status=ACTIVE&limit=200`
|
1. `GET /questions/type-definition-groups?status=ACTIVE&limit=200`
|
||||||
2. For each group: `GET /questions/type-definitions?group_id=<id>&include_system=true`
|
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.
|
**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` |
|
| Update group | `questions.update` | `PUT /api/v1/questions/type-definition-groups/:id` |
|
||||||
| Delete group | `questions.delete` | `DELETE /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` |
|
| 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` |
|
| Create definition (with `group_ids`) | `questions.create` | `POST /api/v1/questions/type-definitions` |
|
||||||
| Update definition `group_id` | `questions.update` | `PUT /api/v1/questions/type-definitions/:id` |
|
| 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
|
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`**
|
**Success — `200 OK`**
|
||||||
|
|
||||||
|
|
@ -298,7 +284,7 @@ Returns the group row plus all definitions where `group_id = 1` (includes system
|
||||||
"Key": "timed_speaking",
|
"Key": "timed_speaking",
|
||||||
"DisplayName": "Timed Speaking",
|
"DisplayName": "Timed Speaking",
|
||||||
"Description": null,
|
"Description": null,
|
||||||
"group_id": 1,
|
"group_ids": [1, 3],
|
||||||
"StimulusComponentKinds": ["AUDIO_PROMPT"],
|
"StimulusComponentKinds": ["AUDIO_PROMPT"],
|
||||||
"ResponseComponentKinds": ["ANSWER_TIMER", "AUDIO_RESPONSE"],
|
"ResponseComponentKinds": ["ANSWER_TIMER", "AUDIO_RESPONSE"],
|
||||||
"StimulusSchema": [],
|
"StimulusSchema": [],
|
||||||
|
|
@ -359,9 +345,8 @@ Partial update — only sent fields change.
|
||||||
DELETE /api/v1/questions/type-definition-groups/1
|
DELETE /api/v1/questions/type-definition-groups/1
|
||||||
```
|
```
|
||||||
|
|
||||||
- Deletes the group row only.
|
- Deletes the group row and its junction-table memberships only.
|
||||||
- All definitions that referenced this group get `group_id = null` (database `ON DELETE SET NULL`).
|
- Definitions are **not** deleted.
|
||||||
- Does **not** delete definitions or questions using those definitions.
|
|
||||||
|
|
||||||
**Success — `200 OK`**
|
**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).
|
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
|
```http
|
||||||
POST /api/v1/questions/type-definitions
|
POST /api/v1/questions/type-definitions
|
||||||
```
|
```
|
||||||
|
|
||||||
Add optional `group_id`:
|
Add optional `group_ids`:
|
||||||
|
|
||||||
```json
|
```json
|
||||||
{
|
{
|
||||||
"key": "timed_speaking",
|
"key": "timed_speaking",
|
||||||
"display_name": "Timed Speaking",
|
"display_name": "Timed Speaking",
|
||||||
"group_id": 1,
|
"group_ids": [1, 3],
|
||||||
"stimulus_component_kinds": ["AUDIO_PROMPT"],
|
"stimulus_component_kinds": ["AUDIO_PROMPT"],
|
||||||
"response_component_kinds": ["ANSWER_TIMER", "AUDIO_RESPONSE"],
|
"response_component_kinds": ["ANSWER_TIMER", "AUDIO_RESPONSE"],
|
||||||
"stimulus_schema": [],
|
"stimulus_schema": [],
|
||||||
|
|
@ -401,46 +386,51 @@ Add optional `group_id`:
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
| `group_id` value | Effect |
|
| `group_ids` value | Effect |
|
||||||
|------------------|--------|
|
|-------------------|--------|
|
||||||
| Omitted | Ungrouped (`group_id: null` in response) |
|
| Omitted, `null`, or `[]` | Ungrouped (`group_ids: null` in response) |
|
||||||
| `null` | Ungrouped |
|
| `[1, 3]` | Linked to groups 1 and 3 (all ids must exist; duplicates deduped) |
|
||||||
| Positive integer | Must reference an existing group; else `404` |
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
### Update definition group membership
|
### Update definition group memberships
|
||||||
|
|
||||||
```http
|
```http
|
||||||
PUT /api/v1/questions/type-definitions/42
|
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 |
|
| Request body | Effect |
|
||||||
|--------------|--------|
|
|--------------|--------|
|
||||||
| Field **omitted** | Keep current `group_id` |
|
| Field **omitted** | Keep current memberships |
|
||||||
| `"group_id": null` | Detach from any group |
|
| `"group_ids": null` or `[]` | Detach from all groups |
|
||||||
| `"group_id": 0` or invalid | Treated as detach (`null`) |
|
| `"group_ids": [1, 3]` | Replace memberships with groups 1 and 3 |
|
||||||
| `"group_id": 1` | Assign to group `1` (must exist) |
|
|
||||||
|
|
||||||
**Detach example**
|
**Clear all groups**
|
||||||
|
|
||||||
```json
|
```json
|
||||||
{
|
{
|
||||||
"group_id": null
|
"group_ids": null
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
**Move example**
|
**Set multiple groups**
|
||||||
|
|
||||||
```json
|
```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
|
```json
|
||||||
{
|
{
|
||||||
|
|
@ -481,7 +471,7 @@ GET /api/v1/questions/type-definitions?group_id=1&include_system=true&limit=50&o
|
||||||
"ID": 42,
|
"ID": 42,
|
||||||
"Key": "timed_speaking",
|
"Key": "timed_speaking",
|
||||||
"DisplayName": "Timed Speaking",
|
"DisplayName": "Timed Speaking",
|
||||||
"group_id": 1,
|
"group_ids": [1, 3],
|
||||||
"StimulusComponentKinds": ["AUDIO_PROMPT"],
|
"StimulusComponentKinds": ["AUDIO_PROMPT"],
|
||||||
"ResponseComponentKinds": ["ANSWER_TIMER", "AUDIO_RESPONSE"],
|
"ResponseComponentKinds": ["ANSWER_TIMER", "AUDIO_RESPONSE"],
|
||||||
"IsSystem": false,
|
"IsSystem": false,
|
||||||
|
|
@ -503,7 +493,7 @@ GET /api/v1/questions/type-definitions?group_id=1&include_system=true&limit=50&o
|
||||||
|
|
||||||
| Field | JSON key |
|
| 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) |
|
| Schema elements | `id`, `kind`, `label`, `required`, `config` (snake_case via struct tags) |
|
||||||
|
|
||||||
Normalize in your API client if the UI prefers camelCase:
|
Normalize in your API client if the UI prefers camelCase:
|
||||||
|
|
@ -514,7 +504,7 @@ function normalizeDefinition(raw: ApiQuestionTypeDefinition): QuestionTypeDefini
|
||||||
id: raw.ID,
|
id: raw.ID,
|
||||||
key: raw.Key,
|
key: raw.Key,
|
||||||
displayName: raw.DisplayName,
|
displayName: raw.DisplayName,
|
||||||
groupId: raw.group_id ?? null,
|
groupIds: raw.group_ids ?? null,
|
||||||
stimulusComponentKinds: raw.StimulusComponentKinds ?? [],
|
stimulusComponentKinds: raw.StimulusComponentKinds ?? [],
|
||||||
responseComponentKinds: raw.ResponseComponentKinds ?? [],
|
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
|
### Group list page
|
||||||
|
|
||||||
- Table/cards: name, description snippet, definition count (from group detail or cached), `status`, `display_order`
|
- 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)
|
- Sort by `display_order`, then name (matches API)
|
||||||
- Filter: `ACTIVE` / `INACTIVE` / all
|
- Filter: `ACTIVE` / `INACTIVE` / all
|
||||||
|
|
||||||
|
|
@ -556,23 +546,23 @@ flowchart LR
|
||||||
- Load: `GET /questions/type-definition-groups/:id`
|
- Load: `GET /questions/type-definition-groups/:id`
|
||||||
- Show group metadata + `definitions` table
|
- Show group metadata + `definitions` table
|
||||||
- Actions:
|
- Actions:
|
||||||
- **Add definition** → definition create form with `group_id` pre-filled
|
- **Add definition** → definition create form with `group_ids` including current group
|
||||||
- **Move out** → `PUT` definition with `group_id: null`
|
- **Remove from this group** → `PUT` with `group_ids` filtered to exclude this group id
|
||||||
- **Move to another group** → `PUT` with new `group_id`
|
- **Edit memberships** → multi-select groups on definition edit form
|
||||||
|
|
||||||
### Definition create / 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`
|
1. Load groups: `GET /questions/type-definition-groups?status=ACTIVE&limit=200`
|
||||||
2. Option “No group” → omit `group_id` or send `null` on create
|
2. Empty selection → omit `group_ids`, send `null`, or `[]` on create
|
||||||
3. Selected group id → `group_id` on create; on edit use three-state update rules
|
3. On edit, send full desired `group_ids` array to replace memberships
|
||||||
- When opened from group detail, pre-select that group
|
- When opened from group detail, pre-select that group (and allow adding more)
|
||||||
|
|
||||||
### Definition picker (e.g. when authoring questions)
|
### Definition picker (e.g. when authoring questions)
|
||||||
|
|
||||||
- Tabs or sidebar: one tab per group + “Ungrouped”
|
- Tabs or sidebar: one tab per group + “Ungrouped”
|
||||||
- Per tab: `GET /questions/type-definitions?group_id=<id>&status=ACTIVE`
|
- 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
|
### Delete group confirmation copy
|
||||||
|
|
||||||
|
|
@ -643,7 +633,7 @@ export interface ApiQuestionTypeDefinition {
|
||||||
Key: string;
|
Key: string;
|
||||||
DisplayName: string;
|
DisplayName: string;
|
||||||
Description?: string | null;
|
Description?: string | null;
|
||||||
group_id: number | null;
|
group_ids: number[] | null;
|
||||||
StimulusComponentKinds: string[];
|
StimulusComponentKinds: string[];
|
||||||
ResponseComponentKinds: string[];
|
ResponseComponentKinds: string[];
|
||||||
StimulusSchema?: DynamicElementDefinition[];
|
StimulusSchema?: DynamicElementDefinition[];
|
||||||
|
|
@ -682,7 +672,7 @@ export function normalizeDefinition(raw: ApiQuestionTypeDefinition): QuestionTyp
|
||||||
key: raw.Key,
|
key: raw.Key,
|
||||||
displayName: raw.DisplayName,
|
displayName: raw.DisplayName,
|
||||||
description: raw.Description ?? null,
|
description: raw.Description ?? null,
|
||||||
groupId: raw.group_id ?? null,
|
groupIds: raw.group_ids ?? null,
|
||||||
stimulusComponentKinds: raw.StimulusComponentKinds ?? [],
|
stimulusComponentKinds: raw.StimulusComponentKinds ?? [],
|
||||||
responseComponentKinds: raw.ResponseComponentKinds ?? [],
|
responseComponentKinds: raw.ResponseComponentKinds ?? [],
|
||||||
isSystem: raw.IsSystem,
|
isSystem: raw.IsSystem,
|
||||||
|
|
@ -781,8 +771,8 @@ export const questionTypeDefinitionsApi = {
|
||||||
});
|
});
|
||||||
},
|
},
|
||||||
|
|
||||||
assignGroup(definitionId: number, groupId: number | null) {
|
assignGroups(definitionId: number, groupIds: number[] | null) {
|
||||||
return this.update(definitionId, { group_id: groupId });
|
return this.update(definitionId, { group_ids: groupIds });
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
```
|
```
|
||||||
|
|
@ -910,7 +900,7 @@ async function createDefinitionInGroup(
|
||||||
) {
|
) {
|
||||||
return questionTypeDefinitionsApi.create({
|
return questionTypeDefinitionsApi.create({
|
||||||
...payload,
|
...payload,
|
||||||
group_id: groupId,
|
group_ids: groupIds,
|
||||||
status: "ACTIVE",
|
status: "ACTIVE",
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
@ -934,8 +924,8 @@ async function createDefinitionInGroup(
|
||||||
|
|
||||||
| HTTP | `message` | Typical cause |
|
| HTTP | `message` | Typical cause |
|
||||||
|------|-----------|---------------|
|
|------|-----------|---------------|
|
||||||
| 400 | `Invalid group_id` | Non-numeric `group_id` query param |
|
| 400 | `Invalid group_ids` | Malformed `group_ids` array on update |
|
||||||
| 404 | `Question type definition group not found` | `group_id` on create/update/list filter points to missing group |
|
| 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 create question type definition` | Validation error (kinds, schemas, etc.) — unchanged |
|
||||||
| 400 | `Unable to update question type definition` | Same |
|
| 400 | `Unable to update question type definition` | Same |
|
||||||
|
|
||||||
|
|
@ -952,32 +942,32 @@ async function createDefinitionInGroup(
|
||||||
| Topic | Behavior |
|
| Topic | Behavior |
|
||||||
|-------|----------|
|
|-------|----------|
|
||||||
| System definitions | Can be assigned to a group like any other definition (`include_system` affects list) |
|
| 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 |
|
| Multiple groups per definition | **Supported** — `group_ids: [1, 2, 3]` |
|
||||||
| Delete group | Definitions survive with `group_id: null` |
|
| Delete group | Definitions survive; only memberships for that group are removed |
|
||||||
| Delete definition | Unchanged; group unaffected |
|
| Delete definition | Unchanged; group unaffected |
|
||||||
| Questions referencing definitions | Unaffected by grouping (FK is `question_type_definition_id`, not group) |
|
| Questions referencing definitions | Unaffected by grouping (FK is `question_type_definition_id`, not group) |
|
||||||
| Empty group | Valid — group with zero definitions returns `"definitions": []` |
|
| Empty group | Valid — group with zero definitions returns `"definitions": []` |
|
||||||
| Inactive group | Definitions may still reference it; consider UI warning or blocking new assignments |
|
| Inactive group | Definitions may still reference it; consider UI warning or blocking new assignments |
|
||||||
| `display_order` ties | Secondary sort is `name` ASC |
|
| `display_order` ties | Secondary sort is `name` ASC |
|
||||||
| Pagination | Use `total_count`, `limit`, `offset` on both list endpoints |
|
| 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
|
## 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
|
- [ ] Add **Groups** section to question-type admin navigation
|
||||||
- [ ] Implement group list (CRUD) against `/questions/type-definition-groups`
|
- [ ] Implement group list (CRUD) against `/questions/type-definition-groups`
|
||||||
- [ ] Implement group detail using `GET .../type-definition-groups/:id` (definitions embedded)
|
- [ ] Implement group detail using `GET .../type-definition-groups/:id` (definitions embedded)
|
||||||
- [ ] Add **Group** field to definition create/edit (`group_id`)
|
- [ ] Add **Groups** multi-select to definition create/edit (`group_ids`)
|
||||||
- [ ] Support `group_id: null` on update to detach
|
- [ ] Support `group_ids: null` / `[]` on update to clear all memberships
|
||||||
- [ ] Add optional `group_id` filter to definition list / picker
|
- [ ] Add optional `group_id` query filter to definition list / picker
|
||||||
- [ ] Handle `404` when group id is invalid on filtered list
|
- [ ] Handle `404` when group id is invalid on filtered list
|
||||||
- [ ] Normalize PascalCase definition fields + snake_case `group_id` in API client
|
- [ ] Normalize PascalCase definition fields + snake_case `group_ids` in API client
|
||||||
- [ ] Show delete-group confirmation (definitions become ungrouped)
|
- [ ] Show delete-group confirmation (memberships removed; definitions remain)
|
||||||
- [ ] Verify permissions: `questions.list`, `.get`, `.create`, `.update`, `.delete`
|
- [ ] 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 |
|
| `PUT` | `/api/v1/questions/type-definition-groups/:id` | Update group |
|
||||||
| `DELETE` | `/api/v1/questions/type-definition-groups/:id` | Delete group |
|
| `DELETE` | `/api/v1/questions/type-definition-groups/:id` | Delete group |
|
||||||
| `GET` | `/api/v1/questions/type-definitions?group_id=:id` | List definitions in 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) |
|
| `POST` | `/api/v1/questions/type-definitions` | Create definition (`group_ids` optional) |
|
||||||
| `PUT` | `/api/v1/questions/type-definitions/:id` | Update definition (`group_id` optional / null) |
|
| `PUT` | `/api/v1/questions/type-definitions/:id` | Update definition (`group_ids` replace / null) |
|
||||||
|
|
||||||
### `group_id` cheat sheet
|
### `group_ids` cheat sheet
|
||||||
|
|
||||||
| Context | Value | Result |
|
| Context | Value | Result |
|
||||||
|---------|-------|--------|
|
|---------|-------|--------|
|
||||||
| Create | omitted / `null` | Ungrouped |
|
| Create | omitted / `null` / `[]` | Ungrouped |
|
||||||
| Create | `1` | Linked to group 1 |
|
| Create | `[1, 3]` | Member of groups 1 and 3 |
|
||||||
| Update | omitted | No change |
|
| Update | omitted | No membership change |
|
||||||
| Update | `null` | Detach |
|
| Update | `null` / `[]` | Detach from all groups |
|
||||||
| Update | `2` | Move to group 2 |
|
| Update | `[1, 2]` | Replace memberships with groups 1 and 2 |
|
||||||
| Response | `null` | Not in any group |
|
| Response | `null` | Not in any group |
|
||||||
| Response | `1` | Member of group 1 |
|
| Response | `[1, 3]` | Member of groups 1 and 3 |
|
||||||
|
|
||||||
### Minimal happy path
|
### Minimal happy path
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# 1. Create group
|
# 1. Create groups
|
||||||
POST /api/v1/questions/type-definition-groups
|
POST /api/v1/questions/type-definition-groups
|
||||||
{ "name": "Reading" }
|
{ "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
|
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
|
# 3. Verify
|
||||||
GET /api/v1/questions/type-definition-groups/1
|
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=1
|
||||||
|
GET /api/v1/questions/type-definitions?group_id=2
|
||||||
```
|
```
|
||||||
|
|
|
||||||
|
|
@ -36,8 +36,33 @@ type UpdateQuestionTypeDefinitionGroupInput struct {
|
||||||
Status *string
|
Status *string
|
||||||
}
|
}
|
||||||
|
|
||||||
// NullableIDPatch supports three-state updates: omit (Set=false), clear (Set=true, Value=nil), set (Set=true, Value!=nil).
|
// DefinitionGroupIDsPtr returns nil when there are no groups (JSON null); otherwise a pointer to the slice.
|
||||||
type NullableIDPatch struct {
|
func DefinitionGroupIDsPtr(groupIDs []int64) *[]int64 {
|
||||||
Set bool
|
if len(groupIDs) == 0 {
|
||||||
Value *int64
|
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
|
Key string
|
||||||
DisplayName string
|
DisplayName string
|
||||||
Description *string
|
Description *string
|
||||||
GroupID *int64 `json:"group_id"`
|
GroupIDs *[]int64 `json:"group_ids"`
|
||||||
StimulusComponentKinds []string
|
StimulusComponentKinds []string
|
||||||
ResponseComponentKinds []string
|
ResponseComponentKinds []string
|
||||||
StimulusSchema []DynamicElementDefinition
|
StimulusSchema []DynamicElementDefinition
|
||||||
|
|
@ -22,7 +22,7 @@ type CreateQuestionTypeDefinitionInput struct {
|
||||||
Key string
|
Key string
|
||||||
DisplayName string
|
DisplayName string
|
||||||
Description *string
|
Description *string
|
||||||
GroupID *int64
|
GroupIDs []int64
|
||||||
StimulusComponentKinds []string
|
StimulusComponentKinds []string
|
||||||
ResponseComponentKinds []string
|
ResponseComponentKinds []string
|
||||||
StimulusSchema []DynamicElementDefinition
|
StimulusSchema []DynamicElementDefinition
|
||||||
|
|
@ -34,7 +34,7 @@ type CreateQuestionTypeDefinitionInput struct {
|
||||||
type UpdateQuestionTypeDefinitionInput struct {
|
type UpdateQuestionTypeDefinitionInput struct {
|
||||||
DisplayName *string
|
DisplayName *string
|
||||||
Description *string
|
Description *string
|
||||||
GroupID NullableIDPatch
|
GroupIDs NullableGroupIDsPatch
|
||||||
StimulusComponentKinds []string
|
StimulusComponentKinds []string
|
||||||
ResponseComponentKinds []string
|
ResponseComponentKinds []string
|
||||||
StimulusSchema []DynamicElementDefinition
|
StimulusSchema []DynamicElementDefinition
|
||||||
|
|
|
||||||
|
|
@ -36,18 +36,93 @@ func questionTypeDefinitionGroupToDomain(
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *Store) validateQuestionTypeDefinitionGroupID(ctx context.Context, groupID *int64) error {
|
func (s *Store) validateQuestionTypeDefinitionGroupIDs(ctx context.Context, groupIDs []int64) error {
|
||||||
if groupID == nil || *groupID <= 0 {
|
for _, id := range domain.DedupeGroupIDs(groupIDs) {
|
||||||
return nil
|
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 {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
if !exists {
|
defer tx.Rollback(ctx)
|
||||||
return domain.ErrQuestionTypeDefinitionGroupNotFound
|
|
||||||
|
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) {
|
func (s *Store) QuestionTypeDefinitionGroupExists(ctx context.Context, id int64) (bool, error) {
|
||||||
|
|
|
||||||
|
|
@ -180,7 +180,6 @@ func questionTypeDefinitionToDomain(
|
||||||
key string,
|
key string,
|
||||||
displayName string,
|
displayName string,
|
||||||
description pgtype.Text,
|
description pgtype.Text,
|
||||||
groupID pgtype.Int8,
|
|
||||||
stimulusKinds []string,
|
stimulusKinds []string,
|
||||||
responseKinds []string,
|
responseKinds []string,
|
||||||
stimulusSchema []byte,
|
stimulusSchema []byte,
|
||||||
|
|
@ -204,7 +203,6 @@ func questionTypeDefinitionToDomain(
|
||||||
Key: key,
|
Key: key,
|
||||||
DisplayName: displayName,
|
DisplayName: displayName,
|
||||||
Description: fromPgText(description),
|
Description: fromPgText(description),
|
||||||
GroupID: fromPgInt8(groupID),
|
|
||||||
StimulusComponentKinds: stimulusKinds,
|
StimulusComponentKinds: stimulusKinds,
|
||||||
ResponseComponentKinds: responseKinds,
|
ResponseComponentKinds: responseKinds,
|
||||||
StimulusSchema: stimulusSchemaDef,
|
StimulusSchema: stimulusSchemaDef,
|
||||||
|
|
@ -306,20 +304,16 @@ func (s *Store) CreateQuestionTypeDefinition(ctx context.Context, input domain.C
|
||||||
if err := domain.ValidatePersistableQuestionTypeDefinition(normalizedKey, responseKinds); err != nil {
|
if err := domain.ValidatePersistableQuestionTypeDefinition(normalizedKey, responseKinds); err != nil {
|
||||||
return domain.QuestionTypeDefinition{}, err
|
return domain.QuestionTypeDefinition{}, err
|
||||||
}
|
}
|
||||||
if err := s.validateQuestionTypeDefinitionGroupID(ctx, input.GroupID); err != nil {
|
|
||||||
return domain.QuestionTypeDefinition{}, err
|
|
||||||
}
|
|
||||||
|
|
||||||
row := s.conn.QueryRow(ctx, `
|
row := s.conn.QueryRow(ctx, `
|
||||||
INSERT INTO question_type_definitions
|
INSERT INTO question_type_definitions
|
||||||
(key, display_name, description, group_id, stimulus_component_kinds, response_component_kinds, stimulus_schema, response_schema, is_system, status)
|
(key, display_name, description, 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)
|
VALUES ($1, $2, $3, $4, $5, $6::jsonb, $7::jsonb, $8, $9)
|
||||||
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
|
RETURNING id, key, display_name, description, stimulus_component_kinds, response_component_kinds, stimulus_schema, response_schema, is_system, status, created_at, updated_at
|
||||||
`,
|
`,
|
||||||
normalizedKey,
|
normalizedKey,
|
||||||
strings.TrimSpace(input.DisplayName),
|
strings.TrimSpace(input.DisplayName),
|
||||||
toPgText(input.Description),
|
toPgText(input.Description),
|
||||||
toPgInt8(input.GroupID),
|
|
||||||
stimulusKinds,
|
stimulusKinds,
|
||||||
responseKinds,
|
responseKinds,
|
||||||
mustJSON(stimulusSchema),
|
mustJSON(stimulusSchema),
|
||||||
|
|
@ -333,7 +327,6 @@ func (s *Store) CreateQuestionTypeDefinition(ctx context.Context, input domain.C
|
||||||
key string
|
key string
|
||||||
displayName string
|
displayName string
|
||||||
description pgtype.Text
|
description pgtype.Text
|
||||||
groupID pgtype.Int8
|
|
||||||
stimulus []string
|
stimulus []string
|
||||||
response []string
|
response []string
|
||||||
stimulusSch []byte
|
stimulusSch []byte
|
||||||
|
|
@ -343,16 +336,27 @@ func (s *Store) CreateQuestionTypeDefinition(ctx context.Context, input domain.C
|
||||||
createdAt time.Time
|
createdAt time.Time
|
||||||
updatedAt pgtype.Timestamptz
|
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 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) {
|
func (s *Store) GetQuestionTypeDefinitionByID(ctx context.Context, id int64) (domain.QuestionTypeDefinition, error) {
|
||||||
row := s.conn.QueryRow(ctx, `
|
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
|
FROM question_type_definitions
|
||||||
WHERE id = $1
|
WHERE id = $1
|
||||||
`, id)
|
`, id)
|
||||||
|
|
@ -361,7 +365,6 @@ func (s *Store) GetQuestionTypeDefinitionByID(ctx context.Context, id int64) (do
|
||||||
key string
|
key string
|
||||||
displayName string
|
displayName string
|
||||||
description pgtype.Text
|
description pgtype.Text
|
||||||
groupID pgtype.Int8
|
|
||||||
stimulus []string
|
stimulus []string
|
||||||
response []string
|
response []string
|
||||||
stimulusSch []byte
|
stimulusSch []byte
|
||||||
|
|
@ -371,18 +374,31 @@ func (s *Store) GetQuestionTypeDefinitionByID(ctx context.Context, id int64) (do
|
||||||
createdAt time.Time
|
createdAt time.Time
|
||||||
updatedAt pgtype.Timestamptz
|
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 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) {
|
func (s *Store) ListQuestionTypeDefinitions(ctx context.Context, status *string, includeSystem bool, groupID *int64, limit, offset int32) ([]domain.QuestionTypeDefinition, int64, error) {
|
||||||
const baseWhere = `
|
const baseWhere = `
|
||||||
FROM question_type_definitions
|
FROM question_type_definitions d
|
||||||
WHERE ($1::VARCHAR IS NULL OR status = $1)
|
WHERE ($1::VARCHAR IS NULL OR d.status = $1)
|
||||||
AND ($2::BOOLEAN = TRUE OR is_system = FALSE)
|
AND ($2::BOOLEAN = TRUE OR d.is_system = FALSE)
|
||||||
AND ($3::BIGINT IS NULL OR group_id = $3)`
|
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
|
var total int64
|
||||||
if err := s.conn.QueryRow(ctx, `SELECT COUNT(*)`+baseWhere, status, includeSystem, toPgInt8(groupID)).Scan(&total); err != nil {
|
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 := `
|
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 + `
|
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 is_system DESC, display_name ASC`
|
ORDER BY d.is_system DESC, d.display_name ASC`
|
||||||
|
|
||||||
args := []interface{}{status, includeSystem, toPgInt8(groupID)}
|
args := []interface{}{status, includeSystem, toPgInt8(groupID)}
|
||||||
if limit > 0 {
|
if limit > 0 {
|
||||||
|
|
@ -412,7 +428,6 @@ func (s *Store) ListQuestionTypeDefinitions(ctx context.Context, status *string,
|
||||||
key string
|
key string
|
||||||
displayName string
|
displayName string
|
||||||
description pgtype.Text
|
description pgtype.Text
|
||||||
groupID pgtype.Int8
|
|
||||||
stimulus []string
|
stimulus []string
|
||||||
response []string
|
response []string
|
||||||
stimulusSch []byte
|
stimulusSch []byte
|
||||||
|
|
@ -422,13 +437,21 @@ func (s *Store) ListQuestionTypeDefinitions(ctx context.Context, status *string,
|
||||||
createdAt time.Time
|
createdAt time.Time
|
||||||
updatedAt pgtype.Timestamptz
|
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
|
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 {
|
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)
|
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, `
|
_, err = s.conn.Exec(ctx, `
|
||||||
UPDATE question_type_definitions
|
UPDATE question_type_definitions
|
||||||
SET display_name = $2,
|
SET display_name = $2,
|
||||||
description = $3,
|
description = $3,
|
||||||
group_id = $4,
|
stimulus_component_kinds = $4,
|
||||||
stimulus_component_kinds = $5,
|
response_component_kinds = $5,
|
||||||
response_component_kinds = $6,
|
stimulus_schema = $6::jsonb,
|
||||||
stimulus_schema = $7::jsonb,
|
response_schema = $7::jsonb,
|
||||||
response_schema = $8::jsonb,
|
status = $8,
|
||||||
status = $9,
|
|
||||||
updated_at = NOW()
|
updated_at = NOW()
|
||||||
WHERE id = $1
|
WHERE id = $1
|
||||||
`, id, displayName, toPgText(description), toPgInt8(groupID), stimulusKinds, responseKinds, mustJSON(stimulusSchema), mustJSON(responseSchema), status)
|
`, id, displayName, toPgText(description), stimulusKinds, responseKinds, mustJSON(stimulusSchema), mustJSON(responseSchema), status)
|
||||||
return err
|
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 {
|
func (s *Store) DeleteQuestionTypeDefinition(ctx context.Context, id int64) error {
|
||||||
|
|
|
||||||
|
|
@ -34,7 +34,7 @@ type createQuestionTypeDefinitionReq struct {
|
||||||
Key string `json:"key" validate:"required"`
|
Key string `json:"key" validate:"required"`
|
||||||
DisplayName string `json:"display_name" validate:"required"`
|
DisplayName string `json:"display_name" validate:"required"`
|
||||||
Description *string `json:"description"`
|
Description *string `json:"description"`
|
||||||
GroupID *int64 `json:"group_id"`
|
GroupIDs []int64 `json:"group_ids"`
|
||||||
StimulusComponentKinds []string `json:"stimulus_component_kinds"`
|
StimulusComponentKinds []string `json:"stimulus_component_kinds"`
|
||||||
ResponseComponentKinds []string `json:"response_component_kinds"`
|
ResponseComponentKinds []string `json:"response_component_kinds"`
|
||||||
StimulusSchema []domain.DynamicElementDefinition `json:"stimulus_schema"`
|
StimulusSchema []domain.DynamicElementDefinition `json:"stimulus_schema"`
|
||||||
|
|
@ -45,7 +45,7 @@ type createQuestionTypeDefinitionReq struct {
|
||||||
type updateQuestionTypeDefinitionReq struct {
|
type updateQuestionTypeDefinitionReq struct {
|
||||||
DisplayName *string `json:"display_name"`
|
DisplayName *string `json:"display_name"`
|
||||||
Description *string `json:"description"`
|
Description *string `json:"description"`
|
||||||
GroupID json.RawMessage `json:"group_id"`
|
GroupIDs json.RawMessage `json:"group_ids"`
|
||||||
StimulusComponentKinds []string `json:"stimulus_component_kinds"`
|
StimulusComponentKinds []string `json:"stimulus_component_kinds"`
|
||||||
ResponseComponentKinds []string `json:"response_component_kinds"`
|
ResponseComponentKinds []string `json:"response_component_kinds"`
|
||||||
StimulusSchema []domain.DynamicElementDefinition `json:"stimulus_schema"`
|
StimulusSchema []domain.DynamicElementDefinition `json:"stimulus_schema"`
|
||||||
|
|
@ -74,21 +74,18 @@ type listQuestionTypeDefinitionGroupsData struct {
|
||||||
Offset int `json:"offset"`
|
Offset int `json:"offset"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func parseNullableIDPatch(raw json.RawMessage) (domain.NullableIDPatch, error) {
|
func parseNullableGroupIDsPatch(raw json.RawMessage) (domain.NullableGroupIDsPatch, error) {
|
||||||
if raw == nil {
|
if raw == nil {
|
||||||
return domain.NullableIDPatch{}, nil
|
return domain.NullableGroupIDsPatch{}, nil
|
||||||
}
|
}
|
||||||
if string(raw) == "null" {
|
if string(raw) == "null" {
|
||||||
return domain.NullableIDPatch{Set: true, Value: nil}, nil
|
return domain.NullableGroupIDsPatch{Set: true, Value: nil}, nil
|
||||||
}
|
}
|
||||||
var id int64
|
var ids []int64
|
||||||
if err := json.Unmarshal(raw, &id); err != nil {
|
if err := json.Unmarshal(raw, &ids); err != nil {
|
||||||
return domain.NullableIDPatch{}, err
|
return domain.NullableGroupIDsPatch{}, err
|
||||||
}
|
}
|
||||||
if id <= 0 {
|
return domain.NullableGroupIDsPatch{Set: true, Value: domain.DedupeGroupIDs(ids)}, nil
|
||||||
return domain.NullableIDPatch{Set: true, Value: nil}, nil
|
|
||||||
}
|
|
||||||
return domain.NullableIDPatch{Set: true, Value: &id}, nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func parseOptionalGroupIDQuery(c *fiber.Ctx) (*int64, error) {
|
func parseOptionalGroupIDQuery(c *fiber.Ctx) (*int64, error) {
|
||||||
|
|
@ -182,7 +179,7 @@ func (h *Handler) CreateQuestionTypeDefinition(c *fiber.Ctx) error {
|
||||||
Key: strings.TrimSpace(req.Key),
|
Key: strings.TrimSpace(req.Key),
|
||||||
DisplayName: strings.TrimSpace(req.DisplayName),
|
DisplayName: strings.TrimSpace(req.DisplayName),
|
||||||
Description: req.Description,
|
Description: req.Description,
|
||||||
GroupID: req.GroupID,
|
GroupIDs: domain.DedupeGroupIDs(req.GroupIDs),
|
||||||
StimulusComponentKinds: req.StimulusComponentKinds,
|
StimulusComponentKinds: req.StimulusComponentKinds,
|
||||||
ResponseComponentKinds: req.ResponseComponentKinds,
|
ResponseComponentKinds: req.ResponseComponentKinds,
|
||||||
StimulusSchema: req.StimulusSchema,
|
StimulusSchema: req.StimulusSchema,
|
||||||
|
|
@ -425,10 +422,10 @@ func (h *Handler) UpdateQuestionTypeDefinition(c *fiber.Ctx) error {
|
||||||
req.DisplayName = &displayName
|
req.DisplayName = &displayName
|
||||||
}
|
}
|
||||||
|
|
||||||
groupIDPatch, err := parseNullableIDPatch(req.GroupID)
|
groupIDsPatch, err := parseNullableGroupIDsPatch(req.GroupIDs)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
|
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
|
||||||
Message: "Invalid group_id",
|
Message: "Invalid group_ids",
|
||||||
Error: err.Error(),
|
Error: err.Error(),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
@ -436,7 +433,7 @@ func (h *Handler) UpdateQuestionTypeDefinition(c *fiber.Ctx) error {
|
||||||
err = h.questionsSvc.UpdateQuestionTypeDefinition(c.Context(), id, domain.UpdateQuestionTypeDefinitionInput{
|
err = h.questionsSvc.UpdateQuestionTypeDefinition(c.Context(), id, domain.UpdateQuestionTypeDefinitionInput{
|
||||||
DisplayName: req.DisplayName,
|
DisplayName: req.DisplayName,
|
||||||
Description: req.Description,
|
Description: req.Description,
|
||||||
GroupID: groupIDPatch,
|
GroupIDs: groupIDsPatch,
|
||||||
StimulusComponentKinds: req.StimulusComponentKinds,
|
StimulusComponentKinds: req.StimulusComponentKinds,
|
||||||
ResponseComponentKinds: req.ResponseComponentKinds,
|
ResponseComponentKinds: req.ResponseComponentKinds,
|
||||||
StimulusSchema: req.StimulusSchema,
|
StimulusSchema: req.StimulusSchema,
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue
Block a user