feat: add question associations for practice section sequencing

Add associated_question_id on question set items so authors can group practice questions into ordered sections. Expose prerequisite_question_ids on read APIs for client-side gating, validate associations on save, and document admin panel integration.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
Yared Yemane 2026-06-18 03:18:24 -07:00
parent c66a7be28f
commit 8dd0c2d784
17 changed files with 1264 additions and 95 deletions

View File

@ -0,0 +1,4 @@
DROP INDEX IF EXISTS idx_question_set_items_associated_question_id;
ALTER TABLE question_set_items
DROP COLUMN IF EXISTS associated_question_id;

View File

@ -0,0 +1,5 @@
ALTER TABLE question_set_items
ADD COLUMN associated_question_id BIGINT REFERENCES questions(id) ON DELETE SET NULL;
CREATE INDEX idx_question_set_items_associated_question_id
ON question_set_items(associated_question_id);

View File

@ -2,7 +2,8 @@
INSERT INTO question_set_items (
set_id,
question_id,
display_order
display_order,
associated_question_id
)
VALUES (
sqlc.arg('set_id'),
@ -14,9 +15,12 @@ VALUES (
FROM question_set_items AS qsi
WHERE qsi.set_id = sqlc.arg('set_id')
), 0) + 1
)
),
sqlc.narg('associated_question_id')
)
ON CONFLICT (set_id, question_id) DO UPDATE SET display_order = EXCLUDED.display_order
ON CONFLICT (set_id, question_id) DO UPDATE SET
display_order = EXCLUDED.display_order,
associated_question_id = EXCLUDED.associated_question_id
RETURNING *;
-- name: GetQuestionSetItems :many
@ -25,6 +29,7 @@ SELECT
qsi.set_id,
qsi.question_id,
qsi.display_order,
qsi.associated_question_id,
q.question_text,
q.question_type,
q.dynamic_payload,
@ -51,6 +56,7 @@ SELECT
qsi.set_id,
qsi.question_id,
qsi.display_order,
qsi.associated_question_id,
q.question_text,
q.question_type,
q.dynamic_payload,
@ -79,6 +85,7 @@ SELECT
qsi.set_id,
qsi.question_id,
qsi.display_order,
qsi.associated_question_id,
q.question_text,
q.question_type,
q.dynamic_payload,
@ -101,10 +108,11 @@ ORDER BY qsi.display_order;
DELETE FROM question_set_items
WHERE set_id = $1 AND question_id = $2;
-- name: UpdateQuestionOrder :exec
-- name: UpdateQuestionSetItem :exec
UPDATE question_set_items
SET display_order = $1
WHERE set_id = $2 AND question_id = $3;
SET display_order = $1,
associated_question_id = $2
WHERE set_id = $3 AND question_id = $4;
-- name: CountQuestionsInSet :one
SELECT COUNT(*) as count

View File

