feat: support nullable parents for exam-prep practices
Add POST/GET /exam-prep/practices and PUT .../parents mirroring the LMS shell-then-link flow. Update admin panel integration guide and exam_prep.practices.list permission. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
parent
bfa96b7372
commit
75fb913704
|
|
@ -64,3 +64,32 @@ RETURNING *;
|
|||
-- name: ExamPrepDeleteLessonPractice :exec
|
||||
DELETE FROM exam_prep.lesson_practices
|
||||
WHERE id = $1;
|
||||
|
||||
-- name: ListAllExamPrepPractices :many
|
||||
SELECT
|
||||
COUNT(*) OVER () AS total_count,
|
||||
p.id,
|
||||
p.title,
|
||||
p.story_description,
|
||||
p.story_image,
|
||||
p.persona_id,
|
||||
p.question_set_id,
|
||||
p.quick_tips,
|
||||
p.publish_status,
|
||||
p.created_at,
|
||||
p.updated_at
|
||||
FROM exam_prep.lesson_practices p
|
||||
WHERE (
|
||||
sqlc.arg('published_only')::boolean = FALSE
|
||||
OR p.publish_status = 'PUBLISHED'::TEXT
|
||||
)
|
||||
AND (
|
||||
sqlc.arg('unlinked_only')::boolean = FALSE
|
||||
OR NOT EXISTS (
|
||||
SELECT 1
|
||||
FROM exam_prep.practice_parents pp
|
||||
WHERE pp.practice_id = p.id
|
||||
)
|
||||
)
|
||||
ORDER BY p.created_at DESC
|
||||
LIMIT $1 OFFSET $2;
|
||||
|
|
|
|||
|
|
@ -1,11 +1,11 @@
|
|||
# Create Practice with Nullable `parents` — Admin Panel Guide
|
||||
|
||||
This guide explains how the admin panel should **create LMS practices** when `parents` is **optional**. You can create a practice shell first (linked only to a question set), then attach it to courses, modules, and/or lessons later.
|
||||
This guide explains how the admin panel should **create practices** when `parents` is **optional** — for both **Learn English (LMS)** and **Exam Prep**. You can create a practice shell first (linked only to a question set), then attach it to hierarchy nodes later.
|
||||
|
||||
> **Scope:** `POST /api/v1/practices` (Learn English LMS). Exam-prep creation is unchanged.
|
||||
> **Scope:** `POST /api/v1/practices` (LMS) and `POST /api/v1/exam-prep/practices` (Exam Prep). Nested create routes under catalog courses, units, and lessons still work; see [Exam Prep](#exam-prep).
|
||||
>
|
||||
> **Related guides:**
|
||||
> - [practice-multi-parent-admin-panel-integration.md](./practice-multi-parent-admin-panel-integration.md) — multi-parent editing, list endpoints, constraints
|
||||
> - [practice-multi-parent-admin-panel-integration.md](./practice-multi-parent-admin-panel-integration.md) — multi-parent editing, list endpoints, LMS constraints
|
||||
> - [practice-question-associations-admin-panel-integration.md](./practice-question-associations-admin-panel-integration.md) — adding questions after the shell exists
|
||||
|
||||
---
|
||||
|
|
@ -26,19 +26,25 @@ This guide explains how the admin panel should **create LMS practices** when `pa
|
|||
12. [Error handling](#error-handling)
|
||||
13. [Integration checklist](#integration-checklist)
|
||||
14. [Quick reference](#quick-reference)
|
||||
15. [Exam Prep](#exam-prep)
|
||||
|
||||
---
|
||||
|
||||
## Summary
|
||||
|
||||
| Topic | Behavior |
|
||||
|-------|----------|
|
||||
| Required on create | `question_set_id` only |
|
||||
| `parents` on create | **Optional** — omit, `null`, or an array |
|
||||
| Response when unlinked | `"parents": null` |
|
||||
| Response when linked | `"parents": [{ "parent_kind", "parent_id" }, …]` |
|
||||
| Link after create | `PUT /api/v1/practices/:id/parents` |
|
||||
| Add questions after create | `PUT /api/v1/practices/:id/full` |
|
||||
| Topic | LMS | Exam Prep |
|
||||
|-------|-----|-----------|
|
||||
| Required on create | `question_set_id` | `question_set_id` |
|
||||
| `parents` on create | **Optional** — omit, `null`, or array | **Optional** — omit, `null`, or array |
|
||||
| Response when unlinked | `"parents": null` | `"parents": null` |
|
||||
| Create endpoint | `POST /api/v1/practices` | `POST /api/v1/exam-prep/practices` |
|
||||
| Link after create | `PUT /api/v1/practices/:id/parents` | `PUT /api/v1/exam-prep/practices/:id/parents` |
|
||||
| Add questions after create | `PUT /api/v1/practices/:id/full` | `PUT /api/v1/exam-prep/practices/:id/full` |
|
||||
| Parent kinds | `COURSE`, `MODULE`, `LESSON` | `CATALOG_COURSE`, `UNIT`, `LESSON` |
|
||||
| One practice per parent | **Yes** (409 conflict) | **No** — multiple practices per parent allowed |
|
||||
| List unlinked (admin) | `GET /api/v1/practices?unlinked_only=true` | `GET /api/v1/exam-prep/practices?unlinked_only=true` |
|
||||
|
||||
The sections below through [Quick reference](#quick-reference) describe **LMS** unless noted. [Exam Prep](#exam-prep) mirrors the same flow with exam-prep paths and parent kinds.
|
||||
|
||||
The nullable `parents` field supports a **two-phase authoring** model:
|
||||
|
||||
|
|
@ -502,7 +508,7 @@ async function createPracticeWorkflow(questionSetId: number, token: string) {
|
|||
| User action | API result | Suggested UI |
|
||||
|-------------|------------|--------------|
|
||||
| Create without `question_set_id` | 400 validation | Block submit; highlight question set field |
|
||||
| Create with taken lesson parent | 409 conflict | Toast: “This lesson already has a practice” |
|
||||
| Create with taken lesson parent | 409 conflict | Toast: “This lesson already has a practice” *(LMS only)* |
|
||||
| Attach invalid module id | 404 | Refresh hierarchy picker data |
|
||||
| Create unlinked, user expects lesson list | Practice missing from list | Explain “Attach to lesson first” |
|
||||
|
||||
|
|
@ -531,11 +537,11 @@ Always show the API `error` string when present.
|
|||
- [ ] `PUT /parents` with lesson → appears in `GET /lessons/:id/practices`
|
||||
- [ ] Create with parents at once still works
|
||||
- [ ] Legacy `parent_kind` + `parent_id` still works
|
||||
- [ ] 409 when attaching to entity that already has another practice
|
||||
- [ ] 409 when attaching to entity that already has another practice *(LMS only; Exam Prep allows multiple practices per parent)*
|
||||
|
||||
---
|
||||
|
||||
## Quick reference
|
||||
## Quick reference (LMS)
|
||||
|
||||
```bash
|
||||
# 1. Create unlinked shell
|
||||
|
|
@ -563,3 +569,225 @@ curl -s -X PUT "$API/api/v1/practices/55/parents" \
|
|||
| Create shell | `POST` | `/api/v1/practices` | `null` / omit / optional array |
|
||||
| Attach locations | `PUT` | `/api/v1/practices/:id/parents` | required array |
|
||||
| Add questions | `PUT` | `/api/v1/practices/:id/full` | not used |
|
||||
|
||||
---
|
||||
|
||||
## Exam Prep
|
||||
|
||||
Exam Prep uses the same **two-phase authoring** model as LMS: create an unlinked shell, attach catalog course / unit / lesson parents when ready, then save questions via the full endpoint.
|
||||
|
||||
### Endpoints
|
||||
|
||||
| Action | Permission | Endpoint |
|
||||
|--------|------------|----------|
|
||||
| Create practice | `exam_prep.practices.create` | `POST /api/v1/exam-prep/practices` |
|
||||
| List practices (incl. unlinked) | `exam_prep.practices.list` | `GET /api/v1/exam-prep/practices` |
|
||||
| Attach / update parents | `exam_prep.practices.update` | `PUT /api/v1/exam-prep/practices/:id/parents` |
|
||||
| Add questions | `exam_prep.practices.update` | `PUT /api/v1/exam-prep/practices/:id/full` |
|
||||
|
||||
Nested create routes (parent from URL when `parents` is omitted in body):
|
||||
|
||||
| Context | `POST` |
|
||||
|---------|--------|
|
||||
| Catalog course | `/api/v1/exam-prep/catalog-courses/:catalogCourseId/practices` |
|
||||
| Unit | `/api/v1/exam-prep/units/:unitId/practices` |
|
||||
| Lesson | `/api/v1/exam-prep/lessons/:lessonId/practices` |
|
||||
|
||||
If the request body includes `parents` (non-null), that array is used and the URL parent is ignored.
|
||||
|
||||
### Request body (`POST /api/v1/exam-prep/practices`)
|
||||
|
||||
Same shape as LMS, with exam-prep parent kinds:
|
||||
|
||||
| Field | Type | Required | Notes |
|
||||
|-------|------|----------|-------|
|
||||
| `question_set_id` | `number` | **Yes** | Must exist in `question_sets` |
|
||||
| `parents` | `array \| null` | No | Omit or `null` = unlinked shell |
|
||||
| `parent_kind` | `string` | No | Legacy: `CATALOG_COURSE` \| `UNIT` \| `LESSON` |
|
||||
| `parent_id` | `number` | No | Legacy; use with `parent_kind` |
|
||||
| `title`, `story_description`, `story_image`, `persona_id`, `quick_tips`, `publish_status` | | No | Same as LMS |
|
||||
|
||||
### `parents` item shape (Exam Prep)
|
||||
|
||||
| Field | Type | Values |
|
||||
|-------|------|--------|
|
||||
| `parent_kind` | `string` | `CATALOG_COURSE`, `UNIT`, `LESSON` |
|
||||
| `parent_id` | `number` | ID of that exam-prep entity |
|
||||
|
||||
### Create variants
|
||||
|
||||
**Unlinked shell:**
|
||||
|
||||
```json
|
||||
{
|
||||
"parents": null,
|
||||
"question_set_id": 100,
|
||||
"title": "New exam prep practice",
|
||||
"publish_status": "DRAFT"
|
||||
}
|
||||
```
|
||||
|
||||
**Create with unit parent:**
|
||||
|
||||
```json
|
||||
{
|
||||
"parents": [
|
||||
{ "parent_kind": "UNIT", "parent_id": 5 }
|
||||
],
|
||||
"question_set_id": 100,
|
||||
"publish_status": "DRAFT"
|
||||
}
|
||||
```
|
||||
|
||||
### Link parents after create
|
||||
|
||||
```http
|
||||
PUT /api/v1/exam-prep/practices/:id/parents
|
||||
Authorization: Bearer <token>
|
||||
Content-Type: application/json
|
||||
```
|
||||
|
||||
```json
|
||||
{
|
||||
"parents": [
|
||||
{ "parent_kind": "LESSON", "parent_id": 42 },
|
||||
{ "parent_kind": "CATALOG_COURSE", "parent_id": 7 }
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
- Replaces **all** links on each call.
|
||||
- Use `"parents": []` to detach completely.
|
||||
- **No 409 conflict** when a catalog course, unit, or lesson already has other practices (multiple practices per parent are allowed).
|
||||
|
||||
### List unlinked practices (admin)
|
||||
|
||||
```http
|
||||
GET /api/v1/exam-prep/practices?unlinked_only=true&limit=20&offset=0
|
||||
Authorization: Bearer <token>
|
||||
```
|
||||
|
||||
Requires `exam_prep.practices.list`. Only users who can manage exam-prep practices should pass `unlinked_only=true` (same pattern as LMS).
|
||||
|
||||
### TypeScript (Exam Prep)
|
||||
|
||||
```typescript
|
||||
type ExamPrepParentKind = "CATALOG_COURSE" | "UNIT" | "LESSON";
|
||||
|
||||
interface ExamPrepPracticeParent {
|
||||
parent_kind: ExamPrepParentKind;
|
||||
parent_id: number;
|
||||
}
|
||||
|
||||
interface CreateExamPrepPracticeInput {
|
||||
question_set_id: number;
|
||||
parents?: ExamPrepPracticeParent[] | null;
|
||||
parent_kind?: ExamPrepParentKind;
|
||||
parent_id?: number;
|
||||
title?: string;
|
||||
story_description?: string;
|
||||
story_image?: string;
|
||||
persona_id?: number;
|
||||
quick_tips?: string;
|
||||
publish_status?: "DRAFT" | "PUBLISHED";
|
||||
}
|
||||
```
|
||||
|
||||
```typescript
|
||||
async function createUnlinkedExamPrepPractice(
|
||||
questionSetId: number,
|
||||
token: string,
|
||||
meta?: { title?: string }
|
||||
) {
|
||||
const res = await fetch(`${API_BASE}/api/v1/exam-prep/practices`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
Authorization: `Bearer ${token}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
parents: null,
|
||||
question_set_id: questionSetId,
|
||||
title: meta?.title ?? "",
|
||||
publish_status: "DRAFT",
|
||||
}),
|
||||
});
|
||||
if (!res.ok) throw new Error((await res.json()).message);
|
||||
return (await res.json()).data;
|
||||
}
|
||||
|
||||
async function attachExamPrepPracticeParents(
|
||||
practiceId: number,
|
||||
parents: ExamPrepPracticeParent[],
|
||||
token: string
|
||||
) {
|
||||
const res = await fetch(
|
||||
`${API_BASE}/api/v1/exam-prep/practices/${practiceId}/parents`,
|
||||
{
|
||||
method: "PUT",
|
||||
headers: {
|
||||
Authorization: `Bearer ${token}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({ parents }),
|
||||
}
|
||||
);
|
||||
if (!res.ok) throw new Error((await res.json()).message);
|
||||
return (await res.json()).data;
|
||||
}
|
||||
```
|
||||
|
||||
### Exam Prep — error handling
|
||||
|
||||
| HTTP | `message` | Cause |
|
||||
|------|-----------|-------|
|
||||
| 400 | `Validation failed` | Missing `question_set_id` |
|
||||
| 404 | `Question set not found` | Invalid `question_set_id` |
|
||||
| 404 | `Catalog course not found` / `Unit not found` / `Lesson not found` | Bad `parent_id` |
|
||||
| 400 | `Invalid parent` | Unknown `parent_kind` |
|
||||
| 403 | Permission denied | Missing `exam_prep.practices.create` or `exam_prep.practices.update` |
|
||||
|
||||
> Exam Prep does **not** return 409 for “parent already has a practice”.
|
||||
|
||||
### Exam Prep — integration checklist
|
||||
|
||||
- [ ] `POST /exam-prep/practices` works with `parents` omitted or `null`
|
||||
- [ ] `GET /exam-prep/practices?unlinked_only=true` lists shells awaiting placement
|
||||
- [ ] `PUT /exam-prep/practices/:id/parents` wired for “Attach to…” step
|
||||
- [ ] `PUT /exam-prep/practices/:id/full` used for questions (not parents)
|
||||
- [ ] Nested routes (`/catalog-courses/.../practices`, etc.) still work when opened from hierarchy pages
|
||||
- [ ] UI uses `CATALOG_COURSE` / `UNIT` / `LESSON` — not LMS `COURSE` / `MODULE`
|
||||
|
||||
### Exam Prep — quick reference
|
||||
|
||||
```bash
|
||||
# 1. Create unlinked shell
|
||||
curl -s -X POST "$API/api/v1/exam-prep/practices" \
|
||||
-H "Authorization: Bearer $TOKEN" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{
|
||||
"parents": null,
|
||||
"question_set_id": 100,
|
||||
"title": "Draft exam prep practice",
|
||||
"publish_status": "DRAFT"
|
||||
}'
|
||||
|
||||
# 2. Attach to lesson 42 (use id from step 1)
|
||||
curl -s -X PUT "$API/api/v1/exam-prep/practices/55/parents" \
|
||||
-H "Authorization: Bearer $TOKEN" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{
|
||||
"parents": [{ "parent_kind": "LESSON", "parent_id": 42 }]
|
||||
}'
|
||||
|
||||
# 3. List unlinked practices (admin)
|
||||
curl -s "$API/api/v1/exam-prep/practices?unlinked_only=true" \
|
||||
-H "Authorization: Bearer $TOKEN"
|
||||
```
|
||||
|
||||
| Step | Method | Path | `parents` |
|
||||
|------|--------|------|-----------|
|
||||
| Create shell | `POST` | `/api/v1/exam-prep/practices` | `null` / omit / optional array |
|
||||
| Attach locations | `PUT` | `/api/v1/exam-prep/practices/:id/parents` | required array |
|
||||
| Add questions | `PUT` | `/api/v1/exam-prep/practices/:id/full` | not used |
|
||||
| List unlinked | `GET` | `/api/v1/exam-prep/practices?unlinked_only=true` | — |
|
||||
|
|
|
|||
|
|
@ -258,3 +258,91 @@ func (q *Queries) ExamPrepUpdateLessonPractice(ctx context.Context, arg ExamPrep
|
|||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const ListAllExamPrepPractices = `-- name: ListAllExamPrepPractices :many
|
||||
SELECT
|
||||
COUNT(*) OVER () AS total_count,
|
||||
p.id,
|
||||
p.title,
|
||||
p.story_description,
|
||||
p.story_image,
|
||||
p.persona_id,
|
||||
p.question_set_id,
|
||||
p.quick_tips,
|
||||
p.publish_status,
|
||||
p.created_at,
|
||||
p.updated_at
|
||||
FROM exam_prep.lesson_practices p
|
||||
WHERE (
|
||||
$3::boolean = FALSE
|
||||
OR p.publish_status = 'PUBLISHED'::TEXT
|
||||
)
|
||||
AND (
|
||||
$4::boolean = FALSE
|
||||
OR NOT EXISTS (
|
||||
SELECT 1
|
||||
FROM exam_prep.practice_parents pp
|
||||
WHERE pp.practice_id = p.id
|
||||
)
|
||||
)
|
||||
ORDER BY p.created_at DESC
|
||||
LIMIT $1 OFFSET $2
|
||||
`
|
||||
|
||||
type ListAllExamPrepPracticesParams struct {
|
||||
Limit int32 `json:"limit"`
|
||||
Offset int32 `json:"offset"`
|
||||
PublishedOnly bool `json:"published_only"`
|
||||
UnlinkedOnly bool `json:"unlinked_only"`
|
||||
}
|
||||
|
||||
type ListAllExamPrepPracticesRow struct {
|
||||
TotalCount int64 `json:"total_count"`
|
||||
ID int64 `json:"id"`
|
||||
Title string `json:"title"`
|
||||
StoryDescription pgtype.Text `json:"story_description"`
|
||||
StoryImage pgtype.Text `json:"story_image"`
|
||||
PersonaID pgtype.Int8 `json:"persona_id"`
|
||||
QuestionSetID int64 `json:"question_set_id"`
|
||||
QuickTips pgtype.Text `json:"quick_tips"`
|
||||
PublishStatus string `json:"publish_status"`
|
||||
CreatedAt pgtype.Timestamptz `json:"created_at"`
|
||||
UpdatedAt pgtype.Timestamptz `json:"updated_at"`
|
||||
}
|
||||
|
||||
func (q *Queries) ListAllExamPrepPractices(ctx context.Context, arg ListAllExamPrepPracticesParams) ([]ListAllExamPrepPracticesRow, error) {
|
||||
rows, err := q.db.Query(ctx, ListAllExamPrepPractices,
|
||||
arg.Limit,
|
||||
arg.Offset,
|
||||
arg.PublishedOnly,
|
||||
arg.UnlinkedOnly,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var items []ListAllExamPrepPracticesRow
|
||||
for rows.Next() {
|
||||
var i ListAllExamPrepPracticesRow
|
||||
if err := rows.Scan(
|
||||
&i.TotalCount,
|
||||
&i.ID,
|
||||
&i.Title,
|
||||
&i.StoryDescription,
|
||||
&i.StoryImage,
|
||||
&i.PersonaID,
|
||||
&i.QuestionSetID,
|
||||
&i.QuickTips,
|
||||
&i.PublishStatus,
|
||||
&i.CreatedAt,
|
||||
&i.UpdatedAt,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
|
|
|||
|
|
@ -64,15 +64,53 @@ func (p ExamPrepPractice) VisibleToLearners() bool {
|
|||
return p.PublishStatus == PracticePublishPublished
|
||||
}
|
||||
|
||||
// CreateExamPrepPracticeInput is the body for POST .../exam-prep/{parent}/practices.
|
||||
// CreateExamPrepPracticeInput is the body for POST .../exam-prep/practices and nested parent routes.
|
||||
type CreateExamPrepPracticeInput struct {
|
||||
Title *string `json:"title,omitempty"`
|
||||
StoryDescription *string `json:"story_description,omitempty"`
|
||||
StoryImage *string `json:"story_image,omitempty"`
|
||||
PersonaID *int64 `json:"persona_id,omitempty"`
|
||||
QuestionSetID int64 `json:"question_set_id" validate:"required,gt=0"`
|
||||
QuickTips *string `json:"quick_tips,omitempty"`
|
||||
PublishStatus string `json:"publish_status,omitempty" validate:"omitempty,oneof=DRAFT draft PUBLISHED published"`
|
||||
// Parents optionally attaches the practice to catalog course, unit, or lesson. Omit or null to create unlinked.
|
||||
Parents *[]ExamPrepPracticeParent `json:"parents" validate:"omitempty,dive"`
|
||||
// ParentKind and ParentID are accepted for backward compatibility when parents is omitted.
|
||||
ParentKind ExamPrepParentKind `json:"parent_kind,omitempty" validate:"omitempty,oneof=CATALOG_COURSE UNIT LESSON"`
|
||||
ParentID int64 `json:"parent_id,omitempty" validate:"omitempty,gt=0"`
|
||||
Title *string `json:"title,omitempty"`
|
||||
StoryDescription *string `json:"story_description,omitempty"`
|
||||
StoryImage *string `json:"story_image,omitempty"`
|
||||
PersonaID *int64 `json:"persona_id,omitempty"`
|
||||
QuestionSetID int64 `json:"question_set_id" validate:"required,gt=0"`
|
||||
QuickTips *string `json:"quick_tips,omitempty"`
|
||||
PublishStatus string `json:"publish_status,omitempty" validate:"omitempty,oneof=DRAFT draft PUBLISHED published"`
|
||||
}
|
||||
|
||||
// ResolvedParents returns deduplicated parents from parents or the legacy single-parent fields.
|
||||
func (in CreateExamPrepPracticeInput) ResolvedParents() []ExamPrepPracticeParent {
|
||||
if in.Parents != nil {
|
||||
return DedupeExamPrepPracticeParents(*in.Parents)
|
||||
}
|
||||
if in.ParentKind != "" && in.ParentID > 0 {
|
||||
return []ExamPrepPracticeParent{{Kind: in.ParentKind, ID: in.ParentID}}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// UpdateExamPrepPracticeParentsInput replaces all parent links on an existing exam-prep practice.
|
||||
type UpdateExamPrepPracticeParentsInput struct {
|
||||
Parents []ExamPrepPracticeParent `json:"parents" validate:"required,dive"`
|
||||
}
|
||||
|
||||
// DedupeExamPrepPracticeParents removes invalid and duplicate parent entries.
|
||||
func DedupeExamPrepPracticeParents(parents []ExamPrepPracticeParent) []ExamPrepPracticeParent {
|
||||
seen := make(map[ExamPrepPracticeParent]struct{}, len(parents))
|
||||
out := make([]ExamPrepPracticeParent, 0, len(parents))
|
||||
for _, p := range parents {
|
||||
if p.Kind == "" || p.ID <= 0 {
|
||||
continue
|
||||
}
|
||||
if _, ok := seen[p]; ok {
|
||||
continue
|
||||
}
|
||||
seen[p] = struct{}{}
|
||||
out = append(out, p)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
type UpdateExamPrepPracticeInput struct {
|
||||
|
|
|
|||
|
|
@ -7,12 +7,14 @@ import (
|
|||
|
||||
// ExamPrepPracticeStore persists exam_prep.lesson_practices and exam_prep.practice_parents.
|
||||
type ExamPrepPracticeStore interface {
|
||||
CreateExamPrepPractice(ctx context.Context, parent domain.ExamPrepPracticeParent, in domain.CreateExamPrepPracticeInput) (domain.ExamPrepPractice, error)
|
||||
CreateExamPrepPractice(ctx context.Context, in domain.CreateExamPrepPracticeInput, parents []domain.ExamPrepPracticeParent) (domain.ExamPrepPractice, error)
|
||||
GetExamPrepLessonPracticeByID(ctx context.Context, id int64) (domain.ExamPrepPractice, error)
|
||||
TryGetExamPrepLessonPracticeByQuestionSetID(ctx context.Context, questionSetID int64) (domain.ExamPrepPractice, bool, error)
|
||||
ListExamPrepPracticesByParent(ctx context.Context, parent domain.ExamPrepPracticeParent, publishedOnly bool, limit, offset int32) ([]domain.ExamPrepPractice, int64, error)
|
||||
ListAllExamPrepPractices(ctx context.Context, publishedOnly, unlinkedOnly bool, limit, offset int32) ([]domain.ExamPrepPractice, int64, error)
|
||||
CountExamPrepPracticesByParent(ctx context.Context, kind domain.ExamPrepParentKind, parentID int64) (int64, error)
|
||||
CountExamPrepPracticesByParentExcludingPractice(ctx context.Context, kind domain.ExamPrepParentKind, parentID, excludePracticeID int64) (int64, error)
|
||||
UpdateExamPrepLessonPractice(ctx context.Context, id int64, input domain.UpdateExamPrepPracticeInput) (domain.ExamPrepPractice, error)
|
||||
ReplaceExamPrepPracticeParents(ctx context.Context, practiceID int64, parents []domain.ExamPrepPracticeParent) error
|
||||
DeleteExamPrepLessonPractice(ctx context.Context, id int64) error
|
||||
}
|
||||
|
|
|
|||
|
|
@ -87,7 +87,62 @@ func (s *Store) insertExamPrepPracticeParent(ctx context.Context, q *dbgen.Queri
|
|||
return err
|
||||
}
|
||||
|
||||
func (s *Store) CreateExamPrepPractice(ctx context.Context, parent domain.ExamPrepPracticeParent, in domain.CreateExamPrepPracticeInput) (domain.ExamPrepPractice, error) {
|
||||
func (s *Store) insertExamPrepPracticeParents(ctx context.Context, q *dbgen.Queries, practiceID int64, parents []domain.ExamPrepPracticeParent) error {
|
||||
for _, parent := range parents {
|
||||
if err := s.insertExamPrepPracticeParent(ctx, q, practiceID, parent); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Store) attachParentsToExamPrepPractices(ctx context.Context, practices []domain.ExamPrepPractice) ([]domain.ExamPrepPractice, error) {
|
||||
if len(practices) == 0 {
|
||||
return practices, nil
|
||||
}
|
||||
ids := make([]int64, len(practices))
|
||||
for i, p := range practices {
|
||||
ids[i] = p.ID
|
||||
}
|
||||
rows, err := s.queries.ListExamPrepPracticeParentsByPracticeIDs(ctx, ids)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
accum := make(map[int64][]domain.ExamPrepPracticeParent, len(practices))
|
||||
for _, row := range rows {
|
||||
accum[row.PracticeID] = append(accum[row.PracticeID], examPrepPracticeParentFromDB(row))
|
||||
}
|
||||
for i, p := range practices {
|
||||
parents := accum[p.ID]
|
||||
practices[i].Parents = domain.ExamPrepPracticeParentsPtr(parents)
|
||||
for _, parent := range parents {
|
||||
if parent.Kind == domain.ExamPrepParentKindLesson {
|
||||
id := parent.ID
|
||||
practices[i].LessonID = &id
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
return practices, nil
|
||||
}
|
||||
|
||||
func examPrepPracticeFromListAllRow(r dbgen.ListAllExamPrepPracticesRow) domain.ExamPrepPractice {
|
||||
p := dbgen.ExamPrepLessonPractice{
|
||||
ID: r.ID,
|
||||
Title: r.Title,
|
||||
StoryDescription: r.StoryDescription,
|
||||
StoryImage: r.StoryImage,
|
||||
PersonaID: r.PersonaID,
|
||||
QuestionSetID: r.QuestionSetID,
|
||||
QuickTips: r.QuickTips,
|
||||
PublishStatus: r.PublishStatus,
|
||||
CreatedAt: r.CreatedAt,
|
||||
UpdatedAt: r.UpdatedAt,
|
||||
}
|
||||
return examPrepPracticeToDomain(p, nil)
|
||||
}
|
||||
|
||||
func (s *Store) CreateExamPrepPractice(ctx context.Context, in domain.CreateExamPrepPracticeInput, parents []domain.ExamPrepPracticeParent) (domain.ExamPrepPractice, error) {
|
||||
ps := domain.ParsePracticePublishStatusInput(in.PublishStatus)
|
||||
q, tx, err := s.BeginTx(ctx)
|
||||
if err != nil {
|
||||
|
|
@ -107,13 +162,13 @@ func (s *Store) CreateExamPrepPractice(ctx context.Context, parent domain.ExamPr
|
|||
if err != nil {
|
||||
return domain.ExamPrepPractice{}, err
|
||||
}
|
||||
if err := s.insertExamPrepPracticeParent(ctx, q, p.ID, parent); err != nil {
|
||||
if err := s.insertExamPrepPracticeParents(ctx, q, p.ID, parents); err != nil {
|
||||
return domain.ExamPrepPractice{}, err
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return domain.ExamPrepPractice{}, fmt.Errorf("commit: %w", err)
|
||||
}
|
||||
return examPrepPracticeToDomain(p, []domain.ExamPrepPracticeParent{parent}), nil
|
||||
return examPrepPracticeToDomain(p, parents), nil
|
||||
}
|
||||
|
||||
func (s *Store) GetExamPrepLessonPracticeByID(ctx context.Context, id int64) (domain.ExamPrepPractice, error) {
|
||||
|
|
@ -171,6 +226,50 @@ func (s *Store) ListExamPrepPracticesByParent(ctx context.Context, parent domain
|
|||
return out, total, nil
|
||||
}
|
||||
|
||||
func (s *Store) ListAllExamPrepPractices(ctx context.Context, publishedOnly, unlinkedOnly bool, limit, offset int32) ([]domain.ExamPrepPractice, int64, error) {
|
||||
rows, err := s.queries.ListAllExamPrepPractices(ctx, dbgen.ListAllExamPrepPracticesParams{
|
||||
PublishedOnly: publishedOnly,
|
||||
UnlinkedOnly: unlinkedOnly,
|
||||
Limit: limit,
|
||||
Offset: offset,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
if len(rows) == 0 {
|
||||
return []domain.ExamPrepPractice{}, 0, nil
|
||||
}
|
||||
var total int64
|
||||
out := make([]domain.ExamPrepPractice, 0, len(rows))
|
||||
for i, r := range rows {
|
||||
if i == 0 {
|
||||
total = r.TotalCount
|
||||
}
|
||||
out = append(out, examPrepPracticeFromListAllRow(r))
|
||||
}
|
||||
out, err = s.attachParentsToExamPrepPractices(ctx, out)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
return out, total, nil
|
||||
}
|
||||
|
||||
func (s *Store) ReplaceExamPrepPracticeParents(ctx context.Context, practiceID int64, parents []domain.ExamPrepPracticeParent) error {
|
||||
q, tx, err := s.BeginTx(ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("begin tx: %w", err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback(ctx) }()
|
||||
|
||||
if err := q.DeleteExamPrepPracticeParentsByPracticeID(ctx, practiceID); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := s.insertExamPrepPracticeParents(ctx, q, practiceID, parents); err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Commit(ctx)
|
||||
}
|
||||
|
||||
func (s *Store) CountExamPrepPracticesByParent(ctx context.Context, kind domain.ExamPrepParentKind, parentID int64) (int64, error) {
|
||||
return s.queries.CountExamPrepPracticesByParent(ctx, dbgen.CountExamPrepPracticesByParentParams{
|
||||
ParentKind: string(kind),
|
||||
|
|
|
|||
|
|
@ -14,6 +14,8 @@ var ErrUnitNotFound = errors.New("exam prep unit not found")
|
|||
var ErrModuleNotFound = errors.New("exam prep module not found")
|
||||
var ErrLessonNotFound = errors.New("exam prep lesson not found")
|
||||
var ErrPracticeNotFound = errors.New("exam prep practice not found")
|
||||
var ErrQuestionSetNotFound = errors.New("question set not found")
|
||||
var ErrInvalidExamPrepPracticeParent = errors.New("parent_kind and parent_id do not match an allowed exam prep parent")
|
||||
|
||||
// examPrepStore is implemented by *repository.Store (catalog courses, units, modules, lessons, practices, personas).
|
||||
type examPrepStore interface {
|
||||
|
|
@ -23,6 +25,7 @@ type examPrepStore interface {
|
|||
ports.ExamPrepLessonStore
|
||||
ports.ExamPrepPracticeStore
|
||||
ports.LmsPersonaReader
|
||||
ports.QuestionSetByID
|
||||
}
|
||||
|
||||
type Service struct {
|
||||
|
|
@ -363,13 +366,65 @@ func (s *Service) ensureLesson(ctx context.Context, lessonID int64) error {
|
|||
return nil
|
||||
}
|
||||
|
||||
func (s *Service) createExamPrepPractice(ctx context.Context, parent domain.ExamPrepPracticeParent, input domain.CreateExamPrepPracticeInput) (domain.ExamPrepPractice, error) {
|
||||
func (s *Service) validateQuestionSet(ctx context.Context, id int64) error {
|
||||
_, err := s.store.GetQuestionSetByID(ctx, id)
|
||||
if err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return ErrQuestionSetNotFound
|
||||
}
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Service) validateExamPrepParent(ctx context.Context, parent domain.ExamPrepPracticeParent) error {
|
||||
switch parent.Kind {
|
||||
case domain.ExamPrepParentKindCatalogCourse:
|
||||
return s.ensureCatalogCourse(ctx, parent.ID)
|
||||
case domain.ExamPrepParentKindUnit:
|
||||
return s.ensureUnit(ctx, parent.ID)
|
||||
case domain.ExamPrepParentKindLesson:
|
||||
return s.ensureLesson(ctx, parent.ID)
|
||||
default:
|
||||
return ErrInvalidExamPrepPracticeParent
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Service) validateExamPrepParentList(ctx context.Context, parents []domain.ExamPrepPracticeParent) error {
|
||||
for _, parent := range parents {
|
||||
if err := s.validateExamPrepParent(ctx, parent); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Service) resolveNestedCreateParents(input domain.CreateExamPrepPracticeInput, urlParent domain.ExamPrepPracticeParent) []domain.ExamPrepPracticeParent {
|
||||
if input.Parents != nil {
|
||||
return input.ResolvedParents()
|
||||
}
|
||||
return []domain.ExamPrepPracticeParent{urlParent}
|
||||
}
|
||||
|
||||
func (s *Service) createExamPrepPractice(ctx context.Context, parents []domain.ExamPrepPracticeParent, input domain.CreateExamPrepPracticeInput) (domain.ExamPrepPractice, error) {
|
||||
if err := s.validateQuestionSet(ctx, input.QuestionSetID); err != nil {
|
||||
return domain.ExamPrepPractice{}, err
|
||||
}
|
||||
if input.PersonaID != nil {
|
||||
if err := s.ensurePersonaRef(ctx, *input.PersonaID); err != nil {
|
||||
return domain.ExamPrepPractice{}, err
|
||||
}
|
||||
}
|
||||
return s.store.CreateExamPrepPractice(ctx, parent, input)
|
||||
if len(parents) > 0 {
|
||||
if err := s.validateExamPrepParentList(ctx, parents); err != nil {
|
||||
return domain.ExamPrepPractice{}, err
|
||||
}
|
||||
}
|
||||
return s.store.CreateExamPrepPractice(ctx, input, parents)
|
||||
}
|
||||
|
||||
func (s *Service) CreateExamPrepPracticeFromInput(ctx context.Context, input domain.CreateExamPrepPracticeInput) (domain.ExamPrepPractice, error) {
|
||||
return s.createExamPrepPractice(ctx, input.ResolvedParents(), input)
|
||||
}
|
||||
|
||||
func (s *Service) listExamPrepPractices(ctx context.Context, parent domain.ExamPrepPracticeParent, publishedOnly bool, limit, offset int32) ([]domain.ExamPrepPractice, int64, error) {
|
||||
|
|
@ -389,30 +444,33 @@ func (s *Service) CreateExamPrepPractice(ctx context.Context, lessonID int64, in
|
|||
if err := s.ensureLesson(ctx, lessonID); err != nil {
|
||||
return domain.ExamPrepPractice{}, err
|
||||
}
|
||||
return s.createExamPrepPractice(ctx, domain.ExamPrepPracticeParent{
|
||||
parents := s.resolveNestedCreateParents(input, domain.ExamPrepPracticeParent{
|
||||
Kind: domain.ExamPrepParentKindLesson,
|
||||
ID: lessonID,
|
||||
}, input)
|
||||
})
|
||||
return s.createExamPrepPractice(ctx, parents, input)
|
||||
}
|
||||
|
||||
func (s *Service) CreateExamPrepPracticeForCatalogCourse(ctx context.Context, catalogCourseID int64, input domain.CreateExamPrepPracticeInput) (domain.ExamPrepPractice, error) {
|
||||
if err := s.ensureCatalogCourse(ctx, catalogCourseID); err != nil {
|
||||
return domain.ExamPrepPractice{}, err
|
||||
}
|
||||
return s.createExamPrepPractice(ctx, domain.ExamPrepPracticeParent{
|
||||
parents := s.resolveNestedCreateParents(input, domain.ExamPrepPracticeParent{
|
||||
Kind: domain.ExamPrepParentKindCatalogCourse,
|
||||
ID: catalogCourseID,
|
||||
}, input)
|
||||
})
|
||||
return s.createExamPrepPractice(ctx, parents, input)
|
||||
}
|
||||
|
||||
func (s *Service) CreateExamPrepPracticeForUnit(ctx context.Context, unitID int64, input domain.CreateExamPrepPracticeInput) (domain.ExamPrepPractice, error) {
|
||||
if err := s.ensureUnit(ctx, unitID); err != nil {
|
||||
return domain.ExamPrepPractice{}, err
|
||||
}
|
||||
return s.createExamPrepPractice(ctx, domain.ExamPrepPracticeParent{
|
||||
parents := s.resolveNestedCreateParents(input, domain.ExamPrepPracticeParent{
|
||||
Kind: domain.ExamPrepParentKindUnit,
|
||||
ID: unitID,
|
||||
}, input)
|
||||
})
|
||||
return s.createExamPrepPractice(ctx, parents, input)
|
||||
}
|
||||
|
||||
func (s *Service) ListExamPrepPracticesByLesson(ctx context.Context, lessonID int64, publishedOnly bool, limit, offset int32) ([]domain.ExamPrepPractice, int64, error) {
|
||||
|
|
@ -445,6 +503,38 @@ func (s *Service) ListExamPrepPracticesByUnit(ctx context.Context, unitID int64,
|
|||
}, publishedOnly, limit, offset)
|
||||
}
|
||||
|
||||
func (s *Service) ListAllExamPrepPractices(ctx context.Context, publishedOnly, unlinkedOnly bool, limit, offset int32) ([]domain.ExamPrepPractice, int64, error) {
|
||||
if limit <= 0 {
|
||||
limit = 20
|
||||
}
|
||||
if limit > 200 {
|
||||
limit = 200
|
||||
}
|
||||
if offset < 0 {
|
||||
offset = 0
|
||||
}
|
||||
return s.store.ListAllExamPrepPractices(ctx, publishedOnly, unlinkedOnly, limit, offset)
|
||||
}
|
||||
|
||||
func (s *Service) UpdateExamPrepPracticeParents(ctx context.Context, id int64, in domain.UpdateExamPrepPracticeParentsInput) (domain.ExamPrepPractice, error) {
|
||||
if _, err := s.store.GetExamPrepLessonPracticeByID(ctx, id); err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return domain.ExamPrepPractice{}, ErrPracticeNotFound
|
||||
}
|
||||
return domain.ExamPrepPractice{}, err
|
||||
}
|
||||
parents := domain.DedupeExamPrepPracticeParents(in.Parents)
|
||||
if len(parents) > 0 {
|
||||
if err := s.validateExamPrepParentList(ctx, parents); err != nil {
|
||||
return domain.ExamPrepPractice{}, err
|
||||
}
|
||||
}
|
||||
if err := s.store.ReplaceExamPrepPracticeParents(ctx, id, parents); err != nil {
|
||||
return domain.ExamPrepPractice{}, err
|
||||
}
|
||||
return s.store.GetExamPrepLessonPracticeByID(ctx, id)
|
||||
}
|
||||
|
||||
func (s *Service) GetExamPrepPracticeByID(ctx context.Context, id int64) (domain.ExamPrepPractice, error) {
|
||||
p, err := s.store.GetExamPrepLessonPracticeByID(ctx, id)
|
||||
if err != nil {
|
||||
|
|
|
|||
|
|
@ -54,7 +54,8 @@ var AllPermissions = []domain.PermissionSeed{
|
|||
{Key: "exam_prep.lessons.update", Name: "Update Exam Prep Lesson", Description: "Update an exam prep lesson", GroupName: "Exam Prep"},
|
||||
{Key: "exam_prep.lessons.delete", Name: "Delete Exam Prep Lesson", Description: "Delete an exam prep lesson", GroupName: "Exam Prep"},
|
||||
{Key: "exam_prep.lessons.reorder", Name: "Reorder Exam Prep Lessons", Description: "Reorder lessons within an exam prep unit module", GroupName: "Exam Prep"},
|
||||
{Key: "exam_prep.practices.create", Name: "Create Exam Prep Practice", Description: "Create a practice under an exam prep catalog course, unit, or lesson (references question_sets)", GroupName: "Exam Prep"},
|
||||
{Key: "exam_prep.practices.create", Name: "Create Exam Prep Practice", Description: "Create an exam prep practice (optional catalog course, unit, or lesson parent; references question_sets)", GroupName: "Exam Prep"},
|
||||
{Key: "exam_prep.practices.list", Name: "List Exam Prep Practices", Description: "List exam prep practices globally or unlinked only", GroupName: "Exam Prep"},
|
||||
{Key: "exam_prep.practices.list_by_catalog_course", Name: "List Exam Prep Practices by Catalog Course", Description: "List practices for an exam prep catalog course", GroupName: "Exam Prep"},
|
||||
{Key: "exam_prep.practices.list_by_unit", Name: "List Exam Prep Practices by Unit", Description: "List practices for an exam prep unit", GroupName: "Exam Prep"},
|
||||
{Key: "exam_prep.practices.list_by_lesson", Name: "List Exam Prep Practices by Lesson", Description: "List practices for an exam prep lesson", GroupName: "Exam Prep"},
|
||||
|
|
@ -361,7 +362,7 @@ var defaultStudentLearnerPermissions = []string{
|
|||
"exam_prep.units.list", "exam_prep.units.get",
|
||||
"exam_prep.modules.list", "exam_prep.modules.get",
|
||||
"exam_prep.lessons.list_by_module", "exam_prep.lessons.get",
|
||||
"exam_prep.practices.list_by_catalog_course", "exam_prep.practices.list_by_unit", "exam_prep.practices.list_by_lesson", "exam_prep.practices.get",
|
||||
"exam_prep.practices.list", "exam_prep.practices.list_by_catalog_course", "exam_prep.practices.list_by_unit", "exam_prep.practices.list_by_lesson", "exam_prep.practices.get",
|
||||
"lms.get_my_progress",
|
||||
|
||||
// Questions (read + attempt)
|
||||
|
|
@ -425,7 +426,7 @@ var DefaultRolePermissions = map[string][]string{
|
|||
"exam_prep.units.create", "exam_prep.units.list", "exam_prep.units.get", "exam_prep.units.update", "exam_prep.units.delete", "exam_prep.units.reorder",
|
||||
"exam_prep.modules.create", "exam_prep.modules.list", "exam_prep.modules.get", "exam_prep.modules.update", "exam_prep.modules.delete", "exam_prep.modules.reorder",
|
||||
"exam_prep.lessons.create", "exam_prep.lessons.list_by_module", "exam_prep.lessons.get", "exam_prep.lessons.update", "exam_prep.lessons.delete", "exam_prep.lessons.reorder",
|
||||
"exam_prep.practices.create", "exam_prep.practices.list_by_catalog_course", "exam_prep.practices.list_by_unit", "exam_prep.practices.list_by_lesson", "exam_prep.practices.get", "exam_prep.practices.update", "exam_prep.practices.delete",
|
||||
"exam_prep.practices.create", "exam_prep.practices.list", "exam_prep.practices.list_by_catalog_course", "exam_prep.practices.list_by_unit", "exam_prep.practices.list_by_lesson", "exam_prep.practices.get", "exam_prep.practices.update", "exam_prep.practices.delete",
|
||||
"lms.get_my_progress",
|
||||
|
||||
// Modules
|
||||
|
|
@ -544,7 +545,7 @@ var DefaultRolePermissions = map[string][]string{
|
|||
"exam_prep.units.list", "exam_prep.units.get",
|
||||
"exam_prep.modules.list", "exam_prep.modules.get",
|
||||
"exam_prep.lessons.list_by_module", "exam_prep.lessons.get",
|
||||
"exam_prep.practices.list_by_catalog_course", "exam_prep.practices.list_by_unit", "exam_prep.practices.list_by_lesson", "exam_prep.practices.get",
|
||||
"exam_prep.practices.list", "exam_prep.practices.list_by_catalog_course", "exam_prep.practices.list_by_unit", "exam_prep.practices.list_by_lesson", "exam_prep.practices.get",
|
||||
"lms.get_my_progress",
|
||||
|
||||
"personas.create", "personas.list", "personas.get", "personas.update", "personas.delete",
|
||||
|
|
@ -611,7 +612,7 @@ var DefaultRolePermissions = map[string][]string{
|
|||
"exam_prep.units.list", "exam_prep.units.get",
|
||||
"exam_prep.modules.list", "exam_prep.modules.get",
|
||||
"exam_prep.lessons.list_by_module", "exam_prep.lessons.get",
|
||||
"exam_prep.practices.list_by_catalog_course", "exam_prep.practices.list_by_unit", "exam_prep.practices.list_by_lesson", "exam_prep.practices.get",
|
||||
"exam_prep.practices.list", "exam_prep.practices.list_by_catalog_course", "exam_prep.practices.list_by_unit", "exam_prep.practices.list_by_lesson", "exam_prep.practices.get",
|
||||
|
||||
"personas.list", "personas.get",
|
||||
|
||||
|
|
|
|||
|
|
@ -10,6 +10,69 @@ import (
|
|||
"github.com/gofiber/fiber/v2"
|
||||
)
|
||||
|
||||
// CreateExamPrepPracticeFromInput godoc
|
||||
// @Summary Create exam-prep practice (optional parents; link later via PUT /exam-prep/practices/:id/parents)
|
||||
// @Tags exam-prep
|
||||
// @Param body body domain.CreateExamPrepPracticeInput true "Practice"
|
||||
// @Router /api/v1/exam-prep/practices [post]
|
||||
func (h *Handler) CreateExamPrepPracticeFromInput(c *fiber.Ctx) error {
|
||||
var req domain.CreateExamPrepPracticeInput
|
||||
if err := c.BodyParser(&req); err != nil {
|
||||
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
|
||||
Message: "Invalid request body",
|
||||
Error: err.Error(),
|
||||
})
|
||||
}
|
||||
if valErrs, ok := h.validator.Validate(c, req); !ok {
|
||||
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
|
||||
Message: "Validation failed",
|
||||
Error: firstValidationError(valErrs),
|
||||
})
|
||||
}
|
||||
p, err := h.examPrepSvc.CreateExamPrepPracticeFromInput(c.Context(), req)
|
||||
if err != nil {
|
||||
if resp := h.mapCreateExamPrepPracticeError(c, err); resp != nil {
|
||||
return resp
|
||||
}
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{
|
||||
Message: "Failed to create practice",
|
||||
Error: err.Error(),
|
||||
})
|
||||
}
|
||||
h.recordActivity(c, domain.ActionExamPrepPracticeCreated, domain.ResourceExamPrepPractice, &p.ID, "Created exam prep practice: "+p.Title, nil)
|
||||
return c.Status(fiber.StatusCreated).JSON(domain.Response{
|
||||
Message: "Practice created successfully",
|
||||
Data: p,
|
||||
Success: true,
|
||||
StatusCode: fiber.StatusCreated,
|
||||
})
|
||||
}
|
||||
|
||||
// ListAllExamPrepPractices godoc
|
||||
// @Summary List exam-prep practices globally
|
||||
// @Tags exam-prep
|
||||
// @Param limit query int false "Page size" default(20)
|
||||
// @Param offset query int false "Offset" default(0)
|
||||
// @Param unlinked_only query bool false "When true, return only practices with no parent links (admin)"
|
||||
// @Router /api/v1/exam-prep/practices [get]
|
||||
func (h *Handler) ListAllExamPrepPractices(c *fiber.Ctx) error {
|
||||
limit, _ := strconv.Atoi(c.Query("limit", "20"))
|
||||
offset, _ := strconv.Atoi(c.Query("offset", "0"))
|
||||
publishedOnly := !h.canManageExamPrepPractices(c)
|
||||
unlinkedOnly := false
|
||||
if h.canManageExamPrepPractices(c) {
|
||||
unlinkedOnly, _ = strconv.ParseBool(c.Query("unlinked_only", "false"))
|
||||
}
|
||||
items, total, err := h.examPrepSvc.ListAllExamPrepPractices(c.Context(), publishedOnly, unlinkedOnly, int32(limit), int32(offset))
|
||||
if err != nil {
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{
|
||||
Message: "Failed to list practices",
|
||||
Error: err.Error(),
|
||||
})
|
||||
}
|
||||
return h.listExamPrepPracticesResponse(c, items, total, limit, offset, nil)
|
||||
}
|
||||
|
||||
// CreateExamPrepPractice godoc
|
||||
// @Summary Create exam-prep practice (under a lesson; uses shared question_sets)
|
||||
// @Tags exam-prep
|
||||
|
|
@ -176,6 +239,61 @@ func (h *Handler) UpdateExamPrepPractice(c *fiber.Ctx) error {
|
|||
})
|
||||
}
|
||||
|
||||
// UpdateExamPrepPracticeParents godoc
|
||||
// @Summary Replace exam-prep practice parent links
|
||||
// @Tags exam-prep
|
||||
// @Param id path int true "Exam prep practice ID"
|
||||
// @Param body body domain.UpdateExamPrepPracticeParentsInput true "Parent links (replaces all; use empty array to detach)"
|
||||
// @Router /api/v1/exam-prep/practices/{id}/parents [put]
|
||||
func (h *Handler) UpdateExamPrepPracticeParents(c *fiber.Ctx) error {
|
||||
id, err := strconv.ParseInt(c.Params("id"), 10, 64)
|
||||
if err != nil {
|
||||
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
|
||||
Message: "Invalid practice id",
|
||||
Error: err.Error(),
|
||||
})
|
||||
}
|
||||
var req domain.UpdateExamPrepPracticeParentsInput
|
||||
if err := c.BodyParser(&req); err != nil {
|
||||
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
|
||||
Message: "Invalid request body",
|
||||
Error: err.Error(),
|
||||
})
|
||||
}
|
||||
if valErrs, ok := h.validator.Validate(c, req); !ok {
|
||||
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
|
||||
Message: "Validation failed",
|
||||
Error: firstValidationError(valErrs),
|
||||
})
|
||||
}
|
||||
p, err := h.examPrepSvc.UpdateExamPrepPracticeParents(c.Context(), id, req)
|
||||
if err != nil {
|
||||
switch {
|
||||
case errors.Is(err, examprep.ErrPracticeNotFound):
|
||||
return c.Status(fiber.StatusNotFound).JSON(domain.ErrorResponse{Message: "Practice not found", Error: err.Error()})
|
||||
case errors.Is(err, examprep.ErrLessonNotFound):
|
||||
return c.Status(fiber.StatusNotFound).JSON(domain.ErrorResponse{Message: "Lesson not found", Error: err.Error()})
|
||||
case errors.Is(err, examprep.ErrUnitNotFound):
|
||||
return c.Status(fiber.StatusNotFound).JSON(domain.ErrorResponse{Message: "Unit not found", Error: err.Error()})
|
||||
case errors.Is(err, examprep.ErrCatalogCourseNotFound):
|
||||
return c.Status(fiber.StatusNotFound).JSON(domain.ErrorResponse{Message: "Catalog course not found", Error: err.Error()})
|
||||
case errors.Is(err, examprep.ErrInvalidExamPrepPracticeParent):
|
||||
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{Message: "Invalid parent", Error: err.Error()})
|
||||
}
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{
|
||||
Message: "Failed to update practice parents",
|
||||
Error: err.Error(),
|
||||
})
|
||||
}
|
||||
h.recordActivity(c, domain.ActionExamPrepPracticeUpdated, domain.ResourceExamPrepPractice, &p.ID, "Updated exam prep practice parents: "+p.Title, nil)
|
||||
return c.JSON(domain.Response{
|
||||
Message: "Practice parents updated successfully",
|
||||
Data: p,
|
||||
Success: true,
|
||||
StatusCode: fiber.StatusOK,
|
||||
})
|
||||
}
|
||||
|
||||
// DeleteExamPrepPractice godoc
|
||||
// @Summary Delete exam-prep practice
|
||||
// @Tags exam-prep
|
||||
|
|
@ -221,6 +339,16 @@ func (h *Handler) mapCreateExamPrepPracticeError(c *fiber.Ctx, err error) error
|
|||
Message: "Persona not found",
|
||||
Error: err.Error(),
|
||||
})
|
||||
case errors.Is(err, examprep.ErrQuestionSetNotFound):
|
||||
return c.Status(fiber.StatusNotFound).JSON(domain.ErrorResponse{
|
||||
Message: "Question set not found",
|
||||
Error: err.Error(),
|
||||
})
|
||||
case errors.Is(err, examprep.ErrInvalidExamPrepPracticeParent):
|
||||
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
|
||||
Message: "Invalid parent",
|
||||
Error: err.Error(),
|
||||
})
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
|
|
|
|||
|
|
@ -116,9 +116,12 @@ func (a *App) initAppRoutes() {
|
|||
examPrep.Put("/modules/:moduleId/lessons/reorder", a.RequirePermission("exam_prep.lessons.reorder"), h.ReorderExamPrepLessonsInUnitModule)
|
||||
examPrep.Post("/lessons/:lessonId/practices", a.RequirePermission("exam_prep.practices.create"), h.CreateExamPrepPractice)
|
||||
examPrep.Get("/lessons/:lessonId/practices", a.RequirePermission("exam_prep.practices.list_by_lesson"), h.ListExamPrepPracticesByLesson)
|
||||
examPrep.Post("/practices", a.RequirePermission("exam_prep.practices.create"), h.CreateExamPrepPracticeFromInput)
|
||||
examPrep.Get("/practices", a.RequirePermission("exam_prep.practices.list"), h.ListAllExamPrepPractices)
|
||||
examPrep.Get("/practices/:id", a.RequirePermission("exam_prep.practices.get"), h.GetExamPrepPracticeByID)
|
||||
examPrep.Get("/practices/:id/full", a.RequirePermission("exam_prep.practices.get"), h.GetExamPrepPracticeFull)
|
||||
examPrep.Put("/practices/:id", a.RequirePermission("exam_prep.practices.update"), h.UpdateExamPrepPractice)
|
||||
examPrep.Put("/practices/:id/parents", a.RequirePermission("exam_prep.practices.update"), h.UpdateExamPrepPracticeParents)
|
||||
examPrep.Put("/practices/:id/full", a.RequirePermission("exam_prep.practices.update"), h.UpdateExamPrepPracticeFull)
|
||||
examPrep.Delete("/practices/:id", a.RequirePermission("exam_prep.practices.delete"), h.DeleteExamPrepPractice)
|
||||
examPrep.Get("/lessons/:id", a.RequirePermission("exam_prep.lessons.get"), h.GetExamPrepLessonByID)
|
||||
|
|
|
|||
Loading…
Reference in New Issue
Block a user