@ -0,0 +1,836 @@
# Practice Question Associations — Admin Panel Integration Guide
This guide documents how to integrate **question associations** into the Yimaru admin panel practice authoring flow. Associations let content authors group questions into **sequential sections** within a practice. Learners must complete earlier sections (in `display_order`) before later ones unlock.
> **Scope:** This feature adds `associated_question_id` on question set membership (`question_set_items`). It works alongside existing `display_order`. There is **no server-side per-question progress table** — the API returns `prerequisite_question_ids` so the **learner app** (or admin preview) can gate access client-side.
---
## Table of contents
1. [Feature overview](#feature-overview)
2. [Concepts: sections, anchors, and prerequisites](#concepts-sections-anchors-and-prerequisites)
3. [Architecture](#architecture)
4. [Prerequisites (backend)](#prerequisites-backend)
5. [Authentication & permissions](#authentication--permissions)
6. [Data model](#data-model)
7. [Response envelopes](#response-envelopes)
8. [Primary API: full practice save/load](#primary-api-full-practice-saveload)
9. [Granular question-set item APIs](#granular-question-set-item-apis)
10. [Recommended admin UI changes](#recommended-admin-ui-changes)
11. [Form state & serialization](#form-state--serialization)
12. [Client-side validation (mirror backend)](#client-side-validation-mirror-backend)
13. [TypeScript types & helpers](#typescript-types--helpers)
14. [React integration patterns](#react-integration-patterns)
15. [Error handling](#error-handling)
16. [Learner app note](#learner-app-note)
17. [Integration checklist](#integration-checklist)
18. [Limitations](#limitations)
19. [Quick reference](#quick-reference)
---
## Feature overview
| Capability | Admin panel | Learner app |
|------------|-------------|-------------|
| Set `display_order` per question in a practice | Yes (existing) | Uses order for presentation |
| Set `associated_question_id` per question | **Yes (new)** | Uses for section gating |
| Server tracks per-question completion | **No** | Client tracks locally / on submit |
| Read computed `prerequisite_question_ids` | Yes (in GET responses) | Yes — gate question access |
| Create associations for brand-new questions in one save | Yes | N/A |
### What problem this solves
Without associations, all questions in a practice are effectively one flat list ordered by `display_order`. With associations, authors can define **blocks**:
- **Section 1:** Questions 1–3 must be done in order.
- **Section 2:** Unlocks only after section 1 is fully complete.
- **Section 3:** Another independent block, and so on.
Authors express this by marking the **first question of each section** as a **section anchor** (`associated_question_id: null`) and linking follow-up questions in that section to the anchor’s question `id`.
---
## Concepts: sections, anchors, and prerequisites
### Fields on each question in a practice
| Field | Type | Meaning |
|-------|------|---------|
| `display_order` | `number` | Sort position within the practice (1-based typical). Controls presentation order. |
| `associated_question_id` | `number \| null` | If set, this question belongs to the section whose **anchor** is that question ID. If `null`, this question **is** a section anchor (starts a new block). |
### Example layout
| Question ID | display_order | associated_question_id | Role |
|-------------|---------------|------------------------|------|
| `101` | 1 | `null` | Anchor — section A |
| `102` | 2 | `101` | Section A, step 2 |
| `103` | 3 | `101` | Section A, step 3 |
| `104` | 4 | `null` | Anchor — section B |
| `105` | 5 | `104` | Section B, step 2 |
### Unlock rules (for learner gating)
The API computes `prerequisite_question_ids` for each question. A learner should not open question **Q** until every ID in `prerequisite_question_ids` is considered “completed” by the client.
**Anchor question** (`associated_question_id` is `null`):
- Prerequisites = all other questions in the set with **lower** `display_order`.
**Associated question** (`associated_question_id` = anchor ID):
- Prerequisites = all questions with `display_order` **before the anchor’s** `display_order` (previous sections), **plus** all questions in the **same section** with lower `display_order` (including the anchor).
### Visual diagram
```mermaid
flowchart LR
subgraph SectionA["Section A (anchor: Q101)"]
Q101["Q101 order=1"]
Q102["Q102 order=2"]
Q103["Q103 order=3"]
Q101 --> Q102 --> Q103
end
subgraph SectionB["Section B (anchor: Q104)"]
Q104["Q104 order=4"]
Q105["Q105 order=5"]
Q104 --> Q105
end
SectionA -->|"all of A complete"| SectionB
```
---
## Architecture
```mermaid
flowchart TB
subgraph AdminPanel["Admin panel"]
PracticeEditor[Practice question editor]
SectionUI[Section / association controls]
SaveBtn[Save practice]
end
subgraph API["Yimaru API"]
GetFull["GET /practices/:id/full"]
PutFull["PUT /practices/:id/full"]
GetEpFull["GET /exam-prep/practices/:id/full"]
PutEpFull["PUT /exam-prep/practices/:id/full"]
end
subgraph DB["PostgreSQL"]
QSI["question_set_items.associated_question_id"]
end
PracticeEditor --> SectionUI
SaveBtn --> PutFull
SaveBtn --> PutEpFull
GetFull --> PracticeEditor
GetEpFull --> PracticeEditor
PutFull --> QSI
PutEpFull --> QSI
```
- **Migration:** `000088_question_set_item_associations` — adds `associated_question_id` to `question_set_items`.
- **Domain logic:** `internal/domain/question_set_item.go` — validation + `PrerequisiteQuestionIDs`.
- **Sync:** `internal/services/practicecontent/question_sync.go` — applies associations on full practice update (two-pass for new questions).
- **Handlers:** `internal/web_server/handlers/practice_full_update_handler.go`, `questions.go`.
---
## Prerequisites (backend)
Before testing from the admin panel:
1. Run database migrations (includes `000088`):
```bash
docker compose up migrate
```
2. Regenerate sqlc / redeploy API if you are on a dev branch that added this feature.
3. Confirm `question_set_items` has column `associated_question_id`:
```sql
\d question_set_items
```
---
## Authentication & permissions
Use a **team member** or **platform admin** token:
```http
Authorization: Bearer <access_token>
Content-Type: application/json
```
### LMS practices (Learn English)
| Action | Permission | HTTP |
|--------|------------|------|
| Load practice + questions | `practices.get` | `GET /api/v1/practices/:id/full` |
| Save practice + questions | `practices.update` | `PUT /api/v1/practices/:id/full` |
### Exam-prep practices
| Action | Permission | HTTP |
|--------|------------|------|
| Load | `exam_prep.practices.get` | `GET /api/v1/exam-prep/practices/:id/full` |
| Save | `exam_prep.practices.update` | `PUT /api/v1/exam-prep/practices/:id/full` |
### Granular question-set routes (optional)
| Action | Permission | HTTP |
|--------|------------|------|
| Add question to set | `question_set_items.add` | `POST /api/v1/question-sets/:setId/questions` |
| Update order + association | `question_set_items.update_order` | `PUT /api/v1/question-sets/:setId/questions/:questionId/order` |
| List questions in set | `question_set_items.list` | `GET /api/v1/question-sets/:setId/questions` |
The admin practice editor should prefer **`/practices/:id/full`** so metadata, question set settings, and all questions sync in one request.
---
## Data model
### Database
Table `question_set_items`:
| Column | Type | Notes |
|--------|------|-------|
| `set_id` | `bigint` | Question set linked to practice |
| `question_id` | `bigint` | Question bank row |
| `display_order` | `int` | Sort order in set |
| `associated_question_id` | `bigint NULL` | FK → `questions(id)`, `ON DELETE SET NULL` |
### JSON on each question (admin + learner list responses)
```typescript
interface PracticeQuestion {
id: number;
display_order?: number;
associated_question_id?: number | null;
prerequisite_question_ids?: number[];
// ...existing question fields (question_type, options, dynamic_payload, etc.)
}
```
- **`associated_question_id`** — what the author configured.
- **`prerequisite_question_ids`** — read-only, computed by API for gating. Do not send on save; the backend recalculates on read.
---
## Response envelopes
Success:
```json
{
"message": "Practice updated successfully",
"data": { },
"success": true,
"status_code": 200
}
```
Validation error (invalid association):
```json
{
"message": "Invalid question association",
"error": "invalid question association: associated question 102 must have a lower display_order than question 101"
}
```
---
## Primary API: full practice save/load
### Load practice (LMS)
```http
GET /api/v1/practices/:id/full
Authorization: Bearer <token>
```
**Response `data` shape (relevant parts):**
```json
{
"practice": { "id": 12, "title": "...", "question_set_id": 55, "persona_id": 1 },
"question_set": { "id": 55, "title": "...", "question_count": 5 },
"questions": [
{
"id": 101,
"display_order": 1,
"associated_question_id": null,
"prerequisite_question_ids": [],
"question_type": "MCQ",
"options": []
},
{
"id": 102,
"display_order": 2,
"associated_question_id": 101,
"prerequisite_question_ids": [101],
"question_type": "MCQ",
"options": []
}
]
}
```
### Save practice (LMS)
```http
PUT /api/v1/practices/:id/full
Authorization: Bearer <token>
Content-Type: application/json
```
**Request body (questions portion):**
```json
{
"practice": {
"title": "Listening drill",
"publish_status": "PUBLISHED"
},
"question_set": {
"shuffle_questions": false,
"status": "PUBLISHED"
},
"questions": [
{
"id": 101,
"display_order": 1,
"associated_question_id": null,
"question_type": "MCQ",
"question_text": "First prompt",
"options": [
{ "option_text": "A", "option_order": 1, "is_correct": true },
{ "option_text": "B", "option_order": 2, "is_correct": false }
]
},
{
"id": 102,
"display_order": 2,
"associated_question_id": 101,
"question_type": "MCQ",
"question_text": "Follow-up prompt",
"options": []
},
{
"display_order": 3,
"associated_question_id": 101,
"question_type": "SHORT_ANSWER",
"question_text": "New question in same section",
"short_answers": [{ "acceptable_answer": "hello", "match_type": "EXACT" }]
},
{
"display_order": 4,
"associated_question_id": null,
"question_type": "AUDIO",
"voice_prompt": "minio://audio/uuid.mp3",
"audio_correct_answer_text": "expected transcript"
}
]
}
```
| Field | On save | Notes |
|-------|---------|-------|
| `id` | Optional | Omit to **create** a new question. Include to **update** existing. |
| `display_order` | Recommended | Defaults to 1-based index in `questions` array if omitted. |
| `associated_question_id` | Optional | `null` or omit = section anchor. Must be a **persisted** question ID in the same practice. |
| `prerequisite_question_ids` | **Do not send** | Response-only. |
### Exam-prep equivalent
| LMS | Exam-prep |
|-----|-----------|
| `GET /api/v1/practices/:id/full` | `GET /api/v1/exam-prep/practices/:id/full` |
| `PUT /api/v1/practices/:id/full` | `PUT /api/v1/exam-prep/practices/:id/full` |
Payload shape is identical (`domain.FullUpdatePracticeInput`).
### Sync semantics (important for admin save)
- Questions **omitted** from the `questions` array are **removed from the set** (not deleted from the global question bank).
- On save, the backend:
1. Creates/updates question content.
2. Sets `display_order` on membership.
3. Validates all associations together.
4. Applies `associated_question_id` in a second pass (so new questions can reference other new questions in the **same** save, as long as the anchor already has an `id` from a prior save or appears earlier with an `id`).
**New questions without `id` cannot be used as `associated_question_id` targets until after the first save assigns IDs.** UI should only offer anchors from questions that already have `id`, or re-save after creation.
---
## Granular question-set item APIs
Use these only if the admin panel manages question sets **outside** the full practice editor.
### Add question to set
```http
POST /api/v1/question-sets/:setId/questions
```
```json
{
"question_id": 201,
"display_order": 3,
"associated_question_id": 101
}
```
### Update order and association
```http
PUT /api/v1/question-sets/:setId/questions/:questionId/order
```
```json
{
"display_order": 3,
"associated_question_id": 101
}
```
To clear an association (make question a section anchor), send `"associated_question_id": null`.
---
## Recommended admin UI changes
### 1. Extend the practice question list row
For each question in the practice editor, show:
| UI element | Purpose |
|------------|---------|
| Drag handle / order index | Maps to `display_order` |
| **Section** badge | “Anchor” vs “Part of section {n}” |
| **Section anchor** dropdown | Sets `associated_question_id` (`null` = this row is anchor) |
| Prerequisites preview (read-only) | Optional tooltip listing `prerequisite_question_ids` for author QA |
### 2. Section anchor dropdown options
Populate from questions in the **same practice** that are anchors:
```typescript
function anchorOptions(questions: EditablePracticeQuestion[], currentId?: number) {
return questions
.filter((q) => q.id != null && q.id !== currentId)
.filter((q) => q.associated_question_id == null) // only anchors
.sort((a, b) => (a.display_order ?? 0) - (b.display_order ?? 0))
.map((q) => ({
value: q.id!,
label: `Q${q.display_order} — ${summarizeQuestion(q)}`,
}));
}
```
For a question that **is** an anchor, hide the dropdown or show “This question starts a section” with a control to convert it to an associated question.
### 3. “Start new section” action
When the author clicks **Add section** or **Start new section**:
1. Insert a new question (or mark existing) with `associated_question_id: null`.
2. Subsequent questions added under that section default to `associated_question_id: <anchorId>`.
### 4. Reorder behavior
When `display_order` changes via drag-and-drop:
1. Renumber `display_order` for all rows.
2. Revalidate associations client-side (anchor must still have lower order than associated questions).
3. If invalid, snap back or auto-clear invalid `associated_question_id`.
### 5. Authoring preview (optional)
Use `prerequisite_question_ids` from the last GET response (or compute locally with the same rules) to simulate locked/unlocked states in a preview mode. No extra API is required.
---
## Form state & serialization
### Suggested editable row type
```typescript
interface EditablePracticeQuestion {
/** Present after first save or when loaded from API */
id?: number;
display_order: number;
/** null = section anchor */
associated_question_id: number | null;
question_type: string;
question_text?: string;
question_type_definition_id?: number;
dynamic_payload?: DynamicQuestionPayload;
options?: CreateQuestionOptionInput[];
short_answers?: CreateShortAnswerInput[];
audio_correct_answer_text?: string;
// ...other fields your editor already uses
}
```
### Load: API → form state
```typescript
function mapApiQuestionToEditable(q: PracticeQuestion): EditablePracticeQuestion {
return {
id: q.id,
display_order: q.display_order ?? 1,
associated_question_id: q.associated_question_id ?? null,
question_type: q.question_type,
question_text: q.question_text,
question_type_definition_id: q.question_type_definition_id,
dynamic_payload: q.dynamic_payload,
options: q.options,
short_answers: q.short_answers,
audio_correct_answer_text: q.audio_correct_answer_text,
};
}
```
### Save: form state → API
```typescript
function mapEditableToSaveItem(q: EditablePracticeQuestion): FullUpdatePracticeQuestionItem {
return {
...(q.id != null ? { id: q.id } : {}),
display_order: q.display_order,
associated_question_id: q.associated_question_id,
question_type: q.question_type,
question_text: q.question_text,
question_type_definition_id: q.question_type_definition_id,
dynamic_payload: q.dynamic_payload,
options: q.options,
short_answers: q.short_answers,
audio_correct_answer_text: q.audio_correct_answer_text,
};
}
```
Send the full practice payload:
```typescript
await api.put(`/api/v1/practices/${practiceId}/full`, {
practice: { title, publish_status, persona_id },
question_set: { status: "PUBLISHED", shuffle_questions: false },
questions: editableQuestions.map(mapEditableToSaveItem),
});
```
---
## Client-side validation (mirror backend)
Validate **before** save to avoid round trips. Rules match `domain.ValidateQuestionSetAssociations`:
| Rule | Error message (suggested) |
|------|---------------------------|
| `associated_question_id === question.id` | “A question cannot be associated with itself.” |
| Target ID not in practice list | “Associated question must belong to this practice.” |
| Target is not an anchor (it has its own `associated_question_id`) | “Associated question must be a section anchor.” |
| Target `display_order` ≥ this question’s `display_order` | “Section anchor must appear before this question.” |
```typescript
function validateAssociations(questions: EditablePracticeQuestion[]): string | null {
const byId = new Map<number, EditablePracticeQuestion>();
for (const q of questions) {
if (q.id != null) byId.set(q.id, q);
}
for (const q of questions) {
if (q.associated_question_id == null || q.id == null) continue;
const assocId = q.associated_question_id;
if (assocId === q.id) return "A question cannot be associated with itself.";
const anchor = byId.get(assocId);
if (!anchor) return "Associated question must belong to this practice.";
if (anchor.associated_question_id != null) {
return "Associated question must be a section anchor.";
}
if ((anchor.display_order ?? 0) >= (q.display_order ?? 0)) {
return "Section anchor must appear before this question.";
}
}
return null;
}
```
Skip association targets that only exist as new rows without `id` — show inline hint: “Save once to link new questions to this section.”
---
## TypeScript types & helpers
```typescript
export interface ApiResponse<T> {
message: string;
data: T;
success?: boolean;
status_code?: number;
}
export interface FullUpdatePracticeQuestionItem {
id?: number;
display_order?: number;
associated_question_id?: number | null;
question_text?: string;
question_type?: string;
question_type_definition_id?: number;
dynamic_payload?: unknown;
options?: Array<{
option_text: string;
option_order?: number;
is_correct: boolean;
}>;
short_answers?: Array<{
acceptable_answer: string;
match_type?: string;
}>;
audio_correct_answer_text?: string;
// ...match existing editor fields
}
export interface FullUpdatePracticeInput {
practice?: {
title?: string;
story_description?: string;
persona_id?: number | null;
publish_status?: string;
};
question_set?: {
title?: string;
shuffle_questions?: boolean;
status?: string;
intro_video_url?: string;
};
questions?: FullUpdatePracticeQuestionItem[];
}
export interface PracticeFullResponse {
practice: Record<string, unknown>;
question_set: Record<string, unknown>;
questions: Array<{
id: number;
display_order?: number;
associated_question_id?: number | null;
prerequisite_question_ids?: number[];
question_type: string;
[key: string]: unknown;
}>;
}
```
### Optional: compute prerequisites in the admin preview
If you need live preview before save, port the same logic the API uses (`PrerequisiteQuestionIDs` in `internal/domain/question_set_item.go`). After save, prefer API-returned `prerequisite_question_ids`.
---
## React integration patterns
### Minimal section control on a question card
```tsx
function QuestionAssociationField({
question,
allQuestions,
onChange,
}: {
question: EditablePracticeQuestion;
allQuestions: EditablePracticeQuestion[];
onChange: (patch: Partial<EditablePracticeQuestion>) => void;
}) {
const isAnchor = question.associated_question_id == null;
const anchors = allQuestions.filter(
(q) => q.id != null && q.id !== question.id && q.associated_question_id == null
);
return (
<div>
<label>
<input
type="checkbox"
checked={isAnchor}
onChange={(e) =>
onChange({ associated_question_id: e.target.checked ? null : anchors[0]?.id ?? null })
}
/>
Starts a new section
</label>
{!isAnchor && (
<select
value={question.associated_question_id ?? ""}
onChange={(e) =>
onChange({
associated_question_id: e.target.value ? Number(e.target.value) : null,
})
}
>
<option value="">Select section anchor</option>
{anchors.map((a) => (
<option key={a.id} value={a.id}>
Q{a.display_order} (id {a.id})
</option>
))}
</select>
)}
</div>
);
}
```
### Save handler
```typescript
async function savePractice(practiceId: number, state: PracticeEditorState, token: string) {
const err = validateAssociations(state.questions);
if (err) throw new Error(err);
const res = await fetch(`${API_BASE}/api/v1/practices/${practiceId}/full`, {
method: "PUT",
headers: {
Authorization: `Bearer ${token}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
practice: state.practice,
question_set: state.questionSet,
questions: state.questions.map(mapEditableToSaveItem),
}),
});
if (!res.ok) {
const body = await res.json().catch(() => ({}));
throw new Error(body.error || body.message || `Save failed (${res.status})`);
}
const json: ApiResponse<PracticeFullResponse> = await res.json();
return json.data;
}
```
After save, **replace local state** from the response so new question `id` values and association fields stay in sync.
---
## Error handling
| HTTP | `message` | Typical cause | Admin UI action |
|------|-----------|---------------|-----------------|
| 400 | `Invalid question association` | Broken anchor reference or order | Highlight offending row; show `error` detail |
| 400 | `Invalid question item` | Missing `question_type`, bad dynamic payload, etc. | Existing question validation |
| 404 | `Practice not found` | Wrong ID | Navigate away |
| 403 | Permission denied | Missing `practices.update` | RBAC message |
Always display API `error` string when present — it includes the specific rule that failed.
---
## Learner app note
The admin panel **configures** associations; the learner app **enforces** them without server progress tracking:
1. `GET /api/v1/practices/:practiceId/questions` (paginated) or full practice payload includes `prerequisite_question_ids` per question.
2. The client marks questions complete locally (or on answer submit).
3. A question is enterable only when every ID in `prerequisite_question_ids` is complete.
Admin authors can verify structure using the same fields in GET responses — no separate preview API is required.
---
## Integration checklist
### Data & API
- [ ] Migration `000088` applied in target environments
- [ ] Practice load (`GET .../full`) maps `associated_question_id` into editor state
- [ ] Practice save (`PUT .../full`) sends `associated_question_id` per question
- [ ] Do **not** send `prerequisite_question_ids` on save
- [ ] After save, refresh question list from response (new `id` values)
### UI
- [ ] Section anchor control per question row
- [ ] “Start new section” defaults `associated_question_id: null`
- [ ] Associated questions pick anchor from dropdown (anchors only)
- [ ] Drag-and-drop reorder updates `display_order` and revalidates
- [ ] Client-side validation before save
- [ ] Inline error for invalid association (400 from API)
### QA scenarios
- [ ] Single-section practice — all anchors, all `associated_question_id: null` (behaves like flat sequential list)
- [ ] Two sections — complete validation on save
- [ ] Reorder anchor above its dependents — save rejected or client blocked
- [ ] Associate to non-anchor question — rejected
- [ ] Create new questions + associations in **one** save (anchor has existing `id`)
- [ ] Create brand-new practice: first save creates IDs; second save can link new rows to first anchor
- [ ] Exam-prep practice editor — same fields on `exam-prep/.../full` routes
- [ ] GET response shows expected `prerequisite_question_ids` for learner QA
---
## Limitations
| Topic | Current behavior |
|-------|------------------|
| Server-side question progress | Not implemented — client gates access |
| `associated_question_id` targets | Must be question **IDs** in the same set |
| New question as anchor for same-save children | Anchor must have `id` (from load or prior save) |
| Cross-practice associations | Not supported |
| Branching / skip paths | Only linear sections + order within section |
| `shuffle_questions` on question set | May conflict with authored order — document for authors |
---
## Quick reference
### Full practice (preferred for admin editor)
| Action | LMS | Exam-prep |
|--------|-----|-----------|
| Load | `GET /api/v1/practices/:id/full` | `GET /api/v1/exam-prep/practices/:id/full` |
| Save | `PUT /api/v1/practices/:id/full` | `PUT /api/v1/exam-prep/practices/:id/full` |
### Per-question fields
| Field | Direction | Description |
|-------|-----------|-------------|
| `display_order` | Read/write | Sort position |
| `associated_question_id` | Read/write | `null` = section anchor; else anchor question ID |
| `prerequisite_question_ids` | Read-only | Computed unlock list for clients |
### Validation rules (save)
1. Associated ID must exist in the same practice question list.
2. Associated ID must point to an **anchor** (`associated_question_id` is null).
3. Anchor `display_order` must be **less than** dependent `display_order`.
4. No self-association.
### Example two-section payload (minimal)
```json
{
"questions": [
{ "id": 1, "display_order": 1, "associated_question_id": null },
{ "id": 2, "display_order": 2, "associated_question_id": 1 },
{ "id": 3, "display_order": 3, "associated_question_id": null },
{ "id": 4, "display_order": 4, "associated_question_id": 3 }
]
}
```

View File

@ -382,11 +382,12 @@ type QuestionSet struct {
}
type QuestionSetItem struct {
ID int64 `json:"id"`
SetID int64 `json:"set_id"`
QuestionID int64 `json:"question_id"`
DisplayOrder int32 `json:"display_order"`
CreatedAt pgtype.Timestamptz `json:"created_at"`
ID int64 `json:"id"`
SetID int64 `json:"set_id"`
QuestionID int64 `json:"question_id"`
DisplayOrder int32 `json:"display_order"`
CreatedAt pgtype.Timestamptz `json:"created_at"`
AssociatedQuestionID pgtype.Int8 `json:"associated_question_id"`
}
type QuestionSetPersona struct {

View File

@ -15,7 +15,8 @@ const AddQuestionToSet = `-- name: AddQuestionToSet :one
INSERT INTO question_set_items (
set_id,
question_id,
display_order
display_order,
associated_question_id
)
VALUES (
$1,
@ -27,20 +28,29 @@ VALUES (
FROM question_set_items AS qsi
WHERE qsi.set_id = $1
), 0) + 1
)
),
$4
)
ON CONFLICT (set_id, question_id) DO UPDATE SET display_order = EXCLUDED.display_order
RETURNING id, set_id, question_id, display_order, created_at
ON CONFLICT (set_id, question_id) DO UPDATE SET
display_order = EXCLUDED.display_order,
associated_question_id = EXCLUDED.associated_question_id
RETURNING id, set_id, question_id, display_order, created_at, associated_question_id
`
type AddQuestionToSetParams struct {
SetID int64 `json:"set_id"`
QuestionID int64 `json:"question_id"`
DisplayOrder pgtype.Int4 `json:"display_order"`
SetID int64 `json:"set_id"`
QuestionID int64 `json:"question_id"`
DisplayOrder pgtype.Int4 `json:"display_order"`
AssociatedQuestionID pgtype.Int8 `json:"associated_question_id"`
}
func (q *Queries) AddQuestionToSet(ctx context.Context, arg AddQuestionToSetParams) (QuestionSetItem, error) {
row := q.db.QueryRow(ctx, AddQuestionToSet, arg.SetID, arg.QuestionID, arg.DisplayOrder)
row := q.db.QueryRow(ctx, AddQuestionToSet,
arg.SetID,
arg.QuestionID,
arg.DisplayOrder,
arg.AssociatedQuestionID,
)
var i QuestionSetItem
err := row.Scan(
&i.ID,
@ -48,6 +58,7 @@ func (q *Queries) AddQuestionToSet(ctx context.Context, arg AddQuestionToSetPara
&i.QuestionID,
&i.DisplayOrder,
&i.CreatedAt,
&i.AssociatedQuestionID,
)
return i, err
}
@ -73,6 +84,7 @@ SELECT
qsi.set_id,
qsi.question_id,
qsi.display_order,
qsi.associated_question_id,
q.question_text,
q.question_type,
q.dynamic_payload,
@ -97,6 +109,7 @@ type GetPublishedQuestionsInSetRow struct {
SetID int64 `json:"set_id"`
QuestionID int64 `json:"question_id"`
DisplayOrder int32 `json:"display_order"`
AssociatedQuestionID pgtype.Int8 `json:"associated_question_id"`
QuestionText string `json:"question_text"`
QuestionType string `json:"question_type"`
DynamicPayload []byte `json:"dynamic_payload"`
@ -124,6 +137,7 @@ func (q *Queries) GetPublishedQuestionsInSet(ctx context.Context, setID int64) (
&i.SetID,
&i.QuestionID,
&i.DisplayOrder,
&i.AssociatedQuestionID,
&i.QuestionText,
&i.QuestionType,
&i.DynamicPayload,
@ -152,6 +166,7 @@ SELECT
qsi.set_id,
qsi.question_id,
qsi.display_order,
qsi.associated_question_id,
q.question_text,
q.question_type,
q.dynamic_payload,
@ -177,6 +192,7 @@ type GetQuestionSetItemsRow struct {
SetID int64 `json:"set_id"`
QuestionID int64 `json:"question_id"`
DisplayOrder int32 `json:"display_order"`
AssociatedQuestionID pgtype.Int8 `json:"associated_question_id"`
QuestionText string `json:"question_text"`
QuestionType string `json:"question_type"`
DynamicPayload []byte `json:"dynamic_payload"`
@ -205,6 +221,7 @@ func (q *Queries) GetQuestionSetItems(ctx context.Context, setID int64) ([]GetQu
&i.SetID,
&i.QuestionID,
&i.DisplayOrder,
&i.AssociatedQuestionID,
&i.QuestionText,
&i.QuestionType,
&i.DynamicPayload,
@ -235,6 +252,7 @@ SELECT
qsi.set_id,
qsi.question_id,
qsi.display_order,
qsi.associated_question_id,
q.question_text,
q.question_type,
q.dynamic_payload,
@ -271,6 +289,7 @@ type GetQuestionSetItemsPaginatedRow struct {
SetID int64 `json:"set_id"`
QuestionID int64 `json:"question_id"`
DisplayOrder int32 `json:"display_order"`
AssociatedQuestionID pgtype.Int8 `json:"associated_question_id"`
QuestionText string `json:"question_text"`
QuestionType string `json:"question_type"`
DynamicPayload []byte `json:"dynamic_payload"`
@ -305,6 +324,7 @@ func (q *Queries) GetQuestionSetItemsPaginated(ctx context.Context, arg GetQuest
&i.SetID,
&i.QuestionID,
&i.DisplayOrder,
&i.AssociatedQuestionID,
&i.QuestionText,
&i.QuestionType,
&i.DynamicPayload,
@ -427,19 +447,26 @@ func (q *Queries) RemoveQuestionFromSet(ctx context.Context, arg RemoveQuestionF
return err
}
const UpdateQuestionOrder = `-- name: UpdateQuestionOrder :exec
const UpdateQuestionSetItem = `-- name: UpdateQuestionSetItem :exec
UPDATE question_set_items
SET display_order = $1
WHERE set_id = $2 AND question_id = $3
SET display_order = $1,
associated_question_id = $2
WHERE set_id = $3 AND question_id = $4
`
type UpdateQuestionOrderParams struct {
DisplayOrder int32 `json:"display_order"`
SetID int64 `json:"set_id"`
QuestionID int64 `json:"question_id"`
type UpdateQuestionSetItemParams struct {
DisplayOrder int32 `json:"display_order"`
AssociatedQuestionID pgtype.Int8 `json:"associated_question_id"`
SetID int64 `json:"set_id"`
QuestionID int64 `json:"question_id"`
}
func (q *Queries) UpdateQuestionOrder(ctx context.Context, arg UpdateQuestionOrderParams) error {
_, err := q.db.Exec(ctx, UpdateQuestionOrder, arg.DisplayOrder, arg.SetID, arg.QuestionID)
func (q *Queries) UpdateQuestionSetItem(ctx context.Context, arg UpdateQuestionSetItemParams) error {
_, err := q.db.Exec(ctx, UpdateQuestionSetItem,
arg.DisplayOrder,
arg.AssociatedQuestionID,
arg.SetID,
arg.QuestionID,
)
return err
}

View File

@ -36,6 +36,7 @@ type FullUpdateQuestionSetInput struct {
type FullUpdatePracticeQuestionItem struct {
ID *int64 `json:"id,omitempty"`
DisplayOrder *int32 `json:"display_order,omitempty"`
AssociatedQuestionID *int64 `json:"associated_question_id,omitempty"`
QuestionText *string `json:"question_text,omitempty"`
QuestionType *string `json:"question_type,omitempty"`
QuestionTypeDefinitionID *int64 `json:"question_type_definition_id,omitempty"`

View File

@ -0,0 +1,115 @@
package domain
import (
"errors"
"fmt"
)
var ErrInvalidQuestionAssociation = errors.New("invalid question association")
// QuestionSetMembership describes one question's placement and association within a set.
type QuestionSetMembership struct {
QuestionID int64
DisplayOrder int32
AssociatedQuestionID *int64
}
// ValidateQuestionSetAssociations checks association rules for all memberships in a set.
// associated_question_id must reference a section anchor (no association) in the same set
// with a lower display_order.
func ValidateQuestionSetAssociations(memberships []QuestionSetMembership) error {
byID := make(map[int64]QuestionSetMembership, len(memberships))
for _, m := range memberships {
byID[m.QuestionID] = m
}
for _, m := range memberships {
if m.AssociatedQuestionID == nil {
continue
}
assocID := *m.AssociatedQuestionID
if assocID == m.QuestionID {
return fmt.Errorf("question %d cannot be associated with itself", m.QuestionID)
}
assoc, ok := byID[assocID]
if !ok {
return fmt.Errorf("associated_question_id %d is not in the question set", assocID)
}
if assoc.AssociatedQuestionID != nil {
return fmt.Errorf("associated_question_id %d must reference a section anchor question", assocID)
}
if assoc.DisplayOrder >= m.DisplayOrder {
return fmt.Errorf("associated question %d must have a lower display_order than question %d", assocID, m.QuestionID)
}
}
return nil
}
// PrerequisiteQuestionIDs returns question IDs that must be completed before accessing targetQuestionID.
func PrerequisiteQuestionIDs(memberships []QuestionSetMembership, targetQuestionID int64) []int64 {
byID := make(map[int64]QuestionSetMembership, len(memberships))
ordered := make([]QuestionSetMembership, 0, len(memberships))
for _, m := range memberships {
byID[m.QuestionID] = m
ordered = append(ordered, m)
}
target, ok := byID[targetQuestionID]
if !ok {
return nil
}
seen := make(map[int64]struct{})
add := func(id int64) {
if id == targetQuestionID {
return
}
if _, ok := seen[id]; ok {
return
}
seen[id] = struct{}{}
}
if target.AssociatedQuestionID == nil {
for _, m := range ordered {
if m.DisplayOrder < target.DisplayOrder {
add(m.QuestionID)
}
}
} else {
anchorID := *target.AssociatedQuestionID
anchor := byID[anchorID]
for _, m := range ordered {
if m.DisplayOrder < anchor.DisplayOrder {
add(m.QuestionID)
}
}
for _, m := range ordered {
if m.QuestionID == anchorID || (m.AssociatedQuestionID != nil && *m.AssociatedQuestionID == anchorID) {
if m.DisplayOrder < target.DisplayOrder {
add(m.QuestionID)
}
}
}
}
out := make([]int64, 0, len(seen))
for _, m := range ordered {
if _, ok := seen[m.QuestionID]; ok {
out = append(out, m.QuestionID)
}
}
return out
}
// MembershipsFromQuestionSetItems converts set items to membership inputs for validation.
func MembershipsFromQuestionSetItems(items []QuestionSetItemWithQuestion) []QuestionSetMembership {
out := make([]QuestionSetMembership, len(items))
for i, item := range items {
out[i] = QuestionSetMembership{
QuestionID: item.QuestionID,
DisplayOrder: item.DisplayOrder,
AssociatedQuestionID: item.AssociatedQuestionID,
}
}
return out
}

View File

@ -0,0 +1,51 @@
package domain
import "testing"
func TestValidateQuestionSetAssociations(t *testing.T) {
anchor := int64(1)
associated := int64(2)
invalidAssoc := int64(99)
memberships := []QuestionSetMembership{
{QuestionID: 1, DisplayOrder: 1, AssociatedQuestionID: nil},
{QuestionID: 2, DisplayOrder: 2, AssociatedQuestionID: &anchor},
{QuestionID: 3, DisplayOrder: 3, AssociatedQuestionID: &anchor},
{QuestionID: 4, DisplayOrder: 4, AssociatedQuestionID: nil},
}
if err := ValidateQuestionSetAssociations(memberships); err != nil {
t.Fatalf("expected valid associations, got %v", err)
}
if err := ValidateQuestionSetAssociations([]QuestionSetMembership{
{QuestionID: 2, DisplayOrder: 2, AssociatedQuestionID: &associated},
}); err == nil {
t.Fatal("expected error when associating with non-anchor question")
}
if err := ValidateQuestionSetAssociations([]QuestionSetMembership{
{QuestionID: 2, DisplayOrder: 2, AssociatedQuestionID: &invalidAssoc},
}); err == nil {
t.Fatal("expected error when associated question is not in set")
}
}
func TestPrerequisiteQuestionIDs(t *testing.T) {
anchor := int64(1)
memberships := []QuestionSetMembership{
{QuestionID: 1, DisplayOrder: 1, AssociatedQuestionID: nil},
{QuestionID: 2, DisplayOrder: 2, AssociatedQuestionID: &anchor},
{QuestionID: 3, DisplayOrder: 3, AssociatedQuestionID: &anchor},
{QuestionID: 4, DisplayOrder: 4, AssociatedQuestionID: nil},
}
got := PrerequisiteQuestionIDs(memberships, 3)
if len(got) != 2 || got[0] != 1 || got[1] != 2 {
t.Fatalf("unexpected prerequisites for question 3: %#v", got)
}
got = PrerequisiteQuestionIDs(memberships, 4)
if len(got) != 3 || got[0] != 1 || got[1] != 2 || got[2] != 3 {
t.Fatalf("unexpected prerequisites for question 4: %#v", got)
}
}

View File

@ -113,11 +113,12 @@ type QuestionSet struct {
}
type QuestionSetItem struct {
ID int64
SetID int64
QuestionID int64
DisplayOrder int32
CreatedAt time.Time
ID int64
SetID int64
QuestionID int64
DisplayOrder int32
AssociatedQuestionID *int64
CreatedAt time.Time
}
// QuestionSetQuestionTypeGroup is a raw DB aggregate before resolving builder definitions.

View File

@ -51,12 +51,12 @@ type QuestionStore interface {
DeleteQuestionSet(ctx context.Context, id int64) error
// Question Set Items
AddQuestionToSet(ctx context.Context, setID, questionID int64, displayOrder *int32) (domain.QuestionSetItem, error)
AddQuestionToSet(ctx context.Context, setID, questionID int64, displayOrder *int32, associatedQuestionID *int64) (domain.QuestionSetItem, error)
GetQuestionSetItems(ctx context.Context, setID int64) ([]domain.QuestionSetItemWithQuestion, error)
GetQuestionSetItemsPaginated(ctx context.Context, setID int64, questionType *string, limit, offset int32) ([]domain.QuestionSetItemWithQuestion, int64, error)
GetPublishedQuestionsInSet(ctx context.Context, setID int64) ([]domain.QuestionSetItemWithQuestion, error)
RemoveQuestionFromSet(ctx context.Context, setID, questionID int64) error
UpdateQuestionOrder(ctx context.Context, setID, questionID int64, displayOrder int32) error
UpdateQuestionSetItem(ctx context.Context, setID, questionID int64, displayOrder int32, associatedQuestionID *int64) error
CountQuestionsInSet(ctx context.Context, setID int64) (int64, error)
GetQuestionTypeCountsInSet(ctx context.Context, setID int64) ([]domain.QuestionSetQuestionTypeGroup, error)
GetQuestionSetsContainingQuestion(ctx context.Context, questionID int64) ([]domain.QuestionSet, error)

View File

@ -166,11 +166,12 @@ func questionSetToDomain(qs dbgen.QuestionSet) domain.QuestionSet {
func questionSetItemToDomain(i dbgen.QuestionSetItem) domain.QuestionSetItem {
return domain.QuestionSetItem{
ID: i.ID,
SetID: i.SetID,
QuestionID: i.QuestionID,
DisplayOrder: i.DisplayOrder,
CreatedAt: i.CreatedAt.Time,
ID: i.ID,
SetID: i.SetID,
QuestionID: i.QuestionID,
DisplayOrder: i.DisplayOrder,
AssociatedQuestionID: fromPgInt8(i.AssociatedQuestionID),
CreatedAt: i.CreatedAt.Time,
}
}
@ -1095,16 +1096,12 @@ func (s *Store) DeleteQuestionSet(ctx context.Context, id int64) error {
return s.queries.DeleteQuestionSet(ctx, id)
}
func (s *Store) AddQuestionToSet(ctx context.Context, setID, questionID int64, displayOrder *int32) (domain.QuestionSetItem, error) {
orderParam := pgtype.Int4{Valid: false}
if displayOrder != nil {
orderParam = pgtype.Int4{Int32: *displayOrder, Valid: true}
}
func (s *Store) AddQuestionToSet(ctx context.Context, setID, questionID int64, displayOrder *int32, associatedQuestionID *int64) (domain.QuestionSetItem, error) {
item, err := s.queries.AddQuestionToSet(ctx, dbgen.AddQuestionToSetParams{
SetID: setID,
QuestionID: questionID,
DisplayOrder: orderParam,
SetID: setID,
QuestionID: questionID,
DisplayOrder: toPgInt4(displayOrder),
AssociatedQuestionID: toPgInt8(associatedQuestionID),
})
if err != nil {
return domain.QuestionSetItem{}, err
@ -1122,10 +1119,11 @@ func (s *Store) GetQuestionSetItems(ctx context.Context, setID int64) ([]domain.
for i, r := range rows {
result[i] = domain.QuestionSetItemWithQuestion{
QuestionSetItem: domain.QuestionSetItem{
ID: r.ID,
SetID: r.SetID,
QuestionID: r.QuestionID,
DisplayOrder: r.DisplayOrder,
ID: r.ID,
SetID: r.SetID,
QuestionID: r.QuestionID,
DisplayOrder: r.DisplayOrder,
AssociatedQuestionID: fromPgInt8(r.AssociatedQuestionID),
},
QuestionText: r.QuestionText,
QuestionType: r.QuestionType,
@ -1167,10 +1165,11 @@ func (s *Store) GetQuestionSetItemsPaginated(ctx context.Context, setID int64, q
}
result[i] = domain.QuestionSetItemWithQuestion{
QuestionSetItem: domain.QuestionSetItem{
ID: r.ID,
SetID: r.SetID,
QuestionID: r.QuestionID,
DisplayOrder: r.DisplayOrder,
ID: r.ID,
SetID: r.SetID,
QuestionID: r.QuestionID,
DisplayOrder: r.DisplayOrder,
AssociatedQuestionID: fromPgInt8(r.AssociatedQuestionID),
},
QuestionText: r.QuestionText,
QuestionType: r.QuestionType,
@ -1199,10 +1198,11 @@ func (s *Store) GetPublishedQuestionsInSet(ctx context.Context, setID int64) ([]
for i, r := range rows {
result[i] = domain.QuestionSetItemWithQuestion{
QuestionSetItem: domain.QuestionSetItem{
ID: r.ID,
SetID: r.SetID,
QuestionID: r.QuestionID,
DisplayOrder: r.DisplayOrder,
ID: r.ID,
SetID: r.SetID,
QuestionID: r.QuestionID,
DisplayOrder: r.DisplayOrder,
AssociatedQuestionID: fromPgInt8(r.AssociatedQuestionID),
},
QuestionText: r.QuestionText,
QuestionType: r.QuestionType,
@ -1228,11 +1228,12 @@ func (s *Store) RemoveQuestionFromSet(ctx context.Context, setID, questionID int
})
}
func (s *Store) UpdateQuestionOrder(ctx context.Context, setID, questionID int64, displayOrder int32) error {
return s.queries.UpdateQuestionOrder(ctx, dbgen.UpdateQuestionOrderParams{
SetID: setID,
QuestionID: questionID,
DisplayOrder: displayOrder,
func (s *Store) UpdateQuestionSetItem(ctx context.Context, setID, questionID int64, displayOrder int32, associatedQuestionID *int64) error {
return s.queries.UpdateQuestionSetItem(ctx, dbgen.UpdateQuestionSetItemParams{
SetID: setID,
QuestionID: questionID,
DisplayOrder: displayOrder,
AssociatedQuestionID: toPgInt8(associatedQuestionID),
})
}

View File

@ -3,8 +3,9 @@ package practicecontent
import "errors"
var (
ErrPracticeNotFound = errors.New("practice not found")
ErrQuestionSetNotFound = errors.New("question set not found")
ErrQuestionNotFound = errors.New("question not found")
ErrInvalidQuestionItem = errors.New("invalid question item")
ErrPracticeNotFound = errors.New("practice not found")
ErrQuestionSetNotFound = errors.New("question set not found")
ErrQuestionNotFound = errors.New("question not found")
ErrInvalidQuestionItem = errors.New("invalid question item")
ErrInvalidQuestionAssociation = errors.New("invalid question association")
)

View File

@ -205,6 +205,10 @@ func displayOrderForItem(item domain.FullUpdatePracticeQuestionItem, index int)
return int32(index + 1)
}
func associatedQuestionIDForItem(item domain.FullUpdatePracticeQuestionItem) *int64 {
return item.AssociatedQuestionID
}
func (s *Service) replaceQuestionChildren(ctx context.Context, questionID int64, input domain.CreateQuestionInput) error {
if err := s.questions.DeleteOptionsByQuestionID(ctx, questionID); err != nil {
return err
@ -252,6 +256,7 @@ func (s *Service) syncQuestionsInSet(ctx context.Context, setID int64, items []d
desiredIDs := make(map[int64]struct{}, len(items))
orderedIDs := make([]int64, 0, len(items))
pendingMemberships := make([]domain.QuestionSetMembership, 0, len(items))
for i, item := range items {
order := displayOrderForItem(item, i)
@ -275,15 +280,20 @@ func (s *Service) syncQuestionsInSet(ctx context.Context, setID int64, items []d
}
if _, ok := currentInSet[questionID]; !ok {
if _, err := s.questions.AddQuestionToSet(ctx, setID, questionID, &order); err != nil {
if _, err := s.questions.AddQuestionToSet(ctx, setID, questionID, &order, nil); err != nil {
return nil, err
}
} else if err := s.questions.UpdateQuestionOrder(ctx, setID, questionID, order); err != nil {
} else if err := s.questions.UpdateQuestionSetItem(ctx, setID, questionID, order, nil); err != nil {
return nil, err
}
desiredIDs[questionID] = struct{}{}
orderedIDs = append(orderedIDs, questionID)
pendingMemberships = append(pendingMemberships, domain.QuestionSetMembership{
QuestionID: questionID,
DisplayOrder: order,
AssociatedQuestionID: associatedQuestionIDForItem(item),
})
continue
}
@ -295,11 +305,26 @@ func (s *Service) syncQuestionsInSet(ctx context.Context, setID int64, items []d
if err != nil {
return nil, err
}
if _, err := s.questions.AddQuestionToSet(ctx, setID, created.ID, &order); err != nil {
if _, err := s.questions.AddQuestionToSet(ctx, setID, created.ID, &order, nil); err != nil {
return nil, err
}
desiredIDs[created.ID] = struct{}{}
orderedIDs = append(orderedIDs, created.ID)
pendingMemberships = append(pendingMemberships, domain.QuestionSetMembership{
QuestionID: created.ID,
DisplayOrder: order,
AssociatedQuestionID: associatedQuestionIDForItem(item),
})
}
if err := domain.ValidateQuestionSetAssociations(pendingMemberships); err != nil {
return nil, fmt.Errorf("%w: %s", ErrInvalidQuestionAssociation, err.Error())
}
for _, membership := range pendingMemberships {
if err := s.questions.UpdateQuestionSetItem(ctx, setID, membership.QuestionID, membership.DisplayOrder, membership.AssociatedQuestionID); err != nil {
return nil, err
}
}
for _, it := range currentItems {

View File

@ -4,6 +4,7 @@ import (
"Yimaru-Backend/internal/domain"
"Yimaru-Backend/internal/ports"
"context"
"fmt"
)
type Service struct {
@ -184,8 +185,61 @@ func (s *Service) DeleteQuestionSet(ctx context.Context, id int64) error {
// Question Set Items
func (s *Service) AddQuestionToSet(ctx context.Context, setID, questionID int64, displayOrder *int32) (domain.QuestionSetItem, error) {
return s.questionStore.AddQuestionToSet(ctx, setID, questionID, displayOrder)
func upsertQuestionSetMembership(memberships []domain.QuestionSetMembership, questionID int64, displayOrder int32, associatedQuestionID *int64) []domain.QuestionSetMembership {
out := make([]domain.QuestionSetMembership, 0, len(memberships)+1)
replaced := false
for _, m := range memberships {
if m.QuestionID == questionID {
out = append(out, domain.QuestionSetMembership{
QuestionID: questionID,
DisplayOrder: displayOrder,
AssociatedQuestionID: associatedQuestionID,
})
replaced = true
continue
}
out = append(out, m)
}
if !replaced {
out = append(out, domain.QuestionSetMembership{
QuestionID: questionID,
DisplayOrder: displayOrder,
AssociatedQuestionID: associatedQuestionID,
})
}
return out
}
func (s *Service) validateSetMemberships(memberships []domain.QuestionSetMembership) error {
if err := domain.ValidateQuestionSetAssociations(memberships); err != nil {
return fmt.Errorf("%w: %s", domain.ErrInvalidQuestionAssociation, err.Error())
}
return nil
}
func (s *Service) AddQuestionToSet(ctx context.Context, setID, questionID int64, displayOrder *int32, associatedQuestionID *int64) (domain.QuestionSetItem, error) {
current, err := s.questionStore.GetQuestionSetItems(ctx, setID)
if err != nil {
return domain.QuestionSetItem{}, err
}
order := int32(0)
if displayOrder != nil {
order = *displayOrder
} else if len(current) > 0 {
for _, item := range current {
if item.DisplayOrder > order {
order = item.DisplayOrder
}
}
order++
} else {
order = 1
}
memberships := upsertQuestionSetMembership(domain.MembershipsFromQuestionSetItems(current), questionID, order, associatedQuestionID)
if err := s.validateSetMemberships(memberships); err != nil {
return domain.QuestionSetItem{}, err
}
return s.questionStore.AddQuestionToSet(ctx, setID, questionID, &order, associatedQuestionID)
}
func (s *Service) GetQuestionSetItems(ctx context.Context, setID int64) ([]domain.QuestionSetItemWithQuestion, error) {
@ -204,8 +258,16 @@ func (s *Service) RemoveQuestionFromSet(ctx context.Context, setID, questionID i
return s.questionStore.RemoveQuestionFromSet(ctx, setID, questionID)
}
func (s *Service) UpdateQuestionOrder(ctx context.Context, setID, questionID int64, displayOrder int32) error {
return s.questionStore.UpdateQuestionOrder(ctx, setID, questionID, displayOrder)
func (s *Service) UpdateQuestionSetItem(ctx context.Context, setID, questionID int64, displayOrder int32, associatedQuestionID *int64) error {
current, err := s.questionStore.GetQuestionSetItems(ctx, setID)
if err != nil {
return err
}
memberships := upsertQuestionSetMembership(domain.MembershipsFromQuestionSetItems(current), questionID, displayOrder, associatedQuestionID)
if err := s.validateSetMemberships(memberships); err != nil {
return err
}
return s.questionStore.UpdateQuestionSetItem(ctx, setID, questionID, displayOrder, associatedQuestionID)
}
func (s *Service) CountQuestionsInSet(ctx context.Context, setID int64) (int64, error) {

View File

@ -12,16 +12,23 @@ import (
func fullPracticeQuestionResponses(
questions []domain.QuestionWithDetails,
displayOrderByQuestionID map[int64]int32,
setItems []domain.QuestionSetItemWithQuestion,
catalog []domain.QuestionTypeDefinition,
) []questionRes {
memberships := domain.MembershipsFromQuestionSetItems(setItems)
itemByQuestionID := make(map[int64]domain.QuestionSetItemWithQuestion, len(setItems))
for _, item := range setItems {
itemByQuestionID[item.QuestionID] = item
}
out := make([]questionRes, 0, len(questions))
for _, question := range questions {
res := buildQuestionRes(question, catalog)
if displayOrderByQuestionID != nil {
if order, ok := displayOrderByQuestionID[question.ID]; ok {
res.DisplayOrder = &order
}
if item, ok := itemByQuestionID[question.ID]; ok {
order := item.DisplayOrder
res.DisplayOrder = &order
res.AssociatedQuestionID = item.AssociatedQuestionID
res.PrerequisiteQuestionIDs = domain.PrerequisiteQuestionIDs(memberships, question.ID)
}
out = append(out, res)
}
@ -37,17 +44,13 @@ func (h *Handler) buildFullPracticeResponse(
if err != nil {
return nil, err
}
displayOrderByQuestionID := make(map[int64]int32, len(items))
for _, item := range items {
displayOrderByQuestionID[item.QuestionID] = item.DisplayOrder
}
questionCount := int64(len(items))
qsRes := questionSetResFromDomain(result.QuestionSet)
qsRes.QuestionCount = &questionCount
return fiber.Map{
"practice": result.Practice,
"question_set": qsRes,
"questions": fullPracticeQuestionResponses(result.Questions, displayOrderByQuestionID, catalog),
"questions": fullPracticeQuestionResponses(result.Questions, items, catalog),
}, nil
}
@ -82,6 +85,8 @@ func mapPracticeFullError(err error, action string) (int, string) {
return fiber.StatusNotFound, "Persona not found"
case errors.Is(err, practicecontent.ErrInvalidQuestionItem):
return fiber.StatusBadRequest, "Invalid question item"
case errors.Is(err, practicecontent.ErrInvalidQuestionAssociation):
return fiber.StatusBadRequest, "Invalid question association"
default:
if action == "load" {
return fiber.StatusInternalServerError, "Failed to load practice"

View File

@ -59,6 +59,8 @@ type shortAnswerRes struct {
type questionRes struct {
ID int64 `json:"id"`
DisplayOrder *int32 `json:"display_order,omitempty"`
AssociatedQuestionID *int64 `json:"associated_question_id,omitempty"`
PrerequisiteQuestionIDs []int64 `json:"prerequisite_question_ids,omitempty"`
QuestionText *string `json:"question_text,omitempty"`
QuestionType string `json:"question_type"`
QuestionTypeDefinitionID *int64 `json:"question_type_definition_id,omitempty"`
@ -1268,6 +1270,8 @@ type addQuestionToSetReq struct {
QuestionID int64 `json:"question_id" validate:"required"`
// Omit to append after the current highest display_order in the set; set explicitly to insert at a position.
DisplayOrder *int32 `json:"display_order,omitempty" validate:"omitempty,min=0"`
// Section anchor question in the same set; must have a lower display_order and no association of its own.
AssociatedQuestionID *int64 `json:"associated_question_id,omitempty" validate:"omitempty,min=1"`
}
type questionSetItemRes struct {
@ -1275,6 +1279,8 @@ type questionSetItemRes struct {
SetID int64 `json:"set_id"`
QuestionID int64 `json:"question_id"`
DisplayOrder int32 `json:"display_order"`
AssociatedQuestionID *int64 `json:"associated_question_id,omitempty"`
PrerequisiteQuestionIDs []int64 `json:"prerequisite_question_ids,omitempty"`
QuestionText *string `json:"question_text,omitempty"`
QuestionType string `json:"question_type"`
DynamicPayload *domain.DynamicQuestionPayload `json:"dynamic_payload,omitempty"`
@ -1297,6 +1303,7 @@ type paginatedQuestionSetItemsRes struct {
}
func questionSetItemsToRes(items []domain.QuestionSetItemWithQuestion) []questionSetItemRes {
memberships := domain.MembershipsFromQuestionSetItems(items)
out := make([]questionSetItemRes, 0, len(items))
for _, item := range items {
out = append(out, questionSetItemRes{
@ -1304,6 +1311,8 @@ func questionSetItemsToRes(items []domain.QuestionSetItemWithQuestion) []questio
SetID: item.SetID,
QuestionID: item.QuestionID,
DisplayOrder: item.DisplayOrder,
AssociatedQuestionID: item.AssociatedQuestionID,
PrerequisiteQuestionIDs: domain.PrerequisiteQuestionIDs(memberships, item.QuestionID),
QuestionText: questionTextField(item.QuestionType, item.QuestionText),
QuestionType: item.QuestionType,
DynamicPayload: item.DynamicPayload,
@ -1357,8 +1366,14 @@ func (h *Handler) AddQuestionToSet(c *fiber.Ctx) error {
})
}
item, err := h.questionsSvc.AddQuestionToSet(c.Context(), setID, req.QuestionID, req.DisplayOrder)
item, err := h.questionsSvc.AddQuestionToSet(c.Context(), setID, req.QuestionID, req.DisplayOrder, req.AssociatedQuestionID)
if err != nil {
if errors.Is(err, domain.ErrInvalidQuestionAssociation) {
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
Message: "Invalid question association",
Error: err.Error(),
})
}
return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{
Message: "Failed to add question to set",
Error: err.Error(),
@ -1379,10 +1394,11 @@ func (h *Handler) AddQuestionToSet(c *fiber.Ctx) error {
return c.Status(fiber.StatusCreated).JSON(domain.Response{
Message: "Question added to set successfully",
Data: map[string]interface{}{
"id": item.ID,
"set_id": item.SetID,
"question_id": item.QuestionID,
"display_order": item.DisplayOrder,
"id": item.ID,
"set_id": item.SetID,
"question_id": item.QuestionID,
"display_order": item.DisplayOrder,
"associated_question_id": item.AssociatedQuestionID,
},
})
}
@ -1486,6 +1502,7 @@ func (h *Handler) GetQuestionsInSet(c *fiber.Ctx) error {
}
questionResponses := make([]questionRes, 0, len(items))
memberships := domain.MembershipsFromQuestionSetItems(items)
for _, item := range items {
question, err := h.questionsSvc.GetQuestionWithDetails(c.Context(), item.QuestionID)
if err != nil {
@ -1498,6 +1515,8 @@ func (h *Handler) GetQuestionsInSet(c *fiber.Ctx) error {
res := buildQuestionRes(question, catalog)
order := item.DisplayOrder
res.DisplayOrder = &order
res.AssociatedQuestionID = item.AssociatedQuestionID
res.PrerequisiteQuestionIDs = domain.PrerequisiteQuestionIDs(memberships, item.QuestionID)
questionResponses = append(questionResponses, res)
}
@ -1771,7 +1790,8 @@ func (h *Handler) RemoveQuestionFromSet(c *fiber.Ctx) error {
}
type updateQuestionOrderReq struct {
DisplayOrder int32 `json:"display_order" validate:"required"`
DisplayOrder int32 `json:"display_order" validate:"required"`
AssociatedQuestionID *int64 `json:"associated_question_id,omitempty" validate:"omitempty,min=1"`
}
// UpdateQuestionOrder godoc
@ -1814,10 +1834,16 @@ func (h *Handler) UpdateQuestionOrderInSet(c *fiber.Ctx) error {
})
}
err = h.questionsSvc.UpdateQuestionOrder(c.Context(), setID, questionID, req.DisplayOrder)
err = h.questionsSvc.UpdateQuestionSetItem(c.Context(), setID, questionID, req.DisplayOrder, req.AssociatedQuestionID)
if err != nil {
if errors.Is(err, domain.ErrInvalidQuestionAssociation) {
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
Message: "Invalid question association",
Error: err.Error(),
})
}
return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{
Message: "Failed to update question order",
Message: "Failed to update question set item",
Error: err.Error(),
})
}