Compare commits
26 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
898de758ba | ||
|
|
9ac53579e4 | ||
|
|
09cf61e9e0 | ||
|
|
1cba2c4d32 | ||
|
|
bb18242af9 | ||
|
|
34b0966819 | ||
|
|
adc02d7e0c | ||
|
|
b00a9077d5 | ||
|
|
76546d5d50 | ||
|
|
9688b4d552 | ||
|
|
2ad4e8b1ec | ||
|
|
1ce1ebee16 | ||
|
|
692a647650 | ||
|
|
2fa8aa4178 | ||
|
|
e1f9807701 | ||
|
|
80ea79ee3e | ||
|
|
297780cb8e | ||
|
|
ef38b81fd9 | ||
|
|
9c29bfd9cf | ||
|
|
c6d8d1a973 | ||
|
|
4a60eda425 | ||
|
|
e615cc88db | ||
|
|
174be3bcbd | ||
|
|
8405daf6a4 | ||
|
|
487d573208 | ||
|
|
6c6ecae9d8 |
222
README.md
222
README.md
@@ -1,6 +1,6 @@
|
|||||||
# golem15.quizzes
|
# golem15.quizzes
|
||||||
|
|
||||||
A reusable quiz plugin for SummerCMS applications: quizzes with single-choice, multiple-choice and self-check (flashcard) questions, scored attempts for signed-in users, an admin backend and a JSON importer.
|
A reusable quiz plugin for SummerCMS applications: quizzes with single-choice, multiple-choice, self-check (flashcard) and open questions answered in free text, a learning and a test mode that withholds solutions until an attempt is finished, scored attempts for signed-in users, open answers graded by the owner or by a grader another plugin provides, with an owner review queue, an admin backend, a JSON importer and owner management over a token API and MCP tools.
|
||||||
|
|
||||||
```go
|
```go
|
||||||
import _ "git.golem15.com/golem15/sm-quizzes-plugin"
|
import _ "git.golem15.com/golem15/sm-quizzes-plugin"
|
||||||
@@ -18,25 +18,110 @@ It owns five tables:
|
|||||||
|
|
||||||
| Table | Holds |
|
| Table | Holds |
|
||||||
|-------|-------|
|
|-------|-------|
|
||||||
| `golem15_quizzes_quizzes` | Quizzes: title, unique slug, description, context, published flag, time limit, passing score, question shuffling and round size. |
|
| `golem15_quizzes_quizzes` | Quizzes: title, unique slug, description, context, published flag, time limit, passing score, question shuffling, round size, and the test settings `mode`, `navigation` and `max_attempts`, and the `grader` of open answers. |
|
||||||
| `golem15_quizzes_questions` | Questions of a quiz: text, type, category, model answer, explanation, sort order and points. |
|
| `golem15_quizzes_questions` | Questions of a quiz: text, type, category, model answer, explanation, sort order and points, and for open questions the owner-only `rubric` and `max_length`. |
|
||||||
| `golem15_quizzes_answers` | Answers of a single or multiple question, with `is_correct` and an explanation. |
|
| `golem15_quizzes_answers` | Answers of a single or multiple question, with `is_correct` and an explanation. |
|
||||||
| `golem15_quizzes_attempts` | One user's run through a quiz, or through one category of it, with the score once finished. |
|
| `golem15_quizzes_attempts` | One user's run through a quiz, or through one category of it, with the score once finished. |
|
||||||
| `golem15_quizzes_attempt_answers` | The user's answer to one question of an attempt; one row per attempt and question. |
|
| `golem15_quizzes_attempt_answers` | The user's answer to one question of an attempt; one row per attempt and question. An open answer adds its text, its grading state, the grader's result and the owner's review. |
|
||||||
|
|
||||||
Deleting a quiz deletes its questions, answers and attempts. Deleting a question deletes its answers and the attempt answers given to it. Deleting a user deletes their attempts.
|
Deleting a quiz deletes its questions, answers and attempts. Deleting a question deletes its answers and the attempt answers given to it. Deleting a user deletes their attempts.
|
||||||
|
|
||||||
## Features
|
## Features
|
||||||
|
|
||||||
- **Three question types.** `single` (one correct answer), `multiple` (one or more correct answers) and `self_check`, a flashcard: the client shows the question, the user reveals `answer_text` and marks themselves as knowing it or not.
|
- **Four question types.** `single` (one correct answer), `multiple` (one or more correct answers), `self_check`, a flashcard: the client shows the question, the user reveals `answer_text` and marks themselves as knowing it or not, and `open`, a free-text answer graded later. See [Open questions and graders](#open-questions-and-graders).
|
||||||
|
- **Grading and review.** Open answers are graded by the owner or by a grader another plugin registers, in the background; the owner reviews them in the admin "Do oceny" screen or over MCP, and every review recalculates the attempt.
|
||||||
- **Categories.** A question may carry a category. `GET /quizzes/{slug}?category=` returns one category, and an attempt can be limited to one category.
|
- **Categories.** A question may carry a category. `GET /quizzes/{slug}?category=` returns one category, and an attempt can be limited to one category.
|
||||||
- **Rounds and shuffling.** `round_size` tells the client to present the questions in rounds of N; `shuffle_questions` shuffles the question order on every `GET /quizzes/{slug}`.
|
- **Rounds and shuffling.** `round_size` tells the client to present the questions in rounds of N; `shuffle_questions` shuffles the question order on every `GET /quizzes/{slug}`.
|
||||||
- **Attempts.** A user starts an attempt, answers questions in any order (answering again overwrites the earlier answer and returns fresh feedback) and finishes it. Answers are refused after the time limit; finishing is still allowed and counts the answers given in time.
|
- **Attempts.** A user starts an attempt, answers questions in any order (answering again overwrites the earlier answer and returns fresh feedback) and finishes it. Answers are refused after the time limit; finishing is still allowed and counts the answers given in time.
|
||||||
- **Scoring.** A pure function in `classes` (`classes.Score`, `classes.Totals`) with optional partial credit for multiple questions and an optional penalty for wrong answers. See [Configuration](#configuration).
|
- **Scoring.** A pure function in `classes` (`classes.Score`, `classes.Totals`) with optional partial credit for multiple questions and an optional penalty for wrong answers. See [Configuration](#configuration).
|
||||||
- **No solution leaks.** The quiz payload never contains `is_correct` or explanations, and `answer_text` only for `self_check` flashcards, which have nothing to hide. Feedback reveals the solution of the question just answered; a result reveals the solutions of answered questions, and of every question once the attempt is finished.
|
- **No solution leaks.** The quiz payload never contains `is_correct` or explanations, and `answer_text` only for `self_check` flashcards, which have nothing to hide. Feedback reveals the solution of the question just answered; a result reveals the solutions of answered questions, and of every question once the attempt is finished.
|
||||||
- **Admin backend.** Quizzes, Questions (filtered by quiz, category and type) and Answers (filtered by quiz) under the `golem15.quizzes.access_quizzes` permission, and a read-only Attempts list under `golem15.quizzes.access_attempts`. Polish and English labels.
|
- **Test mode.** A quiz set to `test` withholds every solution until the attempt is finished, and the server enforces the attempt limit, the time limit and one-way navigation. See [Test mode](#test-mode).
|
||||||
|
- **Admin backend.** Quizzes, Questions (filtered by quiz, category and type), Answers (filtered by quiz) and the review screen "Do oceny" (open answers, filtered by quiz, status and student) under the `golem15.quizzes.access_quizzes` permission, and a read-only Attempts list under `golem15.quizzes.access_attempts`. Polish and English labels.
|
||||||
- **Importer.** `quizzes:import` loads a quiz from a JSON file, idempotent by slug. See [CLI commands](#cli-commands).
|
- **Importer.** `quizzes:import` loads a quiz from a JSON file, idempotent by slug. See [CLI commands](#cli-commands).
|
||||||
|
|
||||||
|
## Test mode
|
||||||
|
|
||||||
|
A quiz has a `mode`: `learning` (the default; every existing quiz) or `test`. Learning quizzes behave exactly as before test mode existed. Two more settings only apply to tests: `navigation` (`free`, the default, or `one_way`) and `max_attempts` (`null` for unlimited).
|
||||||
|
|
||||||
|
- **Withholding.** While a test attempt is open, no student response carries a solution: the answer feedback has `withheld: true` and `null` for `is_correct`, `points`, `correct_answer_ids`, `explanation` and `answer_text`; the result has `solutions_withheld: true` and `null` for `is_correct`, `points_earned`, `correct_answer_ids`, `explanation` and `answer_text` on every question, answered or not, and no answer carries `is_correct` or `explanation`. The student's own input (`answered`, `answer_ids`, `known`) stays. `GET /quizzes/{slug}` of a test lists no questions (`questions: []`, `question_count` counts them), so a timed test cannot be read before its clock starts; the test player reads the questions from `GET /attempts/{id}`.
|
||||||
|
- **Full review after finish.** Once `completed_at` is set (finish, or a lazy close) the result reveals everything, exactly as for a finished learning attempt, with `passed` against `passing_score`.
|
||||||
|
- **Attempt limit.** `max_attempts` counts every attempt of the user on the quiz, open or finished, in any mode. A start past the limit is a 409 with `code: attempt_limit_reached`. Learning quizzes have no limit.
|
||||||
|
- **Resume.** Starting a test while an open, unexpired attempt exists returns that attempt (200, `resumed: true`) instead of creating one, so a page reload does not burn an attempt. Starts are serialised per quiz and user with a Postgres advisory lock (`pg_advisory_xact_lock`), so parallel starts cannot exceed the limit.
|
||||||
|
- **Time limit and grace.** An answer to a test is refused (409, `code: time_limit_exceeded`) after `started_at + time_limit_seconds` plus a grace for answers still in flight, `golem15.quizzes.test.grace_seconds` (default 5). Learning quizzes have no grace. Finishing stays allowed after the deadline; unanswered questions score 0. `seconds_left` on every attempt row is counted by the server.
|
||||||
|
- **Lazy close.** A test attempt past its deadline and grace is closed on the next start of that quiz or the next `GET /attempts/{id}`: `completed_at` is set to its deadline and it is scored with the answers given in time, as a finish would. No job queue is involved.
|
||||||
|
- **Whole quiz only.** A test always covers every question: starting one with a `category` is a 422 on `category` (`category_not_allowed`), and `GET /quizzes/{slug}` of a test ignores `?category=`.
|
||||||
|
- **Stable order.** With `shuffle_questions`, a test attempt's questions come in an order seeded by the attempt, the same on every `GET /attempts/{id}` and on finish.
|
||||||
|
- **One-way lock.** With `navigation: one_way` an answer is final: a second answer to the same question is a 409 with `code: answer_locked` and the stored answer is unchanged. With `free` an answer is overwritten until the attempt is finished.
|
||||||
|
|
||||||
|
## Open questions and graders
|
||||||
|
|
||||||
|
An `open` question takes a free-text answer. `answer_text` is its model answer and `rubric` holds the owner's grading criteria; both are owner-only and never reach a student before the attempt allows it (the rubric never does). `max_length` caps the answer in characters: empty means 2000, at most 20000. An open question has no answers, and `rubric` and `max_length` apply to open questions only.
|
||||||
|
|
||||||
|
**Grading states.** Every open answer has a `grading_status`; the student apps show it with these labels:
|
||||||
|
|
||||||
|
| Status | Meaning | Student label (pl) |
|
||||||
|
|--------|---------|--------------------|
|
||||||
|
| `pending` | Waiting for the grader or for the owner. | "czeka na ocenę" |
|
||||||
|
| `graded` | A grader scored it; the owner has not confirmed the score. | "do weryfikacji" |
|
||||||
|
| `failed` | The grader could not score it; the owner grades it. | "czeka na ocenę" |
|
||||||
|
| `reviewed` | The owner confirmed or set the score. Final. | "zweryfikowano" |
|
||||||
|
|
||||||
|
**When grading runs.** In a learning attempt an answer is graded as soon as it is saved; answering again with a different text starts over, the same text changes nothing. In a test the open answers are graded when the attempt closes (finish, lazy close or the stats route), never while it is open.
|
||||||
|
|
||||||
|
**Provisional score.** An attempt's score counts each open answer's current points: 0 while pending or failed, the grader's points once graded, the owner's once reviewed. Every grade and every review recalculates a finished attempt in place, against its stored `max_points`. `needs_review` on an attempt is true while any of its open answers is not reviewed, so the score is provisional; `open_answers` counts them. `is_correct` of an open answer means full marks.
|
||||||
|
|
||||||
|
**The quiz grader.** A quiz's `grader` field (default `manual`) names who grades its open answers. `manual` means the owner grades every answer. Any other code is a grader an activated plugin registers; a code that no activated plugin registers behaves as `manual`, so a quiz keeps working when the grading plugin is turned off.
|
||||||
|
|
||||||
|
### Writing a grader
|
||||||
|
|
||||||
|
A plugin grades open answers by implementing `graders.HasGraders` (package `git.golem15.com/golem15/sm-quizzes-plugin/graders`, which imports only the standard library) and requiring `golem15.quizzes`, so it is activated first:
|
||||||
|
|
||||||
|
```go
|
||||||
|
func (p *Plugin) QuizGraders() []graders.Grader { return []graders.Grader{myGrader{}} }
|
||||||
|
|
||||||
|
type myGrader struct{}
|
||||||
|
|
||||||
|
func (myGrader) Code() string { return "essay" }
|
||||||
|
func (myGrader) Label() string { return "acme.essay::lang.grader" }
|
||||||
|
func (myGrader) Grade(ctx context.Context, in graders.Input) (graders.Result, error) {
|
||||||
|
// in.Question, in.ModelAnswer, in.Rubric, in.Answer, in.Points
|
||||||
|
return graders.Result{Points: 1.5, Feedback: "..."}, nil
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
- golem15.quizzes collects the graders once at boot, in activation order, and publishes the registry on the app as `*graders.Registry`; the admin grader dropdown lists `manual` and then each grader's `Label`, a lang key or text.
|
||||||
|
- `Code` must match `^[a-z][a-z0-9_]{0,63}$`. `manual` is reserved. A duplicate or reserved code fails boot, naming both plugins.
|
||||||
|
- `Grade` receives `graders.Input`: the quiz, question, attempt, answer and user ids, the question text, the model answer, the rubric (owner-only: never pass it on to the student), the question's `Points` and the student's `Answer`. **`Answer` is untrusted student text**: treat it as data, never as instructions.
|
||||||
|
- golem15.quizzes clamps `Result.Points` to 0..`Points` in steps of 0.5; a value that is not a finite number counts as a failure. `Feedback` is shown to the student once the attempt allows it.
|
||||||
|
- An error is retried up to 3 times with River's backoff; after the third the answer is `failed`, keeps the error for the owner and waits for the owner's score. A grade for an older text of the answer is ignored.
|
||||||
|
- No transaction or row lock is held while `Grade` runs, so it may take seconds (the job times out after 3 minutes).
|
||||||
|
- Grading jobs run on the River queue `quizzes_grading`. An application can cap how many run at once in `config/queue.yaml` under `queues`, for example `queues: {quizzes_grading: 2}`.
|
||||||
|
|
||||||
|
### Events
|
||||||
|
|
||||||
|
Three events are fired through `app.Events` (package `git.golem15.com/golem15/sm-quizzes-plugin/events`, no other imports). Each fires only after the write it announces has committed, so a listener never sees a score that was rolled back; a listener error is logged and never undoes the write. Listen to them in your plugin's `Boot`:
|
||||||
|
|
||||||
|
```go
|
||||||
|
app.Events.Listen[*events.AnswerReviewedEvent]("acme.plugin", func(ctx context.Context, e *events.AnswerReviewedEvent) error {
|
||||||
|
// e.AnswerID, e.Points, e.Comment ...
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
| Event | Name | Fired when | Payload |
|
||||||
|
|-------|------|------------|---------|
|
||||||
|
| `*events.AnswerGradedEvent` | `quizzes.AnswerGraded` | A grader's score is stored (status `graded`). | `QuizID, QuestionID, AttemptID, AnswerID, UserID, Grader, Points, MaxPoints, Feedback` |
|
||||||
|
| `*events.AnswerReviewedEvent` | `quizzes.AnswerReviewed` | The owner confirms or sets a score (status `reviewed`). | `QuizID, QuestionID, AttemptID, AnswerID, UserID, Points, MaxPoints, GraderPoints, Comment, ReviewerUserID, ReviewerAdminID` |
|
||||||
|
| `*events.AttemptReviewedEvent` | `quizzes.AttemptReviewed` | Every open answer of a completed attempt is reviewed (also when an attempt reviewed while open closes, and again when a score of such an attempt changes). | `QuizID, AttemptID, UserID, ScorePoints, MaxPoints, ScorePercent, Passed` |
|
||||||
|
|
||||||
|
### For student-facing tools
|
||||||
|
|
||||||
|
A tool or app that serves quizzes to students (another MCP tool, a chat, a mobile app) must follow the rules the student API follows:
|
||||||
|
|
||||||
|
- never return the `rubric` or a `grading_error`;
|
||||||
|
- treat an `open` question as a text input and send the answer as `text` (not `answer_ids` or `known`), within its `max_length`;
|
||||||
|
- in an unfinished test keep open grades hidden: no `grading_status`, `grader_feedback`, `review_comment`, points or model answer until the attempt is finished, as `classes.Withheld` decides.
|
||||||
|
|
||||||
## Usage
|
## Usage
|
||||||
|
|
||||||
Mount the plugin in an application as a git submodule at `plugins/golem15/quizzes`, next to `plugins/golem15/user`, add it to the application's `go.work`, require it in the application's `go.mod` with a local replace, and list it in `summer.yaml` after `golem15.user`:
|
Mount the plugin in an application as a git submodule at `plugins/golem15/quizzes`, next to `plugins/golem15/user`, add it to the application's `go.work`, require it in the application's `go.mod` with a local replace, and list it in `summer.yaml` after `golem15.user`:
|
||||||
@@ -60,8 +145,8 @@ All routes are mounted under `/_quizzes/api/v1` with the `jwt.auth` middleware o
|
|||||||
| Method and path | Handler | Does |
|
| Method and path | Handler | Does |
|
||||||
|-----------------|---------|------|
|
|-----------------|---------|------|
|
||||||
| `GET /quizzes` | `api.Handlers.ListQuizzes` | Published quizzes, by title, with the caller's statistics. Query: `context`. |
|
| `GET /quizzes` | `api.Handlers.ListQuizzes` | Published quizzes, by title, with the caller's statistics. Query: `context`. |
|
||||||
| `GET /quizzes/{slug}` | `api.Handlers.ShowQuiz` | A published quiz with its questions and answers, without solutions (a `self_check` question carries its `answer_text`). Query: `category`. |
|
| `GET /quizzes/{slug}` | `api.Handlers.ShowQuiz` | A published quiz with its questions and answers, without solutions (a `self_check` question carries its `answer_text`); a test lists no questions. Query: `category`. |
|
||||||
| `POST /quizzes/{slug}/attempts` | `api.Handlers.StartAttempt` | Starts an attempt. Body (optional): `{"category": "..."}`. |
|
| `POST /quizzes/{slug}/attempts` | `api.Handlers.StartAttempt` | Starts an attempt, or resumes an open test attempt. Body (optional): `{"category": "..."}`. |
|
||||||
| `POST /attempts/{id}/answers` | `api.Handlers.Answer` | Saves or overwrites the answer to one question and returns feedback. |
|
| `POST /attempts/{id}/answers` | `api.Handlers.Answer` | Saves or overwrites the answer to one question and returns feedback. |
|
||||||
| `POST /attempts/{id}/finish` | `api.Handlers.Finish` | Finishes the attempt and returns the result. |
|
| `POST /attempts/{id}/finish` | `api.Handlers.Finish` | Finishes the attempt and returns the result. |
|
||||||
| `GET /attempts/{id}` | `api.Handlers.ShowAttempt` | The result with per-question details. |
|
| `GET /attempts/{id}` | `api.Handlers.ShowAttempt` | The result with per-question details. |
|
||||||
@@ -76,12 +161,14 @@ All routes are mounted under `/_quizzes/api/v1` with the `jwt.auth` middleware o
|
|||||||
| 401 | `{"error": true, "message": "Token not provided"}` | No or invalid token (from the guard). |
|
| 401 | `{"error": true, "message": "Token not provided"}` | No or invalid token (from the guard). |
|
||||||
| 404 | `{"error": "Quiz not found"}` | Unknown or unpublished slug. |
|
| 404 | `{"error": "Quiz not found"}` | Unknown or unpublished slug. |
|
||||||
| 404 | `{"error": "Attempt not found"}` | Unknown attempt, or another user's attempt. |
|
| 404 | `{"error": "Attempt not found"}` | Unknown attempt, or another user's attempt. |
|
||||||
| 409 | `{"error": "The attempt is already completed."}` | Answering or finishing a finished attempt. |
|
| 409 | `{"error": "The attempt is already completed.", "code": "attempt_completed"}` | Answering or finishing a finished attempt. |
|
||||||
| 409 | `{"error": "The time limit of this attempt has been exceeded."}` | Answering after `started_at + time_limit_seconds`. |
|
| 409 | `{"error": "The time limit of this attempt has been exceeded.", "code": "time_limit_exceeded"}` | Answering after `started_at + time_limit_seconds` (plus the grace of a test). |
|
||||||
|
| 409 | `{"error": "All attempts at this test have been used.", "code": "attempt_limit_reached"}` | Starting a test after `max_attempts` attempts. |
|
||||||
|
| 409 | `{"error": "An answer in this test cannot be changed.", "code": "answer_locked"}` | Answering a question of a `one_way` test again. |
|
||||||
| 413 | `{"error": "Payload too large"}` | A body over the route's limit. |
|
| 413 | `{"error": "Payload too large"}` | A body over the route's limit. |
|
||||||
| 422 | `{"error": "<first message>", "errors": {"<field>": ["<message>"]}}` | Invalid input, the shape `golem15.user` uses. Keys follow the rule order. |
|
| 422 | `{"error": "<first message>", "errors": {"<field>": ["<message>"]}}` | Invalid input, the shape `golem15.user` uses. Keys follow the rule order. Starting a test with a category is a 422 on `category`: "A test covers the whole quiz; a category cannot be chosen." |
|
||||||
|
|
||||||
The messages are translated into the request locale (`golem15.quizzes::lang.api.*`, Polish and English).
|
Every 409 body carries `code`, a stable key clients can branch on; the `error` message is for people. The messages are translated into the request locale (`golem15.quizzes::lang.api.*`, Polish and English).
|
||||||
|
|
||||||
### GET /quizzes
|
### GET /quizzes
|
||||||
|
|
||||||
@@ -98,11 +185,16 @@ The messages are translated into the request locale (`golem15.quizzes::lang.api.
|
|||||||
"round_size": 5,
|
"round_size": 5,
|
||||||
"shuffle_questions": false,
|
"shuffle_questions": false,
|
||||||
"best_score_percent": 83.33,
|
"best_score_percent": 83.33,
|
||||||
"attempts_count": 2
|
"attempts_count": 2,
|
||||||
|
"mode": "test",
|
||||||
|
"navigation": "free",
|
||||||
|
"max_attempts": 3,
|
||||||
|
"attempts_left": 1,
|
||||||
|
"question_types": {"single": 20, "multiple": 10, "self_check": 24, "open": 0}
|
||||||
}]}
|
}]}
|
||||||
```
|
```
|
||||||
|
|
||||||
`attempts_count` counts the caller's finished attempts and `best_score_percent` is their best finished result (`null` before the first one).
|
`attempts_count` counts the caller's finished attempts and `best_score_percent` is their best finished result (`null` before the first one). `question_types` counts the questions per type, with all four keys always present. `attempts_left` is how many attempts the caller may still start at a test with a limit (every attempt counts, open or finished); it is `null` for a learning quiz or a test without a limit.
|
||||||
|
|
||||||
### GET /quizzes/{slug}
|
### GET /quizzes/{slug}
|
||||||
|
|
||||||
@@ -113,6 +205,7 @@ The messages are translated into the request locale (`golem15.quizzes::lang.api.
|
|||||||
"round_size": 5, "shuffle_questions": false,
|
"round_size": 5, "shuffle_questions": false,
|
||||||
"question_count": 2,
|
"question_count": 2,
|
||||||
"categories": ["Documents", "Theory"],
|
"categories": ["Documents", "Theory"],
|
||||||
|
"mode": "learning", "navigation": "free", "max_attempts": null, "attempts_left": null,
|
||||||
"questions": [
|
"questions": [
|
||||||
{"id": 10, "text": "What is societal resilience?", "type": "self_check", "category": "Theory",
|
{"id": 10, "text": "What is societal resilience?", "type": "self_check", "category": "Theory",
|
||||||
"points": 1, "sort_order": 1, "answer_text": "The ability of a society to withstand a crisis.", "answers": []},
|
"points": 1, "sort_order": 1, "answer_text": "The ability of a society to withstand a crisis.", "answers": []},
|
||||||
@@ -122,11 +215,11 @@ The messages are translated into the request locale (`golem15.quizzes::lang.api.
|
|||||||
}}
|
}}
|
||||||
```
|
```
|
||||||
|
|
||||||
`categories` lists every category of the quiz; with `?category=` the questions are only that category's and `question_count` counts them. Questions come in `sort_order`, or shuffled when `shuffle_questions` is true. Answers come in their sort order.
|
`categories` lists every category of the quiz; with `?category=` the questions are only that category's and `question_count` counts them. An `open` question carries `max_length` (its effective limit, 2000 when unset) and no answers; never its rubric or model answer. Questions come in `sort_order`, or shuffled when `shuffle_questions` is true. Answers come in their sort order. For a test, `questions` is empty, `question_count` counts the whole quiz, `?category=` is ignored and `attempts_left` is set as in the list.
|
||||||
|
|
||||||
### POST /quizzes/{slug}/attempts
|
### POST /quizzes/{slug}/attempts
|
||||||
|
|
||||||
Body, optional: `{"category": "Theory"}` limits the attempt to one category; a category without questions is a 422 on `category`. Answers status 201:
|
Body, optional: `{"category": "Theory"}` limits the attempt to one category; a category without questions is a 422 on `category`, and a test refuses any category. Answers status 201 with a new attempt, or 200 when an open test attempt is resumed:
|
||||||
|
|
||||||
```json
|
```json
|
||||||
{"data": {
|
{"data": {
|
||||||
@@ -137,11 +230,13 @@ Body, optional: `{"category": "Theory"}` limits the attempt to one category; a c
|
|||||||
"completed_at": null,
|
"completed_at": null,
|
||||||
"answered_count": 0,
|
"answered_count": 0,
|
||||||
"score_points": 0, "max_points": 54, "score_percent": null,
|
"score_points": 0, "max_points": 54, "score_percent": null,
|
||||||
"passing_score": 50, "passed": null
|
"passing_score": 50, "passed": null,
|
||||||
|
"quiz_mode": "learning", "quiz_navigation": "free", "seconds_left": null,
|
||||||
|
"resumed": false, "attempts_left": null
|
||||||
}}
|
}}
|
||||||
```
|
```
|
||||||
|
|
||||||
`expires_at` is `started_at + time_limit_seconds`, or `null` without a limit. `max_points` sums the points of the questions the attempt covers. This attempt shape is also each row of `GET /attempts`.
|
`expires_at` is `started_at + time_limit_seconds`, or `null` without a limit. `seconds_left` is the whole seconds until `expires_at`, rounded up and never below 0, counted by the server; it is `null` without a limit and once the attempt is finished. `quiz_mode` and `quiz_navigation` tell the player which flow to run. `max_points` sums the points of the questions the attempt covers. This attempt shape, without `resumed` and `attempts_left`, is also each row of `GET /attempts` and the head of a result. `resumed` is true when an open test attempt was returned; `attempts_left` counts the attempts left after this one (`null` for a learning quiz or without a limit).
|
||||||
|
|
||||||
### POST /attempts/{id}/answers
|
### POST /attempts/{id}/answers
|
||||||
|
|
||||||
@@ -152,12 +247,14 @@ Body:
|
|||||||
| `question_id` | Required integer; the question must belong to the attempt's quiz (and category). |
|
| `question_id` | Required integer; the question must belong to the attempt's quiz (and category). |
|
||||||
| `answer_ids` | Array of answer IDs. Required for `single` (exactly one) and `multiple`; every ID must belong to the question. |
|
| `answer_ids` | Array of answer IDs. Required for `single` (exactly one) and `multiple`; every ID must belong to the question. |
|
||||||
| `known` | Boolean. Required for `self_check`. |
|
| `known` | Boolean. Required for `self_check`. |
|
||||||
|
| `text` | String. Required for `open`: not blank (422 `text_required`), at most the question's `max_length` characters (422 `text_too_long`). NUL bytes are dropped. |
|
||||||
|
|
||||||
Checks run in this order: the body (422), the attempt belongs to the caller (404), it is not finished (409), it is within the time limit (409), the question belongs to it (422 on `question_id`), the answer fits the question (422 on `answer_ids` or `known`). Answering a question again overwrites the stored answer. Answers status 200:
|
Checks run in this order: the body (422), the attempt belongs to the caller (404), it is not finished (409), it is within the time limit plus the grace of a test (409), the question belongs to it (422 on `question_id`), a `one_way` test has no answer to it yet (409), the answer fits the question (422 on `answer_ids` or `known`). Answering a question again overwrites the stored answer. Answers status 200:
|
||||||
|
|
||||||
```json
|
```json
|
||||||
{"data": {
|
{"data": {
|
||||||
"question_id": 11,
|
"question_id": 11,
|
||||||
|
"withheld": false,
|
||||||
"is_correct": false,
|
"is_correct": false,
|
||||||
"points": 0,
|
"points": 0,
|
||||||
"correct_answer_ids": [30],
|
"correct_answer_ids": [30],
|
||||||
@@ -170,7 +267,7 @@ Checks run in this order: the body (422), the attempt belongs to the caller (404
|
|||||||
}}
|
}}
|
||||||
```
|
```
|
||||||
|
|
||||||
`points` can be negative when `scoring.penalty_wrong` is set. For a `self_check` question `correct_answer_ids` and `answers` are empty and `answer_text` holds the model answer.
|
For an `open` question the feedback adds `text` (the stored answer), `grading_status`, `grader_feedback` and `review_comment`; `is_correct` and `points` stay `null` until the answer is graded or reviewed. `points` can be negative when `scoring.penalty_wrong` is set. For a `self_check` question `correct_answer_ids` and `answers` are empty and `answer_text` holds the model answer. For an open test attempt `withheld` is true and `is_correct`, `points`, `correct_answer_ids`, `explanation` and `answer_text` are `null`; the answers carry only `id` and `text` (`is_correct` and `explanation` `null`).
|
||||||
|
|
||||||
### POST /attempts/{id}/finish and GET /attempts/{id}
|
### POST /attempts/{id}/finish and GET /attempts/{id}
|
||||||
|
|
||||||
@@ -182,6 +279,8 @@ Finishing sums the stored points, floors the total at 0, sets `score_percent = s
|
|||||||
"started_at": "2026-10-02T12:00:00+00:00", "expires_at": null, "completed_at": "2026-10-02T12:09:41+00:00",
|
"started_at": "2026-10-02T12:00:00+00:00", "expires_at": null, "completed_at": "2026-10-02T12:09:41+00:00",
|
||||||
"answered_count": 2, "score_points": 1, "max_points": 2, "score_percent": 50,
|
"answered_count": 2, "score_points": 1, "max_points": 2, "score_percent": 50,
|
||||||
"passing_score": 50, "passed": true,
|
"passing_score": 50, "passed": true,
|
||||||
|
"quiz_mode": "learning", "quiz_navigation": "free", "seconds_left": null,
|
||||||
|
"solutions_withheld": false,
|
||||||
"questions": [
|
"questions": [
|
||||||
{"id": 10, "text": "What is societal resilience?", "type": "self_check", "category": "Theory", "points": 1,
|
{"id": 10, "text": "What is societal resilience?", "type": "self_check", "category": "Theory", "points": 1,
|
||||||
"answered": true, "answer_ids": [], "known": true, "is_correct": true, "points_earned": 1,
|
"answered": true, "answer_ids": [], "known": true, "is_correct": true, "points_earned": 1,
|
||||||
@@ -195,7 +294,7 @@ Finishing sums the stored points, floors the total at 0, sets `score_percent = s
|
|||||||
}}
|
}}
|
||||||
```
|
```
|
||||||
|
|
||||||
`passed` is `score_percent >= passing_score` once the attempt is finished, else `null`. While the attempt is open, an unanswered question has `correct_answer_ids`, `explanation` and `answer_text` set to `null` and `is_correct`/`explanation` of its answers set to `null`.
|
An `open` question's row adds `text_answer` (the student's text; `text` is the question), `max_length`, `grading_status`, `grader_feedback` and `review_comment`, with `is_correct` and `points_earned` `null` until it is graded or reviewed; in an open test attempt every grading key is `null`. Every attempt shape (this one, the start answer and the rows of `GET /attempts`) carries `needs_review` and `open_answers`. `passed` is `score_percent >= passing_score` once the attempt is finished, else `null`. While the attempt is open, an unanswered question has `correct_answer_ids`, `explanation` and `answer_text` set to `null` and `is_correct`/`explanation` of its answers set to `null`; its own `is_correct` is `false` and `points_earned` 0. While a test attempt is open `solutions_withheld` is true and every question, answered or not, has `is_correct`, `points_earned`, `correct_answer_ids`, `explanation` and `answer_text` set to `null`, with no answer `is_correct` or `explanation`; `answered`, `answer_ids` and `known` stay. With `shuffle_questions` a test attempt lists its questions in an order seeded by the attempt, the same on every call; other attempts list them in sort order.
|
||||||
|
|
||||||
### GET /attempts
|
### GET /attempts
|
||||||
|
|
||||||
@@ -206,12 +305,58 @@ Finishing sums the stored points, floors the total at 0, sets `score_percent = s
|
|||||||
|
|
||||||
### Packages
|
### Packages
|
||||||
|
|
||||||
- `classes`: `Score`, `Totals` and `ScoringConfigFrom` (scoring); `Service` (the API's queries and writes); `ParseImport` and `Import` (the importer).
|
- `classes`: `Score`, `Totals` and `ScoringConfigFrom` (scoring); `Service` (the API's queries and writes); `IsTest`, `Withheld`, `OneWay`, `AnswerDeadline`, `Expired`, `SecondsLeft`, `AttemptsLeft`, `AttemptLockKey` and `TestGraceFrom` (the test-mode policy); `ParseImport`, `Import` and `CheckQuestion` (the importer and its per-question rules); `ListManagedQuizzes`, `ManagedQuiz`, `CreateQuiz`, `UpdateQuiz`, `DeleteQuiz`, `SetPublished`, `CreateQuestion`, `UpdateQuestion`, `MergeQuestion`, `DeleteQuestion`, `ReorderQuestions`, `QuizStats` and `BuildStats` (owner management).
|
||||||
- `controllers/api`: `Handlers`, the HTTP handlers.
|
- `controllers/api`: `Handlers`, the HTTP handlers.
|
||||||
- `controllers`: the admin controllers `QuizzesController`, `QuestionsController`, `AnswersController` and `AttemptsController`.
|
- `classes` (open questions): `CheckOpenText`, `GraderFor`, `GradeAnswer`, `ForApp`, and the review service `ReviewQueue`, `ReviewItem`, `Confirm`, `SetScore`, `ConfirmBulk` and `Regrade`, shared by the review routes and the admin.
|
||||||
- `models`: `Quiz`, `Question`, `Answer`, `Attempt`, `AttemptAnswer` and `Slugify`.
|
- `controllers`: the admin controllers `QuizzesController`, `QuestionsController`, `AnswersController`, `ReviewsController` and `AttemptsController`.
|
||||||
|
- `models`: `Quiz`, `Question`, `Answer`, `Attempt`, `AttemptAnswer`, `Review` (an open answer as the admin review screen reads it) and `Slugify`.
|
||||||
|
- `graders`: `Grader`, `Input`, `Result`, `HasGraders`, `Registry` and `Manual`, the grader contract.
|
||||||
|
- `events`: `AnswerGradedEvent`, `AnswerReviewedEvent` and `AttemptReviewedEvent`.
|
||||||
|
- `jobs`: `Queue` (`quizzes_grading`) and `GradeAnswerArgs`.
|
||||||
- `console`: `ImportCommand`.
|
- `console`: `ImportCommand`.
|
||||||
|
|
||||||
|
## Management API and MCP tools
|
||||||
|
|
||||||
|
The owner manages quizzes from an MCP client (or any HTTP client) with a `golem15.user` API token. Every route below runs behind `user.api_token`, the per-user throttle `golem15.quizzes.manage` (120 requests a minute), the token scope named in the table and the `golem15.quizzes.access_quizzes` permission. The plugin declares that permission through `pact.HasFrontendPermissions`, so it shows up in golem15.user's User Groups editor. Grant it to the owner's group only, because the stats show student emails and names. Declaring it grants nothing. There is no owner column: a holder of the permission manages every quiz, as in the admin. Quizzes are addressed by slug.
|
||||||
|
|
||||||
|
| Method and path under `/api/v1/quizzes` | Scope | MCP tool | Answer |
|
||||||
|
|---|---|---|---|
|
||||||
|
| `GET ""` (`?context=`) | read | `quizzes_list_quizzes` | Every quiz, published or not, ordered by context (none last) and title. |
|
||||||
|
| `GET /{slug}` | read | `quizzes_show_quiz` | The quiz with its questions and answers, solutions included. |
|
||||||
|
| `POST ""` | write | `quizzes_create_quiz` | 201. The new quiz starts unpublished. A taken slug is a 409. |
|
||||||
|
| `PATCH /{slug}` | write | `quizzes_update_quiz` | Only sent fields change. `0` clears `time_limit_seconds`, `max_attempts` and `round_size`, and `""` clears `description` and `context`. It cannot publish or change the slug. |
|
||||||
|
| `DELETE /{slug}?confirm={slug}` | write | `quizzes_delete_quiz` | `{id, slug, title, questions, attempts}`. A 422 unless `confirm` repeats the slug. |
|
||||||
|
| `POST /{slug}/publish`, `POST /{slug}/unpublish` | write | `quizzes_publish`, `quizzes_unpublish` | The quiz. Both are idempotent. |
|
||||||
|
| `GET /{slug}/stats` | read | `quizzes_quiz_stats` | `students` and `questions` (see below). |
|
||||||
|
| `POST /{slug}/questions` | write | `quizzes_create_question` | 201 with the question. It goes last unless `sort_order` is given, and its answers come inline. |
|
||||||
|
| `PATCH /{slug}/questions/{id}` | write | `quizzes_update_question` | The question. Only sent fields change. A sent `answers` list keeps and updates the answers with an `id`, creates the ones without and deletes the missing ones. |
|
||||||
|
| `DELETE /{slug}/questions/{id}` | write | `quizzes_delete_question` | `{id, quiz_slug}`. |
|
||||||
|
| `PUT /{slug}/questions/order` | write | `quizzes_reorder_questions` | The quiz with its questions. `question_ids` must list every question exactly once. |
|
||||||
|
| `POST /import?replace=` | write | `quizzes_import_quiz` | The import route (see CLI commands). It has its own `throttle:60,1`. With `replace` it deletes the attempt answers of the old questions, open answers with their grades and reviews. |
|
||||||
|
|
||||||
|
The quiz shape is `id, slug, title, description, context, mode, navigation, max_attempts, time_limit_seconds, passing_score, shuffle_questions, round_size, grader, is_published, question_count, attempts_count, created_at, updated_at`. The question shape is `id, text, type, category, answer_text, explanation, points, sort_order, rubric, max_length, answers [{id, text, is_correct, explanation, sort_order}]`; `rubric` and `max_length` are `null` unless set on an open question. These owner shapes are never used by a student route.
|
||||||
|
|
||||||
|
`grader` on a quiz create or update must be `manual` or a code an activated plugin registers; anything else is a 422 listing the valid codes. `rubric` and `max_length` on a question create or update follow the importer's rules; `""` clears `rubric` and `0` clears `max_length`.
|
||||||
|
|
||||||
|
**Review routes.** The open answers are reviewed under a prefix of their own, with the same token, throttle, scopes and permission:
|
||||||
|
|
||||||
|
| Method and path under `/api/v1/quiz-reviews` | Scope | MCP tool | Answer |
|
||||||
|
|---|---|---|---|
|
||||||
|
| `GET ""` (`?status=&quiz=&user_id=&attempt_id=&page=&per_page=`) | read | `quizzes_review_list` | Open answers, oldest change first. `status` is `open` (the default: pending, graded and failed), a grading status or `all`. Rows carry a 300-character excerpt with `text_truncated`. |
|
||||||
|
| `GET /{id}` | read | `quizzes_review_show` | One answer with the whole text, the question with its model answer, rubric and `max_length`, the grader's result or error and the review so far. |
|
||||||
|
| `POST /{id}/confirm` | write | `quizzes_review_confirm` | The grader's score becomes final. 409 `no_grader_score` for a pending or failed answer; a reviewed answer is returned unchanged. |
|
||||||
|
| `POST /{id}/score` | write | `quizzes_review_set_score` | `{points, comment}`: 0 up to the question's points in steps of 0.5 (else 422), on any status; the comment (at most 2000 characters) replaces an earlier one, and leaving it out clears it. |
|
||||||
|
| `POST /confirm` | write | `quizzes_review_confirm_bulk` | `{quiz}` or `{attempt_id}`: confirms every graded answer in scope; answers `{confirmed: n}`. |
|
||||||
|
| `POST /regrade` | write | `quizzes_review_regrade` | `{answer_id}`, `{attempt_id}` or `{quiz}`: pending, graded and failed answers go back to the grader; answers `{regraded: n}`. 409 `already_reviewed` for one reviewed answer, 409 `grader_manual` when the quiz's grader is manual or not registered. |
|
||||||
|
|
||||||
|
Every 409 body is `{"error": true, "message", "code"}`. Every review action recalculates a finished attempt and fires the events above.
|
||||||
|
|
||||||
|
Input is checked before the database is read. Invalid JSON, an unknown key or a broken rule is a 422 `{"message"}`. A merged question must pass the importer's rules (`classes.CheckQuestion`), and an answer `id` that belongs to another question is refused. A missing quiz or question is a 404.
|
||||||
|
|
||||||
|
**History (D-16).** A question can be edited while its quiz has attempts. Finished attempts keep their stored scores, and their reviews show the current question. Answers are updated by id and never deleted and recreated, so the answer ids stored in past attempts stay valid. Deleting a question cascades to its answers and to the attempt answers given to it, and an import with `replace` does the same for every question. On a quiz with attempts, prefer the per-question tools.
|
||||||
|
|
||||||
|
**Stats.** The stats route first closes the quiz's expired open test attempts at their deadline. `students [{user_id, email, name, surname, attempts, best_score_percent, last_score_percent, last_completed_at, passed}]` counts each student's completed whole-quiz attempts. Learning rounds of one category are left out, and `passed` is `best_score_percent >= passing_score`. `questions [{id, text, type, answered, correct, correct_percent, most_chosen_wrong}]` counts the answers of every completed attempt. `correct_percent` is `null` when nobody answered. `most_chosen_wrong` is `{answer_id, text, count}`, or `null` for self_check and open questions and when no wrong answer was chosen. Each question also has `unreviewed`, the open answers of completed attempts still pending, graded or failed, and `average_points`, the mean score of an open question's graded and reviewed answers (`null` for other types and before any grade). The report's top-level `unreviewed` is the sum.
|
||||||
|
|
||||||
## Configuration
|
## Configuration
|
||||||
|
|
||||||
Defaults live in `config/config.yaml` and are merged under `golem15.quizzes.*`.
|
Defaults live in `config/config.yaml` and are merged under `golem15.quizzes.*`.
|
||||||
@@ -220,6 +365,9 @@ Defaults live in `config/config.yaml` and are merged under `golem15.quizzes.*`.
|
|||||||
|-----|---------|---------|
|
|-----|---------|---------|
|
||||||
| `golem15.quizzes.scoring.multiple_partial` | `false` | Partial credit on `multiple` questions: `(correct chosen - wrong chosen) / correct answers` of the points, floored at 0. Without it only the exact set earns points. |
|
| `golem15.quizzes.scoring.multiple_partial` | `false` | Partial credit on `multiple` questions: `(correct chosen - wrong chosen) / correct answers` of the points, floored at 0. Without it only the exact set earns points. |
|
||||||
| `golem15.quizzes.scoring.penalty_wrong` | `0` | Fraction (0 to 1) of a question's points subtracted for a wrong answer: a non-empty `single` or `multiple` answer that earns nothing. `self_check` answers marked as unknown and empty answers are never penalised. An attempt's total never goes below 0. |
|
| `golem15.quizzes.scoring.penalty_wrong` | `0` | Fraction (0 to 1) of a question's points subtracted for a wrong answer: a non-empty `single` or `multiple` answer that earns nothing. `self_check` answers marked as unknown and empty answers are never penalised. An attempt's total never goes below 0. |
|
||||||
|
| `golem15.quizzes.test.grace_seconds` | `5` | Seconds after a test's time limit during which an answer still in flight is accepted, clamped to 0..120. A missing or non-numeric value is 5. Learning quizzes have no grace. |
|
||||||
|
| `golem15.quizzes.throttle.answers_per_minute` | `60` | Per-user limit of `POST /attempts/{id}/answers` (bucket `golem15.quizzes.answer`). With a grader such as `ai`, every new or changed open answer in a learning quiz is a paid grading call. A missing, non-numeric or sub-1 value is 60. |
|
||||||
|
| `golem15.quizzes.throttle.attempts_per_minute` | `10` | Per-user limit of `POST /quizzes/{slug}/attempts` (bucket `golem15.quizzes.start`). A missing, non-numeric or sub-1 value is 10. |
|
||||||
|
|
||||||
Scores are rounded to two decimals.
|
Scores are rounded to two decimals.
|
||||||
|
|
||||||
@@ -230,8 +378,13 @@ Scores are rounded to two decimals.
|
|||||||
| Quizzes | `golem15/quizzes/quizzes` | `golem15.quizzes.access_quizzes` |
|
| Quizzes | `golem15/quizzes/quizzes` | `golem15.quizzes.access_quizzes` |
|
||||||
| Questions | `golem15/quizzes/questions` | `golem15.quizzes.access_quizzes` |
|
| Questions | `golem15/quizzes/questions` | `golem15.quizzes.access_quizzes` |
|
||||||
| Answers | `golem15/quizzes/answers` | `golem15.quizzes.access_quizzes` |
|
| Answers | `golem15/quizzes/answers` | `golem15.quizzes.access_quizzes` |
|
||||||
|
| Do oceny (open answers) | `golem15/quizzes/reviews` | `golem15.quizzes.access_quizzes` |
|
||||||
| Attempts (read-only) | `golem15/quizzes/attempts` | `golem15.quizzes.access_attempts` |
|
| Attempts (read-only) | `golem15/quizzes/attempts` | `golem15.quizzes.access_attempts` |
|
||||||
|
|
||||||
|
The quiz form has three test settings: Mode (Learning / Test), Test navigation (Free / One way) and Attempt limit (empty for none); the last two say in their comments that they apply to tests only. It also has the grader dropdown "Ocenianie pytań otwartych": Manual and every grader an activated plugin registers. The quiz list shows the mode and the grader. The question form offers the type "Pytanie otwarte" with the fields rubric (the comment says only the grader sees it) and max_length.
|
||||||
|
|
||||||
|
"Do oceny" lists the open answers only, oldest change first, filtered by quiz, status and student. Opening one shows, read-only, the quiz, the student, the question, the model answer, the rubric, the student's text, the grader with its points, feedback and any error, and the current review. Saving the form with "Punkty (ostateczne)" (0 to the question's points, steps of 0.5) and an optional "Komentarz dla studenta" stores the owner's score; a comment without points is refused. The record action "Zatwierdź ocenę" confirms a graded answer, "Oceń ponownie" sends an answer back to the grader (offered only when the quiz has a registered grader and the answer is not reviewed), and the bulk action "Zatwierdź zaznaczone" confirms the selected graded answers. The administrator is stored as the reviewer (`reviewed_by_admin_id`). Answers cannot be created or deleted there. The screen uses the same review service as the MCP tools.
|
||||||
|
|
||||||
The navigation item is "Quizzes" ("Quizy" in Polish). The admin's relation manager links records through a pivot table only, so questions and answers have their own lists instead of being edited inside the quiz form; filter them by quiz.
|
The navigation item is "Quizzes" ("Quizy" in Polish). The admin's relation manager links records through a pivot table only, so questions and answers have their own lists instead of being edited inside the quiz form; filter them by quiz.
|
||||||
|
|
||||||
## CLI commands
|
## CLI commands
|
||||||
@@ -246,7 +399,7 @@ The import runs in one transaction and is idempotent by slug:
|
|||||||
|
|
||||||
- a new slug creates the quiz;
|
- a new slug creates the quiz;
|
||||||
- an existing slug is refused unless `--replace` is given;
|
- an existing slug is refused unless `--replace` is given;
|
||||||
- with `--replace` the quiz's fields are updated and all its questions are deleted and recreated. The attempts stay, but the attempt answers given to the old questions are deleted with them.
|
- with `--replace` the quiz's fields are updated and all its questions are deleted and recreated. The attempts stay, but the attempt answers given to the old questions are deleted with them, open answers with their grades and reviews.
|
||||||
|
|
||||||
The file is checked before anything is written, and unknown keys are an error. Format:
|
The file is checked before anything is written, and unknown keys are an error. Format:
|
||||||
|
|
||||||
@@ -261,6 +414,7 @@ The file is checked before anything is written, and unknown keys are an error. F
|
|||||||
"round_size": 5,
|
"round_size": 5,
|
||||||
"time_limit_seconds": 1800,
|
"time_limit_seconds": 1800,
|
||||||
"shuffle_questions": false,
|
"shuffle_questions": false,
|
||||||
|
"grader": "manual",
|
||||||
"questions": [
|
"questions": [
|
||||||
{"text": "What is societal resilience?", "type": "self_check", "category": "Theory",
|
{"text": "What is societal resilience?", "type": "self_check", "category": "Theory",
|
||||||
"answer_text": "The ability of a society to withstand a crisis and recover."},
|
"answer_text": "The ability of a society to withstand a crisis and recover."},
|
||||||
@@ -270,6 +424,9 @@ The file is checked before anything is written, and unknown keys are an error. F
|
|||||||
{"text": "National Security Strategy", "is_correct": true},
|
{"text": "National Security Strategy", "is_correct": true},
|
||||||
{"text": "Highway Code", "is_correct": false, "explanation": "A traffic law."}
|
{"text": "Highway Code", "is_correct": false, "explanation": "A traffic law."}
|
||||||
]},
|
]},
|
||||||
|
{"text": "Why did the Cold War end?", "type": "open", "points": 2, "max_length": 1500,
|
||||||
|
"answer_text": "Economic exhaustion of the USSR, reforms and arms control...",
|
||||||
|
"rubric": "1 point for internal causes, 1 for international ones."},
|
||||||
{"text": "Which countries are NATO members?", "type": "multiple", "points": 2,
|
{"text": "Which countries are NATO members?", "type": "multiple", "points": 2,
|
||||||
"answers": [
|
"answers": [
|
||||||
{"text": "Poland", "is_correct": true},
|
{"text": "Poland", "is_correct": true},
|
||||||
@@ -289,11 +446,17 @@ The file is checked before anything is written, and unknown keys are an error. F
|
|||||||
| `passing_score` | no | 0 to 100, default 50. |
|
| `passing_score` | no | 0 to 100, default 50. |
|
||||||
| `round_size`, `time_limit_seconds` | no | At least 1; `null` or missing for none. |
|
| `round_size`, `time_limit_seconds` | no | At least 1; `null` or missing for none. |
|
||||||
| `shuffle_questions` | no | Default `false`. |
|
| `shuffle_questions` | no | Default `false`. |
|
||||||
|
| `mode` | no | `learning` or `test`. Missing keeps the quiz's current mode on `--replace` and `learning` on create. |
|
||||||
|
| `navigation` | no | `free` or `one_way` (tests only). Missing keeps the current value on `--replace` and `free` on create. |
|
||||||
|
| `max_attempts` | no | At least 1 (tests only). Missing keeps the current value on `--replace` and no limit on create. |
|
||||||
|
| `grader` | no | A well-formed grader code (lowercase letters, digits and `_`). Missing keeps the current value on `--replace` and `manual` on create. A code no activated plugin registers grades as `manual`. |
|
||||||
| `questions` | yes | At least one. The file order becomes `sort_order`. |
|
| `questions` | yes | At least one. The file order becomes `sort_order`. |
|
||||||
| `questions[].text`, `questions[].type` | yes | `type` is `single`, `multiple` or `self_check`. |
|
| `questions[].text`, `questions[].type` | yes | `type` is `single`, `multiple`, `self_check` or `open`. |
|
||||||
| `questions[].category`, `answer_text`, `explanation` | no | |
|
| `questions[].category`, `answer_text`, `explanation` | no | `answer_text` is a flashcard's answer or an open question's model answer. |
|
||||||
|
| `questions[].rubric` | no | Open questions only: the owner's grading criteria, never shown to students. |
|
||||||
|
| `questions[].max_length` | no | Open questions only: 1 to 20000 characters; missing means 2000. |
|
||||||
| `questions[].points` | no | Default 1, not negative. |
|
| `questions[].points` | no | Default 1, not negative. |
|
||||||
| `questions[].answers` | for `single` and `multiple` | `single`: at least two answers, exactly one correct. `multiple`: at least two, one or more correct. `self_check`: none. |
|
| `questions[].answers` | for `single` and `multiple` | `single`: at least two answers, exactly one correct. `multiple`: at least two, one or more correct. `self_check` and `open`: none. |
|
||||||
| `answers[].text` | yes | |
|
| `answers[].text` | yes | |
|
||||||
| `answers[].is_correct`, `answers[].explanation` | no | |
|
| `answers[].is_correct`, `answers[].explanation` | no | |
|
||||||
|
|
||||||
@@ -303,6 +466,7 @@ The file is checked before anything is written, and unknown keys are an error. F
|
|||||||
|
|
||||||
- The SummerCMS framework, `git.golem15.com/golem15/summercms` (modules `backpack`, `bonfire`, `bouncer`, `cabana`, `lagoon`, `pact`, `party`, `phrasebook`, `surf`, `wire`).
|
- The SummerCMS framework, `git.golem15.com/golem15/summercms` (modules `backpack`, `bonfire`, `bouncer`, `cabana`, `lagoon`, `pact`, `party`, `phrasebook`, `surf`, `wire`).
|
||||||
- `golem15.user`, `git.golem15.com/golem15/sm-user-plugin`: the `jwt.auth` middleware and the `users` table.
|
- `golem15.user`, `git.golem15.com/golem15/sm-user-plugin`: the `jwt.auth` middleware and the `users` table.
|
||||||
|
- River, through the framework's `conga` module, runs the grading jobs. Without a job queue, open answers wait for the owner.
|
||||||
- gormigrate and GORM, as pinned in `go.mod`.
|
- gormigrate and GORM, as pinned in `go.mod`.
|
||||||
- testcontainers-go and pgx for the Postgres-backed tests.
|
- testcontainers-go and pgx for the Postgres-backed tests.
|
||||||
|
|
||||||
@@ -315,4 +479,4 @@ go test ./... # full run, starts Postgres with testcontainers (needs D
|
|||||||
|
|
||||||
The unit tests cover scoring, request validation, the handlers without a database, the response shapes, the import parser and the admin schema compilation. The Postgres tests run the whole API flow, time limits, cascades, the admin lists and filters and the import command against a throwaway database per test.
|
The unit tests cover scoring, request validation, the handlers without a database, the response shapes, the import parser and the admin schema compilation. The Postgres tests run the whole API flow, time limits, cascades, the admin lists and filters and the import command against a throwaway database per test.
|
||||||
|
|
||||||
Known framework limitations are marked `TODO: requires SummerCMS change` in the code: admin filter choices read the database through `models.FilterDB` because `pact.FilterOptions` receives no context or database; category filter values travel hex-encoded (`models.EncodeCategoryValue`) because the admin accepts only integer or identifier scope values; and the quiz form cannot embed its questions because the relation manager handles pivot relations only.
|
Known framework limitations are marked `TODO: requires SummerCMS change` in the code: admin filter choices read the database through `models.FilterDB` because `pact.FilterOptions` receives no context or database; category filter values travel hex-encoded (`models.EncodeCategoryValue`) because the admin accepts only integer or identifier scope values; the quiz form cannot embed its questions because the relation manager handles pivot relations only; and the admin grader dropdown and review screen reach the grader registry and the review service through the package-level hooks `controllers.GraderOptions` and `controllers.Reviews`, because admin hooks receive no app.
|
||||||
|
|||||||
@@ -2,12 +2,16 @@ package quizzes_test
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"slices"
|
"slices"
|
||||||
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"git.golem15.com/golem15/sm-quizzes-plugin/models"
|
"git.golem15.com/golem15/sm-quizzes-plugin/models"
|
||||||
"git.golem15.com/golem15/summercms/modules/bouncer"
|
"git.golem15.com/golem15/summercms/modules/bouncer"
|
||||||
"git.golem15.com/golem15/summercms/modules/cabana"
|
"git.golem15.com/golem15/summercms/modules/cabana"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/lagoon"
|
||||||
"git.golem15.com/golem15/summercms/modules/pact"
|
"git.golem15.com/golem15/summercms/modules/pact"
|
||||||
|
"gorm.io/gorm"
|
||||||
|
"gorm.io/gorm/utils/tests"
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestAdminCompiles(t *testing.T) {
|
func TestAdminCompiles(t *testing.T) {
|
||||||
@@ -37,7 +41,7 @@ func TestAdminCompiles(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
slices.Sort(ids)
|
slices.Sort(ids)
|
||||||
want := []string{"golem15.quizzes.answers", "golem15.quizzes.attempts", "golem15.quizzes.questions", "golem15.quizzes.quizzes"}
|
want := []string{"golem15.quizzes.answers", "golem15.quizzes.attempts", "golem15.quizzes.questions", "golem15.quizzes.quizzes", "golem15.quizzes.reviews"}
|
||||||
if !slices.Equal(ids, want) {
|
if !slices.Equal(ids, want) {
|
||||||
t.Errorf("controllers = %v, want %v", ids, want)
|
t.Errorf("controllers = %v, want %v", ids, want)
|
||||||
}
|
}
|
||||||
@@ -52,17 +56,78 @@ func TestAdminCompiles(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
nav := p.(pact.HasNavigation).Navigation()
|
nav := p.(pact.HasNavigation).Navigation()
|
||||||
if len(nav) != 1 || nav[0].Label != "golem15.quizzes::lang.plugin.name" || len(nav[0].SideMenu) != 4 {
|
if len(nav) != 1 || nav[0].Label != "golem15.quizzes::lang.plugin.name" || len(nav[0].SideMenu) != 5 {
|
||||||
t.Errorf("navigation = %+v", nav)
|
t.Errorf("navigation = %+v", nav)
|
||||||
|
} else {
|
||||||
|
var codes []string
|
||||||
|
for _, item := range nav[0].SideMenu {
|
||||||
|
codes = append(codes, item.Code)
|
||||||
|
}
|
||||||
|
if !slices.Equal(codes, []string{"quizzes", "questions", "answers", "reviews", "attempts"}) {
|
||||||
|
t.Errorf("side menu = %v, want reviews after answers", codes)
|
||||||
|
}
|
||||||
|
if review := nav[0].SideMenu[3]; review.Controller != "golem15.quizzes.reviews" || !slices.Equal(review.Permissions, []string{"golem15.quizzes.access_quizzes"}) {
|
||||||
|
t.Errorf("reviews entry = %+v", review)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestQuestionFilterScopes(t *testing.T) {
|
func TestQuestionFilterScopes(t *testing.T) {
|
||||||
q := models.Question{}
|
q := models.Question{}
|
||||||
if got := q.FilterOptions(models.ScopeByType); len(got) != 3 {
|
if got := q.FilterOptions(models.ScopeByType); len(got) != 4 || got[3].Value != models.TypeOpen {
|
||||||
t.Errorf("type options = %v", got)
|
t.Errorf("type options = %v", got)
|
||||||
}
|
}
|
||||||
if got := q.FilterScope("unknown", nil, "x"); got != nil {
|
if got := q.FilterScope("unknown", nil, "x"); got != nil {
|
||||||
t.Errorf("FilterScope on a nil db = %v", got)
|
t.Errorf("FilterScope on a nil db = %v", got)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestReviewFilterScopes(t *testing.T) {
|
||||||
|
r := models.Review{}
|
||||||
|
if got := r.FilterScopes(); !slices.Equal(got, []string{models.ScopeByQuiz, models.ScopeByStatus, models.ScopeByStudent}) {
|
||||||
|
t.Errorf("FilterScopes = %v", got)
|
||||||
|
}
|
||||||
|
opts := r.FilterOptions(models.ScopeByStatus)
|
||||||
|
var values []string
|
||||||
|
for _, o := range opts {
|
||||||
|
values = append(values, o.Value)
|
||||||
|
if o.Label != "golem15.quizzes::lang.reviews.status_"+o.Value {
|
||||||
|
t.Errorf("status %s label = %q", o.Value, o.Label)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !slices.Equal(values, []string{"pending", "graded", "failed", "reviewed"}) {
|
||||||
|
t.Errorf("status options = %v", values)
|
||||||
|
}
|
||||||
|
if got := r.FilterScope("unknown", nil, "x"); got != nil {
|
||||||
|
t.Errorf("FilterScope on a nil db = %v", got)
|
||||||
|
}
|
||||||
|
|
||||||
|
db, err := gorm.Open(tests.DummyDialector{}, &gorm.Config{DryRun: true})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("dry-run db: %v", err)
|
||||||
|
}
|
||||||
|
sqlOf := func(scope string, value any) string {
|
||||||
|
var rows []models.Review
|
||||||
|
stmt := r.FilterScope(scope, db.Session(&gorm.Session{DryRun: true}).Model(&models.Review{}), value).Find(&rows).Statement
|
||||||
|
return stmt.SQL.String()
|
||||||
|
}
|
||||||
|
if got := sqlOf(models.ScopeByStatus, []any{"graded"}); !strings.Contains(got, "golem15_quizzes_attempt_answers.grading_status IN") {
|
||||||
|
t.Errorf("status SQL = %s", got)
|
||||||
|
}
|
||||||
|
if got := sqlOf(models.ScopeByStatus, []any{"bogus"}); !strings.Contains(got, "1 = 0") {
|
||||||
|
t.Errorf("unknown status SQL = %s, want no rows", got)
|
||||||
|
}
|
||||||
|
if got := sqlOf(models.ScopeByQuiz, []any{"3"}); !strings.Contains(got, "question_id IN (SELECT id FROM golem15_quizzes_questions WHERE quiz_id IN") {
|
||||||
|
t.Errorf("quiz SQL = %s", got)
|
||||||
|
}
|
||||||
|
if got := sqlOf(models.ScopeByStudent, []any{"7"}); !strings.Contains(got, "attempt_id IN (SELECT id FROM golem15_quizzes_attempts WHERE user_id IN") {
|
||||||
|
t.Errorf("student SQL = %s", got)
|
||||||
|
}
|
||||||
|
if got := sqlOf(models.ScopeByQuiz, nil); strings.Contains(got, "question_id IN") {
|
||||||
|
t.Errorf("empty value SQL = %s, want no filter", got)
|
||||||
|
}
|
||||||
|
|
||||||
|
if name, err := lagoon.MorphType(nil, &models.Review{}); err != nil || name == "golem15_quizzes_attempt_answers" {
|
||||||
|
t.Errorf("Review morph type = %q, %v; it must differ from AttemptAnswer's table", name, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
32
classes/app.go
Normal file
32
classes/app.go
Normal file
@@ -0,0 +1,32 @@
|
|||||||
|
package classes
|
||||||
|
|
||||||
|
import (
|
||||||
|
"git.golem15.com/golem15/sm-quizzes-plugin/graders"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/backpack"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/conga"
|
||||||
|
"gorm.io/gorm"
|
||||||
|
)
|
||||||
|
|
||||||
|
// ForApp builds the service the application runs on db: the scoring and
|
||||||
|
// test grace from its config, the grader registry golem15.quizzes
|
||||||
|
// published at boot, its event bus and its job queue. Each part that is
|
||||||
|
// missing stays nil and the service works without it (no graders, no
|
||||||
|
// events, no jobs). A nil app gives a service with the default grace only.
|
||||||
|
func ForApp(app *backpack.App, db *gorm.DB) *Service {
|
||||||
|
if app == nil {
|
||||||
|
return &Service{DB: db, Grace: DefaultTestGrace}
|
||||||
|
}
|
||||||
|
s := &Service{
|
||||||
|
DB: db,
|
||||||
|
Scoring: ScoringConfigFrom(app.Config),
|
||||||
|
Grace: TestGraceFrom(app.Config),
|
||||||
|
Events: app.Events,
|
||||||
|
}
|
||||||
|
if reg, ok := app.Lookup[*graders.Registry](); ok {
|
||||||
|
s.Graders = reg
|
||||||
|
}
|
||||||
|
if m, err := conga.From(app); err == nil && m != nil {
|
||||||
|
s.Jobs = m
|
||||||
|
}
|
||||||
|
return s
|
||||||
|
}
|
||||||
477
classes/grading.go
Normal file
477
classes/grading.go
Normal file
@@ -0,0 +1,477 @@
|
|||||||
|
package classes
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
"unicode"
|
||||||
|
"unicode/utf8"
|
||||||
|
|
||||||
|
"git.golem15.com/golem15/sm-quizzes-plugin/events"
|
||||||
|
"git.golem15.com/golem15/sm-quizzes-plugin/graders"
|
||||||
|
"git.golem15.com/golem15/sm-quizzes-plugin/jobs"
|
||||||
|
"git.golem15.com/golem15/sm-quizzes-plugin/models"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/conga"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/lagoon"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/pact"
|
||||||
|
"gorm.io/gorm"
|
||||||
|
"gorm.io/gorm/clause"
|
||||||
|
)
|
||||||
|
|
||||||
|
// GradeMaxAttempts is how many times one open answer is handed to its
|
||||||
|
// grader before it is marked failed (D-17). The grading job's River attempt
|
||||||
|
// limit is the same number.
|
||||||
|
const GradeMaxAttempts = 3
|
||||||
|
|
||||||
|
// GradeTimeout is the deadline of one grading job attempt.
|
||||||
|
const GradeTimeout = 3 * time.Minute
|
||||||
|
|
||||||
|
// Text limits of what a grading writes.
|
||||||
|
const (
|
||||||
|
maxGraderFeedback = 2000
|
||||||
|
maxGradingError = 500
|
||||||
|
)
|
||||||
|
|
||||||
|
// errInvalidScore is a grader result ClampOpenPoints refuses; it counts as
|
||||||
|
// a failed attempt.
|
||||||
|
var errInvalidScore = errors.New("quizzes: grader returned an invalid score")
|
||||||
|
|
||||||
|
// Enqueuer inserts a background job, joining db's transaction when there is
|
||||||
|
// one. *conga.Manager implements it; tests record the jobs instead.
|
||||||
|
type Enqueuer interface {
|
||||||
|
Enqueue(ctx context.Context, db *gorm.DB, args pact.JobArgs, o conga.EnqueueOpts) error
|
||||||
|
}
|
||||||
|
|
||||||
|
// GraderFor returns the grader of a quiz: false for a nil registry or quiz,
|
||||||
|
// for manual and for a code no activated plugin registered (D-05). An
|
||||||
|
// answer without a grader waits for the owner.
|
||||||
|
func GraderFor(reg *graders.Registry, quiz *models.Quiz) (graders.Grader, bool) {
|
||||||
|
if quiz == nil {
|
||||||
|
return nil, false
|
||||||
|
}
|
||||||
|
return reg.Get(quiz.Grader)
|
||||||
|
}
|
||||||
|
|
||||||
|
// GradingStep is what a grading job does with an answer.
|
||||||
|
type GradingStep int
|
||||||
|
|
||||||
|
// Grading steps.
|
||||||
|
const (
|
||||||
|
// GradingSkip leaves the answer alone: it is no longer pending or it
|
||||||
|
// has a newer text than the job.
|
||||||
|
GradingSkip GradingStep = iota
|
||||||
|
// GradingRetry returns the grader's error so River retries the job.
|
||||||
|
GradingRetry
|
||||||
|
// GradingFail marks the answer failed after the last attempt.
|
||||||
|
GradingFail
|
||||||
|
// GradingStore stores the grader's score.
|
||||||
|
GradingStore
|
||||||
|
)
|
||||||
|
|
||||||
|
// NextGrading decides a grading job's step from the answer's status and
|
||||||
|
// grading_seq, the job's seq, the attempts used for this text (the current
|
||||||
|
// one included) and the grader's error. It is pure.
|
||||||
|
func NextGrading(status *string, rowSeq, jobSeq, attempts int, gradeErr error) GradingStep {
|
||||||
|
if status == nil || *status != models.GradingPending || rowSeq != jobSeq {
|
||||||
|
return GradingSkip
|
||||||
|
}
|
||||||
|
if gradeErr == nil {
|
||||||
|
return GradingStore
|
||||||
|
}
|
||||||
|
if attempts >= GradeMaxAttempts {
|
||||||
|
return GradingFail
|
||||||
|
}
|
||||||
|
return GradingRetry
|
||||||
|
}
|
||||||
|
|
||||||
|
// enqueueGrading hands a pending open answer to the quiz's grader as a
|
||||||
|
// background job inside tx, so the job exists only if the answer commits.
|
||||||
|
// Without a job queue or a registered grader (manual, unknown) it does
|
||||||
|
// nothing: the answer waits for the owner.
|
||||||
|
func (s *Service) enqueueGrading(ctx context.Context, tx *gorm.DB, answerID uint, seq int, attempt *models.Attempt) error {
|
||||||
|
if s.Jobs == nil || attempt == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if _, ok := GraderFor(s.Graders, attempt.Quiz); !ok {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return s.Jobs.Enqueue(ctx, tx, jobs.GradeAnswerArgs{AnswerID: answerID, Seq: seq}, conga.EnqueueOpts{
|
||||||
|
Queue: jobs.Queue,
|
||||||
|
MaxAttempts: GradeMaxAttempts,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// enqueuePending enqueues every pending open answer of a test attempt that
|
||||||
|
// is being closed, one job per answer (UD-2): answers given during a test
|
||||||
|
// are graded only once it ends.
|
||||||
|
func (s *Service) enqueuePending(ctx context.Context, tx *gorm.DB, attempt *models.Attempt) error {
|
||||||
|
if s.Jobs == nil || !IsTest(attempt.Quiz) {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if _, ok := GraderFor(s.Graders, attempt.Quiz); !ok {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
var rows []models.AttemptAnswer
|
||||||
|
if err := tx.WithContext(ctx).Where("attempt_id = ? AND grading_status = ?", attempt.ID, models.GradingPending).
|
||||||
|
Order("id ASC").Find(&rows).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
for _, r := range rows {
|
||||||
|
if err := s.enqueueGrading(ctx, tx, r.ID, r.GradingSeq, attempt); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// lockAttempt locks the attempt row FOR UPDATE, so a grade, a review and
|
||||||
|
// Finish of one attempt never interleave. A missing attempt is
|
||||||
|
// gorm.ErrRecordNotFound.
|
||||||
|
func lockAttempt(ctx context.Context, tx *gorm.DB, attemptID uint) (*models.Attempt, error) {
|
||||||
|
var a models.Attempt
|
||||||
|
err := tx.WithContext(ctx).Clauses(clause.Locking{Strength: "UPDATE", Table: clause.Table{Name: clause.CurrentTable}}).
|
||||||
|
Where("id = ?", attemptID).Take(&a).Error
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &a, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// recalcAttempt recomputes the score of a completed attempt from its
|
||||||
|
// answers after a grade or a review (Pitfall 2), under the attempt row
|
||||||
|
// lock. The percentage is taken against the attempt's stored max_points,
|
||||||
|
// so a later question edit does not move an old attempt's maximum. An open
|
||||||
|
// or missing attempt is left alone: close scores it.
|
||||||
|
func (s *Service) recalcAttempt(ctx context.Context, tx *gorm.DB, attemptID uint) error {
|
||||||
|
tx = tx.WithContext(ctx)
|
||||||
|
a, err := lockAttempt(ctx, tx, attemptID)
|
||||||
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if a.CompletedAt == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
var points []float64
|
||||||
|
if err := tx.Model(&models.AttemptAnswer{}).Where("attempt_id = ?", attemptID).Pluck("points", &points).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
score, percent := Totals(points, a.MaxPoints)
|
||||||
|
return tx.Model(&models.Attempt{}).Where("id = ?", attemptID).Updates(map[string]any{
|
||||||
|
"score_points": score,
|
||||||
|
"score_percent": percent,
|
||||||
|
"updated_at": s.now().UTC(),
|
||||||
|
}).Error
|
||||||
|
}
|
||||||
|
|
||||||
|
// fireAfterCommit fires event on s.Events once tx commits (never when it
|
||||||
|
// rolls back). A listener error is logged with the event name and never
|
||||||
|
// returned: the write it announces stays (D-14).
|
||||||
|
func fireAfterCommit[T any](ctx context.Context, s *Service, tx *gorm.DB, name string, event T) {
|
||||||
|
if s == nil || s.Events == nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
bus := s.Events
|
||||||
|
lagoon.AfterCommit(ctx, tx, func(ctx context.Context, _ *gorm.DB) {
|
||||||
|
if err := bus.Fire(ctx, event); err != nil {
|
||||||
|
pluginLog.Warn("quizzes: event listener failed", "event", name, "error", err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// GradeAnswer is the body of the grading job: it asks the quiz's grader to
|
||||||
|
// score one pending open answer (D-06). The grader runs with no transaction
|
||||||
|
// open and no row lock held, so a slow grader blocks no student.
|
||||||
|
//
|
||||||
|
// A missing answer, one that is no longer pending (graded, failed or
|
||||||
|
// reviewed by the owner), one whose grading_seq differs from seq (the
|
||||||
|
// student wrote a newer text) and one whose question is no longer open are
|
||||||
|
// left alone, as is an answer whose quiz has no registered grader. Each
|
||||||
|
// run counts an attempt for the current text first. A grader error, or a
|
||||||
|
// score ClampOpenPoints refuses, is returned for River to retry while
|
||||||
|
// fewer than GradeMaxAttempts attempts were made; the last one marks the
|
||||||
|
// answer failed with the error and returns nil (D-17), as does an error
|
||||||
|
// storing the score on the last attempt. A score is stored as graded with points clamped to
|
||||||
|
// 0..question points in steps of 0.5, the attempt's score is recalculated
|
||||||
|
// when it is completed, and AnswerGradedEvent fires after the commit.
|
||||||
|
func (s *Service) GradeAnswer(ctx context.Context, answerID uint, seq int) error {
|
||||||
|
db := s.db(ctx)
|
||||||
|
var row models.AttemptAnswer
|
||||||
|
if err := db.Where("id = ?", answerID).Take(&row).Error; err != nil {
|
||||||
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if NextGrading(row.GradingStatus, row.GradingSeq, seq, 0, nil) == GradingSkip {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
var question models.Question
|
||||||
|
if err := db.Where("id = ?", row.QuestionID).Take(&question).Error; err != nil {
|
||||||
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if question.Type != models.TypeOpen {
|
||||||
|
// The question stopped being open after the job was queued.
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
var attempt models.Attempt
|
||||||
|
if err := db.Preload("Quiz").Where("id = ?", row.AttemptID).Take(&attempt).Error; err != nil {
|
||||||
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
grader, ok := GraderFor(s.Graders, attempt.Quiz)
|
||||||
|
if !ok {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
var attempts int
|
||||||
|
if err := db.Raw(`UPDATE golem15_quizzes_attempt_answers SET grading_attempts = grading_attempts + 1
|
||||||
|
WHERE id = ? AND grading_status = ? AND grading_seq = ? RETURNING grading_attempts`,
|
||||||
|
answerID, models.GradingPending, seq).Scan(&attempts).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if attempts == 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
res, gradeErr := grader.Grade(ctx, graders.Input{
|
||||||
|
QuizID: attempt.QuizID,
|
||||||
|
QuestionID: question.ID,
|
||||||
|
AttemptID: attempt.ID,
|
||||||
|
AnswerID: row.ID,
|
||||||
|
UserID: attempt.UserID,
|
||||||
|
Question: question.Text,
|
||||||
|
ModelAnswer: deref(question.AnswerText),
|
||||||
|
Rubric: deref(question.Rubric),
|
||||||
|
Answer: deref(row.TextAnswer),
|
||||||
|
Points: question.Points,
|
||||||
|
})
|
||||||
|
var points float64
|
||||||
|
if gradeErr == nil {
|
||||||
|
p, ok := ClampOpenPoints(res.Points, question.Points)
|
||||||
|
if !ok {
|
||||||
|
gradeErr = errInvalidScore
|
||||||
|
}
|
||||||
|
points = p
|
||||||
|
}
|
||||||
|
pending := models.GradingPending
|
||||||
|
switch NextGrading(&pending, seq, seq, attempts, gradeErr) {
|
||||||
|
case GradingRetry:
|
||||||
|
return gradeErr
|
||||||
|
case GradingFail:
|
||||||
|
return s.failLast(ctx, row.ID, attempt.ID, seq, grader.Code(), gradeErr)
|
||||||
|
case GradingStore:
|
||||||
|
err := s.storeGrade(ctx, row.ID, seq, &attempt, question, grader.Code(), points, res.Feedback)
|
||||||
|
if err != nil && attempts >= GradeMaxAttempts {
|
||||||
|
// River will not run the job again: without this the answer
|
||||||
|
// would stay pending with no job (D-17).
|
||||||
|
return s.failLast(ctx, row.ID, attempt.ID, seq, grader.Code(), err)
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// failLastTimeout bounds the write that marks an answer failed after its
|
||||||
|
// last attempt.
|
||||||
|
const failLastTimeout = 30 * time.Second
|
||||||
|
|
||||||
|
// failLast marks an answer failed after its last grading attempt on a
|
||||||
|
// context detached from the job's, so a job that timed out or was
|
||||||
|
// cancelled still records the failure. If even that write fails, both
|
||||||
|
// errors are returned and the answer stays pending for a regrade.
|
||||||
|
func (s *Service) failLast(ctx context.Context, answerID, attemptID uint, seq int, code string, cause error) error {
|
||||||
|
fctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), failLastTimeout)
|
||||||
|
defer cancel()
|
||||||
|
if err := s.failGrading(fctx, answerID, attemptID, seq, code, cause); err != nil {
|
||||||
|
return errors.Join(cause, err)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// stillPending re-reads an answer inside the grading write's transaction
|
||||||
|
// (the attempt row is locked) and reports whether the job's seq still
|
||||||
|
// applies.
|
||||||
|
func stillPending(ctx context.Context, tx *gorm.DB, answerID uint, seq int) (bool, error) {
|
||||||
|
var cur models.AttemptAnswer
|
||||||
|
err := tx.WithContext(ctx).Where("id = ?", answerID).Take(&cur).Error
|
||||||
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||||
|
return false, nil
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return false, err
|
||||||
|
}
|
||||||
|
return NextGrading(cur.GradingStatus, cur.GradingSeq, seq, 0, nil) != GradingSkip, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// failGrading marks an answer failed after its last grading attempt.
|
||||||
|
func (s *Service) failGrading(ctx context.Context, answerID, attemptID uint, seq int, code string, gradeErr error) error {
|
||||||
|
return lagoon.Transaction(ctx, s.DB, func(ctx context.Context, tx *gorm.DB) error {
|
||||||
|
tx = tx.WithContext(ctx)
|
||||||
|
if _, err := lockAttempt(ctx, tx, attemptID); err != nil {
|
||||||
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if ok, err := stillPending(ctx, tx, answerID, seq); err != nil || !ok {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return tx.Model(&models.AttemptAnswer{}).Where("id = ?", answerID).Updates(map[string]any{
|
||||||
|
"grading_status": models.GradingFailed,
|
||||||
|
"grader": code,
|
||||||
|
"grading_error": cutRunes(gradeErr.Error(), maxGradingError),
|
||||||
|
"updated_at": s.now().UTC(),
|
||||||
|
}).Error
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// storeGrade stores a grader's clamped score as graded, recalculates a
|
||||||
|
// completed attempt and fires AnswerGradedEvent after the commit. Feedback
|
||||||
|
// that repeats the rubric (LeaksRubric) is dropped, for the student and the
|
||||||
|
// event alike, and noted for the owner in grading_error.
|
||||||
|
func (s *Service) storeGrade(ctx context.Context, answerID uint, seq int, attempt *models.Attempt, question models.Question, code string, points float64, feedback string) error {
|
||||||
|
return lagoon.Transaction(ctx, s.DB, func(ctx context.Context, tx *gorm.DB) error {
|
||||||
|
tx = tx.WithContext(ctx)
|
||||||
|
if _, err := lockAttempt(ctx, tx, attempt.ID); err != nil {
|
||||||
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if ok, err := stillPending(ctx, tx, answerID, seq); err != nil || !ok {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
feedback = cutRunes(strings.TrimSpace(feedback), maxGraderFeedback)
|
||||||
|
var note any
|
||||||
|
if LeaksRubric(feedback, deref(question.Rubric), question.Text, deref(question.AnswerText)) {
|
||||||
|
pluginLog.Warn("quizzes: grader feedback withheld, it repeats the rubric", "answer_id", answerID, "grader", code)
|
||||||
|
feedback, note = "", feedbackWithheldNote
|
||||||
|
}
|
||||||
|
var fb any
|
||||||
|
if feedback != "" {
|
||||||
|
fb = feedback
|
||||||
|
}
|
||||||
|
now := s.now().UTC()
|
||||||
|
if err := tx.Model(&models.AttemptAnswer{}).Where("id = ?", answerID).Updates(map[string]any{
|
||||||
|
"grading_status": models.GradingGraded,
|
||||||
|
"grader": code,
|
||||||
|
"grader_points": points,
|
||||||
|
"points": points,
|
||||||
|
"is_correct": OpenCorrect(points, question.Points),
|
||||||
|
"grader_feedback": fb,
|
||||||
|
"grading_error": note,
|
||||||
|
"graded_at": now,
|
||||||
|
"updated_at": now,
|
||||||
|
}).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := s.recalcAttempt(ctx, tx, attempt.ID); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
fireAfterCommit(ctx, s, tx, events.AnswerGradedEventName, &events.AnswerGradedEvent{
|
||||||
|
QuizID: attempt.QuizID,
|
||||||
|
QuestionID: question.ID,
|
||||||
|
AttemptID: attempt.ID,
|
||||||
|
AnswerID: answerID,
|
||||||
|
UserID: attempt.UserID,
|
||||||
|
Grader: code,
|
||||||
|
Points: points,
|
||||||
|
MaxPoints: question.Points,
|
||||||
|
Feedback: feedback,
|
||||||
|
})
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// feedbackWithheldNote is the owner's note on a graded answer whose
|
||||||
|
// feedback LeaksRubric dropped; students never see grading_error.
|
||||||
|
const feedbackWithheldNote = "feedback withheld: it repeated the rubric"
|
||||||
|
|
||||||
|
// Rubric leak detection: a run of rubricRunWords consecutive words shared
|
||||||
|
// by the feedback and the rubric counts as quoting it. A rubric shorter
|
||||||
|
// than that counts when the feedback holds it whole, unless it has fewer
|
||||||
|
// than minRubricWords words (too short to tell from ordinary wording).
|
||||||
|
const (
|
||||||
|
rubricRunWords = 6
|
||||||
|
minRubricWords = 4
|
||||||
|
)
|
||||||
|
|
||||||
|
// LeaksRubric reports whether a grader's feedback repeats the owner-only
|
||||||
|
// rubric (D-01): a run of words of the rubric, compared case-insensitively
|
||||||
|
// word by word, that does not also occur in one of the public texts (the
|
||||||
|
// question and the model answer, which the student is shown anyway). It is
|
||||||
|
// a deterministic guard behind the grader's prompt, so a model talked into
|
||||||
|
// listing the rubric never puts it in a student response verbatim.
|
||||||
|
func LeaksRubric(feedback, rubric string, public ...string) bool {
|
||||||
|
rw := words(rubric)
|
||||||
|
if len(rw) < minRubricWords {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
n := min(rubricRunWords, len(rw))
|
||||||
|
fw := words(feedback)
|
||||||
|
if len(fw) < n {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
skip := map[string]bool{}
|
||||||
|
for _, p := range public {
|
||||||
|
for g := range ngrams(words(p), n) {
|
||||||
|
skip[g] = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
secret := map[string]bool{}
|
||||||
|
for g := range ngrams(rw, n) {
|
||||||
|
if !skip[g] {
|
||||||
|
secret[g] = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(secret) == 0 {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
for g := range ngrams(fw, n) {
|
||||||
|
if secret[g] {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
// words splits s into lower-case words of letters and digits.
|
||||||
|
func words(s string) []string {
|
||||||
|
return strings.FieldsFunc(strings.ToLower(s), func(r rune) bool {
|
||||||
|
return !unicode.IsLetter(r) && !unicode.IsNumber(r)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// ngrams is the set of runs of n consecutive words of w, joined by spaces.
|
||||||
|
func ngrams(w []string, n int) map[string]bool {
|
||||||
|
out := map[string]bool{}
|
||||||
|
for i := 0; i+n <= len(w); i++ {
|
||||||
|
out[strings.Join(w[i:i+n], " ")] = true
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
// cutRunes keeps at most n runes of s.
|
||||||
|
func cutRunes(s string, n int) string {
|
||||||
|
if utf8.RuneCountInString(s) <= n {
|
||||||
|
return s
|
||||||
|
}
|
||||||
|
r := []rune(s)
|
||||||
|
return string(r[:n])
|
||||||
|
}
|
||||||
|
|
||||||
|
func deref(s *string) string {
|
||||||
|
if s == nil {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
return *s
|
||||||
|
}
|
||||||
105
classes/grading_test.go
Normal file
105
classes/grading_test.go
Normal file
@@ -0,0 +1,105 @@
|
|||||||
|
package classes_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"git.golem15.com/golem15/sm-quizzes-plugin/classes"
|
||||||
|
"git.golem15.com/golem15/sm-quizzes-plugin/graders"
|
||||||
|
"git.golem15.com/golem15/sm-quizzes-plugin/models"
|
||||||
|
)
|
||||||
|
|
||||||
|
type stubGrader struct{ code string }
|
||||||
|
|
||||||
|
func (g stubGrader) Code() string { return g.code }
|
||||||
|
func (g stubGrader) Label() string { return g.code }
|
||||||
|
func (g stubGrader) Grade(context.Context, graders.Input) (graders.Result, error) {
|
||||||
|
return graders.Result{}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestGraderFor(t *testing.T) {
|
||||||
|
reg := graders.NewRegistry()
|
||||||
|
if err := reg.Add("acme.x", stubGrader{"x"}); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if g, ok := classes.GraderFor(reg, &models.Quiz{Grader: "x"}); !ok || g.Code() != "x" {
|
||||||
|
t.Errorf("GraderFor(x) = %v, %v", g, ok)
|
||||||
|
}
|
||||||
|
for _, code := range []string{graders.Manual, "unknown", ""} {
|
||||||
|
if _, ok := classes.GraderFor(reg, &models.Quiz{Grader: code}); ok {
|
||||||
|
t.Errorf("GraderFor(%q) = true, want false", code)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if _, ok := classes.GraderFor(nil, &models.Quiz{Grader: "x"}); ok {
|
||||||
|
t.Error("GraderFor(nil registry) = true")
|
||||||
|
}
|
||||||
|
if _, ok := classes.GraderFor(reg, nil); ok {
|
||||||
|
t.Error("GraderFor(nil quiz) = true")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestNextGrading(t *testing.T) {
|
||||||
|
str := func(s string) *string { return &s }
|
||||||
|
boom := errors.New("boom")
|
||||||
|
cases := []struct {
|
||||||
|
name string
|
||||||
|
status *string
|
||||||
|
rowSeq int
|
||||||
|
jobSeq int
|
||||||
|
attempts int
|
||||||
|
err error
|
||||||
|
want classes.GradingStep
|
||||||
|
}{
|
||||||
|
{"nil status", nil, 1, 1, 1, nil, classes.GradingSkip},
|
||||||
|
{"graded", str(models.GradingGraded), 1, 1, 1, nil, classes.GradingSkip},
|
||||||
|
{"failed", str(models.GradingFailed), 1, 1, 1, nil, classes.GradingSkip},
|
||||||
|
{"reviewed", str(models.GradingReviewed), 1, 1, 1, nil, classes.GradingSkip},
|
||||||
|
{"stale seq", str(models.GradingPending), 2, 1, 1, nil, classes.GradingSkip},
|
||||||
|
{"stale seq with error", str(models.GradingPending), 2, 1, 3, boom, classes.GradingSkip},
|
||||||
|
{"store", str(models.GradingPending), 1, 1, 1, nil, classes.GradingStore},
|
||||||
|
{"retry 1", str(models.GradingPending), 1, 1, 1, boom, classes.GradingRetry},
|
||||||
|
{"retry 2", str(models.GradingPending), 1, 1, 2, boom, classes.GradingRetry},
|
||||||
|
{"fail at max", str(models.GradingPending), 1, 1, classes.GradeMaxAttempts, boom, classes.GradingFail},
|
||||||
|
{"fail past max", str(models.GradingPending), 1, 1, classes.GradeMaxAttempts + 1, boom, classes.GradingFail},
|
||||||
|
}
|
||||||
|
for _, tc := range cases {
|
||||||
|
if got := classes.NextGrading(tc.status, tc.rowSeq, tc.jobSeq, tc.attempts, tc.err); got != tc.want {
|
||||||
|
t.Errorf("%s: NextGrading = %v, want %v", tc.name, got, tc.want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if classes.GradeMaxAttempts != 3 {
|
||||||
|
t.Errorf("GradeMaxAttempts = %d, want 3", classes.GradeMaxAttempts)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLeaksRubric(t *testing.T) {
|
||||||
|
rubric := "Pełne punkty: wymienia trzy przyczyny upadku Republiki Weimarskiej, w tym kryzys gospodarczy z 1929 roku."
|
||||||
|
question := "Wyjaśnij, dlaczego upadła Republika Weimarska."
|
||||||
|
model := "Republika upadła przez kryzys gospodarczy z 1929 roku i słabość instytucji."
|
||||||
|
cases := []struct {
|
||||||
|
name string
|
||||||
|
feedback string
|
||||||
|
want bool
|
||||||
|
}{
|
||||||
|
{"own words", "Dobra odpowiedź, ale zabrakło trzeciej przyczyny i dat.", false},
|
||||||
|
{"verbatim run", "Oczekiwano, że odpowiedź WYMIENIA trzy przyczyny upadku Republiki Weimarskiej.", true},
|
||||||
|
{"punctuation and case ignored", "pełne punkty - wymienia, trzy; przyczyny upadku republiki!", true},
|
||||||
|
{"run also in the model answer", "Brakuje wzmianki o tym, że kryzys gospodarczy z 1929 roku i słabość instytucji zaszkodziły.", false},
|
||||||
|
{"empty feedback", "", false},
|
||||||
|
}
|
||||||
|
for _, tc := range cases {
|
||||||
|
if got := classes.LeaksRubric(tc.feedback, rubric, question, model); got != tc.want {
|
||||||
|
t.Errorf("%s: LeaksRubric = %v, want %v", tc.name, got, tc.want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if classes.LeaksRubric("Za mało szczegółów.", "", question) {
|
||||||
|
t.Error("an empty rubric leaks")
|
||||||
|
}
|
||||||
|
if classes.LeaksRubric("Wymień trzy przyczyny.", "trzy przyczyny", question) {
|
||||||
|
t.Error("a rubric under the minimum length leaks")
|
||||||
|
}
|
||||||
|
if !classes.LeaksRubric("Wymagano: podać daty, nazwiska i skutki. Zabrakło dat.", "Podać daty, nazwiska i skutki.") {
|
||||||
|
t.Error("a short rubric quoted whole does not leak")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -8,12 +8,16 @@ import (
|
|||||||
"slices"
|
"slices"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
|
"git.golem15.com/golem15/sm-quizzes-plugin/graders"
|
||||||
"git.golem15.com/golem15/sm-quizzes-plugin/models"
|
"git.golem15.com/golem15/sm-quizzes-plugin/models"
|
||||||
"git.golem15.com/golem15/summercms/modules/lagoon"
|
"git.golem15.com/golem15/summercms/modules/lagoon"
|
||||||
"gorm.io/gorm"
|
"gorm.io/gorm"
|
||||||
)
|
)
|
||||||
|
|
||||||
// ImportQuiz is the JSON document quizzes:import reads.
|
// ImportQuiz is the JSON document quizzes:import reads. Mode, Navigation,
|
||||||
|
// MaxAttempts and Grader keep the quiz's current value (the model default
|
||||||
|
// on create) when absent. Grader is any well-formed grader code: one that
|
||||||
|
// no activated plugin registers grades as manual (D-05).
|
||||||
type ImportQuiz struct {
|
type ImportQuiz struct {
|
||||||
Title string `json:"title"`
|
Title string `json:"title"`
|
||||||
Slug string `json:"slug"`
|
Slug string `json:"slug"`
|
||||||
@@ -24,10 +28,16 @@ type ImportQuiz struct {
|
|||||||
PassingScore *int `json:"passing_score"`
|
PassingScore *int `json:"passing_score"`
|
||||||
ShuffleQuestions *bool `json:"shuffle_questions"`
|
ShuffleQuestions *bool `json:"shuffle_questions"`
|
||||||
RoundSize *int `json:"round_size"`
|
RoundSize *int `json:"round_size"`
|
||||||
|
Mode *string `json:"mode"`
|
||||||
|
Navigation *string `json:"navigation"`
|
||||||
|
MaxAttempts *int `json:"max_attempts"`
|
||||||
|
Grader *string `json:"grader"`
|
||||||
Questions []ImportQuestion `json:"questions"`
|
Questions []ImportQuestion `json:"questions"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// ImportQuestion is one question of an ImportQuiz.
|
// ImportQuestion is one question of an ImportQuiz. Rubric (owner-only
|
||||||
|
// grading notes) and MaxLength (the longest answer in characters) belong
|
||||||
|
// to open questions; AnswerText is an open question's model answer.
|
||||||
type ImportQuestion struct {
|
type ImportQuestion struct {
|
||||||
Text string `json:"text"`
|
Text string `json:"text"`
|
||||||
Type string `json:"type"`
|
Type string `json:"type"`
|
||||||
@@ -35,6 +45,8 @@ type ImportQuestion struct {
|
|||||||
AnswerText *string `json:"answer_text"`
|
AnswerText *string `json:"answer_text"`
|
||||||
Explanation *string `json:"explanation"`
|
Explanation *string `json:"explanation"`
|
||||||
Points *int `json:"points"`
|
Points *int `json:"points"`
|
||||||
|
Rubric *string `json:"rubric"`
|
||||||
|
MaxLength *int `json:"max_length"`
|
||||||
Answers []ImportAnswer `json:"answers"`
|
Answers []ImportAnswer `json:"answers"`
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -79,44 +91,22 @@ func ParseImport(raw []byte) (*ImportQuiz, error) {
|
|||||||
if doc.TimeLimitSeconds != nil && *doc.TimeLimitSeconds < 1 {
|
if doc.TimeLimitSeconds != nil && *doc.TimeLimitSeconds < 1 {
|
||||||
problems = append(problems, "time_limit_seconds must be at least 1")
|
problems = append(problems, "time_limit_seconds must be at least 1")
|
||||||
}
|
}
|
||||||
|
if doc.Mode != nil && !slices.Contains(models.QuizModes, *doc.Mode) {
|
||||||
|
problems = append(problems, "mode must be one of "+strings.Join(models.QuizModes, ", "))
|
||||||
|
}
|
||||||
|
if doc.Navigation != nil && !slices.Contains(models.QuizNavigations, *doc.Navigation) {
|
||||||
|
problems = append(problems, "navigation must be one of "+strings.Join(models.QuizNavigations, ", "))
|
||||||
|
}
|
||||||
|
if doc.MaxAttempts != nil && *doc.MaxAttempts < 1 {
|
||||||
|
problems = append(problems, "max_attempts must be at least 1")
|
||||||
|
}
|
||||||
|
problems = append(problems, checkGraderFormat(doc.Grader)...)
|
||||||
if len(doc.Questions) == 0 {
|
if len(doc.Questions) == 0 {
|
||||||
problems = append(problems, "questions must not be empty")
|
problems = append(problems, "questions must not be empty")
|
||||||
}
|
}
|
||||||
for i, q := range doc.Questions {
|
for i := range doc.Questions {
|
||||||
at := fmt.Sprintf("questions[%d]", i)
|
doc.Questions[i].Rubric = nilIfBlank(deref(doc.Questions[i].Rubric), false)
|
||||||
if strings.TrimSpace(q.Text) == "" {
|
problems = append(problems, CheckQuestion(fmt.Sprintf("questions[%d]", i), doc.Questions[i])...)
|
||||||
problems = append(problems, at+".text is required")
|
|
||||||
}
|
|
||||||
if !slices.Contains(models.QuestionTypes, q.Type) {
|
|
||||||
problems = append(problems, fmt.Sprintf("%s.type must be one of %s", at, strings.Join(models.QuestionTypes, ", ")))
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
if q.Points != nil && *q.Points < 0 {
|
|
||||||
problems = append(problems, at+".points must not be negative")
|
|
||||||
}
|
|
||||||
correct := 0
|
|
||||||
for j, a := range q.Answers {
|
|
||||||
if strings.TrimSpace(a.Text) == "" {
|
|
||||||
problems = append(problems, fmt.Sprintf("%s.answers[%d].text is required", at, j))
|
|
||||||
}
|
|
||||||
if a.IsCorrect {
|
|
||||||
correct++
|
|
||||||
}
|
|
||||||
}
|
|
||||||
switch q.Type {
|
|
||||||
case models.TypeSingle:
|
|
||||||
if len(q.Answers) < 2 || correct != 1 {
|
|
||||||
problems = append(problems, at+": a single question needs at least two answers and exactly one correct")
|
|
||||||
}
|
|
||||||
case models.TypeMultiple:
|
|
||||||
if len(q.Answers) < 2 || correct < 1 {
|
|
||||||
problems = append(problems, at+": a multiple question needs at least two answers and one or more correct")
|
|
||||||
}
|
|
||||||
case models.TypeSelfCheck:
|
|
||||||
if len(q.Answers) > 0 {
|
|
||||||
problems = append(problems, at+": a self_check question has no answers; use answer_text")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
if len(problems) > 0 {
|
if len(problems) > 0 {
|
||||||
return nil, fmt.Errorf("invalid quiz: %s", strings.Join(problems, "; "))
|
return nil, fmt.Errorf("invalid quiz: %s", strings.Join(problems, "; "))
|
||||||
@@ -124,6 +114,76 @@ func ParseImport(raw []byte) (*ImportQuiz, error) {
|
|||||||
return &doc, nil
|
return &doc, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// CheckQuestion returns the problems of one question, each prefixed with
|
||||||
|
// at (such as "questions[0]"): the text is required, the type is one of
|
||||||
|
// models.QuestionTypes, points are not negative, answer texts are
|
||||||
|
// required, a single question has at least two answers and exactly one
|
||||||
|
// correct, a multiple question at least two and one or more correct, a
|
||||||
|
// self_check question none, and an open question none either (answer_text
|
||||||
|
// is its model answer). rubric and max_length (1..models.MaxMaxLength)
|
||||||
|
// apply to open questions only. The importer and the manage routes share
|
||||||
|
// it.
|
||||||
|
func CheckQuestion(at string, q ImportQuestion) []string {
|
||||||
|
var problems []string
|
||||||
|
if strings.TrimSpace(q.Text) == "" {
|
||||||
|
problems = append(problems, at+".text is required")
|
||||||
|
}
|
||||||
|
if !slices.Contains(models.QuestionTypes, q.Type) {
|
||||||
|
return append(problems, fmt.Sprintf("%s.type must be one of %s", at, strings.Join(models.QuestionTypes, ", ")))
|
||||||
|
}
|
||||||
|
if q.Points != nil && *q.Points < 0 {
|
||||||
|
problems = append(problems, at+".points must not be negative")
|
||||||
|
}
|
||||||
|
correct := 0
|
||||||
|
for j, a := range q.Answers {
|
||||||
|
if strings.TrimSpace(a.Text) == "" {
|
||||||
|
problems = append(problems, fmt.Sprintf("%s.answers[%d].text is required", at, j))
|
||||||
|
}
|
||||||
|
if a.IsCorrect {
|
||||||
|
correct++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
switch q.Type {
|
||||||
|
case models.TypeSingle:
|
||||||
|
if len(q.Answers) < 2 || correct != 1 {
|
||||||
|
problems = append(problems, at+": a single question needs at least two answers and exactly one correct")
|
||||||
|
}
|
||||||
|
case models.TypeMultiple:
|
||||||
|
if len(q.Answers) < 2 || correct < 1 {
|
||||||
|
problems = append(problems, at+": a multiple question needs at least two answers and one or more correct")
|
||||||
|
}
|
||||||
|
case models.TypeSelfCheck:
|
||||||
|
if len(q.Answers) > 0 {
|
||||||
|
problems = append(problems, at+": a self_check question has no answers; use answer_text")
|
||||||
|
}
|
||||||
|
case models.TypeOpen:
|
||||||
|
if len(q.Answers) > 0 {
|
||||||
|
problems = append(problems, at+": an open question has no answers; put the model answer in answer_text")
|
||||||
|
}
|
||||||
|
if q.MaxLength != nil && (*q.MaxLength < 1 || *q.MaxLength > models.MaxMaxLength) {
|
||||||
|
problems = append(problems, fmt.Sprintf("%s.max_length must be between 1 and %d", at, models.MaxMaxLength))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if q.Type != models.TypeOpen {
|
||||||
|
if q.Rubric != nil && strings.TrimSpace(*q.Rubric) != "" {
|
||||||
|
problems = append(problems, at+".rubric applies to open questions only")
|
||||||
|
}
|
||||||
|
if q.MaxLength != nil {
|
||||||
|
problems = append(problems, at+".max_length applies to open questions only")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return problems
|
||||||
|
}
|
||||||
|
|
||||||
|
// checkGraderFormat is the problem of a sent grader code that is not
|
||||||
|
// well-formed. Whether a plugin registers it is CheckGrader's question.
|
||||||
|
func checkGraderFormat(code *string) []string {
|
||||||
|
if code == nil || graders.ValidCode(*code) {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return []string{"grader must be lowercase letters, digits and underscores"}
|
||||||
|
}
|
||||||
|
|
||||||
// ImportResult reports what an import wrote.
|
// ImportResult reports what an import wrote.
|
||||||
type ImportResult struct {
|
type ImportResult struct {
|
||||||
Quiz models.Quiz
|
Quiz models.Quiz
|
||||||
@@ -164,11 +224,25 @@ func Import(ctx context.Context, db *gorm.DB, doc *ImportQuiz, replace bool) (*I
|
|||||||
if doc.ShuffleQuestions != nil {
|
if doc.ShuffleQuestions != nil {
|
||||||
quiz.ShuffleQuestions = *doc.ShuffleQuestions
|
quiz.ShuffleQuestions = *doc.ShuffleQuestions
|
||||||
}
|
}
|
||||||
|
if doc.Mode != nil {
|
||||||
|
quiz.Mode = *doc.Mode
|
||||||
|
}
|
||||||
|
if doc.Navigation != nil {
|
||||||
|
quiz.Navigation = *doc.Navigation
|
||||||
|
}
|
||||||
|
if doc.MaxAttempts != nil {
|
||||||
|
limit := *doc.MaxAttempts
|
||||||
|
quiz.MaxAttempts = &limit
|
||||||
|
}
|
||||||
|
if doc.Grader != nil {
|
||||||
|
quiz.Grader = *doc.Grader
|
||||||
|
}
|
||||||
if err := tx.Save(&quiz).Error; err != nil {
|
if err := tx.Save(&quiz).Error; err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
if !res.Created {
|
if !res.Created {
|
||||||
// The foreign keys cascade to answers and attempt answers.
|
// The foreign keys cascade to answers and attempt answers,
|
||||||
|
// with the grades and reviews of open answers.
|
||||||
if err := tx.Where("quiz_id = ?", quiz.ID).Delete(&models.Question{}).Error; err != nil {
|
if err := tx.Where("quiz_id = ?", quiz.ID).Delete(&models.Question{}).Error; err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -181,6 +255,7 @@ func Import(ctx context.Context, db *gorm.DB, doc *ImportQuiz, replace bool) (*I
|
|||||||
q := models.Question{
|
q := models.Question{
|
||||||
QuizID: quiz.ID, Text: strings.TrimSpace(in.Text), Type: in.Type, Category: trimmed(in.Category),
|
QuizID: quiz.ID, Text: strings.TrimSpace(in.Text), Type: in.Type, Category: trimmed(in.Category),
|
||||||
AnswerText: in.AnswerText, Explanation: in.Explanation, SortOrder: i + 1, Points: points,
|
AnswerText: in.AnswerText, Explanation: in.Explanation, SortOrder: i + 1, Points: points,
|
||||||
|
Rubric: in.Rubric, MaxLength: in.MaxLength,
|
||||||
}
|
}
|
||||||
if err := tx.Create(&q).Error; err != nil {
|
if err := tx.Create(&q).Error; err != nil {
|
||||||
return err
|
return err
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
package classes_test
|
package classes_test
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"encoding/json"
|
||||||
"os"
|
"os"
|
||||||
"strings"
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
@@ -55,3 +56,99 @@ func TestParseImportRejects(t *testing.T) {
|
|||||||
t.Errorf("explicit slug = %v %v, want moj-slug", doc, err)
|
t.Errorf("explicit slug = %v %v, want moj-slug", doc, err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestParseImportTestMode(t *testing.T) {
|
||||||
|
doc, err := classes.ParseImport([]byte(`{"title":"T","mode":"test","navigation":"one_way","max_attempts":2,"questions":[{"text":"Q","type":"self_check"}]}`))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("ParseImport: %v", err)
|
||||||
|
}
|
||||||
|
if doc.Mode == nil || *doc.Mode != "test" || doc.Navigation == nil || *doc.Navigation != "one_way" || doc.MaxAttempts == nil || *doc.MaxAttempts != 2 {
|
||||||
|
t.Errorf("doc = %+v", doc)
|
||||||
|
}
|
||||||
|
for raw, want := range map[string]string{
|
||||||
|
`{"title":"T","mode":"exam","questions":[{"text":"Q","type":"self_check"}]}`: "mode must be one of learning, test",
|
||||||
|
`{"title":"T","navigation":"back","questions":[{"text":"Q","type":"self_check"}]}`: "navigation must be one of free, one_way",
|
||||||
|
`{"title":"T","max_attempts":0,"questions":[{"text":"Q","type":"self_check"}]}`: "max_attempts must be at least 1",
|
||||||
|
} {
|
||||||
|
if _, err := classes.ParseImport([]byte(raw)); err == nil || !strings.Contains(err.Error(), want) {
|
||||||
|
t.Errorf("ParseImport(%s) = %v, want %q", raw, err, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
raw, err := os.ReadFile("../testdata/quiz.json")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
doc, err = classes.ParseImport(raw)
|
||||||
|
if err != nil || doc.Mode != nil || doc.Navigation != nil || doc.MaxAttempts != nil {
|
||||||
|
t.Errorf("sample = %+v %v, want no test-mode keys", doc, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestCheckQuestion: the per-question rules ParseImport applies, shared
|
||||||
|
// with the manage routes; ParseImport reports exactly these problems.
|
||||||
|
func TestCheckQuestion(t *testing.T) {
|
||||||
|
neg := -1
|
||||||
|
zero, five, tooLong := 0, 500, 20001
|
||||||
|
rubric := "Mentions sovereignty."
|
||||||
|
for name, tc := range map[string]struct {
|
||||||
|
q classes.ImportQuestion
|
||||||
|
want []string
|
||||||
|
}{
|
||||||
|
"no text": {classes.ImportQuestion{Type: "self_check"}, []string{"questions[0].text is required"}},
|
||||||
|
"bad type": {classes.ImportQuestion{Text: "Q", Type: "essay"}, []string{"questions[0].type must be one of single, multiple, self_check, open"}},
|
||||||
|
"negative points": {classes.ImportQuestion{Text: "Q", Type: "self_check", Points: &neg}, []string{"questions[0].points must not be negative"}},
|
||||||
|
"single two right": {classes.ImportQuestion{Text: "Q", Type: "single", Answers: []classes.ImportAnswer{{Text: "a", IsCorrect: true}, {Text: "b", IsCorrect: true}}}, []string{"questions[0]: a single question needs at least two answers and exactly one correct"}},
|
||||||
|
"multiple one item": {classes.ImportQuestion{Text: "Q", Type: "multiple", Answers: []classes.ImportAnswer{{Text: "a", IsCorrect: true}}}, []string{"questions[0]: a multiple question needs at least two answers and one or more correct"}},
|
||||||
|
"self_check answer": {classes.ImportQuestion{Text: "Q", Type: "self_check", Answers: []classes.ImportAnswer{{Text: "a"}}}, []string{"questions[0]: a self_check question has no answers; use answer_text"}},
|
||||||
|
"blank answer": {classes.ImportQuestion{Text: "Q", Type: "single", Answers: []classes.ImportAnswer{{Text: " ", IsCorrect: true}, {Text: "b"}}}, []string{"questions[0].answers[0].text is required"}},
|
||||||
|
"valid single": {classes.ImportQuestion{Text: "Q", Type: "single", Answers: []classes.ImportAnswer{{Text: "a", IsCorrect: true}, {Text: "b"}}}, nil},
|
||||||
|
"valid open": {classes.ImportQuestion{Text: "Q", Type: "open", AnswerText: str("Model"), Rubric: &rubric, MaxLength: &five}, nil},
|
||||||
|
"open with answer": {classes.ImportQuestion{Text: "Q", Type: "open", Answers: []classes.ImportAnswer{{Text: "a"}}}, []string{"questions[0]: an open question has no answers; put the model answer in answer_text"}},
|
||||||
|
"open length 0": {classes.ImportQuestion{Text: "Q", Type: "open", MaxLength: &zero}, []string{"questions[0].max_length must be between 1 and 20000"}},
|
||||||
|
"open length 20001": {classes.ImportQuestion{Text: "Q", Type: "open", MaxLength: &tooLong}, []string{"questions[0].max_length must be between 1 and 20000"}},
|
||||||
|
"single rubric": {classes.ImportQuestion{Text: "Q", Type: "single", Rubric: &rubric, Answers: []classes.ImportAnswer{{Text: "a", IsCorrect: true}, {Text: "b"}}}, []string{"questions[0].rubric applies to open questions only"}},
|
||||||
|
"single max_length": {classes.ImportQuestion{Text: "Q", Type: "single", MaxLength: &five, Answers: []classes.ImportAnswer{{Text: "a", IsCorrect: true}, {Text: "b"}}}, []string{"questions[0].max_length applies to open questions only"}},
|
||||||
|
} {
|
||||||
|
got := classes.CheckQuestion("questions[0]", tc.q)
|
||||||
|
if strings.Join(got, "; ") != strings.Join(tc.want, "; ") {
|
||||||
|
t.Errorf("%s: %q, want %q", name, got, tc.want)
|
||||||
|
}
|
||||||
|
doc, _ := json.Marshal(map[string]any{"title": "T", "questions": []classes.ImportQuestion{tc.q}})
|
||||||
|
_, err := classes.ParseImport(doc)
|
||||||
|
switch {
|
||||||
|
case tc.want == nil && err != nil:
|
||||||
|
t.Errorf("%s: ParseImport: %v", name, err)
|
||||||
|
case tc.want != nil && (err == nil || err.Error() != "invalid quiz: "+strings.Join(tc.want, "; ")):
|
||||||
|
t.Errorf("%s: ParseImport = %v, want the same problems", name, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestParseImportOpen(t *testing.T) {
|
||||||
|
for _, grader := range []string{"ai", "manual"} {
|
||||||
|
raw := `{"title":"O","grader":"` + grader + `","questions":[{"text":"Q","type":"open","answer_text":"M","rubric":"R","max_length":300}]}`
|
||||||
|
doc, err := classes.ParseImport([]byte(raw))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("grader %s: %v", grader, err)
|
||||||
|
}
|
||||||
|
q := doc.Questions[0]
|
||||||
|
if doc.Grader == nil || *doc.Grader != grader || q.Rubric == nil || *q.Rubric != "R" || q.MaxLength == nil || *q.MaxLength != 300 {
|
||||||
|
t.Errorf("grader %s: doc = %+v, question = %+v", grader, doc, q)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if _, err := classes.ParseImport([]byte(`{"title":"O","grader":"Bad Grader","questions":[{"text":"Q","type":"open"}]}`)); err == nil ||
|
||||||
|
!strings.Contains(err.Error(), "grader must be lowercase letters, digits and underscores") {
|
||||||
|
t.Errorf("bad grader = %v", err)
|
||||||
|
}
|
||||||
|
doc, err := classes.ParseImport([]byte(`{"title":"O","questions":[{"text":"Q","type":"open","rubric":" "}]}`))
|
||||||
|
if err != nil || doc.Questions[0].Rubric != nil {
|
||||||
|
t.Errorf("blank rubric = %+v %v, want it dropped", doc, err)
|
||||||
|
}
|
||||||
|
raw, err := os.ReadFile("../testdata/quiz.json")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if doc, err := classes.ParseImport(raw); err != nil || doc.Grader != nil {
|
||||||
|
t.Errorf("sample = %+v %v, want no grader", doc, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
7
classes/logger.go
Normal file
7
classes/logger.go
Normal file
@@ -0,0 +1,7 @@
|
|||||||
|
package classes
|
||||||
|
|
||||||
|
import "git.golem15.com/golem15/summercms/modules/diary"
|
||||||
|
|
||||||
|
// pluginLog is the plugin's logger: its records carry component=quizzes, so
|
||||||
|
// config/log.yaml can raise or lower them (log.components.quizzes).
|
||||||
|
var pluginLog = diary.For("quizzes")
|
||||||
975
classes/manage.go
Normal file
975
classes/manage.go
Normal file
@@ -0,0 +1,975 @@
|
|||||||
|
package classes
|
||||||
|
|
||||||
|
// Owner-side management behind the manage routes under /api/v1/quizzes,
|
||||||
|
// which the MCP quiz tools bind. There is no owner column: a user whose
|
||||||
|
// groups grant golem15.quizzes.access_quizzes manages every quiz, as in the
|
||||||
|
// admin (A7). Quizzes are addressed by slug.
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"math"
|
||||||
|
"slices"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
"unicode/utf8"
|
||||||
|
|
||||||
|
"git.golem15.com/golem15/sm-quizzes-plugin/models"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/lagoon"
|
||||||
|
"gorm.io/gorm"
|
||||||
|
"gorm.io/gorm/clause"
|
||||||
|
)
|
||||||
|
|
||||||
|
// ErrQuestionNotFound is a question id that is not a question of the quiz.
|
||||||
|
// It is an ErrNotFound.
|
||||||
|
var ErrQuestionNotFound = fmt.Errorf("%w: question", ErrNotFound)
|
||||||
|
|
||||||
|
// ValidationError is manage input that breaks a rule (a 422). Problems
|
||||||
|
// read like the importer's: "title is required".
|
||||||
|
type ValidationError struct {
|
||||||
|
Problems []string
|
||||||
|
}
|
||||||
|
|
||||||
|
func (e *ValidationError) Error() string { return "invalid quiz: " + strings.Join(e.Problems, "; ") }
|
||||||
|
|
||||||
|
// invalid wraps problems in a ValidationError, or returns nil for none.
|
||||||
|
func invalid(problems []string) error {
|
||||||
|
if len(problems) == 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return &ValidationError{Problems: problems}
|
||||||
|
}
|
||||||
|
|
||||||
|
// QuizInput is the quiz fields of a create or a partial update; nil means
|
||||||
|
// not sent. There is no IsPublished: a created quiz starts unpublished and
|
||||||
|
// only SetPublished changes it.
|
||||||
|
type QuizInput struct {
|
||||||
|
Title *string `json:"title"`
|
||||||
|
Slug *string `json:"slug"`
|
||||||
|
Description *string `json:"description"`
|
||||||
|
Context *string `json:"context"`
|
||||||
|
Mode *string `json:"mode"`
|
||||||
|
Navigation *string `json:"navigation"`
|
||||||
|
MaxAttempts *int `json:"max_attempts"`
|
||||||
|
TimeLimitSeconds *int `json:"time_limit_seconds"`
|
||||||
|
PassingScore *int `json:"passing_score"`
|
||||||
|
RoundSize *int `json:"round_size"`
|
||||||
|
ShuffleQuestions *bool `json:"shuffle_questions"`
|
||||||
|
Grader *string `json:"grader"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// CheckQuizInput returns the rule problems of in. On create the title is
|
||||||
|
// required and max_attempts, time_limit_seconds and round_size are at least
|
||||||
|
// 1; on update 0 is allowed for them, as it clears the value.
|
||||||
|
func CheckQuizInput(in QuizInput, create bool) []string {
|
||||||
|
var problems []string
|
||||||
|
switch {
|
||||||
|
case in.Title == nil:
|
||||||
|
if create {
|
||||||
|
problems = append(problems, "title is required")
|
||||||
|
}
|
||||||
|
case strings.TrimSpace(*in.Title) == "":
|
||||||
|
problems = append(problems, "title is required")
|
||||||
|
case utf8.RuneCountInString(strings.TrimSpace(*in.Title)) > 255:
|
||||||
|
problems = append(problems, "title must be at most 255 characters")
|
||||||
|
}
|
||||||
|
if create && in.Slug != nil && strings.TrimSpace(*in.Slug) != "" && models.Slugify(*in.Slug) == "" {
|
||||||
|
problems = append(problems, "slug is empty after normalising it")
|
||||||
|
}
|
||||||
|
if create && (in.Slug == nil || strings.TrimSpace(*in.Slug) == "") && in.Title != nil &&
|
||||||
|
strings.TrimSpace(*in.Title) != "" && models.Slugify(*in.Title) == "" {
|
||||||
|
problems = append(problems, "slug is empty after normalising the title")
|
||||||
|
}
|
||||||
|
if in.Context != nil && utf8.RuneCountInString(strings.TrimSpace(*in.Context)) > 255 {
|
||||||
|
problems = append(problems, "context must be at most 255 characters")
|
||||||
|
}
|
||||||
|
if in.Mode != nil && !slices.Contains(models.QuizModes, *in.Mode) {
|
||||||
|
problems = append(problems, "mode must be one of "+strings.Join(models.QuizModes, ", "))
|
||||||
|
}
|
||||||
|
if in.Navigation != nil && !slices.Contains(models.QuizNavigations, *in.Navigation) {
|
||||||
|
problems = append(problems, "navigation must be one of "+strings.Join(models.QuizNavigations, ", "))
|
||||||
|
}
|
||||||
|
if in.PassingScore != nil && (*in.PassingScore < 0 || *in.PassingScore > 100) {
|
||||||
|
problems = append(problems, "passing_score must be between 0 and 100")
|
||||||
|
}
|
||||||
|
problems = append(problems, checkGraderFormat(in.Grader)...)
|
||||||
|
least, word := 1, "at least 1"
|
||||||
|
if !create {
|
||||||
|
least, word = 0, "0 (clears it) or more"
|
||||||
|
}
|
||||||
|
for _, f := range []struct {
|
||||||
|
name string
|
||||||
|
v *int
|
||||||
|
}{{"max_attempts", in.MaxAttempts}, {"time_limit_seconds", in.TimeLimitSeconds}, {"round_size", in.RoundSize}} {
|
||||||
|
if f.v != nil && *f.v < least {
|
||||||
|
problems = append(problems, f.name+" must be "+word)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return problems
|
||||||
|
}
|
||||||
|
|
||||||
|
// CheckGrader is the problem of a sent grader code that is not one of
|
||||||
|
// known, the codes of the registry (manual first), naming the valid codes.
|
||||||
|
// A nil code is fine.
|
||||||
|
func CheckGrader(code *string, known []string) []string {
|
||||||
|
if code == nil || slices.Contains(known, *code) {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return []string{"grader must be one of " + strings.Join(known, ", ")}
|
||||||
|
}
|
||||||
|
|
||||||
|
// positive is v, or nil when v is nil or not positive (0 clears).
|
||||||
|
func positive(v *int) *int {
|
||||||
|
if v == nil || *v <= 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
n := *v
|
||||||
|
return &n
|
||||||
|
}
|
||||||
|
|
||||||
|
// CreateQuiz creates an unpublished quiz from in. The slug comes from Slug,
|
||||||
|
// or from the title when Slug is empty; a taken slug is ErrQuizExists. The
|
||||||
|
// passing score defaults to 50, mode and navigation to learning / free.
|
||||||
|
func CreateQuiz(ctx context.Context, db *gorm.DB, in QuizInput) (*models.Quiz, error) {
|
||||||
|
if err := invalid(CheckQuizInput(in, true)); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
quiz := models.Quiz{Title: strings.TrimSpace(*in.Title), PassingScore: 50}
|
||||||
|
if in.Slug != nil && strings.TrimSpace(*in.Slug) != "" {
|
||||||
|
quiz.Slug = models.Slugify(*in.Slug)
|
||||||
|
} else {
|
||||||
|
quiz.Slug = models.Slugify(quiz.Title)
|
||||||
|
}
|
||||||
|
applyQuizInput(&quiz, in)
|
||||||
|
err := lagoon.Transaction(ctx, db, func(ctx context.Context, tx *gorm.DB) error {
|
||||||
|
tx = tx.WithContext(ctx)
|
||||||
|
var n int64
|
||||||
|
if err := tx.Model(&models.Quiz{}).Where("slug = ?", quiz.Slug).Count(&n).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if n > 0 {
|
||||||
|
return ErrQuizExists
|
||||||
|
}
|
||||||
|
return tx.Create(&quiz).Error
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &quiz, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// applyQuizInput sets the sent fields of in on quiz, except the slug and
|
||||||
|
// the title's presence check. An empty description or context is NULL, a
|
||||||
|
// 0 limit is NULL.
|
||||||
|
func applyQuizInput(quiz *models.Quiz, in QuizInput) {
|
||||||
|
if in.Title != nil {
|
||||||
|
quiz.Title = strings.TrimSpace(*in.Title)
|
||||||
|
}
|
||||||
|
if in.Description != nil {
|
||||||
|
quiz.Description = nilIfBlank(*in.Description, false)
|
||||||
|
}
|
||||||
|
if in.Context != nil {
|
||||||
|
quiz.Context = nilIfBlank(*in.Context, true)
|
||||||
|
}
|
||||||
|
if in.Mode != nil {
|
||||||
|
quiz.Mode = *in.Mode
|
||||||
|
}
|
||||||
|
if in.Navigation != nil {
|
||||||
|
quiz.Navigation = *in.Navigation
|
||||||
|
}
|
||||||
|
if in.MaxAttempts != nil {
|
||||||
|
quiz.MaxAttempts = positive(in.MaxAttempts)
|
||||||
|
}
|
||||||
|
if in.TimeLimitSeconds != nil {
|
||||||
|
quiz.TimeLimitSeconds = positive(in.TimeLimitSeconds)
|
||||||
|
}
|
||||||
|
if in.RoundSize != nil {
|
||||||
|
quiz.RoundSize = positive(in.RoundSize)
|
||||||
|
}
|
||||||
|
if in.PassingScore != nil {
|
||||||
|
quiz.PassingScore = *in.PassingScore
|
||||||
|
}
|
||||||
|
if in.ShuffleQuestions != nil {
|
||||||
|
quiz.ShuffleQuestions = *in.ShuffleQuestions
|
||||||
|
}
|
||||||
|
if in.Grader != nil {
|
||||||
|
quiz.Grader = *in.Grader
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// nilIfBlank is nil for a blank s, else s (trimmed when trim is set).
|
||||||
|
func nilIfBlank(s string, trim bool) *string {
|
||||||
|
if strings.TrimSpace(s) == "" {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if trim {
|
||||||
|
s = strings.TrimSpace(s)
|
||||||
|
}
|
||||||
|
return &s
|
||||||
|
}
|
||||||
|
|
||||||
|
// UpdateQuiz changes only the sent fields of the quiz with this slug: 0
|
||||||
|
// clears max_attempts, time_limit_seconds and round_size, an empty string
|
||||||
|
// clears description and context. Slug is ignored, and it cannot publish
|
||||||
|
// (A10). A missing slug is ErrNotFound.
|
||||||
|
func UpdateQuiz(ctx context.Context, db *gorm.DB, slug string, in QuizInput) (*models.Quiz, error) {
|
||||||
|
if err := invalid(CheckQuizInput(in, false)); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
var quiz models.Quiz
|
||||||
|
err := lagoon.Transaction(ctx, db, func(ctx context.Context, tx *gorm.DB) error {
|
||||||
|
tx = tx.WithContext(ctx)
|
||||||
|
if err := lockedQuiz(tx, slug, &quiz); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
applyQuizInput(&quiz, in)
|
||||||
|
return tx.Omit(clause.Associations).Save(&quiz).Error
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &quiz, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// lockedQuiz loads the quiz with this slug FOR UPDATE, or ErrNotFound.
|
||||||
|
func lockedQuiz(tx *gorm.DB, slug string, quiz *models.Quiz) error {
|
||||||
|
err := tx.Clauses(clause.Locking{Strength: "UPDATE", Table: clause.Table{Name: clause.CurrentTable}}).
|
||||||
|
Where("slug = ?", slug).Take(quiz).Error
|
||||||
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||||
|
return ErrNotFound
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// ValidateDeleteConfirm refuses a delete whose confirm value is not the
|
||||||
|
// quiz slug, so a stray DELETE cannot remove a quiz by accident.
|
||||||
|
func ValidateDeleteConfirm(slug, confirm string) error {
|
||||||
|
if strings.TrimSpace(confirm) == "" || confirm != slug {
|
||||||
|
return &ValidationError{Problems: []string{"confirm must repeat the quiz slug"}}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// DeletedQuiz is the answer of a quiz delete: what was removed.
|
||||||
|
type DeletedQuiz struct {
|
||||||
|
ID uint
|
||||||
|
Slug string
|
||||||
|
Title string
|
||||||
|
Questions int64
|
||||||
|
Attempts int64
|
||||||
|
}
|
||||||
|
|
||||||
|
// DeleteQuiz removes the quiz with this slug for good. The foreign keys
|
||||||
|
// cascade to its questions, answers, attempts and attempt answers; the
|
||||||
|
// counts are taken first. A missing slug is ErrNotFound.
|
||||||
|
func DeleteQuiz(ctx context.Context, db *gorm.DB, slug string) (*DeletedQuiz, error) {
|
||||||
|
var out DeletedQuiz
|
||||||
|
err := lagoon.Transaction(ctx, db, func(ctx context.Context, tx *gorm.DB) error {
|
||||||
|
tx = tx.WithContext(ctx)
|
||||||
|
var quiz models.Quiz
|
||||||
|
if err := lockedQuiz(tx, slug, &quiz); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
out = DeletedQuiz{ID: quiz.ID, Slug: quiz.Slug, Title: quiz.Title}
|
||||||
|
if err := tx.Model(&models.Question{}).Where("quiz_id = ?", quiz.ID).Count(&out.Questions).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := tx.Model(&models.Attempt{}).Where("quiz_id = ?", quiz.ID).Count(&out.Attempts).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return tx.Where("id = ?", quiz.ID).Delete(&models.Quiz{}).Error
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &out, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// SetPublished publishes or unpublishes the quiz with this slug; doing it
|
||||||
|
// twice is the same as once. A missing slug is ErrNotFound.
|
||||||
|
func SetPublished(ctx context.Context, db *gorm.DB, slug string, published bool) (*models.Quiz, error) {
|
||||||
|
var quiz models.Quiz
|
||||||
|
err := lagoon.Transaction(ctx, db, func(ctx context.Context, tx *gorm.DB) error {
|
||||||
|
tx = tx.WithContext(ctx)
|
||||||
|
if err := lockedQuiz(tx, slug, &quiz); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if quiz.IsPublished == published {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
quiz.IsPublished = published
|
||||||
|
return tx.Model(&models.Quiz{}).Where("id = ?", quiz.ID).
|
||||||
|
Updates(map[string]any{"is_published": published, "updated_at": time.Now().UTC()}).Error
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &quiz, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ManagedRow counts the questions and completed attempts of one quiz, for
|
||||||
|
// the answers of the quiz writes.
|
||||||
|
func ManagedRow(ctx context.Context, db *gorm.DB, quiz models.Quiz) (ManagedQuizRow, error) {
|
||||||
|
row := ManagedQuizRow{Quiz: quiz}
|
||||||
|
var n int64
|
||||||
|
if err := db.WithContext(ctx).Model(&models.Question{}).Where("quiz_id = ?", quiz.ID).Count(&n).Error; err != nil {
|
||||||
|
return row, err
|
||||||
|
}
|
||||||
|
row.QuestionCount = int(n)
|
||||||
|
attempts, err := CompletedAttemptCount(ctx, db, quiz.ID)
|
||||||
|
row.AttemptsCount = attempts
|
||||||
|
return row, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// ManagedQuizRow is one quiz of the owner list with its question count and
|
||||||
|
// the number of completed attempts (of every user).
|
||||||
|
type ManagedQuizRow struct {
|
||||||
|
Quiz models.Quiz
|
||||||
|
QuestionCount int
|
||||||
|
AttemptsCount int
|
||||||
|
}
|
||||||
|
|
||||||
|
// ListManagedQuizzes returns every quiz, published or not, optionally only
|
||||||
|
// those whose context equals quizContext, ordered by context (quizzes
|
||||||
|
// without one last), title and id.
|
||||||
|
func ListManagedQuizzes(ctx context.Context, db *gorm.DB, quizContext string) ([]ManagedQuizRow, error) {
|
||||||
|
db = db.WithContext(ctx)
|
||||||
|
q := db.Model(&models.Quiz{})
|
||||||
|
if quizContext != "" {
|
||||||
|
q = q.Where("context = ?", quizContext)
|
||||||
|
}
|
||||||
|
var quizzes []models.Quiz
|
||||||
|
if err := q.Order("context ASC NULLS LAST, title ASC, id ASC").Find(&quizzes).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
out := make([]ManagedQuizRow, 0, len(quizzes))
|
||||||
|
if len(quizzes) == 0 {
|
||||||
|
return out, nil
|
||||||
|
}
|
||||||
|
ids := make([]uint, len(quizzes))
|
||||||
|
for i, quiz := range quizzes {
|
||||||
|
ids[i] = quiz.ID
|
||||||
|
}
|
||||||
|
type countRow struct {
|
||||||
|
QuizID uint
|
||||||
|
N int
|
||||||
|
}
|
||||||
|
var questions, attempts []countRow
|
||||||
|
if err := db.Model(&models.Question{}).Select("quiz_id, COUNT(*) AS n").
|
||||||
|
Where("quiz_id IN ?", ids).Group("quiz_id").Scan(&questions).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if err := db.Model(&models.Attempt{}).Select("quiz_id, COUNT(*) AS n").
|
||||||
|
Where("quiz_id IN ? AND completed_at IS NOT NULL", ids).Group("quiz_id").Scan(&attempts).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
questionsBy := map[uint]int{}
|
||||||
|
for _, c := range questions {
|
||||||
|
questionsBy[c.QuizID] = c.N
|
||||||
|
}
|
||||||
|
attemptsBy := map[uint]int{}
|
||||||
|
for _, c := range attempts {
|
||||||
|
attemptsBy[c.QuizID] = c.N
|
||||||
|
}
|
||||||
|
for _, quiz := range quizzes {
|
||||||
|
out = append(out, ManagedQuizRow{Quiz: quiz, QuestionCount: questionsBy[quiz.ID], AttemptsCount: attemptsBy[quiz.ID]})
|
||||||
|
}
|
||||||
|
return out, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ManagedQuiz loads a quiz, published or not, with every question in sort
|
||||||
|
// order and every answer of each, solutions included. A missing slug is
|
||||||
|
// ErrNotFound.
|
||||||
|
func ManagedQuiz(ctx context.Context, db *gorm.DB, slug string) (*models.Quiz, error) {
|
||||||
|
var quiz models.Quiz
|
||||||
|
err := db.WithContext(ctx).
|
||||||
|
Preload("Questions", func(tx *gorm.DB) *gorm.DB { return tx.Order("sort_order ASC, id ASC") }).
|
||||||
|
Preload("Questions.Answers", func(tx *gorm.DB) *gorm.DB { return tx.Order("sort_order ASC, id ASC") }).
|
||||||
|
Where("slug = ?", slug).Take(&quiz).Error
|
||||||
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||||
|
return nil, ErrNotFound
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &quiz, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// CompletedAttemptCount counts the completed attempts of every user on a
|
||||||
|
// quiz.
|
||||||
|
func CompletedAttemptCount(ctx context.Context, db *gorm.DB, quizID uint) (int, error) {
|
||||||
|
var n int64
|
||||||
|
err := db.WithContext(ctx).Model(&models.Attempt{}).
|
||||||
|
Where("quiz_id = ? AND completed_at IS NOT NULL", quizID).Count(&n).Error
|
||||||
|
return int(n), err
|
||||||
|
}
|
||||||
|
|
||||||
|
// StudentStat is one student's results on a quiz, over their completed
|
||||||
|
// whole-quiz attempts (category IS NULL, A9).
|
||||||
|
type StudentStat struct {
|
||||||
|
UserID uint
|
||||||
|
Email string
|
||||||
|
Name *string
|
||||||
|
Surname *string
|
||||||
|
Attempts int
|
||||||
|
BestScorePercent *float64
|
||||||
|
LastScorePercent *float64
|
||||||
|
LastCompletedAt *time.Time
|
||||||
|
// Passed is BestScorePercent >= the quiz's passing score.
|
||||||
|
Passed bool
|
||||||
|
}
|
||||||
|
|
||||||
|
// WrongAnswerStat is the wrong answer chosen most often for a question.
|
||||||
|
type WrongAnswerStat struct {
|
||||||
|
AnswerID uint
|
||||||
|
Text string
|
||||||
|
Count int
|
||||||
|
}
|
||||||
|
|
||||||
|
// QuestionStat is one question's results over every completed attempt's
|
||||||
|
// answers. CorrectPercent is nil when nobody answered it; MostChosenWrong
|
||||||
|
// is nil for a self_check or open question and when no wrong answer was
|
||||||
|
// chosen. Unreviewed counts the open answers the owner has not reviewed
|
||||||
|
// yet (pending, graded or failed); AveragePoints is the mean score of an
|
||||||
|
// open question's graded and reviewed answers, nil for other types and
|
||||||
|
// before any grade.
|
||||||
|
type QuestionStat struct {
|
||||||
|
ID uint
|
||||||
|
Text string
|
||||||
|
Type string
|
||||||
|
Answered int
|
||||||
|
Correct int
|
||||||
|
CorrectPercent *float64
|
||||||
|
MostChosenWrong *WrongAnswerStat
|
||||||
|
Unreviewed int
|
||||||
|
AveragePoints *float64
|
||||||
|
}
|
||||||
|
|
||||||
|
// Stats is the owner's report on one quiz (D-15).
|
||||||
|
type Stats struct {
|
||||||
|
Quiz models.Quiz
|
||||||
|
QuestionCount int
|
||||||
|
Students []StudentStat
|
||||||
|
Questions []QuestionStat
|
||||||
|
// Unreviewed is the sum of the questions' Unreviewed.
|
||||||
|
Unreviewed int
|
||||||
|
}
|
||||||
|
|
||||||
|
// StudentRow is one row of the per-student stats query.
|
||||||
|
type StudentRow struct {
|
||||||
|
UserID uint
|
||||||
|
Email string
|
||||||
|
Name *string
|
||||||
|
Surname *string
|
||||||
|
Attempts int
|
||||||
|
BestScorePercent *float64
|
||||||
|
LastScorePercent *float64
|
||||||
|
LastCompletedAt *time.Time
|
||||||
|
}
|
||||||
|
|
||||||
|
// AnswerRow is one row of the per-question answered/correct query.
|
||||||
|
type AnswerRow struct {
|
||||||
|
QuestionID uint
|
||||||
|
Answered int
|
||||||
|
Correct int
|
||||||
|
Unreviewed int
|
||||||
|
AveragePoints *float64
|
||||||
|
}
|
||||||
|
|
||||||
|
// WrongRow is one wrong answer chosen N times for a question.
|
||||||
|
type WrongRow struct {
|
||||||
|
QuestionID uint
|
||||||
|
AnswerID uint
|
||||||
|
Text string
|
||||||
|
N int
|
||||||
|
}
|
||||||
|
|
||||||
|
const (
|
||||||
|
statsStudentsSQL = `SELECT a.user_id, u.email, u.name, u.surname, COUNT(*) AS attempts,
|
||||||
|
MAX(a.score_percent) AS best_score_percent,
|
||||||
|
(ARRAY_AGG(a.score_percent ORDER BY a.completed_at DESC, a.id DESC))[1] AS last_score_percent,
|
||||||
|
MAX(a.completed_at) AS last_completed_at
|
||||||
|
FROM golem15_quizzes_attempts a JOIN users u ON u.id = a.user_id
|
||||||
|
WHERE a.quiz_id = ? AND a.completed_at IS NOT NULL AND a.category IS NULL
|
||||||
|
GROUP BY a.user_id, u.email, u.name, u.surname
|
||||||
|
ORDER BY u.surname ASC NULLS LAST, u.name ASC NULLS LAST, u.email ASC, a.user_id ASC`
|
||||||
|
|
||||||
|
// average_points counts only scored open answers: a pending or failed
|
||||||
|
// answer holds 0 points until it is graded.
|
||||||
|
statsAnswersSQL = `SELECT aa.question_id, COUNT(*) AS answered, COUNT(*) FILTER (WHERE aa.is_correct) AS correct,
|
||||||
|
COUNT(*) FILTER (WHERE aa.grading_status IN ('pending', 'graded', 'failed')) AS unreviewed,
|
||||||
|
AVG(aa.points) FILTER (WHERE aa.grading_status IN ('graded', 'reviewed')) AS average_points
|
||||||
|
FROM golem15_quizzes_attempt_answers aa
|
||||||
|
JOIN golem15_quizzes_attempts a ON a.id = aa.attempt_id
|
||||||
|
WHERE a.quiz_id = ? AND a.completed_at IS NOT NULL
|
||||||
|
GROUP BY aa.question_id`
|
||||||
|
|
||||||
|
// A stored answer_ids that is SQL NULL or not an array (self_check
|
||||||
|
// rows) yields no elements instead of an error.
|
||||||
|
statsWrongSQL = `SELECT aa.question_id, ans.id AS answer_id, ans.text, COUNT(*) AS n
|
||||||
|
FROM golem15_quizzes_attempt_answers aa
|
||||||
|
JOIN golem15_quizzes_attempts a ON a.id = aa.attempt_id
|
||||||
|
CROSS JOIN LATERAL jsonb_array_elements_text(CASE WHEN jsonb_typeof(aa.answer_ids) = 'array' THEN aa.answer_ids ELSE '[]'::jsonb END) AS e(value)
|
||||||
|
JOIN golem15_quizzes_answers ans ON ans.id = e.value::bigint AND ans.question_id = aa.question_id AND ans.is_correct = FALSE
|
||||||
|
WHERE a.quiz_id = ? AND a.completed_at IS NOT NULL
|
||||||
|
GROUP BY aa.question_id, ans.id, ans.text
|
||||||
|
ORDER BY aa.question_id, n DESC, ans.id`
|
||||||
|
)
|
||||||
|
|
||||||
|
// QuizStats reports on the quiz with this slug. For a test it first closes
|
||||||
|
// every expired open attempt at its deadline, through svc, so a student who
|
||||||
|
// left a test counts with the answers given in time. Students are counted
|
||||||
|
// over completed whole-quiz attempts, questions over the answers of every
|
||||||
|
// completed attempt. A missing slug is ErrNotFound.
|
||||||
|
func QuizStats(ctx context.Context, db *gorm.DB, slug string, svc *Service) (*Stats, error) {
|
||||||
|
if svc == nil {
|
||||||
|
svc = &Service{DB: db, Grace: DefaultTestGrace}
|
||||||
|
}
|
||||||
|
var quiz models.Quiz
|
||||||
|
err := db.WithContext(ctx).Where("slug = ?", slug).Take(&quiz).Error
|
||||||
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||||
|
return nil, ErrNotFound
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if IsTest(&quiz) {
|
||||||
|
if err := svc.closeExpired(ctx, db, &quiz); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
tx := db.WithContext(ctx)
|
||||||
|
var questions []models.Question
|
||||||
|
if err := tx.Where("quiz_id = ?", quiz.ID).Order("sort_order ASC, id ASC").Find(&questions).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
var students []StudentRow
|
||||||
|
if err := tx.Raw(statsStudentsSQL, quiz.ID).Scan(&students).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
var answers []AnswerRow
|
||||||
|
if err := tx.Raw(statsAnswersSQL, quiz.ID).Scan(&answers).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
var wrong []WrongRow
|
||||||
|
if err := tx.Raw(statsWrongSQL, quiz.ID).Scan(&wrong).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
stats := BuildStats(quiz, questions, students, answers, wrong)
|
||||||
|
return &stats, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// closeExpired closes every expired open attempt of a test at its
|
||||||
|
// deadline, in one transaction, with the rows locked as Start locks them.
|
||||||
|
func (s *Service) closeExpired(ctx context.Context, db *gorm.DB, quiz *models.Quiz) error {
|
||||||
|
return lagoon.Transaction(ctx, db, func(ctx context.Context, tx *gorm.DB) error {
|
||||||
|
var open []models.Attempt
|
||||||
|
if err := tx.WithContext(ctx).Clauses(clause.Locking{Strength: "UPDATE", Table: clause.Table{Name: clause.CurrentTable}}).
|
||||||
|
Where("quiz_id = ? AND completed_at IS NULL", quiz.ID).Order("id ASC").Find(&open).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
now := s.now()
|
||||||
|
for i := range open {
|
||||||
|
a := &open[i]
|
||||||
|
a.Quiz = quiz
|
||||||
|
if Expired(a, now, s.Grace) {
|
||||||
|
if err := s.close(ctx, tx, a, *Deadline(a)); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// BuildStats assembles the report from the query rows. Every question of
|
||||||
|
// questions appears, in that order, with zero counts when nobody answered
|
||||||
|
// it; correct_percent is rounded to one decimal.
|
||||||
|
func BuildStats(quiz models.Quiz, questions []models.Question, students []StudentRow, answers []AnswerRow, wrong []WrongRow) Stats {
|
||||||
|
out := Stats{
|
||||||
|
Quiz: quiz,
|
||||||
|
QuestionCount: len(questions),
|
||||||
|
Students: make([]StudentStat, 0, len(students)),
|
||||||
|
Questions: make([]QuestionStat, 0, len(questions)),
|
||||||
|
}
|
||||||
|
for _, r := range students {
|
||||||
|
out.Students = append(out.Students, StudentStat{
|
||||||
|
UserID: r.UserID, Email: r.Email, Name: r.Name, Surname: r.Surname, Attempts: r.Attempts,
|
||||||
|
BestScorePercent: r.BestScorePercent, LastScorePercent: r.LastScorePercent, LastCompletedAt: r.LastCompletedAt,
|
||||||
|
Passed: r.BestScorePercent != nil && *r.BestScorePercent >= float64(quiz.PassingScore),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
answeredBy := map[uint]AnswerRow{}
|
||||||
|
for _, r := range answers {
|
||||||
|
answeredBy[r.QuestionID] = r
|
||||||
|
}
|
||||||
|
wrongBy := map[uint]*WrongAnswerStat{}
|
||||||
|
for _, r := range wrong {
|
||||||
|
best := wrongBy[r.QuestionID]
|
||||||
|
if best == nil || r.N > best.Count || (r.N == best.Count && r.AnswerID < best.AnswerID) {
|
||||||
|
wrongBy[r.QuestionID] = &WrongAnswerStat{AnswerID: r.AnswerID, Text: r.Text, Count: r.N}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, q := range questions {
|
||||||
|
a := answeredBy[q.ID]
|
||||||
|
st := QuestionStat{ID: q.ID, Text: q.Text, Type: q.Type, Answered: a.Answered, Correct: a.Correct}
|
||||||
|
if a.Answered > 0 {
|
||||||
|
pct := math.Round(float64(a.Correct)*1000/float64(a.Answered)) / 10
|
||||||
|
st.CorrectPercent = &pct
|
||||||
|
}
|
||||||
|
switch q.Type {
|
||||||
|
case models.TypeSelfCheck:
|
||||||
|
case models.TypeOpen:
|
||||||
|
st.Unreviewed = a.Unreviewed
|
||||||
|
if a.AveragePoints != nil {
|
||||||
|
avg := math.Round(*a.AveragePoints*100) / 100
|
||||||
|
st.AveragePoints = &avg
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
st.MostChosenWrong = wrongBy[q.ID]
|
||||||
|
}
|
||||||
|
out.Unreviewed += st.Unreviewed
|
||||||
|
out.Questions = append(out.Questions, st)
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
// ManagedAnswerInput is one answer of a question write. An ID keeps and
|
||||||
|
// updates that answer of the question; no ID creates one. Explanation nil
|
||||||
|
// keeps a kept answer's explanation, "" clears it.
|
||||||
|
type ManagedAnswerInput struct {
|
||||||
|
ID *uint `json:"id"`
|
||||||
|
Text string `json:"text"`
|
||||||
|
IsCorrect bool `json:"is_correct"`
|
||||||
|
Explanation *string `json:"explanation"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// QuestionInput is the fields of a question create or partial update; nil
|
||||||
|
// means not sent. Answers, when sent, is the question's full new answer
|
||||||
|
// list in order. An empty string clears category, answer_text,
|
||||||
|
// explanation and rubric; a max_length of 0 clears it (the default 2000
|
||||||
|
// applies).
|
||||||
|
type QuestionInput struct {
|
||||||
|
Text *string `json:"text"`
|
||||||
|
Type *string `json:"type"`
|
||||||
|
Category *string `json:"category"`
|
||||||
|
AnswerText *string `json:"answer_text"`
|
||||||
|
Explanation *string `json:"explanation"`
|
||||||
|
Points *int `json:"points"`
|
||||||
|
SortOrder *int `json:"sort_order"`
|
||||||
|
Rubric *string `json:"rubric"`
|
||||||
|
MaxLength *int `json:"max_length"`
|
||||||
|
Answers *[]ManagedAnswerInput `json:"answers"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// MergeQuestion applies the sent fields of in, and its answers list when
|
||||||
|
// sent, to current (a zero Question for a create) and returns the result
|
||||||
|
// in the importer's shape, for CheckQuestion. An answer id that is not an
|
||||||
|
// answer of current, or is listed twice, is a problem.
|
||||||
|
func MergeQuestion(current models.Question, in QuestionInput) (ImportQuestion, []string) {
|
||||||
|
q := ImportQuestion{
|
||||||
|
Text: current.Text, Type: current.Type, Category: current.Category,
|
||||||
|
AnswerText: current.AnswerText, Explanation: current.Explanation,
|
||||||
|
Rubric: current.Rubric, MaxLength: current.MaxLength,
|
||||||
|
}
|
||||||
|
points := current.Points
|
||||||
|
if current.ID == 0 {
|
||||||
|
points = 1
|
||||||
|
}
|
||||||
|
if in.Text != nil {
|
||||||
|
q.Text = strings.TrimSpace(*in.Text)
|
||||||
|
}
|
||||||
|
if in.Type != nil {
|
||||||
|
q.Type = *in.Type
|
||||||
|
}
|
||||||
|
if in.Category != nil {
|
||||||
|
q.Category = nilIfBlank(*in.Category, true)
|
||||||
|
}
|
||||||
|
if in.AnswerText != nil {
|
||||||
|
q.AnswerText = nilIfBlank(*in.AnswerText, false)
|
||||||
|
}
|
||||||
|
if in.Explanation != nil {
|
||||||
|
q.Explanation = nilIfBlank(*in.Explanation, false)
|
||||||
|
}
|
||||||
|
if in.Points != nil {
|
||||||
|
points = *in.Points
|
||||||
|
}
|
||||||
|
if in.Rubric != nil {
|
||||||
|
q.Rubric = nilIfBlank(*in.Rubric, false)
|
||||||
|
}
|
||||||
|
if in.MaxLength != nil {
|
||||||
|
if *in.MaxLength == 0 {
|
||||||
|
q.MaxLength = nil
|
||||||
|
} else {
|
||||||
|
n := *in.MaxLength
|
||||||
|
q.MaxLength = &n
|
||||||
|
}
|
||||||
|
}
|
||||||
|
q.Points = &points
|
||||||
|
var problems []string
|
||||||
|
if in.Category != nil && utf8.RuneCountInString(strings.TrimSpace(*in.Category)) > 255 {
|
||||||
|
problems = append(problems, "category must be at most 255 characters")
|
||||||
|
}
|
||||||
|
if in.Answers == nil {
|
||||||
|
for _, a := range current.Answers {
|
||||||
|
q.Answers = append(q.Answers, ImportAnswer{Text: a.Text, IsCorrect: a.IsCorrect, Explanation: a.Explanation})
|
||||||
|
}
|
||||||
|
return q, problems
|
||||||
|
}
|
||||||
|
byID := map[uint]models.Answer{}
|
||||||
|
for _, a := range current.Answers {
|
||||||
|
byID[a.ID] = a
|
||||||
|
}
|
||||||
|
seen := map[uint]bool{}
|
||||||
|
q.Answers = make([]ImportAnswer, 0, len(*in.Answers))
|
||||||
|
for i, a := range *in.Answers {
|
||||||
|
out := ImportAnswer{Text: strings.TrimSpace(a.Text), IsCorrect: a.IsCorrect, Explanation: a.Explanation}
|
||||||
|
if a.ID != nil {
|
||||||
|
kept, ok := byID[*a.ID]
|
||||||
|
switch {
|
||||||
|
case !ok:
|
||||||
|
problems = append(problems, fmt.Sprintf("answers[%d].id does not belong to this question", i))
|
||||||
|
case seen[*a.ID]:
|
||||||
|
problems = append(problems, fmt.Sprintf("answers[%d].id is listed twice", i))
|
||||||
|
case a.Explanation == nil:
|
||||||
|
out.Explanation = kept.Explanation
|
||||||
|
}
|
||||||
|
seen[*a.ID] = true
|
||||||
|
}
|
||||||
|
if out.Explanation != nil {
|
||||||
|
out.Explanation = nilIfBlank(*out.Explanation, false)
|
||||||
|
}
|
||||||
|
q.Answers = append(q.Answers, out)
|
||||||
|
}
|
||||||
|
return q, problems
|
||||||
|
}
|
||||||
|
|
||||||
|
// CheckNewQuestion is the rule check of a create, before any database
|
||||||
|
// access: text and type are required, answers carry no id, and the merged
|
||||||
|
// question passes CheckQuestion.
|
||||||
|
func CheckNewQuestion(in QuestionInput) []string {
|
||||||
|
var problems []string
|
||||||
|
if in.Text == nil {
|
||||||
|
problems = append(problems, "text is required")
|
||||||
|
}
|
||||||
|
if in.Type == nil {
|
||||||
|
problems = append(problems, "type is required")
|
||||||
|
}
|
||||||
|
if len(problems) > 0 {
|
||||||
|
return problems
|
||||||
|
}
|
||||||
|
merged, problems := MergeQuestion(models.Question{}, in)
|
||||||
|
if in.SortOrder != nil && *in.SortOrder < 1 {
|
||||||
|
problems = append(problems, "sort_order must be at least 1")
|
||||||
|
}
|
||||||
|
return append(problems, CheckQuestion("question", merged)...)
|
||||||
|
}
|
||||||
|
|
||||||
|
// managedQuizID loads the id of the quiz with this slug, or ErrNotFound.
|
||||||
|
func managedQuizID(tx *gorm.DB, slug string) (uint, error) {
|
||||||
|
var quiz models.Quiz
|
||||||
|
if err := lockedQuiz(tx, slug, &quiz); err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
return quiz.ID, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// CreateQuestion adds a question with its answers to the quiz with this
|
||||||
|
// slug: at sort_order when given, else after the last question. Points
|
||||||
|
// default to 1; answers are ordered as sent. A missing slug is ErrNotFound.
|
||||||
|
func CreateQuestion(ctx context.Context, db *gorm.DB, slug string, in QuestionInput) (*models.Question, error) {
|
||||||
|
if err := invalid(CheckNewQuestion(in)); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
merged, _ := MergeQuestion(models.Question{}, in)
|
||||||
|
var q models.Question
|
||||||
|
err := lagoon.Transaction(ctx, db, func(ctx context.Context, tx *gorm.DB) error {
|
||||||
|
tx = tx.WithContext(ctx)
|
||||||
|
quizID, err := managedQuizID(tx, slug)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
order := 0
|
||||||
|
if in.SortOrder != nil {
|
||||||
|
order = *in.SortOrder
|
||||||
|
} else if err := tx.Model(&models.Question{}).Where("quiz_id = ?", quizID).
|
||||||
|
Select("COALESCE(MAX(sort_order), 0) + 1").Scan(&order).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
q = models.Question{
|
||||||
|
QuizID: quizID, Text: merged.Text, Type: merged.Type, Category: merged.Category,
|
||||||
|
AnswerText: merged.AnswerText, Explanation: merged.Explanation, SortOrder: order, Points: *merged.Points,
|
||||||
|
Rubric: merged.Rubric, MaxLength: merged.MaxLength,
|
||||||
|
}
|
||||||
|
if err := tx.Omit(clause.Associations).Create(&q).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
for i, a := range merged.Answers {
|
||||||
|
ans := models.Answer{QuestionID: q.ID, Text: a.Text, IsCorrect: a.IsCorrect, Explanation: a.Explanation, SortOrder: i + 1}
|
||||||
|
if err := tx.Omit(clause.Associations).Create(&ans).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
q.Answers = append(q.Answers, ans)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &q, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// UpdateQuestion changes only the sent fields of one question of the quiz
|
||||||
|
// with this slug. When answers is sent it is the full new list: answers
|
||||||
|
// with an id are updated in place (so the answer ids stored in past
|
||||||
|
// attempts stay valid), answers without one are created, answers missing
|
||||||
|
// from the list are deleted, and the order is the list order. The merged
|
||||||
|
// question must pass CheckQuestion. Stored attempt answers and scores are
|
||||||
|
// never touched (D-16). A missing quiz is ErrNotFound, a missing question
|
||||||
|
// ErrQuestionNotFound.
|
||||||
|
func UpdateQuestion(ctx context.Context, db *gorm.DB, slug string, id uint, in QuestionInput) (*models.Question, error) {
|
||||||
|
if in.SortOrder != nil && *in.SortOrder < 1 {
|
||||||
|
return nil, invalid([]string{"sort_order must be at least 1"})
|
||||||
|
}
|
||||||
|
var q models.Question
|
||||||
|
err := lagoon.Transaction(ctx, db, func(ctx context.Context, tx *gorm.DB) error {
|
||||||
|
tx = tx.WithContext(ctx)
|
||||||
|
quizID, err := managedQuizID(tx, slug)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
err = tx.Clauses(clause.Locking{Strength: "UPDATE", Table: clause.Table{Name: clause.CurrentTable}}).
|
||||||
|
Where("id = ? AND quiz_id = ?", id, quizID).Take(&q).Error
|
||||||
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||||
|
return ErrQuestionNotFound
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := tx.Where("question_id = ?", q.ID).Order("sort_order ASC, id ASC").Find(&q.Answers).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
merged, problems := MergeQuestion(q, in)
|
||||||
|
if err := invalid(append(problems, CheckQuestion("question", merged)...)); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
q.Text, q.Type, q.Category = merged.Text, merged.Type, merged.Category
|
||||||
|
q.AnswerText, q.Explanation, q.Points = merged.AnswerText, merged.Explanation, *merged.Points
|
||||||
|
q.Rubric, q.MaxLength = merged.Rubric, merged.MaxLength
|
||||||
|
if in.SortOrder != nil {
|
||||||
|
q.SortOrder = *in.SortOrder
|
||||||
|
}
|
||||||
|
if err := tx.Omit(clause.Associations).Save(&q).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if in.Answers == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
current := map[uint]models.Answer{}
|
||||||
|
for _, a := range q.Answers {
|
||||||
|
current[a.ID] = a
|
||||||
|
}
|
||||||
|
answers := make([]models.Answer, 0, len(merged.Answers))
|
||||||
|
keep := map[uint]bool{}
|
||||||
|
for i, a := range merged.Answers {
|
||||||
|
ans := models.Answer{QuestionID: q.ID}
|
||||||
|
if sent := (*in.Answers)[i]; sent.ID != nil {
|
||||||
|
ans = current[*sent.ID]
|
||||||
|
keep[ans.ID] = true
|
||||||
|
}
|
||||||
|
ans.Text, ans.IsCorrect, ans.Explanation, ans.SortOrder = a.Text, a.IsCorrect, a.Explanation, i+1
|
||||||
|
if err := tx.Omit(clause.Associations).Save(&ans).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
answers = append(answers, ans)
|
||||||
|
}
|
||||||
|
for _, a := range q.Answers {
|
||||||
|
if !keep[a.ID] {
|
||||||
|
if err := tx.Where("id = ?", a.ID).Delete(&models.Answer{}).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
q.Answers = answers
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &q, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// DeleteQuestion removes one question of the quiz with this slug. The
|
||||||
|
// foreign keys cascade to its answers and the attempt answers given to
|
||||||
|
// it; finished attempts keep their stored scores (D-16).
|
||||||
|
func DeleteQuestion(ctx context.Context, db *gorm.DB, slug string, id uint) error {
|
||||||
|
return lagoon.Transaction(ctx, db, func(ctx context.Context, tx *gorm.DB) error {
|
||||||
|
tx = tx.WithContext(ctx)
|
||||||
|
quizID, err := managedQuizID(tx, slug)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
res := tx.Where("id = ? AND quiz_id = ?", id, quizID).Delete(&models.Question{})
|
||||||
|
if res.Error != nil {
|
||||||
|
return res.Error
|
||||||
|
}
|
||||||
|
if res.RowsAffected == 0 {
|
||||||
|
return ErrQuestionNotFound
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// CheckQuestionOrder is the check of a reorder list before any database
|
||||||
|
// access: not empty, no id twice.
|
||||||
|
func CheckQuestionOrder(ids []uint) []string {
|
||||||
|
seen := map[uint]bool{}
|
||||||
|
for _, id := range ids {
|
||||||
|
if seen[id] {
|
||||||
|
return []string{"question_ids must list every question of the quiz exactly once"}
|
||||||
|
}
|
||||||
|
seen[id] = true
|
||||||
|
}
|
||||||
|
if len(ids) == 0 {
|
||||||
|
return []string{"question_ids must list every question of the quiz exactly once"}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ReorderQuestions sets sort_order = index + 1 for ids, which must be
|
||||||
|
// exactly the quiz's question ids, and returns the managed quiz.
|
||||||
|
func ReorderQuestions(ctx context.Context, db *gorm.DB, slug string, ids []uint) (*models.Quiz, error) {
|
||||||
|
if err := invalid(CheckQuestionOrder(ids)); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
err := lagoon.Transaction(ctx, db, func(ctx context.Context, tx *gorm.DB) error {
|
||||||
|
tx = tx.WithContext(ctx)
|
||||||
|
quizID, err := managedQuizID(tx, slug)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
var have []uint
|
||||||
|
if err := tx.Model(&models.Question{}).Where("quiz_id = ?", quizID).Pluck("id", &have).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
sorted := slices.Clone(ids)
|
||||||
|
slices.Sort(sorted)
|
||||||
|
slices.Sort(have)
|
||||||
|
if !slices.Equal(sorted, have) {
|
||||||
|
return invalid([]string{"question_ids must list every question of the quiz exactly once"})
|
||||||
|
}
|
||||||
|
now := time.Now().UTC()
|
||||||
|
for i, id := range ids {
|
||||||
|
if err := tx.Model(&models.Question{}).Where("id = ?", id).
|
||||||
|
Updates(map[string]any{"sort_order": i + 1, "updated_at": now}).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return ManagedQuiz(ctx, db, slug)
|
||||||
|
}
|
||||||
262
classes/manage_test.go
Normal file
262
classes/manage_test.go
Normal file
@@ -0,0 +1,262 @@
|
|||||||
|
package classes_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"git.golem15.com/golem15/sm-quizzes-plugin/classes"
|
||||||
|
"git.golem15.com/golem15/sm-quizzes-plugin/models"
|
||||||
|
)
|
||||||
|
|
||||||
|
func str(s string) *string { return &s }
|
||||||
|
func num(n int) *int { return &n }
|
||||||
|
|
||||||
|
func TestCheckQuizInput(t *testing.T) {
|
||||||
|
for name, tc := range map[string]struct {
|
||||||
|
in classes.QuizInput
|
||||||
|
create bool
|
||||||
|
want string
|
||||||
|
}{
|
||||||
|
"missing title": {classes.QuizInput{}, true, "title is required"},
|
||||||
|
"blank title": {classes.QuizInput{Title: str(" ")}, true, "title is required"},
|
||||||
|
"long title": {classes.QuizInput{Title: str(strings.Repeat("a", 256))}, true, "title must be at most 255"},
|
||||||
|
"mode exam": {classes.QuizInput{Title: str("A"), Mode: str("exam")}, true, "mode must be one of"},
|
||||||
|
"navigation back": {classes.QuizInput{Title: str("A"), Navigation: str("back")}, true, "navigation must be one of"},
|
||||||
|
"passing score 101": {classes.QuizInput{Title: str("A"), PassingScore: num(101)}, true, "passing_score must be between"},
|
||||||
|
"max attempts 0": {classes.QuizInput{Title: str("A"), MaxAttempts: num(0)}, true, "max_attempts must be at least 1"},
|
||||||
|
"time limit 0": {classes.QuizInput{Title: str("A"), TimeLimitSeconds: num(0)}, true, "time_limit_seconds must be at least 1"},
|
||||||
|
"long context": {classes.QuizInput{Title: str("A"), Context: str(strings.Repeat("c", 256))}, true, "context must be at most 255"},
|
||||||
|
"update blank title": {classes.QuizInput{Title: str("")}, false, "title is required"},
|
||||||
|
"update negative limit": {classes.QuizInput{MaxAttempts: num(-1)}, false, "max_attempts must be 0"},
|
||||||
|
"bad grader": {classes.QuizInput{Title: str("A"), Grader: str("Bad Grader")}, true, "grader must be lowercase"},
|
||||||
|
"update empty grader": {classes.QuizInput{Grader: str("")}, false, "grader must be lowercase"},
|
||||||
|
} {
|
||||||
|
got := strings.Join(classes.CheckQuizInput(tc.in, tc.create), "; ")
|
||||||
|
if !strings.Contains(got, tc.want) {
|
||||||
|
t.Errorf("%s: problems %q, want %q", name, got, tc.want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if got := classes.CheckQuizInput(classes.QuizInput{Title: str("Pojęcia")}, true); len(got) != 0 {
|
||||||
|
t.Errorf("minimal create: %v", got)
|
||||||
|
}
|
||||||
|
if got := classes.CheckQuizInput(classes.QuizInput{Title: str("A"), Grader: str("ai")}, true); len(got) != 0 {
|
||||||
|
t.Errorf("well-formed grader: %v", got)
|
||||||
|
}
|
||||||
|
if got := classes.CheckQuizInput(classes.QuizInput{}, false); len(got) != 0 {
|
||||||
|
t.Errorf("empty update: %v", got)
|
||||||
|
}
|
||||||
|
clears := classes.QuizInput{MaxAttempts: num(0), TimeLimitSeconds: num(0), RoundSize: num(0), Description: str(""), Context: str("")}
|
||||||
|
if got := classes.CheckQuizInput(clears, false); len(got) != 0 {
|
||||||
|
t.Errorf("update clearing with 0: %v", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestValidateDeleteConfirm(t *testing.T) {
|
||||||
|
if err := classes.ValidateDeleteConfirm("a", "a"); err != nil {
|
||||||
|
t.Errorf("matching confirm: %v", err)
|
||||||
|
}
|
||||||
|
for _, confirm := range []string{"", "b", " a"} {
|
||||||
|
err := classes.ValidateDeleteConfirm("a", confirm)
|
||||||
|
var invalid *classes.ValidationError
|
||||||
|
if !errors.As(err, &invalid) || !strings.Contains(err.Error(), "confirm") {
|
||||||
|
t.Errorf("confirm %q: %v, want a ValidationError naming confirm", confirm, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestBuildStats(t *testing.T) {
|
||||||
|
quiz := models.Quiz{ID: 1, Slug: "q", PassingScore: 60}
|
||||||
|
questions := []models.Question{
|
||||||
|
{ID: 10, Text: "single", Type: models.TypeSingle},
|
||||||
|
{ID: 11, Text: "card", Type: models.TypeSelfCheck},
|
||||||
|
{ID: 12, Text: "unanswered", Type: models.TypeMultiple},
|
||||||
|
{ID: 13, Text: "all right", Type: models.TypeSingle},
|
||||||
|
}
|
||||||
|
best1, best2, last := 75.0, 50.0, 40.0
|
||||||
|
students := []classes.StudentRow{
|
||||||
|
{UserID: 5, Email: "a@x", Attempts: 2, BestScorePercent: &best1, LastScorePercent: &last},
|
||||||
|
{UserID: 6, Email: "b@x", Attempts: 1, BestScorePercent: &best2, LastScorePercent: &best2},
|
||||||
|
{UserID: 7, Email: "c@x", Attempts: 1},
|
||||||
|
}
|
||||||
|
answers := []classes.AnswerRow{
|
||||||
|
{QuestionID: 10, Answered: 3, Correct: 2},
|
||||||
|
{QuestionID: 11, Answered: 4, Correct: 1},
|
||||||
|
{QuestionID: 13, Answered: 2, Correct: 2},
|
||||||
|
}
|
||||||
|
wrong := []classes.WrongRow{
|
||||||
|
{QuestionID: 10, AnswerID: 102, Text: "second", N: 1},
|
||||||
|
{QuestionID: 10, AnswerID: 101, Text: "first", N: 1},
|
||||||
|
{QuestionID: 11, AnswerID: 999, Text: "ignored", N: 9},
|
||||||
|
}
|
||||||
|
s := classes.BuildStats(quiz, questions, students, answers, wrong)
|
||||||
|
if s.QuestionCount != 4 || len(s.Questions) != 4 || len(s.Students) != 3 {
|
||||||
|
t.Fatalf("stats = %+v", s)
|
||||||
|
}
|
||||||
|
if !s.Students[0].Passed || s.Students[1].Passed || s.Students[2].Passed {
|
||||||
|
t.Errorf("passed = %v %v %v, want true false false", s.Students[0].Passed, s.Students[1].Passed, s.Students[2].Passed)
|
||||||
|
}
|
||||||
|
q := s.Questions[0]
|
||||||
|
if q.CorrectPercent == nil || *q.CorrectPercent != 66.7 {
|
||||||
|
t.Errorf("correct_percent 2 of 3 = %v, want 66.7", q.CorrectPercent)
|
||||||
|
}
|
||||||
|
if q.MostChosenWrong == nil || q.MostChosenWrong.AnswerID != 101 || q.MostChosenWrong.Count != 1 {
|
||||||
|
t.Errorf("most_chosen_wrong = %+v, want answer 101 (lowest id on a tie)", q.MostChosenWrong)
|
||||||
|
}
|
||||||
|
if s.Questions[1].MostChosenWrong != nil {
|
||||||
|
t.Errorf("self_check most_chosen_wrong = %+v, want nil", s.Questions[1].MostChosenWrong)
|
||||||
|
}
|
||||||
|
if un := s.Questions[2]; un.ID != 12 || un.Answered != 0 || un.CorrectPercent != nil || un.MostChosenWrong != nil {
|
||||||
|
t.Errorf("unanswered question = %+v", un)
|
||||||
|
}
|
||||||
|
if ok := s.Questions[3]; ok.CorrectPercent == nil || *ok.CorrectPercent != 100 || ok.MostChosenWrong != nil {
|
||||||
|
t.Errorf("all-correct question = %+v", ok)
|
||||||
|
}
|
||||||
|
if s.Unreviewed != 0 || s.Questions[0].AveragePoints != nil || s.Questions[0].Unreviewed != 0 {
|
||||||
|
t.Errorf("closed questions report unreviewed %d, average %v", s.Unreviewed, s.Questions[0].AveragePoints)
|
||||||
|
}
|
||||||
|
more := append(wrong, classes.WrongRow{QuestionID: 10, AnswerID: 103, Text: "third", N: 2})
|
||||||
|
if w := classes.BuildStats(quiz, questions, nil, answers, more).Questions[0].MostChosenWrong; w == nil || w.AnswerID != 103 {
|
||||||
|
t.Errorf("most_chosen_wrong by count = %+v, want 103", w)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func uid(n uint) *uint { return &n }
|
||||||
|
|
||||||
|
// TestBuildStatsOpen: an open question reports its unreviewed answers and
|
||||||
|
// the mean score of its scored answers; it has no most chosen wrong answer.
|
||||||
|
func TestBuildStatsOpen(t *testing.T) {
|
||||||
|
quiz := models.Quiz{ID: 1, Slug: "q", PassingScore: 60}
|
||||||
|
questions := []models.Question{
|
||||||
|
{ID: 20, Text: "essay", Type: models.TypeOpen},
|
||||||
|
{ID: 21, Text: "single", Type: models.TypeSingle},
|
||||||
|
}
|
||||||
|
avg, ignored := 4.0/3.0, 1.5
|
||||||
|
answers := []classes.AnswerRow{
|
||||||
|
{QuestionID: 20, Answered: 3, Correct: 1, Unreviewed: 2, AveragePoints: &avg},
|
||||||
|
{QuestionID: 21, Answered: 2, Correct: 1, Unreviewed: 5, AveragePoints: &ignored},
|
||||||
|
}
|
||||||
|
wrong := []classes.WrongRow{{QuestionID: 20, AnswerID: 1, Text: "never", N: 3}}
|
||||||
|
s := classes.BuildStats(quiz, questions, nil, answers, wrong)
|
||||||
|
open := s.Questions[0]
|
||||||
|
if open.Unreviewed != 2 || open.AveragePoints == nil || *open.AveragePoints != 1.33 || open.MostChosenWrong != nil {
|
||||||
|
t.Errorf("open = %+v (average %v)", open, open.AveragePoints)
|
||||||
|
}
|
||||||
|
if single := s.Questions[1]; single.Unreviewed != 0 || single.AveragePoints != nil {
|
||||||
|
t.Errorf("single = %+v, want no open counts", single)
|
||||||
|
}
|
||||||
|
if s.Unreviewed != 2 {
|
||||||
|
t.Errorf("total unreviewed = %d, want 2", s.Unreviewed)
|
||||||
|
}
|
||||||
|
if none := classes.BuildStats(quiz, questions[:1], nil, nil, nil).Questions[0]; none.AveragePoints != nil || none.Unreviewed != 0 {
|
||||||
|
t.Errorf("unanswered open = %+v", none)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCheckGrader(t *testing.T) {
|
||||||
|
known := []string{"manual"}
|
||||||
|
if got := classes.CheckGrader(str("ai"), known); len(got) != 1 || !strings.Contains(got[0], "grader must be one of manual") {
|
||||||
|
t.Errorf("unknown grader = %v", got)
|
||||||
|
}
|
||||||
|
if got := classes.CheckGrader(str("manual"), known); got != nil {
|
||||||
|
t.Errorf("manual = %v", got)
|
||||||
|
}
|
||||||
|
if got := classes.CheckGrader(nil, known); got != nil {
|
||||||
|
t.Errorf("nil = %v", got)
|
||||||
|
}
|
||||||
|
if got := classes.CheckGrader(str("ai"), []string{"manual", "ai"}); got != nil {
|
||||||
|
t.Errorf("registered ai = %v", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestQuestionInputRules: MergeQuestion applies a partial update and the
|
||||||
|
// answers list to the current question, and with CheckQuestion refuses
|
||||||
|
// what the importer would refuse.
|
||||||
|
func TestQuestionInputRules(t *testing.T) {
|
||||||
|
single := models.Question{ID: 1, Text: "Stolica?", Type: models.TypeSingle, Points: 2, Answers: []models.Answer{
|
||||||
|
{ID: 10, QuestionID: 1, Text: "Warszawa", IsCorrect: true, Explanation: str("Od 1596.")},
|
||||||
|
{ID: 11, QuestionID: 1, Text: "Kraków"},
|
||||||
|
}}
|
||||||
|
card := models.Question{ID: 2, Text: "Odporność?", Type: models.TypeSelfCheck, AnswerText: str("Zdolność"), Points: 1}
|
||||||
|
check := func(current models.Question, in classes.QuestionInput) (classes.ImportQuestion, []string) {
|
||||||
|
merged, problems := classes.MergeQuestion(current, in)
|
||||||
|
return merged, append(problems, classes.CheckQuestion("question", merged)...)
|
||||||
|
}
|
||||||
|
|
||||||
|
merged, problems := check(single, classes.QuestionInput{Text: str(" Stolica Polski? ")})
|
||||||
|
if len(problems) != 0 || merged.Text != "Stolica Polski?" || *merged.Points != 2 || len(merged.Answers) != 2 || *merged.Answers[0].Explanation != "Od 1596." {
|
||||||
|
t.Errorf("text only: %+v %v", merged, problems)
|
||||||
|
}
|
||||||
|
answers := []classes.ManagedAnswerInput{{ID: uid(99), Text: "Gdańsk", IsCorrect: true}, {ID: uid(11), Text: "Kraków"}}
|
||||||
|
if _, problems := check(single, classes.QuestionInput{Answers: &answers}); !strings.Contains(strings.Join(problems, "; "), "answers[0].id does not belong to this question") {
|
||||||
|
t.Errorf("foreign answer id: %v", problems)
|
||||||
|
}
|
||||||
|
twice := []classes.ManagedAnswerInput{{ID: uid(10), Text: "Warszawa", IsCorrect: true}, {ID: uid(10), Text: "Kraków"}}
|
||||||
|
if _, problems := check(single, classes.QuestionInput{Answers: &twice}); !strings.Contains(strings.Join(problems, "; "), "listed twice") {
|
||||||
|
t.Errorf("answer id twice: %v", problems)
|
||||||
|
}
|
||||||
|
two := []classes.ManagedAnswerInput{{ID: uid(10), Text: "Warszawa", IsCorrect: true}, {ID: uid(11), Text: "Kraków", IsCorrect: true}}
|
||||||
|
if _, problems := check(single, classes.QuestionInput{Answers: &two}); !strings.Contains(strings.Join(problems, "; "), "exactly one correct") {
|
||||||
|
t.Errorf("single with two correct: %v", problems)
|
||||||
|
}
|
||||||
|
if _, problems := check(single, classes.QuestionInput{Type: str(models.TypeSelfCheck)}); !strings.Contains(strings.Join(problems, "; "), "self_check question has no answers") {
|
||||||
|
t.Errorf("type to self_check with answers left: %v", problems)
|
||||||
|
}
|
||||||
|
kept := []classes.ManagedAnswerInput{{ID: uid(10), Text: "Warszawa", IsCorrect: true}, {Text: "Gdańsk", Explanation: str("")}}
|
||||||
|
merged, problems = check(single, classes.QuestionInput{Answers: &kept, Explanation: str("")})
|
||||||
|
if len(problems) != 0 || len(merged.Answers) != 2 || *merged.Answers[0].Explanation != "Od 1596." || merged.Answers[1].Explanation != nil || merged.Explanation != nil {
|
||||||
|
t.Errorf("kept and new answers: %+v %v", merged, problems)
|
||||||
|
}
|
||||||
|
toSingle := []classes.ManagedAnswerInput{{Text: "Tak", IsCorrect: true}, {Text: "Nie"}}
|
||||||
|
merged, problems = check(card, classes.QuestionInput{Type: str(models.TypeSingle), Answers: &toSingle, AnswerText: str("")})
|
||||||
|
if len(problems) != 0 || merged.Type != models.TypeSingle || merged.AnswerText != nil {
|
||||||
|
t.Errorf("self_check to single: %+v %v", merged, problems)
|
||||||
|
}
|
||||||
|
if problems := classes.CheckNewQuestion(classes.QuestionInput{Text: str("Q")}); !strings.Contains(strings.Join(problems, "; "), "type is required") {
|
||||||
|
t.Errorf("create without type: %v", problems)
|
||||||
|
}
|
||||||
|
withID := []classes.ManagedAnswerInput{{ID: uid(10), Text: "a", IsCorrect: true}, {Text: "b"}}
|
||||||
|
if problems := classes.CheckNewQuestion(classes.QuestionInput{Text: str("Q"), Type: str("single"), Answers: &withID}); !strings.Contains(strings.Join(problems, "; "), "does not belong") {
|
||||||
|
t.Errorf("create with an answer id: %v", problems)
|
||||||
|
}
|
||||||
|
if problems := classes.CheckNewQuestion(classes.QuestionInput{Text: str("Q"), Type: str("self_check")}); len(problems) != 0 {
|
||||||
|
t.Errorf("minimal self_check create: %v", problems)
|
||||||
|
}
|
||||||
|
|
||||||
|
open := models.Question{ID: 3, Text: "Esej", Type: models.TypeOpen, Points: 2, Rubric: str("Kryteria"), MaxLength: num(500)}
|
||||||
|
merged, problems = check(open, classes.QuestionInput{Text: str("Esej?")})
|
||||||
|
if len(problems) != 0 || merged.Rubric == nil || *merged.Rubric != "Kryteria" || merged.MaxLength == nil || *merged.MaxLength != 500 {
|
||||||
|
t.Errorf("open kept: %+v %v", merged, problems)
|
||||||
|
}
|
||||||
|
merged, problems = check(open, classes.QuestionInput{Rubric: str(""), MaxLength: num(0)})
|
||||||
|
if len(problems) != 0 || merged.Rubric != nil || merged.MaxLength != nil {
|
||||||
|
t.Errorf("open cleared: %+v %v", merged, problems)
|
||||||
|
}
|
||||||
|
if _, problems := check(open, classes.QuestionInput{MaxLength: num(20001)}); !strings.Contains(strings.Join(problems, "; "), "max_length must be between 1 and 20000") {
|
||||||
|
t.Errorf("open max_length 20001: %v", problems)
|
||||||
|
}
|
||||||
|
withAnswers := []classes.ManagedAnswerInput{{Text: "a", IsCorrect: true}}
|
||||||
|
if problems := classes.CheckNewQuestion(classes.QuestionInput{Text: str("Q"), Type: str("open"), Answers: &withAnswers}); !strings.Contains(strings.Join(problems, "; "), "an open question has no answers") {
|
||||||
|
t.Errorf("open create with answers: %v", problems)
|
||||||
|
}
|
||||||
|
if problems := classes.CheckNewQuestion(classes.QuestionInput{Text: str("Q"), Type: str("single"), Rubric: str("R"), Answers: &toSingle}); !strings.Contains(strings.Join(problems, "; "), "rubric applies to open questions only") {
|
||||||
|
t.Errorf("single with rubric: %v", problems)
|
||||||
|
}
|
||||||
|
if _, problems := check(open, classes.QuestionInput{Type: str(models.TypeSingle), Answers: &toSingle}); !strings.Contains(strings.Join(problems, "; "), "rubric applies to open questions only") {
|
||||||
|
t.Errorf("open to single keeping the rubric: %v", problems)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestCheckQuestionOrder: an empty list and a repeated id are refused
|
||||||
|
// before the database; a missing or foreign id is refused by
|
||||||
|
// ReorderQuestions against the quiz's questions.
|
||||||
|
func TestCheckQuestionOrder(t *testing.T) {
|
||||||
|
for _, ids := range [][]uint{nil, {}, {1, 2, 1}} {
|
||||||
|
if problems := classes.CheckQuestionOrder(ids); len(problems) != 1 {
|
||||||
|
t.Errorf("%v: %v, want one problem", ids, problems)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if problems := classes.CheckQuestionOrder([]uint{3, 1, 2}); len(problems) != 0 {
|
||||||
|
t.Errorf("valid order: %v", problems)
|
||||||
|
}
|
||||||
|
}
|
||||||
33
classes/open.go
Normal file
33
classes/open.go
Normal file
@@ -0,0 +1,33 @@
|
|||||||
|
package classes
|
||||||
|
|
||||||
|
import (
|
||||||
|
"strings"
|
||||||
|
"unicode/utf8"
|
||||||
|
|
||||||
|
"git.golem15.com/golem15/sm-quizzes-plugin/models"
|
||||||
|
)
|
||||||
|
|
||||||
|
// MaxLength is the longest answer an open question accepts, in characters:
|
||||||
|
// its MaxLength when set and positive, else models.DefaultMaxLength.
|
||||||
|
func MaxLength(q models.Question) int {
|
||||||
|
if q.MaxLength != nil && *q.MaxLength > 0 {
|
||||||
|
return *q.MaxLength
|
||||||
|
}
|
||||||
|
return models.DefaultMaxLength
|
||||||
|
}
|
||||||
|
|
||||||
|
// CheckOpenText cleans a student's answer to an open question (D-04): it
|
||||||
|
// removes every NUL character (Postgres text refuses them) and the
|
||||||
|
// surrounding whitespace. A blank text is a FieldError text_required and a
|
||||||
|
// text longer than MaxLength(q) characters (runes, not bytes) is a
|
||||||
|
// FieldError text_too_long.
|
||||||
|
func CheckOpenText(text string, q models.Question) (string, error) {
|
||||||
|
text = strings.TrimSpace(strings.ReplaceAll(text, "\x00", ""))
|
||||||
|
if text == "" {
|
||||||
|
return "", &FieldError{Field: "text", Key: "text_required"}
|
||||||
|
}
|
||||||
|
if utf8.RuneCountInString(text) > MaxLength(q) {
|
||||||
|
return "", &FieldError{Field: "text", Key: "text_too_long"}
|
||||||
|
}
|
||||||
|
return text, nil
|
||||||
|
}
|
||||||
59
classes/open_test.go
Normal file
59
classes/open_test.go
Normal file
@@ -0,0 +1,59 @@
|
|||||||
|
package classes_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"git.golem15.com/golem15/sm-quizzes-plugin/classes"
|
||||||
|
"git.golem15.com/golem15/sm-quizzes-plugin/models"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestCheckOpenText(t *testing.T) {
|
||||||
|
q := models.Question{Type: models.TypeOpen}
|
||||||
|
long := 3000
|
||||||
|
wide := models.Question{Type: models.TypeOpen, MaxLength: &long}
|
||||||
|
|
||||||
|
fieldKey := func(err error) string {
|
||||||
|
var fe *classes.FieldError
|
||||||
|
if errors.As(err, &fe) && fe.Field == "text" {
|
||||||
|
return fe.Key
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
if _, err := classes.CheckOpenText(" \n\t ", q); fieldKey(err) != "text_required" {
|
||||||
|
t.Errorf("blank text: err = %v, want text_required", err)
|
||||||
|
}
|
||||||
|
if _, err := classes.CheckOpenText("\x00 \x00", q); fieldKey(err) != "text_required" {
|
||||||
|
t.Errorf("NUL-only text: err = %v, want text_required", err)
|
||||||
|
}
|
||||||
|
over := strings.Repeat("a", 2001)
|
||||||
|
if _, err := classes.CheckOpenText(over, q); fieldKey(err) != "text_too_long" {
|
||||||
|
t.Errorf("2001 runes with default max: err = %v, want text_too_long", err)
|
||||||
|
}
|
||||||
|
if got, err := classes.CheckOpenText(over, wide); err != nil || got != over {
|
||||||
|
t.Errorf("2001 runes with max 3000: %q, %v", got[:10], err)
|
||||||
|
}
|
||||||
|
if got, err := classes.CheckOpenText("a\x00b", q); err != nil || got != "ab" {
|
||||||
|
t.Errorf("NUL stripped: %q, %v; want ab", got, err)
|
||||||
|
}
|
||||||
|
if got, err := classes.CheckOpenText(" moja odpowiedź \n", q); err != nil || got != "moja odpowiedź" {
|
||||||
|
t.Errorf("trimmed: %q, %v", got, err)
|
||||||
|
}
|
||||||
|
polish := strings.Repeat("ż", 2000)
|
||||||
|
if got, err := classes.CheckOpenText(polish, q); err != nil || got != polish {
|
||||||
|
t.Errorf("2000 runes of ż (4000 bytes) refused: %v", err)
|
||||||
|
}
|
||||||
|
five := 5
|
||||||
|
if _, err := classes.CheckOpenText("abcdef", models.Question{MaxLength: &five}); fieldKey(err) != "text_too_long" {
|
||||||
|
t.Errorf("6 runes with max 5: err = %v, want text_too_long", err)
|
||||||
|
}
|
||||||
|
if classes.MaxLength(q) != models.DefaultMaxLength || classes.MaxLength(wide) != 3000 {
|
||||||
|
t.Errorf("MaxLength = %d / %d", classes.MaxLength(q), classes.MaxLength(wide))
|
||||||
|
}
|
||||||
|
zero := 0
|
||||||
|
if classes.MaxLength(models.Question{MaxLength: &zero}) != models.DefaultMaxLength {
|
||||||
|
t.Error("MaxLength of a non-positive value should fall back to the default")
|
||||||
|
}
|
||||||
|
}
|
||||||
154
classes/policy.go
Normal file
154
classes/policy.go
Normal file
@@ -0,0 +1,154 @@
|
|||||||
|
package classes
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"math"
|
||||||
|
"strconv"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"git.golem15.com/golem15/sm-quizzes-plugin/models"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/compass"
|
||||||
|
)
|
||||||
|
|
||||||
|
// IsTest reports whether the quiz runs as a test. A zero or unknown mode is
|
||||||
|
// learning, so a quiz written before test mode existed keeps its behaviour.
|
||||||
|
func IsTest(q *models.Quiz) bool { return q != nil && q.Mode == models.ModeTest }
|
||||||
|
|
||||||
|
// Withheld reports whether an attempt's solutions must stay hidden: it is
|
||||||
|
// an attempt at a test that is not finished yet. Every student serializer
|
||||||
|
// drops is_correct, points, correct answers, explanations and model answers
|
||||||
|
// while it is true.
|
||||||
|
func Withheld(a *models.Attempt) bool {
|
||||||
|
return a != nil && IsTest(a.Quiz) && a.CompletedAt == nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// OneWay reports whether a test's answers are final: navigation one_way.
|
||||||
|
// Learning quizzes ignore the navigation setting.
|
||||||
|
func OneWay(q *models.Quiz) bool { return IsTest(q) && q.Navigation == models.NavigationOneWay }
|
||||||
|
|
||||||
|
// DefaultTestGrace is the test grace without a golem15.quizzes.test.grace_seconds setting.
|
||||||
|
const DefaultTestGrace = 5 * time.Second
|
||||||
|
|
||||||
|
// maxTestGrace caps the configured grace.
|
||||||
|
const maxTestGrace = 120 * time.Second
|
||||||
|
|
||||||
|
// TestGraceFrom reads golem15.quizzes.test.grace_seconds: how long after a
|
||||||
|
// test's deadline an answer in flight is still accepted. A nil config, a
|
||||||
|
// missing key or a value that is not a number give DefaultTestGrace; the
|
||||||
|
// value is clamped to 0..120 seconds. Learning quizzes have no grace.
|
||||||
|
func TestGraceFrom(cfg *compass.Config) time.Duration {
|
||||||
|
if cfg == nil {
|
||||||
|
return DefaultTestGrace
|
||||||
|
}
|
||||||
|
v, ok := cfg.Lookup("golem15.quizzes.test.grace_seconds")
|
||||||
|
if !ok {
|
||||||
|
return DefaultTestGrace
|
||||||
|
}
|
||||||
|
secs, ok := number(v)
|
||||||
|
if !ok {
|
||||||
|
return DefaultTestGrace
|
||||||
|
}
|
||||||
|
grace := time.Duration(secs * float64(time.Second))
|
||||||
|
return min(max(grace, 0), maxTestGrace)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Default per-user rate limits of the student write routes, per minute. In
|
||||||
|
// a learning quiz with a grader every new or changed open answer is a paid
|
||||||
|
// grading call, so answering and starting attempts are throttled (WR-03).
|
||||||
|
const (
|
||||||
|
DefaultAnswersPerMinute = 60
|
||||||
|
DefaultAttemptsPerMinute = 10
|
||||||
|
)
|
||||||
|
|
||||||
|
// maxPerMinute caps a configured per-minute limit.
|
||||||
|
const maxPerMinute = 10000
|
||||||
|
|
||||||
|
// PerMinuteFrom reads a per-minute rate limit at key (for example
|
||||||
|
// golem15.quizzes.throttle.answers_per_minute). A nil config, a missing
|
||||||
|
// key or a value that is not a number of at least 1 give def; the value
|
||||||
|
// is truncated to a whole number and capped at 10000.
|
||||||
|
func PerMinuteFrom(cfg *compass.Config, key string, def int) int {
|
||||||
|
if cfg == nil {
|
||||||
|
return def
|
||||||
|
}
|
||||||
|
v, ok := cfg.Lookup(key)
|
||||||
|
if !ok {
|
||||||
|
return def
|
||||||
|
}
|
||||||
|
n, ok := number(v)
|
||||||
|
if !ok || n < 1 || math.IsInf(n, 0) {
|
||||||
|
return def
|
||||||
|
}
|
||||||
|
return int(min(n, maxPerMinute))
|
||||||
|
}
|
||||||
|
|
||||||
|
// number is v as a float when it is a number or a numeric string.
|
||||||
|
func number(v any) (float64, bool) {
|
||||||
|
switch n := v.(type) {
|
||||||
|
case float64:
|
||||||
|
return n, !math.IsNaN(n)
|
||||||
|
case float32:
|
||||||
|
return float64(n), true
|
||||||
|
case int:
|
||||||
|
return float64(n), true
|
||||||
|
case int64:
|
||||||
|
return float64(n), true
|
||||||
|
case uint64:
|
||||||
|
return float64(n), true
|
||||||
|
case string:
|
||||||
|
f, err := strconv.ParseFloat(n, 64)
|
||||||
|
return f, err == nil && !math.IsNaN(f)
|
||||||
|
}
|
||||||
|
return 0, false
|
||||||
|
}
|
||||||
|
|
||||||
|
// AnswerDeadline is the last moment an answer to the attempt is accepted:
|
||||||
|
// the Deadline plus grace for a test, the Deadline itself for a learning
|
||||||
|
// quiz, nil without a time limit.
|
||||||
|
func AnswerDeadline(a *models.Attempt, grace time.Duration) *time.Time {
|
||||||
|
d := Deadline(a)
|
||||||
|
if d == nil || !IsTest(a.Quiz) {
|
||||||
|
return d
|
||||||
|
}
|
||||||
|
t := d.Add(grace)
|
||||||
|
return &t
|
||||||
|
}
|
||||||
|
|
||||||
|
// Expired reports whether an open test attempt is past its answer deadline,
|
||||||
|
// so it can be closed at its Deadline. Learning and completed attempts never
|
||||||
|
// expire this way.
|
||||||
|
func Expired(a *models.Attempt, now time.Time, grace time.Duration) bool {
|
||||||
|
if a == nil || !IsTest(a.Quiz) || a.CompletedAt != nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
d := AnswerDeadline(a, grace)
|
||||||
|
return d != nil && now.After(*d)
|
||||||
|
}
|
||||||
|
|
||||||
|
// SecondsLeft is the whole seconds until the attempt's Deadline, rounded up
|
||||||
|
// and floored at 0, or nil without a time limit or once completed. The
|
||||||
|
// player runs its countdown from it, not from the client clock.
|
||||||
|
func SecondsLeft(a *models.Attempt, now time.Time) *int {
|
||||||
|
d := Deadline(a)
|
||||||
|
if d == nil || a.CompletedAt != nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
left := max(int(math.Ceil(d.Sub(now).Seconds())), 0)
|
||||||
|
return &left
|
||||||
|
}
|
||||||
|
|
||||||
|
// AttemptsLeft is how many attempts the user may still start: nil for a
|
||||||
|
// learning quiz or a test without a limit, otherwise max(0, limit - used).
|
||||||
|
func AttemptsLeft(q *models.Quiz, used int) *int {
|
||||||
|
if !IsTest(q) || q.MaxAttempts == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
left := max(*q.MaxAttempts-used, 0)
|
||||||
|
return &left
|
||||||
|
}
|
||||||
|
|
||||||
|
// AttemptLockKey names the advisory lock that serialises one user's test
|
||||||
|
// starts on one quiz.
|
||||||
|
func AttemptLockKey(quizID, userID uint) string {
|
||||||
|
return fmt.Sprintf("golem15.quizzes.attempt:%d:%d", quizID, userID)
|
||||||
|
}
|
||||||
148
classes/policy_test.go
Normal file
148
classes/policy_test.go
Normal file
@@ -0,0 +1,148 @@
|
|||||||
|
package classes_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"git.golem15.com/golem15/sm-quizzes-plugin/classes"
|
||||||
|
"git.golem15.com/golem15/sm-quizzes-plugin/models"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/compass"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestIsTestAndWithheld(t *testing.T) {
|
||||||
|
if classes.IsTest(nil) {
|
||||||
|
t.Error("IsTest(nil) = true")
|
||||||
|
}
|
||||||
|
for mode, want := range map[string]bool{"": false, models.ModeLearning: false, "exam": false, models.ModeTest: true} {
|
||||||
|
if got := classes.IsTest(&models.Quiz{Mode: mode}); got != want {
|
||||||
|
t.Errorf("IsTest(mode %q) = %v, want %v", mode, got, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
done := time.Now()
|
||||||
|
test, learning := &models.Quiz{Mode: models.ModeTest}, &models.Quiz{Mode: models.ModeLearning}
|
||||||
|
cases := []struct {
|
||||||
|
name string
|
||||||
|
a *models.Attempt
|
||||||
|
want bool
|
||||||
|
}{
|
||||||
|
{"open test", &models.Attempt{Quiz: test}, true},
|
||||||
|
{"completed test", &models.Attempt{Quiz: test, CompletedAt: &done}, false},
|
||||||
|
{"open learning", &models.Attempt{Quiz: learning}, false},
|
||||||
|
{"zero mode", &models.Attempt{Quiz: &models.Quiz{}}, false},
|
||||||
|
{"nil attempt", nil, false},
|
||||||
|
{"nil quiz", &models.Attempt{}, false},
|
||||||
|
}
|
||||||
|
for _, tc := range cases {
|
||||||
|
if got := classes.Withheld(tc.a); got != tc.want {
|
||||||
|
t.Errorf("Withheld(%s) = %v, want %v", tc.name, got, tc.want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestTestRules(t *testing.T) {
|
||||||
|
limit, two := 60, 2
|
||||||
|
start := time.Date(2026, 11, 9, 10, 0, 0, 0, time.UTC)
|
||||||
|
test := &models.Quiz{Mode: models.ModeTest, TimeLimitSeconds: &limit}
|
||||||
|
learning := &models.Quiz{Mode: models.ModeLearning, TimeLimitSeconds: &limit}
|
||||||
|
grace := 5 * time.Second
|
||||||
|
open := &models.Attempt{StartedAt: start, Quiz: test}
|
||||||
|
deadline := start.Add(60 * time.Second)
|
||||||
|
|
||||||
|
if d := classes.AnswerDeadline(open, grace); d == nil || !d.Equal(deadline.Add(grace)) {
|
||||||
|
t.Errorf("test AnswerDeadline = %v, want deadline + grace", d)
|
||||||
|
}
|
||||||
|
if d := classes.AnswerDeadline(&models.Attempt{StartedAt: start, Quiz: learning}, grace); d == nil || !d.Equal(deadline) {
|
||||||
|
t.Errorf("learning AnswerDeadline = %v, want the deadline itself", d)
|
||||||
|
}
|
||||||
|
if classes.AnswerDeadline(&models.Attempt{StartedAt: start, Quiz: &models.Quiz{Mode: models.ModeTest}}, grace) != nil {
|
||||||
|
t.Error("AnswerDeadline without a time limit is set")
|
||||||
|
}
|
||||||
|
|
||||||
|
if classes.Expired(open, deadline.Add(4*time.Second), grace) {
|
||||||
|
t.Error("test attempt expired inside the grace")
|
||||||
|
}
|
||||||
|
if !classes.Expired(open, deadline.Add(6*time.Second), grace) {
|
||||||
|
t.Error("test attempt past deadline + grace did not expire")
|
||||||
|
}
|
||||||
|
if classes.Expired(&models.Attempt{StartedAt: start, Quiz: learning}, deadline.Add(time.Hour), grace) {
|
||||||
|
t.Error("learning attempt expired")
|
||||||
|
}
|
||||||
|
done := deadline
|
||||||
|
if classes.Expired(&models.Attempt{StartedAt: start, Quiz: test, CompletedAt: &done}, deadline.Add(time.Hour), grace) {
|
||||||
|
t.Error("completed attempt expired")
|
||||||
|
}
|
||||||
|
if classes.Expired(&models.Attempt{StartedAt: start, Quiz: &models.Quiz{Mode: models.ModeTest}}, deadline.Add(time.Hour), grace) {
|
||||||
|
t.Error("attempt without a time limit expired")
|
||||||
|
}
|
||||||
|
|
||||||
|
if got := classes.SecondsLeft(open, start.Add(500*time.Millisecond)); got == nil || *got != 60 {
|
||||||
|
t.Errorf("SecondsLeft at +0.5s = %v, want 60 (rounded up)", got)
|
||||||
|
}
|
||||||
|
if got := classes.SecondsLeft(open, start.Add(59*time.Second)); got == nil || *got != 1 {
|
||||||
|
t.Errorf("SecondsLeft at +59s = %v, want 1", got)
|
||||||
|
}
|
||||||
|
if got := classes.SecondsLeft(open, deadline.Add(time.Minute)); got == nil || *got != 0 {
|
||||||
|
t.Errorf("SecondsLeft after the deadline = %v, want 0", got)
|
||||||
|
}
|
||||||
|
if classes.SecondsLeft(&models.Attempt{StartedAt: start, Quiz: &models.Quiz{}}, start) != nil {
|
||||||
|
t.Error("SecondsLeft without a time limit is set")
|
||||||
|
}
|
||||||
|
if classes.SecondsLeft(&models.Attempt{StartedAt: start, Quiz: test, CompletedAt: &done}, start) != nil {
|
||||||
|
t.Error("SecondsLeft of a completed attempt is set")
|
||||||
|
}
|
||||||
|
|
||||||
|
if classes.AttemptsLeft(&models.Quiz{Mode: models.ModeLearning, MaxAttempts: &two}, 1) != nil {
|
||||||
|
t.Error("AttemptsLeft of a learning quiz is set")
|
||||||
|
}
|
||||||
|
if classes.AttemptsLeft(&models.Quiz{Mode: models.ModeTest}, 1) != nil {
|
||||||
|
t.Error("AttemptsLeft of an unlimited test is set")
|
||||||
|
}
|
||||||
|
for used, want := range map[int]int{0: 2, 1: 1, 2: 0, 3: 0} {
|
||||||
|
if got := classes.AttemptsLeft(&models.Quiz{Mode: models.ModeTest, MaxAttempts: &two}, used); got == nil || *got != want {
|
||||||
|
t.Errorf("AttemptsLeft(max 2, used %d) = %v, want %d", used, got, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tc := range []struct {
|
||||||
|
q *models.Quiz
|
||||||
|
want bool
|
||||||
|
}{
|
||||||
|
{&models.Quiz{Mode: models.ModeTest, Navigation: models.NavigationOneWay}, true},
|
||||||
|
{&models.Quiz{Mode: models.ModeTest, Navigation: models.NavigationFree}, false},
|
||||||
|
{&models.Quiz{Mode: models.ModeLearning, Navigation: models.NavigationOneWay}, false},
|
||||||
|
{nil, false},
|
||||||
|
} {
|
||||||
|
if got := classes.OneWay(tc.q); got != tc.want {
|
||||||
|
t.Errorf("OneWay(%+v) = %v, want %v", tc.q, got, tc.want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if got := classes.AttemptLockKey(3, 7); got != "golem15.quizzes.attempt:3:7" {
|
||||||
|
t.Errorf("AttemptLockKey = %q", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestTestGraceFrom(t *testing.T) {
|
||||||
|
if got := classes.TestGraceFrom(nil); got != 5*time.Second || classes.DefaultTestGrace != 5*time.Second {
|
||||||
|
t.Errorf("nil config = %v, want 5s", got)
|
||||||
|
}
|
||||||
|
dir := t.TempDir()
|
||||||
|
cfg, err := compass.Open(compass.Options{Dir: dir, Env: "testing", Environ: []string{}})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if got := classes.TestGraceFrom(cfg); got != 5*time.Second {
|
||||||
|
t.Errorf("missing key = %v, want 5s", got)
|
||||||
|
}
|
||||||
|
for _, tc := range []struct {
|
||||||
|
value any
|
||||||
|
want time.Duration
|
||||||
|
}{{0, 0}, {30, 30 * time.Second}, {"x", 5 * time.Second}, {900, 120 * time.Second}, {-1, 0}, {"10", 10 * time.Second}} {
|
||||||
|
if err := cfg.Set("golem15.quizzes.test.grace_seconds", tc.value); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if got := classes.TestGraceFrom(cfg); got != tc.want {
|
||||||
|
t.Errorf("grace_seconds %v = %v, want %v", tc.value, got, tc.want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
864
classes/review.go
Normal file
864
classes/review.go
Normal file
@@ -0,0 +1,864 @@
|
|||||||
|
package classes
|
||||||
|
|
||||||
|
// The owner's review queue of open answers: one service shared by the MCP
|
||||||
|
// review routes (/api/v1/quiz-reviews) and the admin "Do oceny" screen.
|
||||||
|
// Reviewers hold the golem15.quizzes.access_quizzes permission (D-13); the
|
||||||
|
// routes and the admin controller check it, this file trusts its caller.
|
||||||
|
//
|
||||||
|
// Every write runs in lagoon.Transaction on s.DB, so a Service whose DB is
|
||||||
|
// an outer transaction (an admin save) nests as a savepoint. A write locks
|
||||||
|
// the answer's attempt first, as grading does, recalculates a completed
|
||||||
|
// attempt and fires its events only after the commit (D-14).
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"math"
|
||||||
|
"slices"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
"unicode/utf8"
|
||||||
|
|
||||||
|
"git.golem15.com/golem15/sm-quizzes-plugin/events"
|
||||||
|
"git.golem15.com/golem15/sm-quizzes-plugin/models"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/lagoon"
|
||||||
|
"gorm.io/gorm"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Review status filters besides the grading statuses themselves.
|
||||||
|
const (
|
||||||
|
// ReviewStatusOpen is every answer the owner has not reviewed yet:
|
||||||
|
// pending, graded and failed, except those of a test attempt that is
|
||||||
|
// still running. It is the default filter.
|
||||||
|
ReviewStatusOpen = "open"
|
||||||
|
// ReviewStatusAll lists every open answer, reviewed ones included.
|
||||||
|
ReviewStatusAll = "all"
|
||||||
|
)
|
||||||
|
|
||||||
|
// ReviewExcerptRunes is how much of a student's text a queue row shows.
|
||||||
|
const ReviewExcerptRunes = 300
|
||||||
|
|
||||||
|
// MaxReviewComment is the longest comment to the student, in runes.
|
||||||
|
const MaxReviewComment = 2000
|
||||||
|
|
||||||
|
// Errors of the review actions, answered as 409s with a code.
|
||||||
|
var (
|
||||||
|
// ErrNoGraderScore is a confirm of an answer that has no grader score:
|
||||||
|
// it is pending or failed, so the owner sets the score instead.
|
||||||
|
ErrNoGraderScore = errors.New("quizzes: the answer has no grader score to confirm")
|
||||||
|
// ErrAlreadyReviewed is a regrade of one answer the owner already
|
||||||
|
// reviewed: owner decisions are final (D-12).
|
||||||
|
ErrAlreadyReviewed = errors.New("quizzes: the answer is already reviewed")
|
||||||
|
// ErrGraderManual is a regrade on a quiz whose grader is manual or not
|
||||||
|
// registered by any activated plugin.
|
||||||
|
ErrGraderManual = errors.New("quizzes: the quiz has no grader that can grade again")
|
||||||
|
// ErrAttemptOpen is a review write on an answer of a test attempt that
|
||||||
|
// is still running: a test's results, the owner's review included, come
|
||||||
|
// only after it ends (Phase 7 D-07, D-08).
|
||||||
|
ErrAttemptOpen = errors.New("quizzes: the test attempt is still open")
|
||||||
|
)
|
||||||
|
|
||||||
|
// ReviewFilter narrows the review queue. Zero values do not filter; Status
|
||||||
|
// is one CheckReviewStatus accepts.
|
||||||
|
type ReviewFilter struct {
|
||||||
|
QuizSlug string
|
||||||
|
Status string
|
||||||
|
UserID uint
|
||||||
|
AttemptID uint
|
||||||
|
}
|
||||||
|
|
||||||
|
// Reviewer is who reviews: a frontend user over MCP (UserID, the API
|
||||||
|
// token's user) or a backend administrator (AdminID). A zero id is stored
|
||||||
|
// as NULL (Pitfall 7: the two live in different tables).
|
||||||
|
type Reviewer struct {
|
||||||
|
UserID uint
|
||||||
|
AdminID uint
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r Reviewer) ids() (user, admin *uint) {
|
||||||
|
if r.UserID != 0 {
|
||||||
|
id := r.UserID
|
||||||
|
user = &id
|
||||||
|
}
|
||||||
|
if r.AdminID != 0 {
|
||||||
|
id := r.AdminID
|
||||||
|
admin = &id
|
||||||
|
}
|
||||||
|
return user, admin
|
||||||
|
}
|
||||||
|
|
||||||
|
// ReviewScope picks the open answers of a bulk action: one answer, one
|
||||||
|
// attempt or one quiz (by slug). Exactly one is set; see CheckReviewScope.
|
||||||
|
type ReviewScope struct {
|
||||||
|
AnswerID uint
|
||||||
|
AttemptID uint
|
||||||
|
QuizSlug string
|
||||||
|
}
|
||||||
|
|
||||||
|
// CheckReviewScope requires exactly one of the scope's keys: answer_id,
|
||||||
|
// attempt_id or quiz when allowAnswer (regrade), attempt_id or quiz
|
||||||
|
// otherwise (bulk confirm).
|
||||||
|
func CheckReviewScope(scope ReviewScope, allowAnswer bool) []string {
|
||||||
|
n := 0
|
||||||
|
if scope.AttemptID != 0 {
|
||||||
|
n++
|
||||||
|
}
|
||||||
|
if strings.TrimSpace(scope.QuizSlug) != "" {
|
||||||
|
n++
|
||||||
|
}
|
||||||
|
if scope.AnswerID != 0 {
|
||||||
|
if !allowAnswer {
|
||||||
|
return []string{"exactly one of attempt_id and quiz is required"}
|
||||||
|
}
|
||||||
|
n++
|
||||||
|
}
|
||||||
|
if n == 1 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if allowAnswer {
|
||||||
|
return []string{"exactly one of answer_id, attempt_id and quiz is required"}
|
||||||
|
}
|
||||||
|
return []string{"exactly one of attempt_id and quiz is required"}
|
||||||
|
}
|
||||||
|
|
||||||
|
// CheckReviewPoints reports whether points is a score the owner may give a
|
||||||
|
// question worth maxPoints: finite, 0..maxPoints (a negative maxPoints
|
||||||
|
// counts as 0) and a multiple of 0.5.
|
||||||
|
func CheckReviewPoints(points float64, maxPoints int) bool {
|
||||||
|
if math.IsNaN(points) || math.IsInf(points, 0) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
full := float64(max(maxPoints, 0))
|
||||||
|
return points >= 0 && points <= full && points*2 == math.Trunc(points*2)
|
||||||
|
}
|
||||||
|
|
||||||
|
// CheckReviewComment cleans the owner's comment to the student: trimmed,
|
||||||
|
// NUL bytes dropped, and nil when nothing is left. More than
|
||||||
|
// MaxReviewComment runes is a problem.
|
||||||
|
func CheckReviewComment(comment *string) (*string, []string) {
|
||||||
|
if comment == nil {
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
c := strings.TrimSpace(strings.ReplaceAll(*comment, "\x00", ""))
|
||||||
|
if c == "" {
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
if utf8.RuneCountInString(c) > MaxReviewComment {
|
||||||
|
return nil, []string{"comment must be at most " + strconv.Itoa(MaxReviewComment) + " characters"}
|
||||||
|
}
|
||||||
|
return &c, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// unreviewedStatuses are the grading statuses the owner still has to act
|
||||||
|
// on.
|
||||||
|
func unreviewedStatuses() []string {
|
||||||
|
return []string{models.GradingPending, models.GradingGraded, models.GradingFailed}
|
||||||
|
}
|
||||||
|
|
||||||
|
// CheckReviewStatus maps a status filter to the grading statuses to list:
|
||||||
|
// "" and open give pending, graded and failed, a grading status gives
|
||||||
|
// itself and all gives nil (no filter). Anything else is a problem naming
|
||||||
|
// the valid values.
|
||||||
|
func CheckReviewStatus(status string) ([]string, []string) {
|
||||||
|
status = strings.TrimSpace(status)
|
||||||
|
switch status {
|
||||||
|
case "", ReviewStatusOpen:
|
||||||
|
return unreviewedStatuses(), nil
|
||||||
|
case ReviewStatusAll:
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
if slices.Contains(models.GradingStatuses, status) {
|
||||||
|
return []string{status}, nil
|
||||||
|
}
|
||||||
|
return nil, []string{"status must be one of open, pending, graded, failed, reviewed, all"}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ReviewRow is one open answer of the review queue. In a queue row Text is
|
||||||
|
// cut to ReviewExcerptRunes+1 runes, enough to tell that it was cut; the
|
||||||
|
// detail carries the whole text.
|
||||||
|
type ReviewRow struct {
|
||||||
|
AnswerID uint
|
||||||
|
Status string
|
||||||
|
QuizID uint
|
||||||
|
QuizSlug string
|
||||||
|
QuizTitle string
|
||||||
|
QuizMode string
|
||||||
|
QuestionID uint
|
||||||
|
QuestionText string
|
||||||
|
QuestionPoints int
|
||||||
|
AttemptID uint
|
||||||
|
AttemptCompletedAt *time.Time
|
||||||
|
UserID uint
|
||||||
|
Email string
|
||||||
|
Name *string
|
||||||
|
Surname *string
|
||||||
|
Text string
|
||||||
|
GraderPoints *float64
|
||||||
|
Points float64
|
||||||
|
GradedAt *time.Time
|
||||||
|
ReviewedAt *time.Time
|
||||||
|
UpdatedAt time.Time
|
||||||
|
}
|
||||||
|
|
||||||
|
// ReviewDetail is one open answer with everything the owner reviews it
|
||||||
|
// against: the model answer and the rubric (owner-only), the grader's
|
||||||
|
// result or error and the review so far. MaxLength is the question's
|
||||||
|
// effective limit.
|
||||||
|
type ReviewDetail struct {
|
||||||
|
ReviewRow
|
||||||
|
AnswerText *string
|
||||||
|
Rubric *string
|
||||||
|
MaxLength int
|
||||||
|
Grader *string
|
||||||
|
GraderFeedback *string
|
||||||
|
GradingError *string
|
||||||
|
ReviewComment *string
|
||||||
|
GradingAttempts int
|
||||||
|
IsCorrect bool
|
||||||
|
ReviewedByUserID *uint
|
||||||
|
ReviewedByAdminID *uint
|
||||||
|
}
|
||||||
|
|
||||||
|
// reviewFromSQL joins an open answer to its question, attempt, quiz and
|
||||||
|
// student. Only open answers (a grading status) are in the queue.
|
||||||
|
const reviewFromSQL = `
|
||||||
|
FROM golem15_quizzes_attempt_answers aa
|
||||||
|
JOIN golem15_quizzes_questions q ON q.id = aa.question_id
|
||||||
|
JOIN golem15_quizzes_attempts a ON a.id = aa.attempt_id
|
||||||
|
JOIN golem15_quizzes_quizzes qz ON qz.id = a.quiz_id
|
||||||
|
JOIN users u ON u.id = a.user_id
|
||||||
|
WHERE aa.grading_status IS NOT NULL`
|
||||||
|
|
||||||
|
// reviewRowColumnsSQL are the columns of a ReviewRow but the text.
|
||||||
|
const reviewRowColumnsSQL = `aa.id AS answer_id, aa.grading_status AS status,
|
||||||
|
qz.id AS quiz_id, qz.slug AS quiz_slug, qz.title AS quiz_title, qz.mode AS quiz_mode,
|
||||||
|
q.id AS question_id, q.text AS question_text, q.points AS question_points,
|
||||||
|
a.id AS attempt_id, a.completed_at AS attempt_completed_at,
|
||||||
|
a.user_id AS user_id, COALESCE(u.email, '') AS email, u.name AS name, u.surname AS surname,
|
||||||
|
aa.grader_points AS grader_points, aa.points AS points,
|
||||||
|
aa.graded_at AS graded_at, aa.reviewed_at AS reviewed_at, aa.updated_at AS updated_at`
|
||||||
|
|
||||||
|
// reviewQueueSQL selects the queue rows; the filter predicates, the order
|
||||||
|
// and the page are appended as bound parameters.
|
||||||
|
const reviewQueueSQL = `SELECT ` + reviewRowColumnsSQL + `,
|
||||||
|
LEFT(COALESCE(aa.text_answer, ''), 301) AS text` + reviewFromSQL
|
||||||
|
|
||||||
|
// reviewDetailSQL selects one open answer by id with the detail columns.
|
||||||
|
const reviewDetailSQL = `SELECT ` + reviewRowColumnsSQL + `,
|
||||||
|
COALESCE(aa.text_answer, '') AS text,
|
||||||
|
q.answer_text AS answer_text, q.rubric AS rubric, q.max_length AS max_length,
|
||||||
|
aa.grader AS grader, aa.grader_feedback AS grader_feedback, aa.grading_error AS grading_error,
|
||||||
|
aa.review_comment AS review_comment, aa.grading_attempts AS grading_attempts,
|
||||||
|
aa.is_correct AS is_correct,
|
||||||
|
aa.reviewed_by_user_id AS reviewed_by_user_id, aa.reviewed_by_admin_id AS reviewed_by_admin_id` +
|
||||||
|
reviewFromSQL + ` AND aa.id = ?`
|
||||||
|
|
||||||
|
// reviewScan is what the review queries scan into.
|
||||||
|
type reviewScan struct {
|
||||||
|
ReviewRow
|
||||||
|
AnswerText *string
|
||||||
|
Rubric *string
|
||||||
|
MaxLength *int
|
||||||
|
Grader *string
|
||||||
|
GraderFeedback *string
|
||||||
|
GradingError *string
|
||||||
|
ReviewComment *string
|
||||||
|
GradingAttempts int
|
||||||
|
IsCorrect bool
|
||||||
|
ReviewedByUserID *uint
|
||||||
|
ReviewedByAdminID *uint
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r reviewScan) detail() *ReviewDetail {
|
||||||
|
maxLength := models.DefaultMaxLength
|
||||||
|
if r.MaxLength != nil {
|
||||||
|
maxLength = *r.MaxLength
|
||||||
|
}
|
||||||
|
return &ReviewDetail{
|
||||||
|
ReviewRow: r.ReviewRow,
|
||||||
|
AnswerText: r.AnswerText,
|
||||||
|
Rubric: r.Rubric,
|
||||||
|
MaxLength: maxLength,
|
||||||
|
Grader: r.Grader,
|
||||||
|
GraderFeedback: r.GraderFeedback,
|
||||||
|
GradingError: r.GradingError,
|
||||||
|
ReviewComment: r.ReviewComment,
|
||||||
|
GradingAttempts: r.GradingAttempts,
|
||||||
|
IsCorrect: r.IsCorrect,
|
||||||
|
ReviewedByUserID: r.ReviewedByUserID,
|
||||||
|
ReviewedByAdminID: r.ReviewedByAdminID,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// reviewWhere turns a filter into predicates appended to reviewFromSQL.
|
||||||
|
// The default open filter leaves out the answers of a test attempt that is
|
||||||
|
// still running: they cannot be reviewed until it ends (ErrAttemptOpen).
|
||||||
|
func reviewWhere(f ReviewFilter, statuses []string) (string, []any) {
|
||||||
|
var b strings.Builder
|
||||||
|
var args []any
|
||||||
|
if statuses != nil {
|
||||||
|
b.WriteString(" AND aa.grading_status IN ?")
|
||||||
|
args = append(args, statuses)
|
||||||
|
}
|
||||||
|
if status := strings.TrimSpace(f.Status); status == "" || status == ReviewStatusOpen {
|
||||||
|
b.WriteString(" AND NOT (qz.mode = ? AND a.completed_at IS NULL)")
|
||||||
|
args = append(args, models.ModeTest)
|
||||||
|
}
|
||||||
|
if slug := strings.TrimSpace(f.QuizSlug); slug != "" {
|
||||||
|
b.WriteString(" AND qz.slug = ?")
|
||||||
|
args = append(args, slug)
|
||||||
|
}
|
||||||
|
if f.UserID != 0 {
|
||||||
|
b.WriteString(" AND a.user_id = ?")
|
||||||
|
args = append(args, f.UserID)
|
||||||
|
}
|
||||||
|
if f.AttemptID != 0 {
|
||||||
|
b.WriteString(" AND aa.attempt_id = ?")
|
||||||
|
args = append(args, f.AttemptID)
|
||||||
|
}
|
||||||
|
return b.String(), args
|
||||||
|
}
|
||||||
|
|
||||||
|
// ReviewQueue lists the open answers matching f, oldest change first, one
|
||||||
|
// page at a time (perPage 1..100, default 20), with the total count. An
|
||||||
|
// invalid status is a *ValidationError.
|
||||||
|
func (s *Service) ReviewQueue(ctx context.Context, f ReviewFilter, page, perPage int) ([]ReviewRow, int64, error) {
|
||||||
|
statuses, problems := CheckReviewStatus(f.Status)
|
||||||
|
if len(problems) > 0 {
|
||||||
|
return nil, 0, &ValidationError{Problems: problems}
|
||||||
|
}
|
||||||
|
if page < 1 {
|
||||||
|
page = 1
|
||||||
|
}
|
||||||
|
if perPage < 1 {
|
||||||
|
perPage = 20
|
||||||
|
}
|
||||||
|
perPage = min(perPage, 100)
|
||||||
|
where, args := reviewWhere(f, statuses)
|
||||||
|
var total int64
|
||||||
|
if err := s.db(ctx).Raw("SELECT COUNT(*)"+reviewFromSQL+where, args...).Scan(&total).Error; err != nil {
|
||||||
|
return nil, 0, err
|
||||||
|
}
|
||||||
|
var scans []reviewScan
|
||||||
|
q := reviewQueueSQL + where + " ORDER BY aa.updated_at ASC, aa.id ASC LIMIT ? OFFSET ?"
|
||||||
|
if err := s.db(ctx).Raw(q, append(args, perPage, (page-1)*perPage)...).Scan(&scans).Error; err != nil {
|
||||||
|
return nil, 0, err
|
||||||
|
}
|
||||||
|
out := make([]ReviewRow, 0, len(scans))
|
||||||
|
for _, sc := range scans {
|
||||||
|
out = append(out, sc.ReviewRow)
|
||||||
|
}
|
||||||
|
return out, total, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ReviewItem loads one open answer with its detail. A missing answer, or
|
||||||
|
// one that is not an open answer, is ErrNotFound.
|
||||||
|
func (s *Service) ReviewItem(ctx context.Context, answerID uint) (*ReviewDetail, error) {
|
||||||
|
return reviewItem(ctx, s.db(ctx), answerID)
|
||||||
|
}
|
||||||
|
|
||||||
|
func reviewItem(ctx context.Context, db *gorm.DB, answerID uint) (*ReviewDetail, error) {
|
||||||
|
var scans []reviewScan
|
||||||
|
if err := db.WithContext(ctx).Raw(reviewDetailSQL, answerID).Scan(&scans).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if len(scans) == 0 {
|
||||||
|
return nil, ErrNotFound
|
||||||
|
}
|
||||||
|
return scans[0].detail(), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// reviewTarget is an open answer loaded for a review write, with its
|
||||||
|
// question and its attempt (quiz set); the attempt row is locked.
|
||||||
|
type reviewTarget struct {
|
||||||
|
Answer models.AttemptAnswer
|
||||||
|
Question models.Question
|
||||||
|
Attempt *models.Attempt
|
||||||
|
}
|
||||||
|
|
||||||
|
// lockReviewTarget locks the attempt of an open answer and reads the
|
||||||
|
// answer again under the lock, so a grading job or a re-answer cannot
|
||||||
|
// change it in between. A missing answer or attempt, or an answer that is
|
||||||
|
// not open, is ErrNotFound; an answer of a test attempt that is still
|
||||||
|
// running is ErrAttemptOpen.
|
||||||
|
func lockReviewTarget(ctx context.Context, tx *gorm.DB, answerID uint) (*reviewTarget, error) {
|
||||||
|
tx = tx.WithContext(ctx)
|
||||||
|
var row models.AttemptAnswer
|
||||||
|
if err := tx.Where("id = ? AND grading_status IS NOT NULL", answerID).Take(&row).Error; err != nil {
|
||||||
|
return nil, notFound(err)
|
||||||
|
}
|
||||||
|
attempt, err := lockAttempt(ctx, tx, row.AttemptID)
|
||||||
|
if err != nil {
|
||||||
|
return nil, notFound(err)
|
||||||
|
}
|
||||||
|
if err := tx.Where("id = ? AND grading_status IS NOT NULL", answerID).Take(&row).Error; err != nil {
|
||||||
|
return nil, notFound(err)
|
||||||
|
}
|
||||||
|
var quiz models.Quiz
|
||||||
|
if err := tx.Where("id = ?", attempt.QuizID).Take(&quiz).Error; err != nil {
|
||||||
|
return nil, notFound(err)
|
||||||
|
}
|
||||||
|
attempt.Quiz = &quiz
|
||||||
|
if Withheld(attempt) {
|
||||||
|
return nil, ErrAttemptOpen
|
||||||
|
}
|
||||||
|
var question models.Question
|
||||||
|
if err := tx.Where("id = ?", row.QuestionID).Take(&question).Error; err != nil {
|
||||||
|
return nil, notFound(err)
|
||||||
|
}
|
||||||
|
return &reviewTarget{Answer: row, Question: question, Attempt: attempt}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// notFound maps gorm.ErrRecordNotFound to ErrNotFound.
|
||||||
|
func notFound(err error) error {
|
||||||
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||||
|
return ErrNotFound
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// Confirm makes the grader's score of a graded answer final: status
|
||||||
|
// reviewed, points = grader_points (D-12), clamped again to the question's
|
||||||
|
// current points. A reviewed answer is returned
|
||||||
|
// unchanged, without a write or an event; a pending or failed answer has
|
||||||
|
// no score to confirm (ErrNoGraderScore). A completed attempt is
|
||||||
|
// recalculated, and AnswerReviewedEvent, plus AttemptReviewedEvent when
|
||||||
|
// the attempt is now fully reviewed, fire after the commit.
|
||||||
|
func (s *Service) Confirm(ctx context.Context, answerID uint, by Reviewer) (*ReviewDetail, error) {
|
||||||
|
var detail *ReviewDetail
|
||||||
|
err := lagoon.Transaction(ctx, s.DB, func(ctx context.Context, tx *gorm.DB) error {
|
||||||
|
t, err := lockReviewTarget(ctx, tx, answerID)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if done, err := s.confirmTarget(ctx, tx, t, by); err != nil {
|
||||||
|
return err
|
||||||
|
} else if done {
|
||||||
|
if err := s.recalcAttempt(ctx, tx, t.Attempt.ID); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := s.fireAttemptReviewedIfDone(ctx, tx, t.Attempt.ID); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
detail, err = reviewItem(ctx, tx, answerID)
|
||||||
|
return err
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return detail, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// confirmTarget confirms one locked answer and reports whether it wrote:
|
||||||
|
// false for a reviewed answer, ErrNoGraderScore without a grader score.
|
||||||
|
// The caller recalculates the attempt.
|
||||||
|
func (s *Service) confirmTarget(ctx context.Context, tx *gorm.DB, t *reviewTarget, by Reviewer) (bool, error) {
|
||||||
|
status := ""
|
||||||
|
if t.Answer.GradingStatus != nil {
|
||||||
|
status = *t.Answer.GradingStatus
|
||||||
|
}
|
||||||
|
switch {
|
||||||
|
case status == models.GradingReviewed:
|
||||||
|
return false, nil
|
||||||
|
case status != models.GradingGraded || t.Answer.GraderPoints == nil:
|
||||||
|
return false, ErrNoGraderScore
|
||||||
|
}
|
||||||
|
// The grader's score was clamped to the question's points at grading
|
||||||
|
// time; the owner may have lowered them since.
|
||||||
|
points, ok := ClampOpenPoints(*t.Answer.GraderPoints, t.Question.Points)
|
||||||
|
if !ok {
|
||||||
|
return false, ErrNoGraderScore
|
||||||
|
}
|
||||||
|
return true, s.storeReview(ctx, tx, t, points, t.Answer.ReviewComment, false, by)
|
||||||
|
}
|
||||||
|
|
||||||
|
// storeReview writes the owner's decision on one locked open answer and
|
||||||
|
// registers its AnswerReviewedEvent. setComment replaces review_comment
|
||||||
|
// with comment (nil clears it); otherwise the comment stays. grader_points
|
||||||
|
// and grader_feedback stay for the record.
|
||||||
|
func (s *Service) storeReview(ctx context.Context, tx *gorm.DB, t *reviewTarget, points float64, comment *string, setComment bool, by Reviewer) error {
|
||||||
|
now := s.now().UTC()
|
||||||
|
user, admin := by.ids()
|
||||||
|
cols := map[string]any{
|
||||||
|
"grading_status": models.GradingReviewed,
|
||||||
|
"points": points,
|
||||||
|
"is_correct": OpenCorrect(points, t.Question.Points),
|
||||||
|
"reviewed_at": now,
|
||||||
|
"reviewed_by_user_id": user,
|
||||||
|
"reviewed_by_admin_id": admin,
|
||||||
|
"updated_at": now,
|
||||||
|
}
|
||||||
|
if setComment {
|
||||||
|
cols["review_comment"] = comment
|
||||||
|
} else {
|
||||||
|
comment = t.Answer.ReviewComment
|
||||||
|
}
|
||||||
|
if err := tx.WithContext(ctx).Model(&models.AttemptAnswer{}).Where("id = ?", t.Answer.ID).Updates(cols).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
fireAfterCommit(ctx, s, tx, events.AnswerReviewedEventName, &events.AnswerReviewedEvent{
|
||||||
|
QuizID: t.Attempt.QuizID,
|
||||||
|
QuestionID: t.Question.ID,
|
||||||
|
AttemptID: t.Attempt.ID,
|
||||||
|
AnswerID: t.Answer.ID,
|
||||||
|
UserID: t.Attempt.UserID,
|
||||||
|
Points: points,
|
||||||
|
MaxPoints: t.Question.Points,
|
||||||
|
GraderPoints: t.Answer.GraderPoints,
|
||||||
|
Comment: comment,
|
||||||
|
ReviewerUserID: user,
|
||||||
|
ReviewerAdminID: admin,
|
||||||
|
})
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// fireAttemptReviewedIfDone registers AttemptReviewedEvent for a completed
|
||||||
|
// attempt that has at least one open answer and none left pending, graded
|
||||||
|
// or failed, with the attempt's stored score; passed compares its percent
|
||||||
|
// with the quiz's passing score. Call it after the attempt is
|
||||||
|
// recalculated, inside the transaction that holds its lock. Without an
|
||||||
|
// event bus it reads nothing.
|
||||||
|
func (s *Service) fireAttemptReviewedIfDone(ctx context.Context, tx *gorm.DB, attemptID uint) error {
|
||||||
|
if s == nil || s.Events == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
tx = tx.WithContext(ctx)
|
||||||
|
var a models.Attempt
|
||||||
|
if err := tx.Preload("Quiz").Where("id = ?", attemptID).Take(&a).Error; err != nil {
|
||||||
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if a.CompletedAt == nil || a.Quiz == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
counts, err := answerCounts(ctx, tx, []uint{attemptID})
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if c := counts[attemptID]; c.OpenN == 0 || c.UnreviewedN > 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
fireAfterCommit(ctx, s, tx, events.AttemptReviewedEventName, &events.AttemptReviewedEvent{
|
||||||
|
QuizID: a.QuizID,
|
||||||
|
AttemptID: a.ID,
|
||||||
|
UserID: a.UserID,
|
||||||
|
ScorePoints: a.ScorePoints,
|
||||||
|
MaxPoints: a.MaxPoints,
|
||||||
|
ScorePercent: a.ScorePercent,
|
||||||
|
Passed: a.ScorePercent != nil && *a.ScorePercent >= float64(a.Quiz.PassingScore),
|
||||||
|
})
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// SetScore gives one open answer the owner's final score, on any status
|
||||||
|
// (D-12): status reviewed, points as given, is_correct for full marks, and
|
||||||
|
// the comment to the student replacing any earlier one (nil or blank
|
||||||
|
// clears it). grader_points and grader_feedback stay for the record.
|
||||||
|
// Points outside 0..question points or not a multiple of 0.5, and a
|
||||||
|
// comment over MaxReviewComment runes, are a *ValidationError. A
|
||||||
|
// completed attempt is recalculated; AnswerReviewedEvent, and
|
||||||
|
// AttemptReviewedEvent when the attempt is fully reviewed, fire after the
|
||||||
|
// commit.
|
||||||
|
func (s *Service) SetScore(ctx context.Context, answerID uint, points float64, comment *string, by Reviewer) (*ReviewDetail, error) {
|
||||||
|
comment, problems := CheckReviewComment(comment)
|
||||||
|
if len(problems) > 0 {
|
||||||
|
return nil, &ValidationError{Problems: problems}
|
||||||
|
}
|
||||||
|
var detail *ReviewDetail
|
||||||
|
err := lagoon.Transaction(ctx, s.DB, func(ctx context.Context, tx *gorm.DB) error {
|
||||||
|
t, err := lockReviewTarget(ctx, tx, answerID)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if !CheckReviewPoints(points, t.Question.Points) {
|
||||||
|
return &ValidationError{Problems: []string{
|
||||||
|
"points must be between 0 and " + strconv.Itoa(max(t.Question.Points, 0)) + " in steps of 0.5",
|
||||||
|
}}
|
||||||
|
}
|
||||||
|
if points == 0 {
|
||||||
|
points = 0 // no negative zero in JSON
|
||||||
|
}
|
||||||
|
if err := s.storeReview(ctx, tx, t, points, comment, true, by); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := s.recalcAttempt(ctx, tx, t.Attempt.ID); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := s.fireAttemptReviewedIfDone(ctx, tx, t.Attempt.ID); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
detail, err = reviewItem(ctx, tx, answerID)
|
||||||
|
return err
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return detail, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ConfirmBulk confirms every graded answer of one quiz (QuizSlug) or one
|
||||||
|
// attempt (AttemptID), exactly as Confirm does, and returns how many it
|
||||||
|
// confirmed. Pending, failed and reviewed answers are left alone. The
|
||||||
|
// affected attempts are locked in id order, recalculated once each, and
|
||||||
|
// every changed answer and every completed attempt that is now fully
|
||||||
|
// reviewed fire their events after the commit. Answers of a test attempt
|
||||||
|
// that is still running are skipped; a scope of one such attempt is
|
||||||
|
// ErrAttemptOpen. A missing quiz or attempt is ErrNotFound; a scope that
|
||||||
|
// is not exactly one of the two is a *ValidationError.
|
||||||
|
func (s *Service) ConfirmBulk(ctx context.Context, scope ReviewScope, by Reviewer) (int, error) {
|
||||||
|
if problems := CheckReviewScope(scope, false); len(problems) > 0 {
|
||||||
|
return 0, &ValidationError{Problems: problems}
|
||||||
|
}
|
||||||
|
confirmed := 0
|
||||||
|
err := lagoon.Transaction(ctx, s.DB, func(ctx context.Context, tx *gorm.DB) error {
|
||||||
|
confirmed = 0
|
||||||
|
quiz, err := scopeQuiz(ctx, tx, scope)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
rows, attempts, err := lockScope(ctx, tx, scope, quiz, []string{models.GradingGraded})
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
questions, err := scopeQuestions(ctx, tx, rows)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
touched := map[uint]bool{}
|
||||||
|
for _, row := range rows {
|
||||||
|
if Withheld(attempts[row.AttemptID]) {
|
||||||
|
if scope.AttemptID != 0 {
|
||||||
|
return ErrAttemptOpen
|
||||||
|
}
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
t := &reviewTarget{Answer: row, Question: questions[row.QuestionID], Attempt: attempts[row.AttemptID]}
|
||||||
|
done, err := s.confirmTarget(ctx, tx, t, by)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if done {
|
||||||
|
confirmed++
|
||||||
|
touched[row.AttemptID] = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, id := range sortedIDs(touched) {
|
||||||
|
if err := s.recalcAttempt(ctx, tx, id); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := s.fireAttemptReviewedIfDone(ctx, tx, id); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
return confirmed, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Regrade sends open answers back to the quiz's grader, e.g. after a
|
||||||
|
// rubric change (D-12): every pending, graded or failed answer of one
|
||||||
|
// answer, attempt or quiz goes back to pending with the next grading_seq
|
||||||
|
// (so a job for the old text is ignored), its grade, error and points
|
||||||
|
// cleared, and is enqueued again. Answers of a test attempt that is still
|
||||||
|
// open are not enqueued: closing the attempt enqueues them (UD-2).
|
||||||
|
// Reviewed answers are skipped, as owner decisions are final; a single
|
||||||
|
// reviewed answer is ErrAlreadyReviewed. A quiz whose grader is manual or
|
||||||
|
// not registered is ErrGraderManual. Completed attempts are recalculated.
|
||||||
|
// It returns how many answers were reset.
|
||||||
|
func (s *Service) Regrade(ctx context.Context, scope ReviewScope) (int, error) {
|
||||||
|
if problems := CheckReviewScope(scope, true); len(problems) > 0 {
|
||||||
|
return 0, &ValidationError{Problems: problems}
|
||||||
|
}
|
||||||
|
regraded := 0
|
||||||
|
err := lagoon.Transaction(ctx, s.DB, func(ctx context.Context, tx *gorm.DB) error {
|
||||||
|
regraded = 0
|
||||||
|
tx = tx.WithContext(ctx)
|
||||||
|
quiz, err := scopeQuiz(ctx, tx, scope)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if _, ok := GraderFor(s.Graders, quiz); !ok {
|
||||||
|
return ErrGraderManual
|
||||||
|
}
|
||||||
|
if scope.AnswerID != 0 {
|
||||||
|
if err := refuseReviewed(ctx, tx, scope.AnswerID); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
rows, attempts, err := lockScope(ctx, tx, scope, quiz, unreviewedStatuses())
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if scope.AnswerID != 0 && len(rows) == 0 {
|
||||||
|
// Reviewed between the first read and the lock.
|
||||||
|
return refuseReviewed(ctx, tx, scope.AnswerID)
|
||||||
|
}
|
||||||
|
now := s.now().UTC()
|
||||||
|
seqs := make(map[uint]int, len(rows))
|
||||||
|
for _, row := range rows {
|
||||||
|
seq := row.GradingSeq + 1
|
||||||
|
if err := tx.Model(&models.AttemptAnswer{}).Where("id = ?", row.ID).Updates(map[string]any{
|
||||||
|
"grading_status": models.GradingPending,
|
||||||
|
"grading_seq": seq,
|
||||||
|
"grading_attempts": 0,
|
||||||
|
"grader": nil,
|
||||||
|
"grader_points": nil,
|
||||||
|
"grader_feedback": nil,
|
||||||
|
"grading_error": nil,
|
||||||
|
"graded_at": nil,
|
||||||
|
"points": 0,
|
||||||
|
"is_correct": false,
|
||||||
|
"updated_at": now,
|
||||||
|
}).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
seqs[row.ID] = seq
|
||||||
|
regraded++
|
||||||
|
}
|
||||||
|
touched := map[uint]bool{}
|
||||||
|
for _, row := range rows {
|
||||||
|
touched[row.AttemptID] = true
|
||||||
|
}
|
||||||
|
for _, id := range sortedIDs(touched) {
|
||||||
|
if err := s.recalcAttempt(ctx, tx, id); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, row := range rows {
|
||||||
|
a := attempts[row.AttemptID]
|
||||||
|
if a.CompletedAt == nil && IsTest(quiz) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if err := s.enqueueGrading(ctx, tx, row.ID, seqs[row.ID], a); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
return regraded, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// refuseReviewed is ErrAlreadyReviewed for a reviewed answer and
|
||||||
|
// ErrNotFound for one that is missing or not open.
|
||||||
|
func refuseReviewed(ctx context.Context, tx *gorm.DB, answerID uint) error {
|
||||||
|
var row models.AttemptAnswer
|
||||||
|
if err := tx.WithContext(ctx).Where("id = ? AND grading_status IS NOT NULL", answerID).Take(&row).Error; err != nil {
|
||||||
|
return notFound(err)
|
||||||
|
}
|
||||||
|
if *row.GradingStatus == models.GradingReviewed {
|
||||||
|
return ErrAlreadyReviewed
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// scopeQuiz resolves the quiz of a review scope: by slug, from the
|
||||||
|
// attempt, or from the open answer's attempt. Anything missing is
|
||||||
|
// ErrNotFound.
|
||||||
|
func scopeQuiz(ctx context.Context, tx *gorm.DB, scope ReviewScope) (*models.Quiz, error) {
|
||||||
|
tx = tx.WithContext(ctx)
|
||||||
|
var quiz models.Quiz
|
||||||
|
var err error
|
||||||
|
switch {
|
||||||
|
case scope.AnswerID != 0:
|
||||||
|
err = tx.Where(`id = (SELECT a.quiz_id FROM golem15_quizzes_attempt_answers aa
|
||||||
|
JOIN golem15_quizzes_attempts a ON a.id = aa.attempt_id
|
||||||
|
WHERE aa.id = ? AND aa.grading_status IS NOT NULL)`, scope.AnswerID).Take(&quiz).Error
|
||||||
|
case scope.AttemptID != 0:
|
||||||
|
err = tx.Where("id = (SELECT quiz_id FROM golem15_quizzes_attempts WHERE id = ?)", scope.AttemptID).Take(&quiz).Error
|
||||||
|
default:
|
||||||
|
err = tx.Where("slug = ?", strings.TrimSpace(scope.QuizSlug)).Take(&quiz).Error
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return nil, notFound(err)
|
||||||
|
}
|
||||||
|
return &quiz, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// scopeRows narrows a query on the attempt answers to a scope of quiz.
|
||||||
|
func scopeRows(q *gorm.DB, scope ReviewScope, quiz *models.Quiz) *gorm.DB {
|
||||||
|
switch {
|
||||||
|
case scope.AnswerID != 0:
|
||||||
|
return q.Where("id = ?", scope.AnswerID)
|
||||||
|
case scope.AttemptID != 0:
|
||||||
|
return q.Where("attempt_id = ?", scope.AttemptID)
|
||||||
|
}
|
||||||
|
return q.Where("attempt_id IN (SELECT id FROM golem15_quizzes_attempts WHERE quiz_id = ?)", quiz.ID)
|
||||||
|
}
|
||||||
|
|
||||||
|
// lockScope locks, in id order, the attempts that have open answers with
|
||||||
|
// one of statuses in scope, then selects those answers again under the
|
||||||
|
// locks (only of the locked attempts, so nothing changes underneath). It
|
||||||
|
// returns the answers by attempt and id, and the locked attempts by id
|
||||||
|
// with their quiz set.
|
||||||
|
func lockScope(ctx context.Context, tx *gorm.DB, scope ReviewScope, quiz *models.Quiz, statuses []string) ([]models.AttemptAnswer, map[uint]*models.Attempt, error) {
|
||||||
|
tx = tx.WithContext(ctx)
|
||||||
|
var ids []uint
|
||||||
|
if err := scopeRows(tx.Model(&models.AttemptAnswer{}), scope, quiz).
|
||||||
|
Where("grading_status IN ?", statuses).Distinct("attempt_id").Order("attempt_id ASC").
|
||||||
|
Pluck("attempt_id", &ids).Error; err != nil {
|
||||||
|
return nil, nil, err
|
||||||
|
}
|
||||||
|
attempts := make(map[uint]*models.Attempt, len(ids))
|
||||||
|
locked := make([]uint, 0, len(ids))
|
||||||
|
for _, id := range ids {
|
||||||
|
a, err := lockAttempt(ctx, tx, id)
|
||||||
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return nil, nil, err
|
||||||
|
}
|
||||||
|
a.Quiz = quiz
|
||||||
|
attempts[id] = a
|
||||||
|
locked = append(locked, id)
|
||||||
|
}
|
||||||
|
if len(locked) == 0 {
|
||||||
|
return nil, attempts, nil
|
||||||
|
}
|
||||||
|
var rows []models.AttemptAnswer
|
||||||
|
if err := scopeRows(tx, scope, quiz).Where("grading_status IN ? AND attempt_id IN ?", statuses, locked).
|
||||||
|
Order("attempt_id ASC, id ASC").Find(&rows).Error; err != nil {
|
||||||
|
return nil, nil, err
|
||||||
|
}
|
||||||
|
return rows, attempts, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// scopeQuestions loads the questions of the given answers by id.
|
||||||
|
func scopeQuestions(ctx context.Context, tx *gorm.DB, rows []models.AttemptAnswer) (map[uint]models.Question, error) {
|
||||||
|
out := map[uint]models.Question{}
|
||||||
|
if len(rows) == 0 {
|
||||||
|
return out, nil
|
||||||
|
}
|
||||||
|
ids := make([]uint, 0, len(rows))
|
||||||
|
for _, r := range rows {
|
||||||
|
ids = append(ids, r.QuestionID)
|
||||||
|
}
|
||||||
|
var questions []models.Question
|
||||||
|
if err := tx.WithContext(ctx).Where("id IN ?", ids).Find(&questions).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
for _, q := range questions {
|
||||||
|
out[q.ID] = q
|
||||||
|
}
|
||||||
|
return out, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// sortedIDs returns the keys of set in ascending order.
|
||||||
|
func sortedIDs(set map[uint]bool) []uint {
|
||||||
|
out := make([]uint, 0, len(set))
|
||||||
|
for id := range set {
|
||||||
|
out = append(out, id)
|
||||||
|
}
|
||||||
|
slices.Sort(out)
|
||||||
|
return out
|
||||||
|
}
|
||||||
115
classes/review_test.go
Normal file
115
classes/review_test.go
Normal file
@@ -0,0 +1,115 @@
|
|||||||
|
package classes_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"math"
|
||||||
|
"slices"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"git.golem15.com/golem15/sm-quizzes-plugin/classes"
|
||||||
|
)
|
||||||
|
|
||||||
|
// TestCheckReviewStatus: "" and open list the three unreviewed statuses,
|
||||||
|
// a grading status lists itself, all lists everything (nil), and any
|
||||||
|
// other value is a problem naming the valid values.
|
||||||
|
func TestCheckReviewStatus(t *testing.T) {
|
||||||
|
open := []string{"pending", "graded", "failed"}
|
||||||
|
for in, want := range map[string][]string{
|
||||||
|
"": open,
|
||||||
|
"open": open,
|
||||||
|
" open ": open,
|
||||||
|
"pending": {"pending"},
|
||||||
|
"graded": {"graded"},
|
||||||
|
"failed": {"failed"},
|
||||||
|
"reviewed": {"reviewed"},
|
||||||
|
"all": nil,
|
||||||
|
} {
|
||||||
|
got, problems := classes.CheckReviewStatus(in)
|
||||||
|
if len(problems) != 0 {
|
||||||
|
t.Errorf("%q: problems %v", in, problems)
|
||||||
|
}
|
||||||
|
if !slices.Equal(got, want) || (want == nil) != (got == nil) {
|
||||||
|
t.Errorf("%q = %v, want %v", in, got, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, in := range []string{"done", "Open", "pending,graded"} {
|
||||||
|
got, problems := classes.CheckReviewStatus(in)
|
||||||
|
if got != nil || len(problems) != 1 || !strings.Contains(problems[0], "open, pending, graded, failed, reviewed, all") {
|
||||||
|
t.Errorf("%q = %v %v, want one problem listing the valid values", in, got, problems)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestCheckReviewPoints: 0..points in steps of 0.5, finite.
|
||||||
|
func TestCheckReviewPoints(t *testing.T) {
|
||||||
|
for _, tc := range []struct {
|
||||||
|
p float64
|
||||||
|
max int
|
||||||
|
want bool
|
||||||
|
}{
|
||||||
|
{0, 2, true}, {1.5, 2, true}, {2, 2, true}, {0, 0, true}, {0.5, 1, true},
|
||||||
|
{-0.5, 2, false}, {2.5, 2, false}, {1.25, 2, false}, {0.1, 2, false},
|
||||||
|
{math.NaN(), 2, false}, {math.Inf(1), 2, false}, {math.Inf(-1), 2, false},
|
||||||
|
{0.5, 0, false}, {0, -1, true}, {1, -1, false},
|
||||||
|
} {
|
||||||
|
if got := classes.CheckReviewPoints(tc.p, tc.max); got != tc.want {
|
||||||
|
t.Errorf("CheckReviewPoints(%v, %d) = %v, want %v", tc.p, tc.max, got, tc.want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestCheckReviewComment: trimmed, blank is no comment, NUL dropped,
|
||||||
|
// at most 2000 runes.
|
||||||
|
func TestCheckReviewComment(t *testing.T) {
|
||||||
|
str := func(s string) *string { return &s }
|
||||||
|
if got, p := classes.CheckReviewComment(nil); got != nil || p != nil {
|
||||||
|
t.Errorf("nil = %v %v", got, p)
|
||||||
|
}
|
||||||
|
if got, p := classes.CheckReviewComment(str(" \n ")); got != nil || p != nil {
|
||||||
|
t.Errorf("spaces = %v %v, want no comment", got, p)
|
||||||
|
}
|
||||||
|
if got, p := classes.CheckReviewComment(str(" Dobrze, ale\x00 brak przykładu. ")); got == nil || *got != "Dobrze, ale brak przykładu." || p != nil {
|
||||||
|
t.Errorf("trimmed = %v %v", got, p)
|
||||||
|
}
|
||||||
|
max := strings.Repeat("ł", classes.MaxReviewComment)
|
||||||
|
if got, p := classes.CheckReviewComment(&max); got == nil || *got != max || p != nil {
|
||||||
|
t.Errorf("2000 runes refused: %v", p)
|
||||||
|
}
|
||||||
|
over := max + "x"
|
||||||
|
if got, p := classes.CheckReviewComment(&over); got != nil || len(p) != 1 || p[0] != "comment must be at most 2000 characters" {
|
||||||
|
t.Errorf("2001 runes = %v %v, want one problem", got, p)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestCheckReviewScope: exactly one key; answer_id only for regrade.
|
||||||
|
func TestCheckReviewScope(t *testing.T) {
|
||||||
|
regrade := "exactly one of answer_id, attempt_id and quiz is required"
|
||||||
|
bulk := "exactly one of attempt_id and quiz is required"
|
||||||
|
for name, tc := range map[string]struct {
|
||||||
|
scope classes.ReviewScope
|
||||||
|
allow bool
|
||||||
|
want string
|
||||||
|
}{
|
||||||
|
"regrade answer": {classes.ReviewScope{AnswerID: 1}, true, ""},
|
||||||
|
"regrade attempt": {classes.ReviewScope{AttemptID: 1}, true, ""},
|
||||||
|
"regrade quiz": {classes.ReviewScope{QuizSlug: "q"}, true, ""},
|
||||||
|
"regrade none": {classes.ReviewScope{}, true, regrade},
|
||||||
|
"regrade blank quiz": {classes.ReviewScope{QuizSlug: " "}, true, regrade},
|
||||||
|
"regrade two": {classes.ReviewScope{AnswerID: 1, QuizSlug: "q"}, true, regrade},
|
||||||
|
"regrade three": {classes.ReviewScope{AnswerID: 1, AttemptID: 2, QuizSlug: "q"}, true, regrade},
|
||||||
|
"bulk attempt": {classes.ReviewScope{AttemptID: 1}, false, ""},
|
||||||
|
"bulk quiz": {classes.ReviewScope{QuizSlug: "q"}, false, ""},
|
||||||
|
"bulk none": {classes.ReviewScope{}, false, bulk},
|
||||||
|
"bulk two": {classes.ReviewScope{AttemptID: 1, QuizSlug: "q"}, false, bulk},
|
||||||
|
"bulk answer": {classes.ReviewScope{AnswerID: 1}, false, bulk},
|
||||||
|
"bulk answer and quiz": {classes.ReviewScope{AnswerID: 1, QuizSlug: "q"}, false, bulk},
|
||||||
|
} {
|
||||||
|
got := classes.CheckReviewScope(tc.scope, tc.allow)
|
||||||
|
switch {
|
||||||
|
case tc.want == "" && got != nil:
|
||||||
|
t.Errorf("%s = %v, want no problem", name, got)
|
||||||
|
case tc.want != "" && (len(got) != 1 || got[0] != tc.want):
|
||||||
|
t.Errorf("%s = %v, want %q", name, got, tc.want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -140,7 +140,8 @@ func Score(in ScoreInput, cfg ScoringConfig) ScoreResult {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Totals sums the earned points of an attempt, floored at 0, and the
|
// Totals sums the earned points of an attempt, floored at 0, and the
|
||||||
// percentage of maxPoints it is. With no points to earn the percentage is 0.
|
// percentage of maxPoints it is, capped at 100. With no points to earn the
|
||||||
|
// percentage is 0.
|
||||||
func Totals(points []float64, maxPoints int) (score, percent float64) {
|
func Totals(points []float64, maxPoints int) (score, percent float64) {
|
||||||
for _, p := range points {
|
for _, p := range points {
|
||||||
score += p
|
score += p
|
||||||
@@ -149,7 +150,30 @@ func Totals(points []float64, maxPoints int) (score, percent float64) {
|
|||||||
if maxPoints <= 0 {
|
if maxPoints <= 0 {
|
||||||
return score, 0
|
return score, 0
|
||||||
}
|
}
|
||||||
return score, round(score / float64(maxPoints) * 100)
|
// A question's points raised after the attempt was scored can push the
|
||||||
|
// score past the attempt's stored maximum; the percentage stays <= 100.
|
||||||
|
return score, round(math.Min(score/float64(maxPoints)*100, 100))
|
||||||
|
}
|
||||||
|
|
||||||
|
// ClampOpenPoints keeps a grader's score of an open question in
|
||||||
|
// 0..points (a negative points value counts as 0), rounded to the nearest
|
||||||
|
// 0.5 (D-02). NaN and ±Inf are not a score: it returns 0, false.
|
||||||
|
func ClampOpenPoints(p float64, points int) (float64, bool) {
|
||||||
|
if math.IsNaN(p) || math.IsInf(p, 0) {
|
||||||
|
return 0, false
|
||||||
|
}
|
||||||
|
full := float64(max(points, 0))
|
||||||
|
p = math.Round(math.Min(math.Max(p, 0), full)*2) / 2
|
||||||
|
if p == 0 {
|
||||||
|
return 0, true // no negative zero in JSON
|
||||||
|
}
|
||||||
|
return p, true
|
||||||
|
}
|
||||||
|
|
||||||
|
// OpenCorrect reports whether an open answer scored p earns full marks: a
|
||||||
|
// question with points earns is_correct only with all of them (D-02).
|
||||||
|
func OpenCorrect(p float64, points int) bool {
|
||||||
|
return points > 0 && p == float64(points)
|
||||||
}
|
}
|
||||||
|
|
||||||
// round keeps two decimals.
|
// round keeps two decimals.
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
package classes_test
|
package classes_test
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"math"
|
||||||
"os"
|
"os"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
"testing"
|
"testing"
|
||||||
@@ -83,6 +84,7 @@ func TestTotals(t *testing.T) {
|
|||||||
{[]float64{2, -0.5}, 4, 1.5, 37.5},
|
{[]float64{2, -0.5}, 4, 1.5, 37.5},
|
||||||
{nil, 0, 0, 0},
|
{nil, 0, 0, 0},
|
||||||
{[]float64{1}, 1, 1, 100},
|
{[]float64{1}, 1, 1, 100},
|
||||||
|
{[]float64{3}, 2, 3, 100},
|
||||||
}
|
}
|
||||||
for _, tc := range cases {
|
for _, tc := range cases {
|
||||||
score, pct := classes.Totals(tc.points, tc.max)
|
score, pct := classes.Totals(tc.points, tc.max)
|
||||||
@@ -130,3 +132,37 @@ func TestScoringConfigFrom(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestClampOpenPoints(t *testing.T) {
|
||||||
|
cases := []struct {
|
||||||
|
p float64
|
||||||
|
points int
|
||||||
|
want float64
|
||||||
|
ok bool
|
||||||
|
}{
|
||||||
|
{1.26, 2, 1.5, true},
|
||||||
|
{-3, 2, 0, true},
|
||||||
|
{7, 2, 2, true},
|
||||||
|
{0.74, 3, 0.5, true},
|
||||||
|
{0.25, 3, 0.5, true},
|
||||||
|
{0.2, 3, 0, true},
|
||||||
|
{2, 2, 2, true},
|
||||||
|
{1, 0, 0, true},
|
||||||
|
{5, -1, 0, true},
|
||||||
|
{math.NaN(), 2, 0, false},
|
||||||
|
{math.Inf(1), 2, 0, false},
|
||||||
|
{math.Inf(-1), 2, 0, false},
|
||||||
|
}
|
||||||
|
for _, tc := range cases {
|
||||||
|
got, ok := classes.ClampOpenPoints(tc.p, tc.points)
|
||||||
|
if got != tc.want || ok != tc.ok {
|
||||||
|
t.Errorf("ClampOpenPoints(%v, %d) = %v, %v; want %v, %v", tc.p, tc.points, got, ok, tc.want, tc.ok)
|
||||||
|
}
|
||||||
|
if math.Signbit(got) {
|
||||||
|
t.Errorf("ClampOpenPoints(%v, %d) is negative zero", tc.p, tc.points)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !classes.OpenCorrect(2, 2) || classes.OpenCorrect(1.5, 2) || classes.OpenCorrect(0, 0) {
|
||||||
|
t.Error("OpenCorrect: want true only for full points of a question worth points")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -7,7 +7,9 @@ import (
|
|||||||
"slices"
|
"slices"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
"git.golem15.com/golem15/sm-quizzes-plugin/graders"
|
||||||
"git.golem15.com/golem15/sm-quizzes-plugin/models"
|
"git.golem15.com/golem15/sm-quizzes-plugin/models"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/festival"
|
||||||
"git.golem15.com/golem15/summercms/modules/lagoon"
|
"git.golem15.com/golem15/summercms/modules/lagoon"
|
||||||
"gorm.io/gorm"
|
"gorm.io/gorm"
|
||||||
"gorm.io/gorm/clause"
|
"gorm.io/gorm/clause"
|
||||||
@@ -19,8 +21,13 @@ var (
|
|||||||
ErrNotFound = errors.New("quizzes: not found")
|
ErrNotFound = errors.New("quizzes: not found")
|
||||||
// ErrCompleted is a write to a finished attempt.
|
// ErrCompleted is a write to a finished attempt.
|
||||||
ErrCompleted = errors.New("quizzes: attempt already completed")
|
ErrCompleted = errors.New("quizzes: attempt already completed")
|
||||||
// ErrTimeLimit is an answer after the quiz's time limit ran out.
|
// ErrTimeLimit is an answer after the quiz's time limit ran out (plus
|
||||||
|
// the grace of a test).
|
||||||
ErrTimeLimit = errors.New("quizzes: time limit exceeded")
|
ErrTimeLimit = errors.New("quizzes: time limit exceeded")
|
||||||
|
// ErrAttemptLimit is a test start after the user used every attempt.
|
||||||
|
ErrAttemptLimit = errors.New("quizzes: attempt limit reached")
|
||||||
|
// ErrAnswerLocked is a changed answer in a one_way test.
|
||||||
|
ErrAnswerLocked = errors.New("quizzes: answer locked")
|
||||||
)
|
)
|
||||||
|
|
||||||
// FieldError is an input error on one request field (a 422).
|
// FieldError is an input error on one request field (a 422).
|
||||||
@@ -40,6 +47,18 @@ type Service struct {
|
|||||||
// Shuffle reorders questions of a quiz with shuffle_questions; it
|
// Shuffle reorders questions of a quiz with shuffle_questions; it
|
||||||
// defaults to math/rand.
|
// defaults to math/rand.
|
||||||
Shuffle func(n int, swap func(i, j int))
|
Shuffle func(n int, swap func(i, j int))
|
||||||
|
// Grace is how long after a test's deadline an answer is still
|
||||||
|
// accepted; it never applies to learning quizzes. See TestGraceFrom.
|
||||||
|
Grace time.Duration
|
||||||
|
// Graders is the grader registry; nil knows only manual, so every open
|
||||||
|
// answer waits for the owner.
|
||||||
|
Graders *graders.Registry
|
||||||
|
// Jobs enqueues grading jobs; nil enqueues nothing (tests and apps
|
||||||
|
// without a queue keep working, the answers stay pending).
|
||||||
|
Jobs Enqueuer
|
||||||
|
// Events is the bus the grading and review events fire on; nil fires
|
||||||
|
// nothing.
|
||||||
|
Events *festival.Bus
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *Service) now() time.Time {
|
func (s *Service) now() time.Time {
|
||||||
@@ -57,11 +76,17 @@ type QuizSummary struct {
|
|||||||
QuestionCount int
|
QuestionCount int
|
||||||
BestScorePercent *float64
|
BestScorePercent *float64
|
||||||
AttemptsCount int
|
AttemptsCount int
|
||||||
|
// QuestionTypes counts the questions per type; every models.QuestionTypes
|
||||||
|
// key is present.
|
||||||
|
QuestionTypes map[string]int
|
||||||
|
// AttemptsUsed counts every attempt of the user, open or completed.
|
||||||
|
AttemptsUsed int
|
||||||
}
|
}
|
||||||
|
|
||||||
// ListQuizzes returns the published quizzes, optionally only those whose
|
// ListQuizzes returns the published quizzes, optionally only those whose
|
||||||
// context equals quizContext, ordered by title. AttemptsCount counts the
|
// context equals quizContext, ordered by title. AttemptsCount counts the
|
||||||
// user's completed attempts and BestScorePercent is their best result.
|
// user's completed attempts, AttemptsUsed every attempt, and
|
||||||
|
// BestScorePercent is their best result.
|
||||||
func (s *Service) ListQuizzes(ctx context.Context, userID uint, quizContext string) ([]QuizSummary, error) {
|
func (s *Service) ListQuizzes(ctx context.Context, userID uint, quizContext string) ([]QuizSummary, error) {
|
||||||
q := s.db(ctx).Where("is_published = ?", true)
|
q := s.db(ctx).Where("is_published = ?", true)
|
||||||
if quizContext != "" {
|
if quizContext != "" {
|
||||||
@@ -81,27 +106,34 @@ func (s *Service) ListQuizzes(ctx context.Context, userID uint, quizContext stri
|
|||||||
}
|
}
|
||||||
type countRow struct {
|
type countRow struct {
|
||||||
QuizID uint
|
QuizID uint
|
||||||
|
Type string
|
||||||
N int
|
N int
|
||||||
}
|
}
|
||||||
var counts []countRow
|
var counts []countRow
|
||||||
if err := s.db(ctx).Model(&models.Question{}).Select("quiz_id, COUNT(*) AS n").
|
if err := s.db(ctx).Model(&models.Question{}).Select("quiz_id, type, COUNT(*) AS n").
|
||||||
Where("quiz_id IN ?", ids).Group("quiz_id").Scan(&counts).Error; err != nil {
|
Where("quiz_id IN ?", ids).Group("quiz_id, type").Scan(&counts).Error; err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
type statRow struct {
|
type statRow struct {
|
||||||
QuizID uint
|
QuizID uint
|
||||||
N int
|
N int
|
||||||
|
Used int
|
||||||
Best *float64
|
Best *float64
|
||||||
}
|
}
|
||||||
var stats []statRow
|
var stats []statRow
|
||||||
if err := s.db(ctx).Model(&models.Attempt{}).Select("quiz_id, COUNT(*) AS n, MAX(score_percent) AS best").
|
if err := s.db(ctx).Model(&models.Attempt{}).
|
||||||
Where("quiz_id IN ? AND user_id = ? AND completed_at IS NOT NULL", ids, userID).
|
Select("quiz_id, COUNT(*) FILTER (WHERE completed_at IS NOT NULL) AS n, COUNT(*) AS used, "+
|
||||||
|
"MAX(score_percent) FILTER (WHERE completed_at IS NOT NULL) AS best").
|
||||||
|
Where("quiz_id IN ? AND user_id = ?", ids, userID).
|
||||||
Group("quiz_id").Scan(&stats).Error; err != nil {
|
Group("quiz_id").Scan(&stats).Error; err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
countBy := map[uint]int{}
|
typesBy := map[uint]map[string]int{}
|
||||||
for _, c := range counts {
|
for _, c := range counts {
|
||||||
countBy[c.QuizID] = c.N
|
if typesBy[c.QuizID] == nil {
|
||||||
|
typesBy[c.QuizID] = map[string]int{}
|
||||||
|
}
|
||||||
|
typesBy[c.QuizID][c.Type] += c.N
|
||||||
}
|
}
|
||||||
statBy := map[uint]statRow{}
|
statBy := map[uint]statRow{}
|
||||||
for _, st := range stats {
|
for _, st := range stats {
|
||||||
@@ -109,7 +141,19 @@ func (s *Service) ListQuizzes(ctx context.Context, userID uint, quizContext stri
|
|||||||
}
|
}
|
||||||
for _, quiz := range quizzes {
|
for _, quiz := range quizzes {
|
||||||
st := statBy[quiz.ID]
|
st := statBy[quiz.ID]
|
||||||
out = append(out, QuizSummary{Quiz: quiz, QuestionCount: countBy[quiz.ID], BestScorePercent: st.Best, AttemptsCount: st.N})
|
types := make(map[string]int, len(models.QuestionTypes))
|
||||||
|
for _, typ := range models.QuestionTypes {
|
||||||
|
types[typ] = 0
|
||||||
|
}
|
||||||
|
total := 0
|
||||||
|
for typ, n := range typesBy[quiz.ID] {
|
||||||
|
types[typ] += n
|
||||||
|
total += n
|
||||||
|
}
|
||||||
|
out = append(out, QuizSummary{
|
||||||
|
Quiz: quiz, QuestionCount: total, BestScorePercent: st.Best, AttemptsCount: st.N,
|
||||||
|
QuestionTypes: types, AttemptsUsed: st.Used,
|
||||||
|
})
|
||||||
}
|
}
|
||||||
return out, nil
|
return out, nil
|
||||||
}
|
}
|
||||||
@@ -123,13 +167,16 @@ type QuizDetail struct {
|
|||||||
|
|
||||||
// GetQuiz loads a published quiz by slug with its questions in sort order
|
// GetQuiz loads a published quiz by slug with its questions in sort order
|
||||||
// (shuffled when the quiz says so) and each question's answers. A non-empty
|
// (shuffled when the quiz says so) and each question's answers. A non-empty
|
||||||
// category keeps only that category's questions. Categories lists every
|
// category keeps only that category's questions; a test ignores it, as it
|
||||||
// category of the quiz.
|
// always covers the whole quiz. Categories lists every category of the quiz.
|
||||||
func (s *Service) GetQuiz(ctx context.Context, slug, category string) (*QuizDetail, error) {
|
func (s *Service) GetQuiz(ctx context.Context, slug, category string) (*QuizDetail, error) {
|
||||||
quiz, err := s.publishedQuiz(ctx, slug)
|
quiz, err := s.publishedQuiz(ctx, slug)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
if IsTest(quiz) {
|
||||||
|
category = ""
|
||||||
|
}
|
||||||
questions, err := s.questions(ctx, quiz.ID, category)
|
questions, err := s.questions(ctx, quiz.ID, category)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@@ -179,38 +226,162 @@ func (s *Service) categories(ctx context.Context, quizID uint) ([]string, error)
|
|||||||
return cats, err
|
return cats, err
|
||||||
}
|
}
|
||||||
|
|
||||||
// StartAttempt starts an attempt at a published quiz for the user. A
|
// Started is the attempt POST /quizzes/{slug}/attempts answers with.
|
||||||
// non-empty category limits the attempt to that category's questions; a
|
type Started struct {
|
||||||
// category without questions is a FieldError on category.
|
Attempt *models.Attempt
|
||||||
|
Quiz *models.Quiz
|
||||||
|
// Resumed is true when an open test attempt was returned instead of a
|
||||||
|
// new one.
|
||||||
|
Resumed bool
|
||||||
|
// AttemptsUsed counts the user's attempts on the quiz, this one
|
||||||
|
// included; it is only counted for tests.
|
||||||
|
AttemptsUsed int
|
||||||
|
// AnsweredCount is the number of questions a resumed attempt answered.
|
||||||
|
AnsweredCount int
|
||||||
|
// OpenAnswers and Unreviewed count the open answers of a resumed
|
||||||
|
// attempt, as in AttemptSummary.
|
||||||
|
OpenAnswers int
|
||||||
|
Unreviewed int
|
||||||
|
}
|
||||||
|
|
||||||
|
// StartAttempt starts an attempt at a published quiz for the user, like
|
||||||
|
// Start without the resume and limit details.
|
||||||
func (s *Service) StartAttempt(ctx context.Context, userID uint, slug, category string) (*models.Attempt, *models.Quiz, error) {
|
func (s *Service) StartAttempt(ctx context.Context, userID uint, slug, category string) (*models.Attempt, *models.Quiz, error) {
|
||||||
quiz, err := s.publishedQuiz(ctx, slug)
|
st, err := s.Start(ctx, userID, slug, category)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, nil, err
|
return nil, nil, err
|
||||||
}
|
}
|
||||||
|
return st.Attempt, st.Quiz, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Start starts an attempt at a published quiz for the user.
|
||||||
|
//
|
||||||
|
// For a learning quiz a non-empty category limits the attempt to that
|
||||||
|
// category's questions; a category without questions is a FieldError on
|
||||||
|
// category. Every call creates a new attempt.
|
||||||
|
//
|
||||||
|
// A test always covers the whole quiz, so a category is a FieldError
|
||||||
|
// (category_not_allowed). Under an advisory lock per (quiz, user) it closes
|
||||||
|
// the user's open attempts past their deadline and grace at the deadline,
|
||||||
|
// resumes a remaining open attempt (Resumed) and otherwise refuses with
|
||||||
|
// ErrAttemptLimit once the user's attempts, open or completed and in any
|
||||||
|
// mode, reach max_attempts.
|
||||||
|
func (s *Service) Start(ctx context.Context, userID uint, slug, category string) (*Started, error) {
|
||||||
|
quiz, err := s.publishedQuiz(ctx, slug)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if IsTest(quiz) {
|
||||||
|
if category != "" {
|
||||||
|
return nil, &FieldError{Field: "category", Key: "category_not_allowed"}
|
||||||
|
}
|
||||||
|
return s.startTest(ctx, userID, quiz)
|
||||||
|
}
|
||||||
attempt := &models.Attempt{QuizID: quiz.ID, UserID: userID, StartedAt: s.now().UTC()}
|
attempt := &models.Attempt{QuizID: quiz.ID, UserID: userID, StartedAt: s.now().UTC()}
|
||||||
if category != "" {
|
if category != "" {
|
||||||
var n int64
|
var n int64
|
||||||
if err := s.db(ctx).Model(&models.Question{}).Where("quiz_id = ? AND category = ?", quiz.ID, category).Count(&n).Error; err != nil {
|
if err := s.db(ctx).Model(&models.Question{}).Where("quiz_id = ? AND category = ?", quiz.ID, category).Count(&n).Error; err != nil {
|
||||||
return nil, nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
if n == 0 {
|
if n == 0 {
|
||||||
return nil, nil, &FieldError{Field: "category", Key: "unknown_category"}
|
return nil, &FieldError{Field: "category", Key: "unknown_category"}
|
||||||
}
|
}
|
||||||
attempt.Category = &category
|
attempt.Category = &category
|
||||||
}
|
}
|
||||||
maxPoints, err := s.maxPoints(ctx, attempt)
|
maxPoints, err := s.maxPoints(ctx, s.DB, attempt)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
attempt.MaxPoints = maxPoints
|
attempt.MaxPoints = maxPoints
|
||||||
if err := s.db(ctx).Create(attempt).Error; err != nil {
|
if err := s.db(ctx).Create(attempt).Error; err != nil {
|
||||||
return nil, nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
return attempt, quiz, nil
|
return &Started{Attempt: attempt, Quiz: quiz}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *Service) maxPoints(ctx context.Context, a *models.Attempt) (int, error) {
|
func (s *Service) startTest(ctx context.Context, userID uint, quiz *models.Quiz) (*Started, error) {
|
||||||
q := s.db(ctx).Model(&models.Question{}).Where("quiz_id = ?", a.QuizID)
|
var st *Started
|
||||||
|
// limited refuses the start after the commit, so the expired attempts
|
||||||
|
// closed on the way stay closed (an error would roll the closes back).
|
||||||
|
var limited bool
|
||||||
|
err := lagoon.Transaction(ctx, s.DB, func(ctx context.Context, tx *gorm.DB) error {
|
||||||
|
tx = tx.WithContext(ctx)
|
||||||
|
if err := tx.Exec(`SELECT pg_advisory_xact_lock(hashtext(?))`, AttemptLockKey(quiz.ID, userID)).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
var open []models.Attempt
|
||||||
|
if err := tx.Clauses(clause.Locking{Strength: "UPDATE", Table: clause.Table{Name: clause.CurrentTable}}).
|
||||||
|
Where("quiz_id = ? AND user_id = ? AND completed_at IS NULL", quiz.ID, userID).
|
||||||
|
Order("started_at ASC, id ASC").Find(&open).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
now := s.now()
|
||||||
|
var resume *models.Attempt
|
||||||
|
for i := range open {
|
||||||
|
a := &open[i]
|
||||||
|
a.Quiz = quiz
|
||||||
|
if Expired(a, now, s.Grace) {
|
||||||
|
if err := s.close(ctx, tx, a, *Deadline(a)); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
// An open attempt left from the quiz's learning days may cover
|
||||||
|
// one category; a test only resumes a whole-quiz attempt.
|
||||||
|
if resume == nil && a.Category == nil {
|
||||||
|
resume = a
|
||||||
|
}
|
||||||
|
}
|
||||||
|
var used int64
|
||||||
|
if err := tx.Model(&models.Attempt{}).Where("quiz_id = ? AND user_id = ?", quiz.ID, userID).Count(&used).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if resume != nil {
|
||||||
|
counts, err := answerCounts(ctx, tx, []uint{resume.ID})
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
c := counts[resume.ID]
|
||||||
|
st = &Started{
|
||||||
|
Attempt: resume, Quiz: quiz, Resumed: true, AttemptsUsed: int(used),
|
||||||
|
AnsweredCount: c.N, OpenAnswers: c.OpenN, Unreviewed: c.UnreviewedN,
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if left := AttemptsLeft(quiz, int(used)); left != nil && *left == 0 {
|
||||||
|
limited = true
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
attempt := &models.Attempt{QuizID: quiz.ID, UserID: userID, StartedAt: now.UTC()}
|
||||||
|
maxPoints, err := s.maxPoints(ctx, tx, attempt)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
attempt.MaxPoints = maxPoints
|
||||||
|
if err := tx.Create(attempt).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
st = &Started{Attempt: attempt, Quiz: quiz, AttemptsUsed: int(used) + 1}
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if limited {
|
||||||
|
return nil, ErrAttemptLimit
|
||||||
|
}
|
||||||
|
return st, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// AttemptsUsed counts the user's attempts on the quiz, open or completed.
|
||||||
|
func (s *Service) AttemptsUsed(ctx context.Context, quizID, userID uint) (int, error) {
|
||||||
|
var n int64
|
||||||
|
err := s.db(ctx).Model(&models.Attempt{}).Where("quiz_id = ? AND user_id = ?", quizID, userID).Count(&n).Error
|
||||||
|
return int(n), err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Service) maxPoints(ctx context.Context, db *gorm.DB, a *models.Attempt) (int, error) {
|
||||||
|
q := db.WithContext(ctx).Model(&models.Question{}).Where("quiz_id = ?", a.QuizID)
|
||||||
if a.Category != nil {
|
if a.Category != nil {
|
||||||
q = q.Where("category = ?", *a.Category)
|
q = q.Where("category = ?", *a.Category)
|
||||||
}
|
}
|
||||||
@@ -251,6 +422,8 @@ type AnswerInput struct {
|
|||||||
QuestionID uint
|
QuestionID uint
|
||||||
AnswerIDs []uint
|
AnswerIDs []uint
|
||||||
Known *bool
|
Known *bool
|
||||||
|
// Text is the answer to an open question.
|
||||||
|
Text *string
|
||||||
}
|
}
|
||||||
|
|
||||||
// Feedback is what the user learns after answering one question.
|
// Feedback is what the user learns after answering one question.
|
||||||
@@ -258,14 +431,27 @@ type Feedback struct {
|
|||||||
Question models.Question
|
Question models.Question
|
||||||
Result ScoreResult
|
Result ScoreResult
|
||||||
CorrectAnswerIDs []uint
|
CorrectAnswerIDs []uint
|
||||||
|
// Withheld is set for an open test attempt: the solutions stay hidden
|
||||||
|
// and the serializer must drop Result, CorrectAnswerIDs and every
|
||||||
|
// solution field of Question.
|
||||||
|
Withheld bool
|
||||||
|
// Answer is the stored row of an open question, with its text and
|
||||||
|
// grading state; it is nil for every other type.
|
||||||
|
Answer *models.AttemptAnswer
|
||||||
}
|
}
|
||||||
|
|
||||||
// Answer records or overwrites the user's answer to one question of an
|
// Answer records or overwrites the user's answer to one question of an
|
||||||
// open attempt and returns the feedback. It checks, in order: the attempt
|
// open attempt and returns the feedback. It checks, in order: the attempt
|
||||||
// belongs to the user (ErrNotFound), is not finished (ErrCompleted), is
|
// belongs to the user (ErrNotFound), is not finished (ErrCompleted), is
|
||||||
// within the time limit (ErrTimeLimit), the question belongs to the attempt
|
// within the time limit, plus the grace of a test (ErrTimeLimit), the
|
||||||
// (FieldError on question_id), and the answer fits the question type
|
// question belongs to the attempt (FieldError on question_id), a one_way
|
||||||
// (FieldError on answer_ids or known).
|
// test has no answer to the question yet (ErrAnswerLocked; the attempt row
|
||||||
|
// is locked, so the check is race-free), and the answer fits the question
|
||||||
|
// type (FieldError on answer_ids, known or text). The feedback of an open
|
||||||
|
// test attempt is Withheld.
|
||||||
|
//
|
||||||
|
// An open question stores its text as pending (see answerOpen) and is never
|
||||||
|
// scored here: a grader or the owner scores it later.
|
||||||
func (s *Service) Answer(ctx context.Context, userID, attemptID uint, in AnswerInput) (*Feedback, error) {
|
func (s *Service) Answer(ctx context.Context, userID, attemptID uint, in AnswerInput) (*Feedback, error) {
|
||||||
var fb *Feedback
|
var fb *Feedback
|
||||||
err := lagoon.Transaction(ctx, s.DB, func(ctx context.Context, tx *gorm.DB) error {
|
err := lagoon.Transaction(ctx, s.DB, func(ctx context.Context, tx *gorm.DB) error {
|
||||||
@@ -276,7 +462,7 @@ func (s *Service) Answer(ctx context.Context, userID, attemptID uint, in AnswerI
|
|||||||
if attempt.CompletedAt != nil {
|
if attempt.CompletedAt != nil {
|
||||||
return ErrCompleted
|
return ErrCompleted
|
||||||
}
|
}
|
||||||
if d := Deadline(attempt); d != nil && s.now().After(*d) {
|
if d := AnswerDeadline(attempt, s.Grace); d != nil && s.now().After(*d) {
|
||||||
return ErrTimeLimit
|
return ErrTimeLimit
|
||||||
}
|
}
|
||||||
var question models.Question
|
var question models.Question
|
||||||
@@ -292,9 +478,33 @@ func (s *Service) Answer(ctx context.Context, userID, attemptID uint, in AnswerI
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
if OneWay(attempt.Quiz) {
|
||||||
|
var given int64
|
||||||
|
if err := tx.WithContext(ctx).Model(&models.AttemptAnswer{}).
|
||||||
|
Where("attempt_id = ? AND question_id = ?", attempt.ID, question.ID).Count(&given).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if given > 0 {
|
||||||
|
return ErrAnswerLocked
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
row := models.AttemptAnswer{AttemptID: attempt.ID, QuestionID: question.ID}
|
row := models.AttemptAnswer{AttemptID: attempt.ID, QuestionID: question.ID}
|
||||||
switch question.Type {
|
switch question.Type {
|
||||||
|
case models.TypeOpen:
|
||||||
|
if in.Text == nil {
|
||||||
|
return &FieldError{Field: "text", Key: "text_required"}
|
||||||
|
}
|
||||||
|
text, err := CheckOpenText(*in.Text, question)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
stored, err := s.answerOpen(ctx, tx, attempt, question, text)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
fb = &Feedback{Question: question, Answer: stored, Withheld: Withheld(attempt)}
|
||||||
|
return nil
|
||||||
case models.TypeSelfCheck:
|
case models.TypeSelfCheck:
|
||||||
if in.Known == nil {
|
if in.Known == nil {
|
||||||
return &FieldError{Field: "known", Key: "known_required"}
|
return &FieldError{Field: "known", Key: "known_required"}
|
||||||
@@ -328,13 +538,21 @@ func (s *Service) Answer(ctx context.Context, userID, attemptID uint, in AnswerI
|
|||||||
row.IsCorrect, row.Points = res.IsCorrect, res.Points
|
row.IsCorrect, row.Points = res.IsCorrect, res.Points
|
||||||
now := s.now().UTC()
|
now := s.now().UTC()
|
||||||
row.CreatedAt, row.UpdatedAt = now, now
|
row.CreatedAt, row.UpdatedAt = now, now
|
||||||
|
// A row left by the question's open past loses its text, grade
|
||||||
|
// and review: a choice or self-check answer has none (its
|
||||||
|
// grading_status NULL keeps a queued grading job from acting).
|
||||||
if err := tx.WithContext(ctx).Clauses(clause.OnConflict{
|
if err := tx.WithContext(ctx).Clauses(clause.OnConflict{
|
||||||
Columns: []clause.Column{{Name: "attempt_id"}, {Name: "question_id"}},
|
Columns: []clause.Column{{Name: "attempt_id"}, {Name: "question_id"}},
|
||||||
DoUpdates: clause.AssignmentColumns([]string{"answer_ids", "self_check_known", "is_correct", "points", "updated_at"}),
|
DoUpdates: clause.AssignmentColumns([]string{
|
||||||
|
"answer_ids", "self_check_known", "is_correct", "points", "updated_at",
|
||||||
|
"text_answer", "grading_status", "grading_attempts", "grader", "grader_points",
|
||||||
|
"grader_feedback", "grading_error", "graded_at", "review_comment", "reviewed_at",
|
||||||
|
"reviewed_by_user_id", "reviewed_by_admin_id",
|
||||||
|
}),
|
||||||
}).Create(&row).Error; err != nil {
|
}).Create(&row).Error; err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
fb = &Feedback{Question: question, Result: res, CorrectAnswerIDs: correct}
|
fb = &Feedback{Question: question, Result: res, CorrectAnswerIDs: correct, Withheld: Withheld(attempt)}
|
||||||
return nil
|
return nil
|
||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -343,6 +561,78 @@ func (s *Service) Answer(ctx context.Context, userID, attemptID uint, in AnswerI
|
|||||||
return fb, nil
|
return fb, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// answerOpen stores a cleaned open answer in a transaction that holds the
|
||||||
|
// attempt row lock, so reading the existing row first is race-free. The
|
||||||
|
// same text again changes nothing. Another text is a new answer (Pitfall 1):
|
||||||
|
// the row goes back to pending with the next grading_seq, and every grade,
|
||||||
|
// error, review and point of the old text is cleared, so a learning
|
||||||
|
// re-answer replaces an earlier grade or review. A first answer creates the
|
||||||
|
// row as pending with seq 1. In a learning quiz a new or changed text is
|
||||||
|
// handed to enqueueGrading at once; a test enqueues its open answers when
|
||||||
|
// it closes (UD-2).
|
||||||
|
func (s *Service) answerOpen(ctx context.Context, tx *gorm.DB, attempt *models.Attempt, question models.Question, text string) (*models.AttemptAnswer, error) {
|
||||||
|
tx = tx.WithContext(ctx)
|
||||||
|
now := s.now().UTC()
|
||||||
|
var existing models.AttemptAnswer
|
||||||
|
err := tx.Where("attempt_id = ? AND question_id = ?", attempt.ID, question.ID).Take(&existing).Error
|
||||||
|
switch {
|
||||||
|
case err == nil:
|
||||||
|
if existing.TextAnswer != nil && *existing.TextAnswer == text && existing.GradingStatus != nil {
|
||||||
|
return &existing, nil
|
||||||
|
}
|
||||||
|
seq := existing.GradingSeq + 1
|
||||||
|
if err := tx.Model(&models.AttemptAnswer{}).Where("id = ?", existing.ID).Updates(map[string]any{
|
||||||
|
"text_answer": text,
|
||||||
|
"answer_ids": nil,
|
||||||
|
"self_check_known": nil,
|
||||||
|
"grading_status": models.GradingPending,
|
||||||
|
"grading_seq": seq,
|
||||||
|
"grading_attempts": 0,
|
||||||
|
"grader": nil,
|
||||||
|
"grader_points": nil,
|
||||||
|
"grader_feedback": nil,
|
||||||
|
"grading_error": nil,
|
||||||
|
"graded_at": nil,
|
||||||
|
"review_comment": nil,
|
||||||
|
"reviewed_at": nil,
|
||||||
|
"reviewed_by_user_id": nil,
|
||||||
|
"reviewed_by_admin_id": nil,
|
||||||
|
"points": 0,
|
||||||
|
"is_correct": false,
|
||||||
|
"updated_at": now,
|
||||||
|
}).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if err := tx.Where("id = ?", existing.ID).Take(&existing).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if !IsTest(attempt.Quiz) {
|
||||||
|
if err := s.enqueueGrading(ctx, tx, existing.ID, seq, attempt); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return &existing, nil
|
||||||
|
case errors.Is(err, gorm.ErrRecordNotFound):
|
||||||
|
default:
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
pending := models.GradingPending
|
||||||
|
row := &models.AttemptAnswer{
|
||||||
|
AttemptID: attempt.ID, QuestionID: question.ID,
|
||||||
|
TextAnswer: &text, GradingStatus: &pending, GradingSeq: 1,
|
||||||
|
CreatedAt: now, UpdatedAt: now,
|
||||||
|
}
|
||||||
|
if err := tx.Create(row).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if !IsTest(attempt.Quiz) {
|
||||||
|
if err := s.enqueueGrading(ctx, tx, row.ID, row.GradingSeq, attempt); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return row, nil
|
||||||
|
}
|
||||||
|
|
||||||
// CorrectAnswerIDs lists the IDs of a question's correct answers in sort
|
// CorrectAnswerIDs lists the IDs of a question's correct answers in sort
|
||||||
// order; it is empty for a self_check question.
|
// order; it is empty for a self_check question.
|
||||||
func CorrectAnswerIDs(q models.Question) []uint {
|
func CorrectAnswerIDs(q models.Question) []uint {
|
||||||
@@ -368,24 +658,7 @@ func (s *Service) Finish(ctx context.Context, userID, attemptID uint) (*AttemptR
|
|||||||
if attempt.CompletedAt != nil {
|
if attempt.CompletedAt != nil {
|
||||||
return ErrCompleted
|
return ErrCompleted
|
||||||
}
|
}
|
||||||
var points []float64
|
return s.close(ctx, tx, attempt, s.now())
|
||||||
if err := tx.WithContext(ctx).Model(&models.AttemptAnswer{}).Where("attempt_id = ?", attempt.ID).
|
|
||||||
Pluck("points", &points).Error; err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
maxPoints, err := s.maxPoints(ctx, attempt)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
score, percent := Totals(points, maxPoints)
|
|
||||||
now := s.now().UTC()
|
|
||||||
return tx.WithContext(ctx).Model(&models.Attempt{}).Where("id = ?", attempt.ID).Updates(map[string]any{
|
|
||||||
"completed_at": now,
|
|
||||||
"score_points": score,
|
|
||||||
"max_points": maxPoints,
|
|
||||||
"score_percent": percent,
|
|
||||||
"updated_at": now,
|
|
||||||
}).Error
|
|
||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@@ -393,10 +666,88 @@ func (s *Service) Finish(ctx context.Context, userID, attemptID uint) (*AttemptR
|
|||||||
return s.Result(ctx, userID, attemptID)
|
return s.Result(ctx, userID, attemptID)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// close completes an attempt at the given time: it sums the recorded
|
||||||
|
// answers, floors the total at 0 and stores the score. Finish closes at the
|
||||||
|
// current time, an expired test closes at its deadline. A test then
|
||||||
|
// enqueues one grading job per pending open answer (UD-2); every caller
|
||||||
|
// sets attempt.Quiz. An attempt whose open answers were all reviewed
|
||||||
|
// while it was open is announced as reviewed once it closes.
|
||||||
|
func (s *Service) close(ctx context.Context, tx *gorm.DB, attempt *models.Attempt, at time.Time) error {
|
||||||
|
tx = tx.WithContext(ctx)
|
||||||
|
var points []float64
|
||||||
|
if err := tx.Model(&models.AttemptAnswer{}).Where("attempt_id = ?", attempt.ID).Pluck("points", &points).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
maxPoints, err := s.maxPoints(ctx, tx, attempt)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
score, percent := Totals(points, maxPoints)
|
||||||
|
at = at.UTC()
|
||||||
|
now := s.now().UTC()
|
||||||
|
if err := tx.Model(&models.Attempt{}).Where("id = ?", attempt.ID).Updates(map[string]any{
|
||||||
|
"completed_at": at,
|
||||||
|
"score_points": score,
|
||||||
|
"max_points": maxPoints,
|
||||||
|
"score_percent": percent,
|
||||||
|
"updated_at": now,
|
||||||
|
}).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := s.enqueuePending(ctx, tx, attempt); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return s.fireAttemptReviewedIfDone(ctx, tx, attempt.ID)
|
||||||
|
}
|
||||||
|
|
||||||
// AttemptSummary is an attempt with its quiz and answered question count.
|
// AttemptSummary is an attempt with its quiz and answered question count.
|
||||||
type AttemptSummary struct {
|
type AttemptSummary struct {
|
||||||
Attempt models.Attempt
|
Attempt models.Attempt
|
||||||
AnsweredCount int
|
AnsweredCount int
|
||||||
|
// OpenAnswers counts the attempt's answers to open questions (rows
|
||||||
|
// with a grading status).
|
||||||
|
OpenAnswers int
|
||||||
|
// Unreviewed counts the open answers the owner has not reviewed yet:
|
||||||
|
// pending, graded or failed.
|
||||||
|
Unreviewed int
|
||||||
|
}
|
||||||
|
|
||||||
|
// answerCountRow is the per-attempt answer counts answerCounts reads.
|
||||||
|
type answerCountRow struct {
|
||||||
|
AttemptID uint
|
||||||
|
N int
|
||||||
|
OpenN int
|
||||||
|
UnreviewedN int
|
||||||
|
}
|
||||||
|
|
||||||
|
// answerCounts counts, per attempt, the answers, the open answers and the
|
||||||
|
// open answers not reviewed yet.
|
||||||
|
func answerCounts(ctx context.Context, db *gorm.DB, attemptIDs []uint) (map[uint]answerCountRow, error) {
|
||||||
|
var rows []answerCountRow
|
||||||
|
if err := db.WithContext(ctx).Model(&models.AttemptAnswer{}).
|
||||||
|
Select("attempt_id, COUNT(*) AS n, "+
|
||||||
|
"COUNT(*) FILTER (WHERE grading_status IS NOT NULL) AS open_n, "+
|
||||||
|
"COUNT(*) FILTER (WHERE grading_status IN ('pending', 'graded', 'failed')) AS unreviewed_n").
|
||||||
|
Where("attempt_id IN ?", attemptIDs).Group("attempt_id").Scan(&rows).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
out := make(map[uint]answerCountRow, len(rows))
|
||||||
|
for _, r := range rows {
|
||||||
|
out[r.AttemptID] = r
|
||||||
|
}
|
||||||
|
return out, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// unreviewed reports whether an open answer still waits for the owner.
|
||||||
|
func unreviewed(a *models.AttemptAnswer) bool {
|
||||||
|
if a == nil || a.GradingStatus == nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
switch *a.GradingStatus {
|
||||||
|
case models.GradingPending, models.GradingGraded, models.GradingFailed:
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
// QuestionResult is one question of an attempt with the user's answer.
|
// QuestionResult is one question of an attempt with the user's answer.
|
||||||
@@ -413,12 +764,33 @@ type AttemptResult struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Result loads the user's attempt with every question it covers and the
|
// Result loads the user's attempt with every question it covers and the
|
||||||
// answers given.
|
// answers given. A test attempt past its deadline and grace is closed at
|
||||||
|
// its deadline first. The questions of a shuffled test come in an order
|
||||||
|
// seeded by the attempt, the same on every call; other attempts list them
|
||||||
|
// in sort order.
|
||||||
func (s *Service) Result(ctx context.Context, userID, attemptID uint) (*AttemptResult, error) {
|
func (s *Service) Result(ctx context.Context, userID, attemptID uint) (*AttemptResult, error) {
|
||||||
attempt, err := s.ownedAttempt(ctx, s.DB, userID, attemptID, false)
|
attempt, err := s.ownedAttempt(ctx, s.DB, userID, attemptID, false)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
if Expired(attempt, s.now(), s.Grace) {
|
||||||
|
err := lagoon.Transaction(ctx, s.DB, func(ctx context.Context, tx *gorm.DB) error {
|
||||||
|
locked, err := s.ownedAttempt(ctx, tx, userID, attemptID, true)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if !Expired(locked, s.now(), s.Grace) {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return s.close(ctx, tx, locked, *Deadline(locked))
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if attempt, err = s.ownedAttempt(ctx, s.DB, userID, attemptID, false); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
}
|
||||||
category := ""
|
category := ""
|
||||||
if attempt.Category != nil {
|
if attempt.Category != nil {
|
||||||
category = *attempt.Category
|
category = *attempt.Category
|
||||||
@@ -427,6 +799,10 @@ func (s *Service) Result(ctx context.Context, userID, attemptID uint) (*AttemptR
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
if IsTest(attempt.Quiz) && attempt.Quiz.ShuffleQuestions {
|
||||||
|
rand.New(rand.NewPCG(uint64(attempt.ID), uint64(attempt.QuizID))).
|
||||||
|
Shuffle(len(questions), func(i, j int) { questions[i], questions[j] = questions[j], questions[i] })
|
||||||
|
}
|
||||||
var answers []models.AttemptAnswer
|
var answers []models.AttemptAnswer
|
||||||
if err := s.db(ctx).Where("attempt_id = ?", attempt.ID).Find(&answers).Error; err != nil {
|
if err := s.db(ctx).Where("attempt_id = ?", attempt.ID).Find(&answers).Error; err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@@ -436,6 +812,14 @@ func (s *Service) Result(ctx context.Context, userID, attemptID uint) (*AttemptR
|
|||||||
byQuestion[answers[i].QuestionID] = &answers[i]
|
byQuestion[answers[i].QuestionID] = &answers[i]
|
||||||
}
|
}
|
||||||
res := &AttemptResult{AttemptSummary: AttemptSummary{Attempt: *attempt, AnsweredCount: len(answers)}}
|
res := &AttemptResult{AttemptSummary: AttemptSummary{Attempt: *attempt, AnsweredCount: len(answers)}}
|
||||||
|
for i := range answers {
|
||||||
|
if answers[i].GradingStatus != nil {
|
||||||
|
res.OpenAnswers++
|
||||||
|
}
|
||||||
|
if unreviewed(&answers[i]) {
|
||||||
|
res.Unreviewed++
|
||||||
|
}
|
||||||
|
}
|
||||||
for _, q := range questions {
|
for _, q := range questions {
|
||||||
res.Questions = append(res.Questions, QuestionResult{Question: q, Answer: byQuestion[q.ID]})
|
res.Questions = append(res.Questions, QuestionResult{Question: q, Answer: byQuestion[q.ID]})
|
||||||
}
|
}
|
||||||
@@ -466,21 +850,13 @@ func (s *Service) History(ctx context.Context, userID uint, quizSlug string, pag
|
|||||||
for i, a := range attempts {
|
for i, a := range attempts {
|
||||||
ids[i] = a.ID
|
ids[i] = a.ID
|
||||||
}
|
}
|
||||||
type countRow struct {
|
countBy, err := answerCounts(ctx, s.DB, ids)
|
||||||
AttemptID uint
|
if err != nil {
|
||||||
N int
|
|
||||||
}
|
|
||||||
var counts []countRow
|
|
||||||
if err := s.db(ctx).Model(&models.AttemptAnswer{}).Select("attempt_id, COUNT(*) AS n").
|
|
||||||
Where("attempt_id IN ?", ids).Group("attempt_id").Scan(&counts).Error; err != nil {
|
|
||||||
return nil, 0, err
|
return nil, 0, err
|
||||||
}
|
}
|
||||||
countBy := map[uint]int{}
|
|
||||||
for _, c := range counts {
|
|
||||||
countBy[c.AttemptID] = c.N
|
|
||||||
}
|
|
||||||
for _, a := range attempts {
|
for _, a := range attempts {
|
||||||
out = append(out, AttemptSummary{Attempt: a, AnsweredCount: countBy[a.ID]})
|
c := countBy[a.ID]
|
||||||
|
out = append(out, AttemptSummary{Attempt: a, AnsweredCount: c.N, OpenAnswers: c.OpenN, Unreviewed: c.UnreviewedN})
|
||||||
}
|
}
|
||||||
return out, total, nil
|
return out, total, nil
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,3 +8,13 @@ scoring:
|
|||||||
# Fraction of a question's points subtracted for a wrong answer (0 to 1).
|
# Fraction of a question's points subtracted for a wrong answer (0 to 1).
|
||||||
# An attempt's total never goes below 0.
|
# An attempt's total never goes below 0.
|
||||||
penalty_wrong: 0
|
penalty_wrong: 0
|
||||||
|
test:
|
||||||
|
# Seconds after a test's time limit during which an answer still in flight
|
||||||
|
# is accepted (0 to 120). Learning quizzes have no grace.
|
||||||
|
grace_seconds: 5
|
||||||
|
throttle:
|
||||||
|
# Per-user limits of the student's answers and attempt starts, per minute.
|
||||||
|
# With a grader such as ai, every new or changed open answer in a learning
|
||||||
|
# quiz is a paid grading call, so keep these low.
|
||||||
|
answers_per_minute: 60
|
||||||
|
attempts_per_minute: 10
|
||||||
|
|||||||
@@ -41,6 +41,7 @@ var (
|
|||||||
{Field: "answer_ids", Rules: lagoon.ParseRules("nullable|array")},
|
{Field: "answer_ids", Rules: lagoon.ParseRules("nullable|array")},
|
||||||
{Field: "answer_ids.*", Rules: lagoon.ParseRules("integer|min:1")},
|
{Field: "answer_ids.*", Rules: lagoon.ParseRules("integer|min:1")},
|
||||||
{Field: "known", Rules: lagoon.ParseRules("nullable|boolean")},
|
{Field: "known", Rules: lagoon.ParseRules("nullable|boolean")},
|
||||||
|
{Field: "text", Rules: lagoon.ParseRules("nullable|string")},
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -62,9 +63,10 @@ func (h *Handlers) ListQuizzes(w http.ResponseWriter, r *http.Request) {
|
|||||||
wire.WriteJSON(w, http.StatusOK, map[string]any{"data": out})
|
wire.WriteJSON(w, http.StatusOK, map[string]any{"data": out})
|
||||||
}
|
}
|
||||||
|
|
||||||
// ShowQuiz answers GET /quizzes/{slug}?category=.
|
// ShowQuiz answers GET /quizzes/{slug}?category=. A test ignores the
|
||||||
|
// category and carries attempts_left.
|
||||||
func (h *Handlers) ShowQuiz(w http.ResponseWriter, r *http.Request) {
|
func (h *Handlers) ShowQuiz(w http.ResponseWriter, r *http.Request) {
|
||||||
_, svc, ok := h.begin(w, r)
|
userID, svc, ok := h.begin(w, r)
|
||||||
if !ok {
|
if !ok {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -73,11 +75,21 @@ func (h *Handlers) ShowQuiz(w http.ResponseWriter, r *http.Request) {
|
|||||||
h.writeError(w, r, err)
|
h.writeError(w, r, err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
wire.WriteJSON(w, http.StatusOK, map[string]any{"data": quizDetail(detail)})
|
out := quizDetail(detail)
|
||||||
|
if classes.IsTest(&detail.Quiz) {
|
||||||
|
used, err := svc.AttemptsUsed(r.Context(), detail.Quiz.ID, userID)
|
||||||
|
if err != nil {
|
||||||
|
wire.WriteOpaque500(w)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
out.AttemptsLeft = classes.AttemptsLeft(&detail.Quiz, used)
|
||||||
|
}
|
||||||
|
wire.WriteJSON(w, http.StatusOK, map[string]any{"data": out})
|
||||||
}
|
}
|
||||||
|
|
||||||
// StartAttempt answers POST /quizzes/{slug}/attempts with an optional
|
// StartAttempt answers POST /quizzes/{slug}/attempts with an optional
|
||||||
// {"category": "..."} body.
|
// {"category": "..."} body: 201 with a new attempt, or 200 when an open
|
||||||
|
// test attempt is resumed.
|
||||||
func (h *Handlers) StartAttempt(w http.ResponseWriter, r *http.Request) {
|
func (h *Handlers) StartAttempt(w http.ResponseWriter, r *http.Request) {
|
||||||
userID, ok := h.user(w, r)
|
userID, ok := h.user(w, r)
|
||||||
if !ok {
|
if !ok {
|
||||||
@@ -92,17 +104,21 @@ func (h *Handlers) StartAttempt(w http.ResponseWriter, r *http.Request) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
category, _ := input["category"].(string)
|
category, _ := input["category"].(string)
|
||||||
a, quiz, err := svc.StartAttempt(r.Context(), userID, r.PathValue("slug"), strings.TrimSpace(category))
|
st, err := svc.Start(r.Context(), userID, r.PathValue("slug"), strings.TrimSpace(category))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
h.writeError(w, r, err)
|
h.writeError(w, r, err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
a.Quiz = quiz
|
status := http.StatusCreated
|
||||||
wire.WriteJSON(w, http.StatusCreated, map[string]any{"data": attempt(classes.AttemptSummary{Attempt: *a})})
|
if st.Resumed {
|
||||||
|
status = http.StatusOK
|
||||||
|
}
|
||||||
|
wire.WriteJSON(w, status, map[string]any{"data": start(st)})
|
||||||
}
|
}
|
||||||
|
|
||||||
// Answer answers POST /attempts/{id}/answers with
|
// Answer answers POST /attempts/{id}/answers with
|
||||||
// {"question_id": 1, "answer_ids": [2], "known": true}.
|
// {"question_id": 1, "answer_ids": [2], "known": true}; an open question
|
||||||
|
// takes {"question_id": 1, "text": "..."}.
|
||||||
func (h *Handlers) Answer(w http.ResponseWriter, r *http.Request) {
|
func (h *Handlers) Answer(w http.ResponseWriter, r *http.Request) {
|
||||||
userID, ok := h.user(w, r)
|
userID, ok := h.user(w, r)
|
||||||
if !ok {
|
if !ok {
|
||||||
@@ -133,6 +149,10 @@ func (h *Handlers) Answer(w http.ResponseWriter, r *http.Request) {
|
|||||||
known := toBool(raw)
|
known := toBool(raw)
|
||||||
in.Known = &known
|
in.Known = &known
|
||||||
}
|
}
|
||||||
|
if raw, present := input["text"]; present && raw != nil {
|
||||||
|
text, _ := raw.(string) // the string rule already refused anything else
|
||||||
|
in.Text = &text
|
||||||
|
}
|
||||||
fb, err := svc.Answer(r.Context(), userID, attemptID, in)
|
fb, err := svc.Answer(r.Context(), userID, attemptID, in)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
h.writeError(w, r, err)
|
h.writeError(w, r, err)
|
||||||
@@ -239,11 +259,9 @@ func (h *Handlers) service(w http.ResponseWriter) (*classes.Service, bool) {
|
|||||||
if h.Service != nil {
|
if h.Service != nil {
|
||||||
return h.Service(gdb), true
|
return h.Service(gdb), true
|
||||||
}
|
}
|
||||||
var scoring classes.ScoringConfig
|
// The scoring and grace come from the config as before; ForApp adds
|
||||||
if h.App != nil {
|
// the grader registry, the job queue and the event bus.
|
||||||
scoring = classes.ScoringConfigFrom(h.App.Config)
|
return classes.ForApp(h.App, gdb), true
|
||||||
}
|
|
||||||
return &classes.Service{DB: gdb, Scoring: scoring}, true
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// input decodes a JSON body (an empty body is {}) and validates it. It
|
// input decodes a JSON body (an empty body is {}) and validates it. It
|
||||||
@@ -315,12 +333,36 @@ var apiMessages = map[string]string{
|
|||||||
"answer_not_in_question": "The chosen answers do not belong to this question.",
|
"answer_not_in_question": "The chosen answers do not belong to this question.",
|
||||||
"single_one_answer": "Choose exactly one answer for this question.",
|
"single_one_answer": "Choose exactly one answer for this question.",
|
||||||
"known_required": "The known field is required for this question.",
|
"known_required": "The known field is required for this question.",
|
||||||
|
"text_required": "Write an answer to this question.",
|
||||||
|
"text_too_long": "The answer is longer than this question allows.",
|
||||||
"unknown_category": "The quiz has no questions in this category.",
|
"unknown_category": "The quiz has no questions in this category.",
|
||||||
"validation_failed": "The given data was invalid.",
|
"validation_failed": "The given data was invalid.",
|
||||||
|
"attempt_limit_reached": "All attempts at this test have been used.",
|
||||||
|
"answer_locked": "An answer in this test cannot be changed.",
|
||||||
|
"category_not_allowed": "A test covers the whole quiz; a category cannot be chosen.",
|
||||||
}
|
}
|
||||||
|
|
||||||
// writeError maps a service error onto the API's status codes.
|
// conflicts are the service errors answered with 409 and the code (also
|
||||||
|
// the lang.api key of the message) the body carries.
|
||||||
|
var conflicts = []struct {
|
||||||
|
err error
|
||||||
|
code string
|
||||||
|
}{
|
||||||
|
{classes.ErrCompleted, "attempt_completed"},
|
||||||
|
{classes.ErrTimeLimit, "time_limit_exceeded"},
|
||||||
|
{classes.ErrAttemptLimit, "attempt_limit_reached"},
|
||||||
|
{classes.ErrAnswerLocked, "answer_locked"},
|
||||||
|
}
|
||||||
|
|
||||||
|
// writeError maps a service error onto the API's status codes. A 409 body
|
||||||
|
// is {"error": message, "code": key}.
|
||||||
func (h *Handlers) writeError(w http.ResponseWriter, r *http.Request, err error) {
|
func (h *Handlers) writeError(w http.ResponseWriter, r *http.Request, err error) {
|
||||||
|
for _, c := range conflicts {
|
||||||
|
if errors.Is(err, c.err) {
|
||||||
|
wire.WriteJSON(w, http.StatusConflict, map[string]any{"error": h.message(r.Context(), c.code), "code": c.code})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
var fe *classes.FieldError
|
var fe *classes.FieldError
|
||||||
switch {
|
switch {
|
||||||
case errors.As(err, &fe):
|
case errors.As(err, &fe):
|
||||||
@@ -332,10 +374,6 @@ func (h *Handlers) writeError(w http.ResponseWriter, r *http.Request, err error)
|
|||||||
key = "quiz_not_found"
|
key = "quiz_not_found"
|
||||||
}
|
}
|
||||||
wire.WriteJSON(w, http.StatusNotFound, map[string]any{"error": h.message(r.Context(), key)})
|
wire.WriteJSON(w, http.StatusNotFound, map[string]any{"error": h.message(r.Context(), key)})
|
||||||
case errors.Is(err, classes.ErrCompleted):
|
|
||||||
wire.WriteJSON(w, http.StatusConflict, map[string]any{"error": h.message(r.Context(), "attempt_completed")})
|
|
||||||
case errors.Is(err, classes.ErrTimeLimit):
|
|
||||||
wire.WriteJSON(w, http.StatusConflict, map[string]any{"error": h.message(r.Context(), "time_limit_exceeded")})
|
|
||||||
default:
|
default:
|
||||||
wire.WriteOpaque500(w)
|
wire.WriteOpaque500(w)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -113,16 +113,21 @@ func TestErrorKeysInRuleOrder(t *testing.T) {
|
|||||||
func TestWriteErrorMapping(t *testing.T) {
|
func TestWriteErrorMapping(t *testing.T) {
|
||||||
h := New(nil)
|
h := New(nil)
|
||||||
cases := []struct {
|
cases := []struct {
|
||||||
err error
|
err error
|
||||||
slug string
|
slug string
|
||||||
code int
|
code int
|
||||||
msg string
|
msg string
|
||||||
|
errCode string
|
||||||
|
errField string
|
||||||
}{
|
}{
|
||||||
{classes.ErrNotFound, "quiz", 404, "Quiz not found"},
|
{classes.ErrNotFound, "quiz", 404, "Quiz not found", "", ""},
|
||||||
{classes.ErrNotFound, "", 404, "Attempt not found"},
|
{classes.ErrNotFound, "", 404, "Attempt not found", "", ""},
|
||||||
{classes.ErrCompleted, "", 409, apiMessages["attempt_completed"]},
|
{classes.ErrCompleted, "", 409, apiMessages["attempt_completed"], "attempt_completed", ""},
|
||||||
{classes.ErrTimeLimit, "", 409, apiMessages["time_limit_exceeded"]},
|
{classes.ErrTimeLimit, "", 409, apiMessages["time_limit_exceeded"], "time_limit_exceeded", ""},
|
||||||
{&classes.FieldError{Field: "question_id", Key: "question_not_in_quiz"}, "", 422, apiMessages["question_not_in_quiz"]},
|
{classes.ErrAttemptLimit, "quiz", 409, apiMessages["attempt_limit_reached"], "attempt_limit_reached", ""},
|
||||||
|
{classes.ErrAnswerLocked, "", 409, apiMessages["answer_locked"], "answer_locked", ""},
|
||||||
|
{&classes.FieldError{Field: "question_id", Key: "question_not_in_quiz"}, "", 422, apiMessages["question_not_in_quiz"], "", "question_id"},
|
||||||
|
{&classes.FieldError{Field: "category", Key: "category_not_allowed"}, "quiz", 422, apiMessages["category_not_allowed"], "", "category"},
|
||||||
}
|
}
|
||||||
for _, tc := range cases {
|
for _, tc := range cases {
|
||||||
req := httptest.NewRequest("GET", "/", nil)
|
req := httptest.NewRequest("GET", "/", nil)
|
||||||
@@ -133,9 +138,17 @@ func TestWriteErrorMapping(t *testing.T) {
|
|||||||
h.writeError(rec, req, tc.err)
|
h.writeError(rec, req, tc.err)
|
||||||
var out map[string]any
|
var out map[string]any
|
||||||
_ = json.Unmarshal(rec.Body.Bytes(), &out)
|
_ = json.Unmarshal(rec.Body.Bytes(), &out)
|
||||||
if rec.Code != tc.code || out["error"] != tc.msg {
|
if rec.Code != tc.code || out["error"] != tc.msg || tc.msg == "" {
|
||||||
t.Errorf("%v = %d %v, want %d %q", tc.err, rec.Code, out, tc.code, tc.msg)
|
t.Errorf("%v = %d %v, want %d %q", tc.err, rec.Code, out, tc.code, tc.msg)
|
||||||
}
|
}
|
||||||
|
if tc.errCode != "" && out["code"] != tc.errCode {
|
||||||
|
t.Errorf("%v code = %v, want %q", tc.err, out["code"], tc.errCode)
|
||||||
|
}
|
||||||
|
if tc.errField != "" {
|
||||||
|
if errs, _ := out["errors"].(map[string]any); errs[tc.errField] == nil {
|
||||||
|
t.Errorf("%v has no error on %s: %v", tc.err, tc.errField, out)
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
rec := httptest.NewRecorder()
|
rec := httptest.NewRecorder()
|
||||||
h.writeError(rec, httptest.NewRequest("GET", "/", nil), http.ErrBodyNotAllowed)
|
h.writeError(rec, httptest.NewRequest("GET", "/", nil), http.ErrBodyNotAllowed)
|
||||||
|
|||||||
@@ -25,11 +25,17 @@ type quizSummaryJSON struct {
|
|||||||
ShuffleQuestions bool `json:"shuffle_questions"`
|
ShuffleQuestions bool `json:"shuffle_questions"`
|
||||||
BestScorePercent *float64 `json:"best_score_percent"`
|
BestScorePercent *float64 `json:"best_score_percent"`
|
||||||
AttemptsCount int `json:"attempts_count"`
|
AttemptsCount int `json:"attempts_count"`
|
||||||
|
Mode string `json:"mode"`
|
||||||
|
Navigation string `json:"navigation"`
|
||||||
|
MaxAttempts *int `json:"max_attempts"`
|
||||||
|
// AttemptsLeft is null for a learning quiz or a test without a limit.
|
||||||
|
AttemptsLeft *int `json:"attempts_left"`
|
||||||
|
QuestionTypes map[string]int `json:"question_types"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func quizSummary(s classes.QuizSummary) quizSummaryJSON {
|
func quizSummary(s classes.QuizSummary) quizSummaryJSON {
|
||||||
q := s.Quiz
|
q := s.Quiz
|
||||||
return quizSummaryJSON{
|
out := quizSummaryJSON{
|
||||||
ID: q.ID,
|
ID: q.ID,
|
||||||
Slug: q.Slug,
|
Slug: q.Slug,
|
||||||
Title: q.Title,
|
Title: q.Title,
|
||||||
@@ -42,10 +48,39 @@ func quizSummary(s classes.QuizSummary) quizSummaryJSON {
|
|||||||
ShuffleQuestions: q.ShuffleQuestions,
|
ShuffleQuestions: q.ShuffleQuestions,
|
||||||
BestScorePercent: s.BestScorePercent,
|
BestScorePercent: s.BestScorePercent,
|
||||||
AttemptsCount: s.AttemptsCount,
|
AttemptsCount: s.AttemptsCount,
|
||||||
|
Mode: quizMode(&q),
|
||||||
|
Navigation: quizNavigation(&q),
|
||||||
|
MaxAttempts: q.MaxAttempts,
|
||||||
|
AttemptsLeft: classes.AttemptsLeft(&q, s.AttemptsUsed),
|
||||||
|
QuestionTypes: make(map[string]int, len(models.QuestionTypes)),
|
||||||
}
|
}
|
||||||
|
for _, typ := range models.QuestionTypes {
|
||||||
|
out.QuestionTypes[typ] = s.QuestionTypes[typ]
|
||||||
|
}
|
||||||
|
return out
|
||||||
}
|
}
|
||||||
|
|
||||||
// quizJSON is GET /quizzes/{slug}: the quiz without any solution.
|
// quizMode is the quiz's mode as the API reports it: test, or learning for
|
||||||
|
// a zero or unknown value (the classes.IsTest rule).
|
||||||
|
func quizMode(q *models.Quiz) string {
|
||||||
|
if classes.IsTest(q) {
|
||||||
|
return models.ModeTest
|
||||||
|
}
|
||||||
|
return models.ModeLearning
|
||||||
|
}
|
||||||
|
|
||||||
|
// quizNavigation is one_way when the quiz says so and free otherwise.
|
||||||
|
func quizNavigation(q *models.Quiz) string {
|
||||||
|
if q != nil && q.Navigation == models.NavigationOneWay {
|
||||||
|
return models.NavigationOneWay
|
||||||
|
}
|
||||||
|
return models.NavigationFree
|
||||||
|
}
|
||||||
|
|
||||||
|
// quizJSON is GET /quizzes/{slug}: the quiz without any solution. A test
|
||||||
|
// lists no questions (QuestionCount still counts them): the test player
|
||||||
|
// reads them from its attempt, so a timed test cannot be read before its
|
||||||
|
// clock starts.
|
||||||
type quizJSON struct {
|
type quizJSON struct {
|
||||||
ID uint `json:"id"`
|
ID uint `json:"id"`
|
||||||
Slug string `json:"slug"`
|
Slug string `json:"slug"`
|
||||||
@@ -59,11 +94,17 @@ type quizJSON struct {
|
|||||||
QuestionCount int `json:"question_count"`
|
QuestionCount int `json:"question_count"`
|
||||||
Categories []string `json:"categories"`
|
Categories []string `json:"categories"`
|
||||||
Questions []questionJSON `json:"questions"`
|
Questions []questionJSON `json:"questions"`
|
||||||
|
Mode string `json:"mode"`
|
||||||
|
Navigation string `json:"navigation"`
|
||||||
|
MaxAttempts *int `json:"max_attempts"`
|
||||||
|
// AttemptsLeft is set by ShowQuiz for a test with a limit.
|
||||||
|
AttemptsLeft *int `json:"attempts_left"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// questionJSON is a question as the player sees it before answering: no
|
// questionJSON is a question as the player sees it before answering: no
|
||||||
// is_correct or explanation, and no answer_text except for self_check
|
// is_correct or explanation, and no answer_text except for self_check
|
||||||
// flashcards, which have no solution to hide.
|
// flashcards, which have no solution to hide. An open question carries its
|
||||||
|
// max_length instead (never its rubric or model answer).
|
||||||
type questionJSON struct {
|
type questionJSON struct {
|
||||||
ID uint `json:"id"`
|
ID uint `json:"id"`
|
||||||
Text string `json:"text"`
|
Text string `json:"text"`
|
||||||
@@ -72,8 +113,10 @@ type questionJSON struct {
|
|||||||
Points int `json:"points"`
|
Points int `json:"points"`
|
||||||
SortOrder int `json:"sort_order"`
|
SortOrder int `json:"sort_order"`
|
||||||
// AnswerText is the model answer of a self_check question only.
|
// AnswerText is the model answer of a self_check question only.
|
||||||
AnswerText *string `json:"answer_text,omitempty"`
|
AnswerText *string `json:"answer_text,omitempty"`
|
||||||
Answers []answerJSON `json:"answers"`
|
// MaxLength is the longest answer of an open question, in characters.
|
||||||
|
MaxLength *int `json:"max_length,omitempty"`
|
||||||
|
Answers []answerJSON `json:"answers"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type answerJSON struct {
|
type answerJSON struct {
|
||||||
@@ -96,6 +139,12 @@ func quizDetail(d *classes.QuizDetail) quizJSON {
|
|||||||
QuestionCount: len(d.Questions),
|
QuestionCount: len(d.Questions),
|
||||||
Categories: wire.Slice(d.Categories),
|
Categories: wire.Slice(d.Categories),
|
||||||
Questions: make([]questionJSON, 0, len(d.Questions)),
|
Questions: make([]questionJSON, 0, len(d.Questions)),
|
||||||
|
Mode: quizMode(&q),
|
||||||
|
Navigation: quizNavigation(&q),
|
||||||
|
MaxAttempts: q.MaxAttempts,
|
||||||
|
}
|
||||||
|
if classes.IsTest(&q) {
|
||||||
|
return out
|
||||||
}
|
}
|
||||||
for _, qu := range d.Questions {
|
for _, qu := range d.Questions {
|
||||||
out.Questions = append(out.Questions, question(qu))
|
out.Questions = append(out.Questions, question(qu))
|
||||||
@@ -116,6 +165,10 @@ func question(q models.Question) questionJSON {
|
|||||||
if q.Type == models.TypeSelfCheck {
|
if q.Type == models.TypeSelfCheck {
|
||||||
out.AnswerText = q.AnswerText
|
out.AnswerText = q.AnswerText
|
||||||
}
|
}
|
||||||
|
if q.Type == models.TypeOpen {
|
||||||
|
n := classes.MaxLength(q)
|
||||||
|
out.MaxLength = &n
|
||||||
|
}
|
||||||
for _, a := range q.Answers {
|
for _, a := range q.Answers {
|
||||||
out.Answers = append(out.Answers, answerJSON{ID: a.ID, Text: a.Text})
|
out.Answers = append(out.Answers, answerJSON{ID: a.ID, Text: a.Text})
|
||||||
}
|
}
|
||||||
@@ -139,19 +192,37 @@ type attemptJSON struct {
|
|||||||
ScorePercent *float64 `json:"score_percent"`
|
ScorePercent *float64 `json:"score_percent"`
|
||||||
PassingScore int `json:"passing_score"`
|
PassingScore int `json:"passing_score"`
|
||||||
Passed *bool `json:"passed"`
|
Passed *bool `json:"passed"`
|
||||||
|
// QuizMode and QuizNavigation tell the player which flow to run.
|
||||||
|
QuizMode string `json:"quiz_mode"`
|
||||||
|
QuizNavigation string `json:"quiz_navigation"`
|
||||||
|
// SecondsLeft is the time left of an open attempt with a limit, counted
|
||||||
|
// by the server.
|
||||||
|
SecondsLeft *int `json:"seconds_left"`
|
||||||
|
// NeedsReview is true while an open answer of the attempt waits for
|
||||||
|
// the owner (pending, graded or failed); OpenAnswers counts its open
|
||||||
|
// answers.
|
||||||
|
NeedsReview bool `json:"needs_review"`
|
||||||
|
OpenAnswers int `json:"open_answers"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// timeNow is the clock of seconds_left; tests pin it.
|
||||||
|
var timeNow = time.Now
|
||||||
|
|
||||||
func attempt(s classes.AttemptSummary) attemptJSON {
|
func attempt(s classes.AttemptSummary) attemptJSON {
|
||||||
a := s.Attempt
|
a := s.Attempt
|
||||||
out := attemptJSON{
|
out := attemptJSON{
|
||||||
ID: a.ID,
|
ID: a.ID,
|
||||||
QuizID: a.QuizID,
|
QuizID: a.QuizID,
|
||||||
Category: a.Category,
|
Category: a.Category,
|
||||||
StartedAt: wireTime(a.StartedAt),
|
StartedAt: wireTime(a.StartedAt),
|
||||||
AnsweredCount: s.AnsweredCount,
|
AnsweredCount: s.AnsweredCount,
|
||||||
ScorePoints: a.ScorePoints,
|
ScorePoints: a.ScorePoints,
|
||||||
MaxPoints: a.MaxPoints,
|
MaxPoints: a.MaxPoints,
|
||||||
ScorePercent: a.ScorePercent,
|
ScorePercent: a.ScorePercent,
|
||||||
|
QuizMode: quizMode(a.Quiz),
|
||||||
|
QuizNavigation: quizNavigation(a.Quiz),
|
||||||
|
NeedsReview: s.Unreviewed > 0,
|
||||||
|
OpenAnswers: s.OpenAnswers,
|
||||||
}
|
}
|
||||||
if a.Quiz != nil {
|
if a.Quiz != nil {
|
||||||
out.QuizSlug, out.QuizTitle, out.PassingScore = a.Quiz.Slug, a.Quiz.Title, a.Quiz.PassingScore
|
out.QuizSlug, out.QuizTitle, out.PassingScore = a.Quiz.Slug, a.Quiz.Title, a.Quiz.PassingScore
|
||||||
@@ -160,6 +231,7 @@ func attempt(s classes.AttemptSummary) attemptJSON {
|
|||||||
t := wireTime(*d)
|
t := wireTime(*d)
|
||||||
out.ExpiresAt = &t
|
out.ExpiresAt = &t
|
||||||
}
|
}
|
||||||
|
out.SecondsLeft = classes.SecondsLeft(&a, timeNow())
|
||||||
if a.CompletedAt != nil {
|
if a.CompletedAt != nil {
|
||||||
t := wireTime(*a.CompletedAt)
|
t := wireTime(*a.CompletedAt)
|
||||||
out.CompletedAt = &t
|
out.CompletedAt = &t
|
||||||
@@ -169,16 +241,47 @@ func attempt(s classes.AttemptSummary) attemptJSON {
|
|||||||
return out
|
return out
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// startJSON is POST /quizzes/{slug}/attempts: the attempt, whether an open
|
||||||
|
// test attempt was resumed, and the attempts left after this one (null for
|
||||||
|
// learning or without a limit).
|
||||||
|
type startJSON struct {
|
||||||
|
attemptJSON
|
||||||
|
Resumed bool `json:"resumed"`
|
||||||
|
AttemptsLeft *int `json:"attempts_left"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func start(st *classes.Started) startJSON {
|
||||||
|
a := *st.Attempt
|
||||||
|
a.Quiz = st.Quiz
|
||||||
|
return startJSON{
|
||||||
|
attemptJSON: attempt(classes.AttemptSummary{
|
||||||
|
Attempt: a, AnsweredCount: st.AnsweredCount, OpenAnswers: st.OpenAnswers, Unreviewed: st.Unreviewed,
|
||||||
|
}),
|
||||||
|
Resumed: st.Resumed,
|
||||||
|
AttemptsLeft: classes.AttemptsLeft(st.Quiz, st.AttemptsUsed),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// resultJSON is GET /attempts/{id} and POST /attempts/{id}/finish.
|
// resultJSON is GET /attempts/{id} and POST /attempts/{id}/finish.
|
||||||
|
// SolutionsWithheld is true for an open test attempt (classes.Withheld).
|
||||||
type resultJSON struct {
|
type resultJSON struct {
|
||||||
attemptJSON
|
attemptJSON
|
||||||
Questions []questionResultJSON `json:"questions"`
|
SolutionsWithheld bool `json:"solutions_withheld"`
|
||||||
|
Questions []questionResultJSON `json:"questions"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// questionResultJSON is one question of a result. The solution fields
|
// questionResultJSON is one question of a result. The solution fields
|
||||||
// (is_correct of the answers, correct_answer_ids, explanation, answer_text)
|
// (is_correct of the answers, correct_answer_ids, explanation, answer_text)
|
||||||
// are revealed for an answered question and for every question once the
|
// are revealed for an answered question and for every question once the
|
||||||
// attempt is completed; otherwise they are null.
|
// attempt is completed; otherwise they are null. While the solutions are
|
||||||
|
// withheld (an open test attempt) every solution field, is_correct and
|
||||||
|
// points_earned included, is null for every question; answered, answer_ids
|
||||||
|
// and known (the student's own input) stay.
|
||||||
|
//
|
||||||
|
// An open question adds the student's text_answer (always: it is their own
|
||||||
|
// input), max_length and, unless withheld, grading_status, grader_feedback
|
||||||
|
// and review_comment; its is_correct and points_earned stay null until the
|
||||||
|
// answer is graded or reviewed. The rubric is never part of it.
|
||||||
type questionResultJSON struct {
|
type questionResultJSON struct {
|
||||||
ID uint `json:"id"`
|
ID uint `json:"id"`
|
||||||
Text string `json:"text"`
|
Text string `json:"text"`
|
||||||
@@ -188,12 +291,20 @@ type questionResultJSON struct {
|
|||||||
Answered bool `json:"answered"`
|
Answered bool `json:"answered"`
|
||||||
AnswerIDs []uint `json:"answer_ids"`
|
AnswerIDs []uint `json:"answer_ids"`
|
||||||
Known *bool `json:"known"`
|
Known *bool `json:"known"`
|
||||||
IsCorrect bool `json:"is_correct"`
|
IsCorrect *bool `json:"is_correct"`
|
||||||
PointsEarned float64 `json:"points_earned"`
|
PointsEarned *float64 `json:"points_earned"`
|
||||||
CorrectAnswerIDs []uint `json:"correct_answer_ids"`
|
CorrectAnswerIDs []uint `json:"correct_answer_ids"`
|
||||||
Explanation *string `json:"explanation"`
|
Explanation *string `json:"explanation"`
|
||||||
AnswerText *string `json:"answer_text"`
|
AnswerText *string `json:"answer_text"`
|
||||||
Answers []resultAnswerJSON `json:"answers"`
|
Answers []resultAnswerJSON `json:"answers"`
|
||||||
|
// TextAnswer is the student's text of an open question. It is not
|
||||||
|
// "text" as in the feedback: text is already the question's text here.
|
||||||
|
TextAnswer *string `json:"text_answer"`
|
||||||
|
GradingStatus *string `json:"grading_status"`
|
||||||
|
GraderFeedback *string `json:"grader_feedback"`
|
||||||
|
ReviewComment *string `json:"review_comment"`
|
||||||
|
// MaxLength is the longest answer of an open question.
|
||||||
|
MaxLength *int `json:"max_length,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type resultAnswerJSON struct {
|
type resultAnswerJSON struct {
|
||||||
@@ -204,7 +315,12 @@ type resultAnswerJSON struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func result(r *classes.AttemptResult) resultJSON {
|
func result(r *classes.AttemptResult) resultJSON {
|
||||||
out := resultJSON{attemptJSON: attempt(r.AttemptSummary), Questions: make([]questionResultJSON, 0, len(r.Questions))}
|
withheld := classes.Withheld(&r.Attempt)
|
||||||
|
out := resultJSON{
|
||||||
|
attemptJSON: attempt(r.AttemptSummary),
|
||||||
|
SolutionsWithheld: withheld,
|
||||||
|
Questions: make([]questionResultJSON, 0, len(r.Questions)),
|
||||||
|
}
|
||||||
completed := r.Attempt.CompletedAt != nil
|
completed := r.Attempt.CompletedAt != nil
|
||||||
for _, qr := range r.Questions {
|
for _, qr := range r.Questions {
|
||||||
q := qr.Question
|
q := qr.Question
|
||||||
@@ -217,14 +333,33 @@ func result(r *classes.AttemptResult) resultJSON {
|
|||||||
AnswerIDs: []uint{},
|
AnswerIDs: []uint{},
|
||||||
Answers: make([]resultAnswerJSON, 0, len(q.Answers)),
|
Answers: make([]resultAnswerJSON, 0, len(q.Answers)),
|
||||||
}
|
}
|
||||||
|
if q.Type == models.TypeOpen {
|
||||||
|
n := classes.MaxLength(q)
|
||||||
|
row.MaxLength = &n
|
||||||
|
}
|
||||||
if a := qr.Answer; a != nil {
|
if a := qr.Answer; a != nil {
|
||||||
row.Answered = true
|
row.Answered = true
|
||||||
row.AnswerIDs = wire.Slice(a.AnswerIDs.Data)
|
row.AnswerIDs = wire.Slice(a.AnswerIDs.Data)
|
||||||
row.Known = a.SelfCheckKnown
|
row.Known = a.SelfCheckKnown
|
||||||
row.IsCorrect = a.IsCorrect
|
if q.Type == models.TypeOpen {
|
||||||
row.PointsEarned = a.Points
|
row.TextAnswer = a.TextAnswer
|
||||||
|
if !withheld {
|
||||||
|
row.GradingStatus, row.GraderFeedback, row.ReviewComment = a.GradingStatus, a.GraderFeedback, a.ReviewComment
|
||||||
|
if openScored(a) {
|
||||||
|
correct, points := a.IsCorrect, a.Points
|
||||||
|
row.IsCorrect, row.PointsEarned = &correct, &points
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else if !withheld {
|
||||||
|
correct, points := a.IsCorrect, a.Points
|
||||||
|
row.IsCorrect, row.PointsEarned = &correct, &points
|
||||||
|
}
|
||||||
|
} else if !withheld {
|
||||||
|
// Learning output keeps false and 0 for an unanswered question.
|
||||||
|
correct, points := false, 0.0
|
||||||
|
row.IsCorrect, row.PointsEarned = &correct, &points
|
||||||
}
|
}
|
||||||
reveal := completed || row.Answered
|
reveal := !withheld && (completed || row.Answered)
|
||||||
if reveal {
|
if reveal {
|
||||||
row.CorrectAnswerIDs = classes.CorrectAnswerIDs(q)
|
row.CorrectAnswerIDs = classes.CorrectAnswerIDs(q)
|
||||||
row.Explanation = q.Explanation
|
row.Explanation = q.Explanation
|
||||||
@@ -244,33 +379,83 @@ func result(r *classes.AttemptResult) resultJSON {
|
|||||||
return out
|
return out
|
||||||
}
|
}
|
||||||
|
|
||||||
// feedbackJSON is POST /attempts/{id}/answers.
|
// feedbackJSON is POST /attempts/{id}/answers. When Withheld (an answer to
|
||||||
|
// an open test attempt) every solution field is null and the answers carry
|
||||||
|
// only their id and text.
|
||||||
|
//
|
||||||
|
// The feedback of an open question carries the student's text and, unless
|
||||||
|
// withheld, the model answer (answer_text), the explanation, grading_status,
|
||||||
|
// grader_feedback and review_comment; is_correct and points stay null until
|
||||||
|
// the answer is graded or reviewed. These four keys are null for every other
|
||||||
|
// type. The rubric is never part of it.
|
||||||
type feedbackJSON struct {
|
type feedbackJSON struct {
|
||||||
QuestionID uint `json:"question_id"`
|
QuestionID uint `json:"question_id"`
|
||||||
IsCorrect bool `json:"is_correct"`
|
Withheld bool `json:"withheld"`
|
||||||
Points float64 `json:"points"`
|
IsCorrect *bool `json:"is_correct"`
|
||||||
|
Points *float64 `json:"points"`
|
||||||
CorrectAnswerIDs []uint `json:"correct_answer_ids"`
|
CorrectAnswerIDs []uint `json:"correct_answer_ids"`
|
||||||
Explanation *string `json:"explanation"`
|
Explanation *string `json:"explanation"`
|
||||||
AnswerText *string `json:"answer_text"`
|
AnswerText *string `json:"answer_text"`
|
||||||
Answers []resultAnswerJSON `json:"answers"`
|
Answers []resultAnswerJSON `json:"answers"`
|
||||||
|
Text *string `json:"text"`
|
||||||
|
GradingStatus *string `json:"grading_status"`
|
||||||
|
GraderFeedback *string `json:"grader_feedback"`
|
||||||
|
ReviewComment *string `json:"review_comment"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func feedback(fb *classes.Feedback) feedbackJSON {
|
func feedback(fb *classes.Feedback) feedbackJSON {
|
||||||
q := fb.Question
|
q := fb.Question
|
||||||
out := feedbackJSON{
|
out := feedbackJSON{QuestionID: q.ID, Withheld: fb.Withheld, Answers: make([]resultAnswerJSON, 0, len(q.Answers))}
|
||||||
QuestionID: q.ID,
|
if q.Type == models.TypeOpen {
|
||||||
IsCorrect: fb.Result.IsCorrect,
|
return openFeedback(fb, out)
|
||||||
Points: fb.Result.Points,
|
|
||||||
CorrectAnswerIDs: wire.Slice(fb.CorrectAnswerIDs),
|
|
||||||
Explanation: q.Explanation,
|
|
||||||
AnswerText: q.AnswerText,
|
|
||||||
Answers: make([]resultAnswerJSON, 0, len(q.Answers)),
|
|
||||||
}
|
}
|
||||||
|
if fb.Withheld {
|
||||||
|
for _, a := range q.Answers {
|
||||||
|
out.Answers = append(out.Answers, resultAnswerJSON{ID: a.ID, Text: a.Text})
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
correct, points := fb.Result.IsCorrect, fb.Result.Points
|
||||||
|
out.IsCorrect, out.Points = &correct, &points
|
||||||
|
out.CorrectAnswerIDs = wire.Slice(fb.CorrectAnswerIDs)
|
||||||
|
out.Explanation, out.AnswerText = q.Explanation, q.AnswerText
|
||||||
for _, a := range q.Answers {
|
for _, a := range q.Answers {
|
||||||
correct := a.IsCorrect
|
c := a.IsCorrect
|
||||||
out.Answers = append(out.Answers, resultAnswerJSON{ID: a.ID, Text: a.Text, IsCorrect: &correct, Explanation: a.Explanation})
|
out.Answers = append(out.Answers, resultAnswerJSON{ID: a.ID, Text: a.Text, IsCorrect: &c, Explanation: a.Explanation})
|
||||||
}
|
}
|
||||||
return out
|
return out
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// openFeedback fills the feedback of an open question from its stored row.
|
||||||
|
func openFeedback(fb *classes.Feedback, out feedbackJSON) feedbackJSON {
|
||||||
|
q, a := fb.Question, fb.Answer
|
||||||
|
if a != nil {
|
||||||
|
out.Text = a.TextAnswer
|
||||||
|
}
|
||||||
|
if fb.Withheld {
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
out.CorrectAnswerIDs = []uint{}
|
||||||
|
out.Explanation, out.AnswerText = q.Explanation, q.AnswerText
|
||||||
|
if a == nil {
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
out.GradingStatus, out.GraderFeedback, out.ReviewComment = a.GradingStatus, a.GraderFeedback, a.ReviewComment
|
||||||
|
if openScored(a) {
|
||||||
|
correct, points := a.IsCorrect, a.Points
|
||||||
|
out.IsCorrect, out.Points = &correct, &points
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
// openScored reports whether an open answer has a score to show: graded
|
||||||
|
// by a grader or reviewed by the owner. Pending and failed answers have
|
||||||
|
// none yet.
|
||||||
|
func openScored(a *models.AttemptAnswer) bool {
|
||||||
|
if a == nil || a.GradingStatus == nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
return *a.GradingStatus == models.GradingGraded || *a.GradingStatus == models.GradingReviewed
|
||||||
|
}
|
||||||
|
|
||||||
func wireTime(t time.Time) wire.Time { return wire.Time{Time: t.UTC().Truncate(time.Second)} }
|
func wireTime(t time.Time) wire.Time { return wire.Time{Time: t.UTC().Truncate(time.Second)} }
|
||||||
|
|||||||
416
controllers/api/json_test.go
Normal file
416
controllers/api/json_test.go
Normal file
@@ -0,0 +1,416 @@
|
|||||||
|
package api
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"git.golem15.com/golem15/sm-quizzes-plugin/classes"
|
||||||
|
"git.golem15.com/golem15/sm-quizzes-plugin/models"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/lagoon"
|
||||||
|
)
|
||||||
|
|
||||||
|
// fixtureQuestion is a question of type typ with every solution field set,
|
||||||
|
// so a serializer that forgets to drop one shows it.
|
||||||
|
func fixtureQuestion(id uint, typ string) models.Question {
|
||||||
|
expl, model, why := "question explanation", "model answer", "answer explanation"
|
||||||
|
q := models.Question{ID: id, Text: "Q", Type: typ, Points: 2, Explanation: &expl, AnswerText: &model}
|
||||||
|
if typ == models.TypeOpen {
|
||||||
|
rubric := "R-SECRET"
|
||||||
|
q.Rubric = &rubric
|
||||||
|
}
|
||||||
|
if isChoice(typ) {
|
||||||
|
q.Answers = []models.Answer{
|
||||||
|
{ID: id*10 + 1, QuestionID: id, Text: "right", IsCorrect: true, Explanation: &why},
|
||||||
|
{ID: id*10 + 2, QuestionID: id, Text: "wrong", Explanation: &why},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return q
|
||||||
|
}
|
||||||
|
|
||||||
|
func isChoice(typ string) bool { return typ == models.TypeSingle || typ == models.TypeMultiple }
|
||||||
|
|
||||||
|
func strPtr(s string) *string { return &s }
|
||||||
|
|
||||||
|
// noRubric fails when a student shape names or contains the rubric or the
|
||||||
|
// grading error.
|
||||||
|
func noRubric(t *testing.T, where, raw string) {
|
||||||
|
t.Helper()
|
||||||
|
if strings.Contains(raw, `"rubric"`) || strings.Contains(raw, "R-SECRET") || strings.Contains(raw, "grading_error") || strings.Contains(raw, "provider exploded") {
|
||||||
|
t.Errorf("%s leaks the rubric or the grading error: %s", where, raw)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// openRow is a stored open answer in the given grading status.
|
||||||
|
func openRow(questionID uint, status string) *models.AttemptAnswer {
|
||||||
|
return &models.AttemptAnswer{
|
||||||
|
AttemptID: 5, QuestionID: questionID,
|
||||||
|
TextAnswer: strPtr("moja odpowiedź"), GradingStatus: strPtr(status), GradingSeq: 1,
|
||||||
|
GradingError: strPtr("provider exploded"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func decode(t *testing.T, v any) (map[string]any, string) {
|
||||||
|
t.Helper()
|
||||||
|
b, err := json.Marshal(v)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
var out map[string]any
|
||||||
|
if err := json.Unmarshal(b, &out); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
return out, string(b)
|
||||||
|
}
|
||||||
|
|
||||||
|
// noSolution fails when any solution key of m (a feedback or a result
|
||||||
|
// question) holds a value.
|
||||||
|
func noSolution(t *testing.T, where string, m map[string]any, keys ...string) {
|
||||||
|
t.Helper()
|
||||||
|
for _, k := range keys {
|
||||||
|
v, ok := m[k]
|
||||||
|
if !ok {
|
||||||
|
t.Errorf("%s: key %s missing", where, k)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if v != nil {
|
||||||
|
t.Errorf("%s: %s = %v, want null", where, k, v)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
answers, _ := m["answers"].([]any)
|
||||||
|
for i, raw := range answers {
|
||||||
|
a := raw.(map[string]any)
|
||||||
|
if a["is_correct"] != nil || a["explanation"] != nil {
|
||||||
|
t.Errorf("%s: answers[%d] = %v, want no is_correct or explanation", where, i, a)
|
||||||
|
}
|
||||||
|
if a["id"] == nil || a["text"] == nil {
|
||||||
|
t.Errorf("%s: answers[%d] lost its id or text: %v", where, i, a)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func noCorrectness(t *testing.T, where, raw string) {
|
||||||
|
t.Helper()
|
||||||
|
if strings.Contains(raw, `"is_correct":true`) || strings.Contains(raw, `"is_correct":false`) {
|
||||||
|
t.Errorf("%s reveals correctness: %s", where, raw)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestWithheldSerializers(t *testing.T) {
|
||||||
|
for _, typ := range models.QuestionTypes {
|
||||||
|
t.Run(typ, func(t *testing.T) {
|
||||||
|
answered, unanswered := fixtureQuestion(1, typ), fixtureQuestion(2, typ)
|
||||||
|
test := &models.Quiz{Slug: "t", PassingScore: 50, Mode: models.ModeTest}
|
||||||
|
|
||||||
|
fb := &classes.Feedback{
|
||||||
|
Question: answered,
|
||||||
|
Result: classes.ScoreResult{IsCorrect: true, Points: 2},
|
||||||
|
CorrectAnswerIDs: classes.CorrectAnswerIDs(answered),
|
||||||
|
Withheld: true,
|
||||||
|
}
|
||||||
|
// gradedOpen is an open answer with every grading field set, so
|
||||||
|
// a serializer that forgets to withhold one shows it.
|
||||||
|
gradedOpen := func() *models.AttemptAnswer {
|
||||||
|
r := openRow(1, models.GradingGraded)
|
||||||
|
two := 2.0
|
||||||
|
r.IsCorrect, r.Points, r.GraderPoints = true, 2, &two
|
||||||
|
r.GraderFeedback, r.ReviewComment = strPtr("feedback"), strPtr("comment")
|
||||||
|
return r
|
||||||
|
}
|
||||||
|
if typ == models.TypeOpen {
|
||||||
|
fb.Answer = gradedOpen()
|
||||||
|
}
|
||||||
|
m, raw := decode(t, feedback(fb))
|
||||||
|
if m["withheld"] != true {
|
||||||
|
t.Errorf("feedback withheld = %v, want true", m["withheld"])
|
||||||
|
}
|
||||||
|
noSolution(t, "feedback", m, "is_correct", "points", "correct_answer_ids", "explanation", "answer_text",
|
||||||
|
"grading_status", "grader_feedback", "review_comment")
|
||||||
|
noCorrectness(t, "feedback", raw)
|
||||||
|
noRubric(t, "feedback", raw)
|
||||||
|
if isChoice(typ) && len(m["answers"].([]any)) != 2 {
|
||||||
|
t.Errorf("feedback answers = %v, want both answers", m["answers"])
|
||||||
|
}
|
||||||
|
if typ == models.TypeOpen && m["text"] != "moja odpowiedź" {
|
||||||
|
t.Errorf("withheld open feedback lost the student's text: %v", m["text"])
|
||||||
|
} else if typ != models.TypeOpen && m["text"] != nil {
|
||||||
|
t.Errorf("%s feedback text = %v, want null", typ, m["text"])
|
||||||
|
}
|
||||||
|
|
||||||
|
known := true
|
||||||
|
row := &models.AttemptAnswer{AttemptID: 5, QuestionID: 1, IsCorrect: true, Points: 2}
|
||||||
|
switch typ {
|
||||||
|
case models.TypeSelfCheck:
|
||||||
|
row.SelfCheckKnown = &known
|
||||||
|
case models.TypeOpen:
|
||||||
|
row = gradedOpen()
|
||||||
|
default:
|
||||||
|
row.AnswerIDs = lagoon.Jsonable[[]uint]{Data: []uint{11}, Valid: true}
|
||||||
|
}
|
||||||
|
res := &classes.AttemptResult{
|
||||||
|
AttemptSummary: classes.AttemptSummary{Attempt: models.Attempt{ID: 5, QuizID: 3, StartedAt: time.Now(), Quiz: test}, AnsweredCount: 1},
|
||||||
|
Questions: []classes.QuestionResult{{Question: answered, Answer: row}, {Question: unanswered}},
|
||||||
|
}
|
||||||
|
m, raw = decode(t, result(res))
|
||||||
|
if m["solutions_withheld"] != true || m["quiz_mode"] != models.ModeTest {
|
||||||
|
t.Errorf("result solutions_withheld = %v quiz_mode = %v", m["solutions_withheld"], m["quiz_mode"])
|
||||||
|
}
|
||||||
|
noCorrectness(t, "result", raw)
|
||||||
|
noRubric(t, "result", raw)
|
||||||
|
questions := m["questions"].([]any)
|
||||||
|
if len(questions) != 2 {
|
||||||
|
t.Fatalf("result questions = %d, want 2", len(questions))
|
||||||
|
}
|
||||||
|
for i, raw := range questions {
|
||||||
|
q := raw.(map[string]any)
|
||||||
|
noSolution(t, "result question "+string(rune('0'+i)), q, "is_correct", "points_earned", "correct_answer_ids", "explanation", "answer_text",
|
||||||
|
"grading_status", "grader_feedback", "review_comment")
|
||||||
|
}
|
||||||
|
first := questions[0].(map[string]any)
|
||||||
|
if first["answered"] != true {
|
||||||
|
t.Errorf("answered question lost answered: %v", first)
|
||||||
|
}
|
||||||
|
switch typ {
|
||||||
|
case models.TypeSelfCheck:
|
||||||
|
if first["known"] != true {
|
||||||
|
t.Errorf("self_check lost the student's known: %v", first)
|
||||||
|
}
|
||||||
|
case models.TypeOpen:
|
||||||
|
if first["text_answer"] != "moja odpowiedź" {
|
||||||
|
t.Errorf("open lost the student's text: %v", first)
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
if ids, _ := first["answer_ids"].([]any); len(ids) != 1 || ids[0] != float64(11) {
|
||||||
|
t.Errorf("answer_ids = %v, want the student's [11]", first["answer_ids"])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
done := time.Now()
|
||||||
|
res.Attempt.CompletedAt = &done
|
||||||
|
m, _ = decode(t, result(res))
|
||||||
|
if m["solutions_withheld"] != false {
|
||||||
|
t.Errorf("completed test still withheld")
|
||||||
|
}
|
||||||
|
for _, raw := range m["questions"].([]any) {
|
||||||
|
q := raw.(map[string]any)
|
||||||
|
if q["is_correct"] == nil || q["points_earned"] == nil || q["explanation"] == nil || q["correct_answer_ids"] == nil {
|
||||||
|
t.Errorf("completed test hides a solution: %v", q)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLearningFeedbackUnchanged(t *testing.T) {
|
||||||
|
q := fixtureQuestion(1, models.TypeSingle)
|
||||||
|
fb := &classes.Feedback{Question: q, Result: classes.ScoreResult{IsCorrect: false, Points: 0}, CorrectAnswerIDs: classes.CorrectAnswerIDs(q)}
|
||||||
|
m, raw := decode(t, feedback(fb))
|
||||||
|
if m["withheld"] != false {
|
||||||
|
t.Errorf("withheld = %v, want false", m["withheld"])
|
||||||
|
}
|
||||||
|
if m["is_correct"] != false || m["points"] != float64(0) {
|
||||||
|
t.Errorf("is_correct / points = %v / %v, want false / 0", m["is_correct"], m["points"])
|
||||||
|
}
|
||||||
|
if ids, ok := m["correct_answer_ids"].([]any); !ok || len(ids) != 1 {
|
||||||
|
t.Errorf("correct_answer_ids = %v, want [11]", m["correct_answer_ids"])
|
||||||
|
}
|
||||||
|
if !strings.Contains(raw, `"is_correct":true`) || m["explanation"] == nil || m["answer_text"] == nil {
|
||||||
|
t.Errorf("learning feedback lost a solution: %s", raw)
|
||||||
|
}
|
||||||
|
|
||||||
|
res := &classes.AttemptResult{
|
||||||
|
AttemptSummary: classes.AttemptSummary{Attempt: models.Attempt{ID: 5, StartedAt: time.Now(), Quiz: &models.Quiz{Slug: "s", PassingScore: 50}}},
|
||||||
|
Questions: []classes.QuestionResult{{Question: q}},
|
||||||
|
}
|
||||||
|
m, _ = decode(t, result(res))
|
||||||
|
row := m["questions"].([]any)[0].(map[string]any)
|
||||||
|
if m["solutions_withheld"] != false || m["quiz_mode"] != models.ModeLearning || m["quiz_navigation"] != models.NavigationFree {
|
||||||
|
t.Errorf("learning result flags = %v %v %v", m["solutions_withheld"], m["quiz_mode"], m["quiz_navigation"])
|
||||||
|
}
|
||||||
|
if row["is_correct"] != false || row["points_earned"] != float64(0) {
|
||||||
|
t.Errorf("unanswered learning question = %v / %v, want false / 0", row["is_correct"], row["points_earned"])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestTestQuizDetailHidesQuestions(t *testing.T) {
|
||||||
|
d := &classes.QuizDetail{
|
||||||
|
Quiz: models.Quiz{Slug: "t", Mode: models.ModeTest, Navigation: models.NavigationOneWay},
|
||||||
|
Questions: []models.Question{fixtureQuestion(1, models.TypeSelfCheck), fixtureQuestion(2, models.TypeSingle)},
|
||||||
|
}
|
||||||
|
m, raw := decode(t, quizDetail(d))
|
||||||
|
if qs, ok := m["questions"].([]any); !ok || len(qs) != 0 {
|
||||||
|
t.Errorf("test detail questions = %v, want []", m["questions"])
|
||||||
|
}
|
||||||
|
if m["question_count"] != float64(2) || m["mode"] != models.ModeTest || m["navigation"] != models.NavigationOneWay {
|
||||||
|
t.Errorf("test detail = %s", raw)
|
||||||
|
}
|
||||||
|
if strings.Contains(raw, "model answer") {
|
||||||
|
t.Errorf("test detail leaks answer_text: %s", raw)
|
||||||
|
}
|
||||||
|
|
||||||
|
d.Quiz.Mode = models.ModeLearning
|
||||||
|
m, _ = decode(t, quizDetail(d))
|
||||||
|
if qs, _ := m["questions"].([]any); len(qs) != 2 {
|
||||||
|
t.Errorf("learning detail questions = %d, want 2", len(qs))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSummaryAndAttemptFields(t *testing.T) {
|
||||||
|
two := 2
|
||||||
|
test := models.Quiz{ID: 3, Slug: "t", Mode: models.ModeTest, MaxAttempts: &two}
|
||||||
|
m, _ := decode(t, quizSummary(classes.QuizSummary{Quiz: test, QuestionCount: 3, AttemptsUsed: 1, QuestionTypes: map[string]int{models.TypeSingle: 3}}))
|
||||||
|
if m["attempts_left"] != float64(1) || m["mode"] != models.ModeTest || m["max_attempts"] != float64(2) {
|
||||||
|
t.Errorf("test summary = %v", m)
|
||||||
|
}
|
||||||
|
types, _ := m["question_types"].(map[string]any)
|
||||||
|
if len(types) != 4 || types["single"] != float64(3) || types["multiple"] != float64(0) || types["self_check"] != float64(0) || types["open"] != float64(0) {
|
||||||
|
t.Errorf("question_types = %v, want all four keys", m["question_types"])
|
||||||
|
}
|
||||||
|
m, _ = decode(t, quizSummary(classes.QuizSummary{Quiz: models.Quiz{ID: 4, Slug: "l"}, AttemptsUsed: 9}))
|
||||||
|
if v, ok := m["attempts_left"]; !ok || v != nil {
|
||||||
|
t.Errorf("learning attempts_left = %v (present %v), want null", v, ok)
|
||||||
|
}
|
||||||
|
if types, _ := m["question_types"].(map[string]any); len(types) != 4 {
|
||||||
|
t.Errorf("learning question_types = %v, want all four keys", m["question_types"])
|
||||||
|
}
|
||||||
|
if m["mode"] != models.ModeLearning || m["navigation"] != models.NavigationFree {
|
||||||
|
t.Errorf("zero-value quiz mode / navigation = %v / %v", m["mode"], m["navigation"])
|
||||||
|
}
|
||||||
|
|
||||||
|
begin := time.Date(2026, 11, 9, 10, 0, 0, 0, time.UTC)
|
||||||
|
defer func(orig func() time.Time) { timeNow = orig }(timeNow)
|
||||||
|
timeNow = func() time.Time { return begin.Add(20 * time.Second) }
|
||||||
|
limit := 60
|
||||||
|
timed := &models.Quiz{Slug: "t", Mode: models.ModeTest, Navigation: models.NavigationOneWay, TimeLimitSeconds: &limit}
|
||||||
|
m, _ = decode(t, attempt(classes.AttemptSummary{Attempt: models.Attempt{ID: 1, StartedAt: begin, Quiz: timed}}))
|
||||||
|
if m["seconds_left"] != float64(40) || m["quiz_mode"] != models.ModeTest || m["quiz_navigation"] != models.NavigationOneWay {
|
||||||
|
t.Errorf("open timed attempt = %v", m)
|
||||||
|
}
|
||||||
|
done := begin.Add(30 * time.Second)
|
||||||
|
m, _ = decode(t, attempt(classes.AttemptSummary{Attempt: models.Attempt{ID: 1, StartedAt: begin, CompletedAt: &done, Quiz: timed}}))
|
||||||
|
if v, ok := m["seconds_left"]; !ok || v != nil {
|
||||||
|
t.Errorf("completed seconds_left = %v (present %v), want null", v, ok)
|
||||||
|
}
|
||||||
|
|
||||||
|
m, _ = decode(t, start(&classes.Started{Attempt: &models.Attempt{ID: 2, StartedAt: begin}, Quiz: &test, Resumed: true, AttemptsUsed: 2, AnsweredCount: 1}))
|
||||||
|
if m["resumed"] != true || m["attempts_left"] != float64(0) || m["answered_count"] != float64(1) || m["quiz_slug"] != "t" {
|
||||||
|
t.Errorf("start json = %v", m)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestOpenSerializers(t *testing.T) {
|
||||||
|
q := fixtureQuestion(1, models.TypeOpen)
|
||||||
|
q.AnswerText = strPtr("MODEL")
|
||||||
|
learning := &models.Quiz{Slug: "l", PassingScore: 50}
|
||||||
|
|
||||||
|
// Feedback of a pending learning answer: the model answer and the
|
||||||
|
// student's text, no score yet, never the rubric.
|
||||||
|
m, raw := decode(t, feedback(&classes.Feedback{Question: q, Answer: openRow(1, models.GradingPending)}))
|
||||||
|
noRubric(t, "pending feedback", raw)
|
||||||
|
if m["answer_text"] != "MODEL" || m["text"] != "moja odpowiedź" || m["grading_status"] != models.GradingPending {
|
||||||
|
t.Errorf("pending feedback = %s", raw)
|
||||||
|
}
|
||||||
|
if m["is_correct"] != nil || m["points"] != nil {
|
||||||
|
t.Errorf("pending feedback has a score: %s", raw)
|
||||||
|
}
|
||||||
|
if a, ok := m["answers"].([]any); !ok || len(a) != 0 {
|
||||||
|
t.Errorf("open feedback answers = %v, want []", m["answers"])
|
||||||
|
}
|
||||||
|
if ids, ok := m["correct_answer_ids"].([]any); !ok || len(ids) != 0 {
|
||||||
|
t.Errorf("open feedback correct_answer_ids = %v, want []", m["correct_answer_ids"])
|
||||||
|
}
|
||||||
|
|
||||||
|
m, raw = decode(t, feedback(&classes.Feedback{Question: q, Answer: openRow(1, models.GradingFailed)}))
|
||||||
|
noRubric(t, "failed feedback", raw)
|
||||||
|
if m["grading_status"] != models.GradingFailed || m["is_correct"] != nil || m["points"] != nil {
|
||||||
|
t.Errorf("failed feedback = %s", raw)
|
||||||
|
}
|
||||||
|
|
||||||
|
graded := openRow(1, models.GradingGraded)
|
||||||
|
graded.Points, graded.IsCorrect, graded.GraderFeedback = 1.5, false, strPtr("Brakuje przykładu.")
|
||||||
|
m, raw = decode(t, feedback(&classes.Feedback{Question: q, Answer: graded}))
|
||||||
|
noRubric(t, "graded feedback", raw)
|
||||||
|
if m["points"] != 1.5 || m["is_correct"] != false || m["grader_feedback"] != "Brakuje przykładu." || m["review_comment"] != nil {
|
||||||
|
t.Errorf("graded feedback = %s", raw)
|
||||||
|
}
|
||||||
|
|
||||||
|
reviewed := openRow(1, models.GradingReviewed)
|
||||||
|
reviewed.Points, reviewed.IsCorrect, reviewed.ReviewComment = 2, true, strPtr("Dobrze.")
|
||||||
|
m, raw = decode(t, feedback(&classes.Feedback{Question: q, Answer: reviewed}))
|
||||||
|
if m["points"] != float64(2) || m["is_correct"] != true || m["review_comment"] != "Dobrze." || m["grading_status"] != models.GradingReviewed {
|
||||||
|
t.Errorf("reviewed feedback = %s", raw)
|
||||||
|
}
|
||||||
|
|
||||||
|
// The question before answering: max_length, no model answer, no rubric.
|
||||||
|
m, raw = decode(t, question(q))
|
||||||
|
noRubric(t, "open question", raw)
|
||||||
|
if m["max_length"] != float64(models.DefaultMaxLength) {
|
||||||
|
t.Errorf("open question max_length = %v, want %d", m["max_length"], models.DefaultMaxLength)
|
||||||
|
}
|
||||||
|
if _, ok := m["answer_text"]; ok {
|
||||||
|
t.Errorf("open question leaks its model answer: %s", raw)
|
||||||
|
}
|
||||||
|
five := 5
|
||||||
|
q5 := q
|
||||||
|
q5.MaxLength = &five
|
||||||
|
if m, _ = decode(t, question(q5)); m["max_length"] != float64(5) {
|
||||||
|
t.Errorf("open question max_length = %v, want 5", m["max_length"])
|
||||||
|
}
|
||||||
|
if _, raw = decode(t, question(fixtureQuestion(2, models.TypeSingle))); strings.Contains(raw, "max_length") {
|
||||||
|
t.Errorf("single question names max_length: %s", raw)
|
||||||
|
}
|
||||||
|
_, raw = decode(t, quizDetail(&classes.QuizDetail{Quiz: *learning, Questions: []models.Question{q}}))
|
||||||
|
noRubric(t, "quiz detail", raw)
|
||||||
|
|
||||||
|
// The result of a learning attempt with a pending open answer.
|
||||||
|
res := &classes.AttemptResult{
|
||||||
|
AttemptSummary: classes.AttemptSummary{
|
||||||
|
Attempt: models.Attempt{ID: 5, StartedAt: time.Now(), Quiz: learning},
|
||||||
|
AnsweredCount: 1, OpenAnswers: 1, Unreviewed: 1,
|
||||||
|
},
|
||||||
|
Questions: []classes.QuestionResult{{Question: q, Answer: openRow(1, models.GradingPending)}, {Question: fixtureQuestion(2, models.TypeSingle)}},
|
||||||
|
}
|
||||||
|
m, raw = decode(t, result(res))
|
||||||
|
noRubric(t, "result", raw)
|
||||||
|
if m["needs_review"] != true || m["open_answers"] != float64(1) {
|
||||||
|
t.Errorf("result needs_review / open_answers = %v / %v", m["needs_review"], m["open_answers"])
|
||||||
|
}
|
||||||
|
row := m["questions"].([]any)[0].(map[string]any)
|
||||||
|
if row["points_earned"] != nil || row["is_correct"] != nil {
|
||||||
|
t.Errorf("pending open result has a score: %v", row)
|
||||||
|
}
|
||||||
|
if row["answer_text"] != "MODEL" || row["text_answer"] != "moja odpowiedź" || row["text"] != "Q" || row["grading_status"] != models.GradingPending {
|
||||||
|
t.Errorf("pending open result = %v", row)
|
||||||
|
}
|
||||||
|
if row["max_length"] != float64(models.DefaultMaxLength) {
|
||||||
|
t.Errorf("open result max_length = %v", row["max_length"])
|
||||||
|
}
|
||||||
|
choice := m["questions"].([]any)[1].(map[string]any)
|
||||||
|
for _, k := range []string{"text_answer", "grading_status", "grader_feedback", "review_comment"} {
|
||||||
|
if v, ok := choice[k]; !ok || v != nil {
|
||||||
|
t.Errorf("single result %s = %v (present %v), want null", k, v, ok)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if _, ok := choice["max_length"]; ok {
|
||||||
|
t.Errorf("single result names max_length: %v", choice)
|
||||||
|
}
|
||||||
|
|
||||||
|
res.Questions[0].Answer = reviewed
|
||||||
|
res.Unreviewed = 0
|
||||||
|
m, _ = decode(t, result(res))
|
||||||
|
row = m["questions"].([]any)[0].(map[string]any)
|
||||||
|
if row["points_earned"] != float64(2) || row["is_correct"] != true || row["review_comment"] != "Dobrze." || m["needs_review"] != false {
|
||||||
|
t.Errorf("reviewed open result = %v (needs_review %v)", row, m["needs_review"])
|
||||||
|
}
|
||||||
|
|
||||||
|
// Every attempt row carries the two review keys.
|
||||||
|
m, _ = decode(t, attempt(classes.AttemptSummary{Attempt: models.Attempt{ID: 1, StartedAt: time.Now(), Quiz: learning}}))
|
||||||
|
if m["needs_review"] != false || m["open_answers"] != float64(0) {
|
||||||
|
t.Errorf("attempt without open answers = %v / %v", m["needs_review"], m["open_answers"])
|
||||||
|
}
|
||||||
|
m, _ = decode(t, start(&classes.Started{Attempt: &models.Attempt{ID: 2, StartedAt: time.Now()}, Quiz: learning, OpenAnswers: 2, Unreviewed: 1}))
|
||||||
|
if m["needs_review"] != true || m["open_answers"] != float64(2) {
|
||||||
|
t.Errorf("start needs_review / open_answers = %v / %v", m["needs_review"], m["open_answers"])
|
||||||
|
}
|
||||||
|
}
|
||||||
366
controllers/api/manage.go
Normal file
366
controllers/api/manage.go
Normal file
@@ -0,0 +1,366 @@
|
|||||||
|
package api
|
||||||
|
|
||||||
|
// The owner manage routes under /api/v1/quizzes, behind user.api_token, the
|
||||||
|
// golem15.quizzes.manage throttle, a token scope and the access_quizzes
|
||||||
|
// permission. The MCP quiz tools bind them. Answers use the owner shapes of
|
||||||
|
// manage_json.go, which carry the solutions.
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"io"
|
||||||
|
"net/http"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"git.golem15.com/golem15/sm-quizzes-plugin/classes"
|
||||||
|
"git.golem15.com/golem15/sm-quizzes-plugin/models"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/wire"
|
||||||
|
"gorm.io/gorm"
|
||||||
|
)
|
||||||
|
|
||||||
|
// manageDB returns the application database, or answers 503 as the student
|
||||||
|
// routes do without one.
|
||||||
|
func (h *Handlers) manageDB(w http.ResponseWriter) (*gorm.DB, bool) {
|
||||||
|
var gdb *gorm.DB
|
||||||
|
if h.App != nil {
|
||||||
|
gdb, _ = h.App.Lookup[*gorm.DB]()
|
||||||
|
}
|
||||||
|
if gdb == nil {
|
||||||
|
wire.WriteJSON(w, http.StatusServiceUnavailable, map[string]any{"error": "Database unavailable"})
|
||||||
|
return nil, false
|
||||||
|
}
|
||||||
|
return gdb, true
|
||||||
|
}
|
||||||
|
|
||||||
|
// writeManaged answers {data: data}, or maps err: ErrNotFound is a 404,
|
||||||
|
// ErrQuizExists a 409, a *classes.ValidationError the import route's 422
|
||||||
|
// {"message"}, anything else an opaque 500.
|
||||||
|
func writeManaged(w http.ResponseWriter, status int, data any, err error) {
|
||||||
|
var invalid *classes.ValidationError
|
||||||
|
switch {
|
||||||
|
case err == nil:
|
||||||
|
wire.WriteJSON(w, status, map[string]any{"data": data})
|
||||||
|
case errors.As(err, &invalid):
|
||||||
|
wire.WriteJSON(w, http.StatusUnprocessableEntity, map[string]any{"message": invalid.Error()})
|
||||||
|
case errors.Is(err, classes.ErrQuestionNotFound):
|
||||||
|
wire.WriteJSON(w, http.StatusNotFound, map[string]any{"error": true, "message": "Question not found."})
|
||||||
|
case errors.Is(err, classes.ErrNotFound):
|
||||||
|
wire.WriteJSON(w, http.StatusNotFound, map[string]any{"error": true, "message": "Quiz not found."})
|
||||||
|
case errors.Is(err, classes.ErrQuizExists):
|
||||||
|
wire.WriteJSON(w, http.StatusConflict, map[string]any{"error": true, "message": "A quiz with this slug already exists."})
|
||||||
|
default:
|
||||||
|
wire.WriteOpaque500(w)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ManageListQuizzes answers GET /api/v1/quizzes?context=: every quiz,
|
||||||
|
// published or not, with its question and completed-attempt counts.
|
||||||
|
func (h *Handlers) ManageListQuizzes(w http.ResponseWriter, r *http.Request) {
|
||||||
|
db, ok := h.manageDB(w)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
rows, err := classes.ListManagedQuizzes(r.Context(), db, strings.TrimSpace(r.URL.Query().Get("context")))
|
||||||
|
if err != nil {
|
||||||
|
writeManaged(w, 0, nil, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
out := make([]managedQuizJSON, 0, len(rows))
|
||||||
|
for _, row := range rows {
|
||||||
|
out = append(out, managedQuizRow(row))
|
||||||
|
}
|
||||||
|
writeManaged(w, http.StatusOK, out, nil)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ManageShowQuiz answers GET /api/v1/quizzes/{slug}: the quiz with every
|
||||||
|
// question and answer, solutions included.
|
||||||
|
func (h *Handlers) ManageShowQuiz(w http.ResponseWriter, r *http.Request) {
|
||||||
|
db, ok := h.manageDB(w)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
h.writeManagedQuiz(w, r, db, http.StatusOK, r.PathValue("slug"))
|
||||||
|
}
|
||||||
|
|
||||||
|
// writeManagedQuiz answers the quiz with its questions and solutions.
|
||||||
|
func (h *Handlers) writeManagedQuiz(w http.ResponseWriter, r *http.Request, db *gorm.DB, status int, slug string) {
|
||||||
|
quiz, err := classes.ManagedQuiz(r.Context(), db, slug)
|
||||||
|
if err != nil {
|
||||||
|
writeManaged(w, 0, nil, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
attempts, err := classes.CompletedAttemptCount(r.Context(), db, quiz.ID)
|
||||||
|
if err != nil {
|
||||||
|
writeManaged(w, 0, nil, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
writeManaged(w, status, managedQuizDetail(*quiz, attempts), nil)
|
||||||
|
}
|
||||||
|
|
||||||
|
// readManaged reads a JSON body into dest, refusing unknown keys: 413 over
|
||||||
|
// the route's body limit, 400 for an unreadable body, 422 {"message"} for
|
||||||
|
// invalid JSON. It writes the answer and reports false on failure.
|
||||||
|
func readManaged(w http.ResponseWriter, r *http.Request, dest any) bool {
|
||||||
|
raw, err := io.ReadAll(r.Body)
|
||||||
|
var tooLarge *http.MaxBytesError
|
||||||
|
switch {
|
||||||
|
case errors.As(err, &tooLarge):
|
||||||
|
wire.WriteJSON(w, http.StatusRequestEntityTooLarge, map[string]any{"error": true, "message": "Request body too large."})
|
||||||
|
return false
|
||||||
|
case err != nil:
|
||||||
|
wire.WriteJSON(w, http.StatusBadRequest, map[string]any{"error": true, "message": "Unreadable request body."})
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
dec := json.NewDecoder(bytes.NewReader(raw))
|
||||||
|
dec.DisallowUnknownFields()
|
||||||
|
if err := dec.Decode(dest); err != nil {
|
||||||
|
wire.WriteJSON(w, http.StatusUnprocessableEntity, map[string]any{"message": "invalid JSON: " + err.Error()})
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
// refuse answers the 422 of a ValidationError and reports whether there
|
||||||
|
// were problems.
|
||||||
|
func refuse(w http.ResponseWriter, problems []string) bool {
|
||||||
|
if len(problems) == 0 {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
writeManaged(w, 0, nil, &classes.ValidationError{Problems: problems})
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
// updateQuizBody is the PATCH /{slug} body: QuizInput without the slug,
|
||||||
|
// which an update cannot change, so sending it is refused as unknown.
|
||||||
|
type updateQuizBody struct {
|
||||||
|
Title *string `json:"title"`
|
||||||
|
Description *string `json:"description"`
|
||||||
|
Context *string `json:"context"`
|
||||||
|
Mode *string `json:"mode"`
|
||||||
|
Navigation *string `json:"navigation"`
|
||||||
|
MaxAttempts *int `json:"max_attempts"`
|
||||||
|
TimeLimitSeconds *int `json:"time_limit_seconds"`
|
||||||
|
PassingScore *int `json:"passing_score"`
|
||||||
|
RoundSize *int `json:"round_size"`
|
||||||
|
ShuffleQuestions *bool `json:"shuffle_questions"`
|
||||||
|
Grader *string `json:"grader"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b updateQuizBody) input() classes.QuizInput {
|
||||||
|
return classes.QuizInput{
|
||||||
|
Title: b.Title, Description: b.Description, Context: b.Context, Mode: b.Mode, Navigation: b.Navigation,
|
||||||
|
MaxAttempts: b.MaxAttempts, TimeLimitSeconds: b.TimeLimitSeconds, PassingScore: b.PassingScore,
|
||||||
|
RoundSize: b.RoundSize, ShuffleQuestions: b.ShuffleQuestions, Grader: b.Grader,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// graderProblems checks a sent grader against the codes the application's
|
||||||
|
// grader registry knows (manual and every registered grader).
|
||||||
|
func (h *Handlers) graderProblems(in classes.QuizInput) []string {
|
||||||
|
return classes.CheckGrader(in.Grader, classes.ForApp(h.App, nil).Graders.Codes())
|
||||||
|
}
|
||||||
|
|
||||||
|
// answerQuiz counts and answers a quiz a write returned, or maps err.
|
||||||
|
func answerQuiz(w http.ResponseWriter, r *http.Request, db *gorm.DB, status int, quiz *models.Quiz, err error) {
|
||||||
|
if err != nil {
|
||||||
|
writeManaged(w, 0, nil, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
row, err := classes.ManagedRow(r.Context(), db, *quiz)
|
||||||
|
if err != nil {
|
||||||
|
writeManaged(w, 0, nil, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
writeManaged(w, status, managedQuizRow(row), nil)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ManageCreateQuiz answers POST /api/v1/quizzes: 201 with a new,
|
||||||
|
// unpublished quiz, 409 on a taken slug. The input is checked before the
|
||||||
|
// database is touched.
|
||||||
|
func (h *Handlers) ManageCreateQuiz(w http.ResponseWriter, r *http.Request) {
|
||||||
|
var in classes.QuizInput
|
||||||
|
if !readManaged(w, r, &in) || refuse(w, classes.CheckQuizInput(in, true)) || refuse(w, h.graderProblems(in)) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
db, ok := h.manageDB(w)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
quiz, err := classes.CreateQuiz(r.Context(), db, in)
|
||||||
|
answerQuiz(w, r, db, http.StatusCreated, quiz, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ManageUpdateQuiz answers PATCH /api/v1/quizzes/{slug}: only the sent
|
||||||
|
// fields change.
|
||||||
|
func (h *Handlers) ManageUpdateQuiz(w http.ResponseWriter, r *http.Request) {
|
||||||
|
var body updateQuizBody
|
||||||
|
if !readManaged(w, r, &body) || refuse(w, classes.CheckQuizInput(body.input(), false)) ||
|
||||||
|
refuse(w, h.graderProblems(body.input())) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
db, ok := h.manageDB(w)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
quiz, err := classes.UpdateQuiz(r.Context(), db, r.PathValue("slug"), body.input())
|
||||||
|
answerQuiz(w, r, db, http.StatusOK, quiz, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ManageDeleteQuiz answers DELETE /api/v1/quizzes/{slug}?confirm={slug}:
|
||||||
|
// the quiz goes with its questions, answers and attempts. A confirm that
|
||||||
|
// does not repeat the slug is a 422 before the database is read.
|
||||||
|
func (h *Handlers) ManageDeleteQuiz(w http.ResponseWriter, r *http.Request) {
|
||||||
|
slug := r.PathValue("slug")
|
||||||
|
if err := classes.ValidateDeleteConfirm(slug, r.URL.Query().Get("confirm")); err != nil {
|
||||||
|
writeManaged(w, 0, nil, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
db, ok := h.manageDB(w)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
del, err := classes.DeleteQuiz(r.Context(), db, slug)
|
||||||
|
if err != nil {
|
||||||
|
writeManaged(w, 0, nil, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
writeManaged(w, http.StatusOK, map[string]any{
|
||||||
|
"id": del.ID, "slug": del.Slug, "title": del.Title, "questions": del.Questions, "attempts": del.Attempts,
|
||||||
|
}, nil)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ManagePublish answers POST /api/v1/quizzes/{slug}/publish.
|
||||||
|
func (h *Handlers) ManagePublish(w http.ResponseWriter, r *http.Request) { h.setPublished(w, r, true) }
|
||||||
|
|
||||||
|
// ManageUnpublish answers POST /api/v1/quizzes/{slug}/unpublish.
|
||||||
|
func (h *Handlers) ManageUnpublish(w http.ResponseWriter, r *http.Request) {
|
||||||
|
h.setPublished(w, r, false)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *Handlers) setPublished(w http.ResponseWriter, r *http.Request, published bool) {
|
||||||
|
db, ok := h.manageDB(w)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
quiz, err := classes.SetPublished(r.Context(), db, r.PathValue("slug"), published)
|
||||||
|
answerQuiz(w, r, db, http.StatusOK, quiz, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ManageQuizStats answers GET /api/v1/quizzes/{slug}/stats: per student
|
||||||
|
// and per question, after closing the quiz's expired open test attempts.
|
||||||
|
func (h *Handlers) ManageQuizStats(w http.ResponseWriter, r *http.Request) {
|
||||||
|
svc, ok := h.service(w)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
stats, err := classes.QuizStats(r.Context(), svc.DB, r.PathValue("slug"), svc)
|
||||||
|
if err != nil {
|
||||||
|
writeManaged(w, 0, nil, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
writeManaged(w, http.StatusOK, quizStats(stats), nil)
|
||||||
|
}
|
||||||
|
|
||||||
|
// questionID reads the {id} path value: anything but a positive integer
|
||||||
|
// is the 404 of a missing question.
|
||||||
|
func questionID(w http.ResponseWriter, r *http.Request) (uint, bool) {
|
||||||
|
id, err := strconv.ParseUint(r.PathValue("id"), 10, 32)
|
||||||
|
if err != nil || id == 0 {
|
||||||
|
writeManaged(w, 0, nil, classes.ErrQuestionNotFound)
|
||||||
|
return 0, false
|
||||||
|
}
|
||||||
|
return uint(id), true
|
||||||
|
}
|
||||||
|
|
||||||
|
// ManageCreateQuestion answers POST /api/v1/quizzes/{slug}/questions: 201
|
||||||
|
// with the new question and its answers.
|
||||||
|
func (h *Handlers) ManageCreateQuestion(w http.ResponseWriter, r *http.Request) {
|
||||||
|
var in classes.QuestionInput
|
||||||
|
if !readManaged(w, r, &in) || refuse(w, classes.CheckNewQuestion(in)) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
db, ok := h.manageDB(w)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
q, err := classes.CreateQuestion(r.Context(), db, r.PathValue("slug"), in)
|
||||||
|
if err != nil {
|
||||||
|
writeManaged(w, 0, nil, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
writeManaged(w, http.StatusCreated, managedQuestion(*q), nil)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ManageUpdateQuestion answers PATCH /api/v1/quizzes/{slug}/questions/{id}:
|
||||||
|
// only the sent fields change; a sent answers list replaces the answers by
|
||||||
|
// id.
|
||||||
|
func (h *Handlers) ManageUpdateQuestion(w http.ResponseWriter, r *http.Request) {
|
||||||
|
id, ok := questionID(w, r)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var in classes.QuestionInput
|
||||||
|
if !readManaged(w, r, &in) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if in.SortOrder != nil && *in.SortOrder < 1 {
|
||||||
|
refuse(w, []string{"sort_order must be at least 1"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
db, ok := h.manageDB(w)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
q, err := classes.UpdateQuestion(r.Context(), db, r.PathValue("slug"), id, in)
|
||||||
|
if err != nil {
|
||||||
|
writeManaged(w, 0, nil, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
writeManaged(w, http.StatusOK, managedQuestion(*q), nil)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ManageDeleteQuestion answers DELETE /api/v1/quizzes/{slug}/questions/{id}
|
||||||
|
// with {id, quiz_slug}.
|
||||||
|
func (h *Handlers) ManageDeleteQuestion(w http.ResponseWriter, r *http.Request) {
|
||||||
|
id, ok := questionID(w, r)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
db, ok := h.manageDB(w)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
slug := r.PathValue("slug")
|
||||||
|
if err := classes.DeleteQuestion(r.Context(), db, slug, id); err != nil {
|
||||||
|
writeManaged(w, 0, nil, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
writeManaged(w, http.StatusOK, map[string]any{"id": id, "quiz_slug": slug}, nil)
|
||||||
|
}
|
||||||
|
|
||||||
|
// reorderBody is the PUT /{slug}/questions/order body.
|
||||||
|
type reorderBody struct {
|
||||||
|
QuestionIDs []uint `json:"question_ids"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// ManageReorderQuestions answers PUT /api/v1/quizzes/{slug}/questions/order
|
||||||
|
// with {"question_ids": [...]}, every question of the quiz exactly once,
|
||||||
|
// with the quiz and its questions in the new order.
|
||||||
|
func (h *Handlers) ManageReorderQuestions(w http.ResponseWriter, r *http.Request) {
|
||||||
|
var body reorderBody
|
||||||
|
if !readManaged(w, r, &body) || refuse(w, classes.CheckQuestionOrder(body.QuestionIDs)) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
db, ok := h.manageDB(w)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
slug := r.PathValue("slug")
|
||||||
|
if _, err := classes.ReorderQuestions(r.Context(), db, slug, body.QuestionIDs); err != nil {
|
||||||
|
writeManaged(w, 0, nil, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
h.writeManagedQuiz(w, r, db, http.StatusOK, slug)
|
||||||
|
}
|
||||||
212
controllers/api/manage_json.go
Normal file
212
controllers/api/manage_json.go
Normal file
@@ -0,0 +1,212 @@
|
|||||||
|
package api
|
||||||
|
|
||||||
|
// The owner shapes of the manage routes. They carry the solutions
|
||||||
|
// (is_correct, explanations, answer_text) and are never used by a student
|
||||||
|
// route; the student shapes live in json.go. Built field by field, so a new
|
||||||
|
// column never leaks.
|
||||||
|
|
||||||
|
import (
|
||||||
|
"git.golem15.com/golem15/sm-quizzes-plugin/classes"
|
||||||
|
"git.golem15.com/golem15/sm-quizzes-plugin/graders"
|
||||||
|
"git.golem15.com/golem15/sm-quizzes-plugin/models"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/wire"
|
||||||
|
)
|
||||||
|
|
||||||
|
type managedQuizJSON struct {
|
||||||
|
ID uint `json:"id"`
|
||||||
|
Slug string `json:"slug"`
|
||||||
|
Title string `json:"title"`
|
||||||
|
Description *string `json:"description"`
|
||||||
|
Context *string `json:"context"`
|
||||||
|
Mode string `json:"mode"`
|
||||||
|
Navigation string `json:"navigation"`
|
||||||
|
MaxAttempts *int `json:"max_attempts"`
|
||||||
|
TimeLimitSeconds *int `json:"time_limit_seconds"`
|
||||||
|
PassingScore int `json:"passing_score"`
|
||||||
|
ShuffleQuestions bool `json:"shuffle_questions"`
|
||||||
|
RoundSize *int `json:"round_size"`
|
||||||
|
Grader string `json:"grader"`
|
||||||
|
IsPublished bool `json:"is_published"`
|
||||||
|
QuestionCount int `json:"question_count"`
|
||||||
|
AttemptsCount int `json:"attempts_count"`
|
||||||
|
CreatedAt wire.Time `json:"created_at"`
|
||||||
|
UpdatedAt wire.Time `json:"updated_at"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type managedQuizDetailJSON struct {
|
||||||
|
managedQuizJSON
|
||||||
|
Questions []managedQuestionJSON `json:"questions"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type managedQuestionJSON struct {
|
||||||
|
ID uint `json:"id"`
|
||||||
|
Text string `json:"text"`
|
||||||
|
Type string `json:"type"`
|
||||||
|
Category *string `json:"category"`
|
||||||
|
AnswerText *string `json:"answer_text"`
|
||||||
|
Explanation *string `json:"explanation"`
|
||||||
|
Points int `json:"points"`
|
||||||
|
SortOrder int `json:"sort_order"`
|
||||||
|
Rubric *string `json:"rubric"`
|
||||||
|
MaxLength *int `json:"max_length"`
|
||||||
|
Answers []managedAnswerJSON `json:"answers"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type managedAnswerJSON struct {
|
||||||
|
ID uint `json:"id"`
|
||||||
|
Text string `json:"text"`
|
||||||
|
IsCorrect bool `json:"is_correct"`
|
||||||
|
Explanation *string `json:"explanation"`
|
||||||
|
SortOrder int `json:"sort_order"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func managedQuiz(q models.Quiz, questions, attempts int) managedQuizJSON {
|
||||||
|
return managedQuizJSON{
|
||||||
|
ID: q.ID,
|
||||||
|
Slug: q.Slug,
|
||||||
|
Title: q.Title,
|
||||||
|
Description: q.Description,
|
||||||
|
Context: q.Context,
|
||||||
|
Mode: quizMode(&q),
|
||||||
|
Navigation: quizNavigation(&q),
|
||||||
|
MaxAttempts: q.MaxAttempts,
|
||||||
|
TimeLimitSeconds: q.TimeLimitSeconds,
|
||||||
|
PassingScore: q.PassingScore,
|
||||||
|
ShuffleQuestions: q.ShuffleQuestions,
|
||||||
|
RoundSize: q.RoundSize,
|
||||||
|
Grader: quizGrader(&q),
|
||||||
|
IsPublished: q.IsPublished,
|
||||||
|
QuestionCount: questions,
|
||||||
|
AttemptsCount: attempts,
|
||||||
|
CreatedAt: wireTime(q.CreatedAt),
|
||||||
|
UpdatedAt: wireTime(q.UpdatedAt),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func managedQuizRow(row classes.ManagedQuizRow) managedQuizJSON {
|
||||||
|
return managedQuiz(row.Quiz, row.QuestionCount, row.AttemptsCount)
|
||||||
|
}
|
||||||
|
|
||||||
|
// managedQuizDetail is a quiz loaded by classes.ManagedQuiz with its
|
||||||
|
// questions; attempts is its completed-attempt count.
|
||||||
|
func managedQuizDetail(q models.Quiz, attempts int) managedQuizDetailJSON {
|
||||||
|
out := managedQuizDetailJSON{
|
||||||
|
managedQuizJSON: managedQuiz(q, len(q.Questions), attempts),
|
||||||
|
Questions: make([]managedQuestionJSON, 0, len(q.Questions)),
|
||||||
|
}
|
||||||
|
for _, question := range q.Questions {
|
||||||
|
out.Questions = append(out.Questions, managedQuestion(question))
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
func managedQuestion(q models.Question) managedQuestionJSON {
|
||||||
|
out := managedQuestionJSON{
|
||||||
|
ID: q.ID,
|
||||||
|
Text: q.Text,
|
||||||
|
Type: q.Type,
|
||||||
|
Category: q.Category,
|
||||||
|
AnswerText: q.AnswerText,
|
||||||
|
Explanation: q.Explanation,
|
||||||
|
Points: q.Points,
|
||||||
|
SortOrder: q.SortOrder,
|
||||||
|
Rubric: q.Rubric,
|
||||||
|
MaxLength: q.MaxLength,
|
||||||
|
Answers: make([]managedAnswerJSON, 0, len(q.Answers)),
|
||||||
|
}
|
||||||
|
for _, a := range q.Answers {
|
||||||
|
out.Answers = append(out.Answers, managedAnswerJSON{
|
||||||
|
ID: a.ID, Text: a.Text, IsCorrect: a.IsCorrect, Explanation: a.Explanation, SortOrder: a.SortOrder,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
type statsJSON struct {
|
||||||
|
Quiz statsQuizJSON `json:"quiz"`
|
||||||
|
Unreviewed int `json:"unreviewed"`
|
||||||
|
Students []studentStatJSON `json:"students"`
|
||||||
|
Questions []questionStatJSON `json:"questions"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type statsQuizJSON struct {
|
||||||
|
ID uint `json:"id"`
|
||||||
|
Slug string `json:"slug"`
|
||||||
|
Title string `json:"title"`
|
||||||
|
Mode string `json:"mode"`
|
||||||
|
PassingScore int `json:"passing_score"`
|
||||||
|
QuestionCount int `json:"question_count"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type studentStatJSON struct {
|
||||||
|
UserID uint `json:"user_id"`
|
||||||
|
Email string `json:"email"`
|
||||||
|
Name *string `json:"name"`
|
||||||
|
Surname *string `json:"surname"`
|
||||||
|
Attempts int `json:"attempts"`
|
||||||
|
BestScorePercent *float64 `json:"best_score_percent"`
|
||||||
|
LastScorePercent *float64 `json:"last_score_percent"`
|
||||||
|
LastCompletedAt *wire.Time `json:"last_completed_at"`
|
||||||
|
Passed bool `json:"passed"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type questionStatJSON struct {
|
||||||
|
ID uint `json:"id"`
|
||||||
|
Text string `json:"text"`
|
||||||
|
Type string `json:"type"`
|
||||||
|
Answered int `json:"answered"`
|
||||||
|
Correct int `json:"correct"`
|
||||||
|
CorrectPercent *float64 `json:"correct_percent"`
|
||||||
|
MostChosenWrong *wrongAnswerJSON `json:"most_chosen_wrong"`
|
||||||
|
Unreviewed int `json:"unreviewed"`
|
||||||
|
AveragePoints *float64 `json:"average_points"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type wrongAnswerJSON struct {
|
||||||
|
AnswerID uint `json:"answer_id"`
|
||||||
|
Text string `json:"text"`
|
||||||
|
Count int `json:"count"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func quizStats(s *classes.Stats) statsJSON {
|
||||||
|
out := statsJSON{
|
||||||
|
Quiz: statsQuizJSON{
|
||||||
|
ID: s.Quiz.ID, Slug: s.Quiz.Slug, Title: s.Quiz.Title, Mode: quizMode(&s.Quiz),
|
||||||
|
PassingScore: s.Quiz.PassingScore, QuestionCount: s.QuestionCount,
|
||||||
|
},
|
||||||
|
Unreviewed: s.Unreviewed,
|
||||||
|
Students: make([]studentStatJSON, 0, len(s.Students)),
|
||||||
|
Questions: make([]questionStatJSON, 0, len(s.Questions)),
|
||||||
|
}
|
||||||
|
for _, st := range s.Students {
|
||||||
|
row := studentStatJSON{
|
||||||
|
UserID: st.UserID, Email: st.Email, Name: st.Name, Surname: st.Surname, Attempts: st.Attempts,
|
||||||
|
BestScorePercent: st.BestScorePercent, LastScorePercent: st.LastScorePercent, Passed: st.Passed,
|
||||||
|
}
|
||||||
|
if st.LastCompletedAt != nil {
|
||||||
|
t := wireTime(*st.LastCompletedAt)
|
||||||
|
row.LastCompletedAt = &t
|
||||||
|
}
|
||||||
|
out.Students = append(out.Students, row)
|
||||||
|
}
|
||||||
|
for _, q := range s.Questions {
|
||||||
|
row := questionStatJSON{
|
||||||
|
ID: q.ID, Text: q.Text, Type: q.Type, Answered: q.Answered, Correct: q.Correct, CorrectPercent: q.CorrectPercent,
|
||||||
|
Unreviewed: q.Unreviewed, AveragePoints: q.AveragePoints,
|
||||||
|
}
|
||||||
|
if q.MostChosenWrong != nil {
|
||||||
|
row.MostChosenWrong = &wrongAnswerJSON{AnswerID: q.MostChosenWrong.AnswerID, Text: q.MostChosenWrong.Text, Count: q.MostChosenWrong.Count}
|
||||||
|
}
|
||||||
|
out.Questions = append(out.Questions, row)
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
// quizGrader is the quiz's grader code, manual for a quiz read before the
|
||||||
|
// column had a value.
|
||||||
|
func quizGrader(q *models.Quiz) string {
|
||||||
|
if q.Grader == "" {
|
||||||
|
return graders.Manual
|
||||||
|
}
|
||||||
|
return q.Grader
|
||||||
|
}
|
||||||
88
controllers/api/manage_test.go
Normal file
88
controllers/api/manage_test.go
Normal file
@@ -0,0 +1,88 @@
|
|||||||
|
package api
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"git.golem15.com/golem15/summercms/modules/backpack"
|
||||||
|
)
|
||||||
|
|
||||||
|
// TestManageHandlersWithoutDatabase: every manage handler answers 503
|
||||||
|
// when the application has no database and the input is valid.
|
||||||
|
func TestManageHandlersWithoutDatabase(t *testing.T) {
|
||||||
|
h := New(backpack.New(nil))
|
||||||
|
for name, tc := range map[string]struct {
|
||||||
|
fn http.HandlerFunc
|
||||||
|
method string
|
||||||
|
target string
|
||||||
|
body string
|
||||||
|
}{
|
||||||
|
"list": {h.ManageListQuizzes, "GET", "/", ""},
|
||||||
|
"show": {h.ManageShowQuiz, "GET", "/", ""},
|
||||||
|
"create": {h.ManageCreateQuiz, "POST", "/", `{"title":"Pojęcia"}`},
|
||||||
|
"update": {h.ManageUpdateQuiz, "PATCH", "/", `{"max_attempts":0}`},
|
||||||
|
"delete": {h.ManageDeleteQuiz, "DELETE", "/?confirm=x", ""},
|
||||||
|
"publish": {h.ManagePublish, "POST", "/", ""},
|
||||||
|
"unpublish": {h.ManageUnpublish, "POST", "/", ""},
|
||||||
|
"stats": {h.ManageQuizStats, "GET", "/", ""},
|
||||||
|
"create question": {h.ManageCreateQuestion, "POST", "/", `{"text":"Q","type":"self_check"}`},
|
||||||
|
"update question": {h.ManageUpdateQuestion, "PATCH", "/", `{"text":"Q"}`},
|
||||||
|
"delete question": {h.ManageDeleteQuestion, "DELETE", "/", ""},
|
||||||
|
"reorder": {h.ManageReorderQuestions, "PUT", "/", `{"question_ids":[2,1]}`},
|
||||||
|
} {
|
||||||
|
code, _ := call(t, tc.fn, tc.method, tc.target, tc.body, 7, map[string]string{"slug": "x", "id": "3"})
|
||||||
|
if code != http.StatusServiceUnavailable {
|
||||||
|
t.Errorf("%s without a database = %d, want 503", name, code)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestManageWritesRefuseBadInputBeforeDatabase: invalid input is a 422
|
||||||
|
// even without a database, so it is checked before any read.
|
||||||
|
func TestManageWritesRefuseBadInputBeforeDatabase(t *testing.T) {
|
||||||
|
h := New(backpack.New(nil))
|
||||||
|
for name, tc := range map[string]struct {
|
||||||
|
fn http.HandlerFunc
|
||||||
|
method string
|
||||||
|
target string
|
||||||
|
body string
|
||||||
|
want string
|
||||||
|
}{
|
||||||
|
"create invalid JSON": {h.ManageCreateQuiz, "POST", "/", `{"title":`, "invalid JSON"},
|
||||||
|
"create empty body": {h.ManageCreateQuiz, "POST", "/", "", "invalid JSON"},
|
||||||
|
"create is_published": {h.ManageCreateQuiz, "POST", "/", `{"title":"A","is_published":true}`, "is_published"},
|
||||||
|
"create missing title": {h.ManageCreateQuiz, "POST", "/", `{"slug":"a"}`, "title is required"},
|
||||||
|
"create mode exam": {h.ManageCreateQuiz, "POST", "/", `{"title":"A","mode":"exam"}`, "mode must be one of"},
|
||||||
|
"update slug": {h.ManageUpdateQuiz, "PATCH", "/", `{"slug":"b"}`, "slug"},
|
||||||
|
"update is_published": {h.ManageUpdateQuiz, "PATCH", "/", `{"is_published":true}`, "is_published"},
|
||||||
|
"update passing 101": {h.ManageUpdateQuiz, "PATCH", "/", `{"passing_score":101}`, "passing_score"},
|
||||||
|
"create unknown grader": {h.ManageCreateQuiz, "POST", "/", `{"title":"A","grader":"zzz"}`, "grader must be one of manual"},
|
||||||
|
"create bad grader": {h.ManageCreateQuiz, "POST", "/", `{"title":"A","grader":"Bad Grader"}`, "grader must be lowercase"},
|
||||||
|
"update unknown grader": {h.ManageUpdateQuiz, "PATCH", "/", `{"grader":"zzz"}`, "grader must be one of manual"},
|
||||||
|
"question open answers": {h.ManageCreateQuestion, "POST", "/", `{"text":"Q","type":"open","answers":[{"text":"a"}]}`, "an open question has no answers"},
|
||||||
|
"question rubric single": {h.ManageCreateQuestion, "POST", "/", `{"text":"Q","type":"single","rubric":"R","answers":[{"text":"a","is_correct":true},{"text":"b"}]}`, "rubric applies to open questions only"},
|
||||||
|
"delete without confirm": {h.ManageDeleteQuiz, "DELETE", "/", "", "confirm must repeat the quiz slug"},
|
||||||
|
"delete wrong confirm": {h.ManageDeleteQuiz, "DELETE", "/?confirm=y", "", "confirm must repeat the quiz slug"},
|
||||||
|
} {
|
||||||
|
code, out := call(t, tc.fn, tc.method, tc.target, tc.body, 7, map[string]string{"slug": "x", "id": "3"})
|
||||||
|
msg, _ := out["message"].(string)
|
||||||
|
if code != http.StatusUnprocessableEntity || !strings.Contains(msg, tc.want) {
|
||||||
|
t.Errorf("%s = %d %v, want 422 with %q", name, code, out, tc.want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestManageQuestionIDs: a question id that is not a positive integer is
|
||||||
|
// the 404 of a missing question, before the database.
|
||||||
|
func TestManageQuestionIDs(t *testing.T) {
|
||||||
|
h := New(backpack.New(nil))
|
||||||
|
for _, id := range []string{"", "0", "abc", "-1"} {
|
||||||
|
for name, fn := range map[string]http.HandlerFunc{"update": h.ManageUpdateQuestion, "delete": h.ManageDeleteQuestion} {
|
||||||
|
code, out := call(t, fn, "PATCH", "/", `{}`, 7, map[string]string{"slug": "x", "id": id})
|
||||||
|
if code != http.StatusNotFound || out["message"] != "Question not found." {
|
||||||
|
t.Errorf("%s id %q = %d %v, want 404 Question not found.", name, id, code, out)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
175
controllers/api/review_json.go
Normal file
175
controllers/api/review_json.go
Normal file
@@ -0,0 +1,175 @@
|
|||||||
|
package api
|
||||||
|
|
||||||
|
// The owner shapes of the review routes. They carry student emails, the
|
||||||
|
// model answer, the rubric and grading errors, and are never used by a
|
||||||
|
// student route; the student shapes live in json.go. Built field by field,
|
||||||
|
// so a new column never leaks.
|
||||||
|
|
||||||
|
import (
|
||||||
|
"time"
|
||||||
|
"unicode/utf8"
|
||||||
|
|
||||||
|
"git.golem15.com/golem15/sm-quizzes-plugin/classes"
|
||||||
|
"git.golem15.com/golem15/sm-quizzes-plugin/models"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/wire"
|
||||||
|
)
|
||||||
|
|
||||||
|
type reviewQuizShape struct {
|
||||||
|
ID uint `json:"id"`
|
||||||
|
Slug string `json:"slug"`
|
||||||
|
Title string `json:"title"`
|
||||||
|
Mode string `json:"mode"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type reviewQuestionShape struct {
|
||||||
|
ID uint `json:"id"`
|
||||||
|
Text string `json:"text"`
|
||||||
|
Points int `json:"points"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type reviewDetailQuestionShape struct {
|
||||||
|
reviewQuestionShape
|
||||||
|
AnswerText *string `json:"answer_text"`
|
||||||
|
Rubric *string `json:"rubric"`
|
||||||
|
MaxLength int `json:"max_length"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type reviewAttemptShape struct {
|
||||||
|
ID uint `json:"id"`
|
||||||
|
Completed bool `json:"completed"`
|
||||||
|
CompletedAt *wire.Time `json:"completed_at"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type reviewStudentShape struct {
|
||||||
|
UserID uint `json:"user_id"`
|
||||||
|
Email string `json:"email"`
|
||||||
|
Name *string `json:"name"`
|
||||||
|
Surname *string `json:"surname"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type reviewerShape struct {
|
||||||
|
UserID *uint `json:"user_id"`
|
||||||
|
AdminID *uint `json:"admin_id"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// reviewRowShape is one row of GET /api/v1/quiz-reviews.
|
||||||
|
type reviewRowShape struct {
|
||||||
|
AnswerID uint `json:"answer_id"`
|
||||||
|
Status string `json:"status"`
|
||||||
|
Quiz reviewQuizShape `json:"quiz"`
|
||||||
|
Question reviewQuestionShape `json:"question"`
|
||||||
|
Attempt reviewAttemptShape `json:"attempt"`
|
||||||
|
Student reviewStudentShape `json:"student"`
|
||||||
|
Text string `json:"text"`
|
||||||
|
TextTruncated bool `json:"text_truncated"`
|
||||||
|
GraderPoints *float64 `json:"grader_points"`
|
||||||
|
Points float64 `json:"points"`
|
||||||
|
GradedAt *wire.Time `json:"graded_at"`
|
||||||
|
ReviewedAt *wire.Time `json:"reviewed_at"`
|
||||||
|
UpdatedAt wire.Time `json:"updated_at"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// reviewDetailShape is GET /api/v1/quiz-reviews/{id} and every review
|
||||||
|
// write: the row keys with the whole text, plus the solution and the
|
||||||
|
// grading and review record.
|
||||||
|
type reviewDetailShape struct {
|
||||||
|
AnswerID uint `json:"answer_id"`
|
||||||
|
Status string `json:"status"`
|
||||||
|
Quiz reviewQuizShape `json:"quiz"`
|
||||||
|
Question reviewDetailQuestionShape `json:"question"`
|
||||||
|
Attempt reviewAttemptShape `json:"attempt"`
|
||||||
|
Student reviewStudentShape `json:"student"`
|
||||||
|
Text string `json:"text"`
|
||||||
|
GraderPoints *float64 `json:"grader_points"`
|
||||||
|
Points float64 `json:"points"`
|
||||||
|
GradedAt *wire.Time `json:"graded_at"`
|
||||||
|
ReviewedAt *wire.Time `json:"reviewed_at"`
|
||||||
|
UpdatedAt wire.Time `json:"updated_at"`
|
||||||
|
Grader *string `json:"grader"`
|
||||||
|
GraderFeedback *string `json:"grader_feedback"`
|
||||||
|
GradingError *string `json:"grading_error"`
|
||||||
|
GradingAttempts int `json:"grading_attempts"`
|
||||||
|
IsCorrect bool `json:"is_correct"`
|
||||||
|
ReviewComment *string `json:"review_comment"`
|
||||||
|
ReviewedBy reviewerShape `json:"reviewed_by"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func wireTimePtr(t *time.Time) *wire.Time {
|
||||||
|
if t == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
w := wireTime(*t)
|
||||||
|
return &w
|
||||||
|
}
|
||||||
|
|
||||||
|
func reviewQuiz(r classes.ReviewRow) reviewQuizShape {
|
||||||
|
return reviewQuizShape{ID: r.QuizID, Slug: r.QuizSlug, Title: r.QuizTitle, Mode: quizMode(&models.Quiz{Mode: r.QuizMode})}
|
||||||
|
}
|
||||||
|
|
||||||
|
func reviewAttempt(r classes.ReviewRow) reviewAttemptShape {
|
||||||
|
return reviewAttemptShape{ID: r.AttemptID, Completed: r.AttemptCompletedAt != nil, CompletedAt: wireTimePtr(r.AttemptCompletedAt)}
|
||||||
|
}
|
||||||
|
|
||||||
|
func reviewStudent(r classes.ReviewRow) reviewStudentShape {
|
||||||
|
return reviewStudentShape{UserID: r.UserID, Email: r.Email, Name: r.Name, Surname: r.Surname}
|
||||||
|
}
|
||||||
|
|
||||||
|
// excerpt keeps the first n runes of s and reports whether it cut.
|
||||||
|
func excerpt(s string, n int) (string, bool) {
|
||||||
|
if utf8.RuneCountInString(s) <= n {
|
||||||
|
return s, false
|
||||||
|
}
|
||||||
|
return string([]rune(s)[:n]), true
|
||||||
|
}
|
||||||
|
|
||||||
|
// reviewRowJSON is one queue row; the text is cut to the first
|
||||||
|
// classes.ReviewExcerptRunes runes with text_truncated set.
|
||||||
|
func reviewRowJSON(r classes.ReviewRow) reviewRowShape {
|
||||||
|
text, cut := excerpt(r.Text, classes.ReviewExcerptRunes)
|
||||||
|
return reviewRowShape{
|
||||||
|
AnswerID: r.AnswerID,
|
||||||
|
Status: r.Status,
|
||||||
|
Quiz: reviewQuiz(r),
|
||||||
|
Question: reviewQuestionShape{ID: r.QuestionID, Text: r.QuestionText, Points: r.QuestionPoints},
|
||||||
|
Attempt: reviewAttempt(r),
|
||||||
|
Student: reviewStudent(r),
|
||||||
|
Text: text,
|
||||||
|
TextTruncated: cut,
|
||||||
|
GraderPoints: r.GraderPoints,
|
||||||
|
Points: r.Points,
|
||||||
|
GradedAt: wireTimePtr(r.GradedAt),
|
||||||
|
ReviewedAt: wireTimePtr(r.ReviewedAt),
|
||||||
|
UpdatedAt: wireTime(r.UpdatedAt),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// reviewDetailJSON is one answer for review, owner view.
|
||||||
|
func reviewDetailJSON(d classes.ReviewDetail) reviewDetailShape {
|
||||||
|
r := d.ReviewRow
|
||||||
|
return reviewDetailShape{
|
||||||
|
AnswerID: r.AnswerID,
|
||||||
|
Status: r.Status,
|
||||||
|
Quiz: reviewQuiz(r),
|
||||||
|
Question: reviewDetailQuestionShape{
|
||||||
|
reviewQuestionShape: reviewQuestionShape{ID: r.QuestionID, Text: r.QuestionText, Points: r.QuestionPoints},
|
||||||
|
AnswerText: d.AnswerText,
|
||||||
|
Rubric: d.Rubric,
|
||||||
|
MaxLength: d.MaxLength,
|
||||||
|
},
|
||||||
|
Attempt: reviewAttempt(r),
|
||||||
|
Student: reviewStudent(r),
|
||||||
|
Text: r.Text,
|
||||||
|
GraderPoints: r.GraderPoints,
|
||||||
|
Points: r.Points,
|
||||||
|
GradedAt: wireTimePtr(r.GradedAt),
|
||||||
|
ReviewedAt: wireTimePtr(r.ReviewedAt),
|
||||||
|
UpdatedAt: wireTime(r.UpdatedAt),
|
||||||
|
Grader: d.Grader,
|
||||||
|
GraderFeedback: d.GraderFeedback,
|
||||||
|
GradingError: d.GradingError,
|
||||||
|
GradingAttempts: d.GradingAttempts,
|
||||||
|
IsCorrect: d.IsCorrect,
|
||||||
|
ReviewComment: d.ReviewComment,
|
||||||
|
ReviewedBy: reviewerShape{UserID: d.ReviewedByUserID, AdminID: d.ReviewedByAdminID},
|
||||||
|
}
|
||||||
|
}
|
||||||
248
controllers/api/reviews.go
Normal file
248
controllers/api/reviews.go
Normal file
@@ -0,0 +1,248 @@
|
|||||||
|
package api
|
||||||
|
|
||||||
|
// The owner review routes under /api/v1/quiz-reviews, behind user.api_token,
|
||||||
|
// the golem15.quizzes.manage throttle, a token scope and the access_quizzes
|
||||||
|
// permission (D-13). The quizzes_review_* MCP tools bind them. Answers use
|
||||||
|
// the owner shapes of review_json.go.
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"net/http"
|
||||||
|
"net/url"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"git.golem15.com/golem15/sm-quizzes-plugin/classes"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/lagoon"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/wire"
|
||||||
|
)
|
||||||
|
|
||||||
|
// reviewConflict answers a review action the answer's state refuses: 409
|
||||||
|
// with a stable code for clients to branch on.
|
||||||
|
func reviewConflict(w http.ResponseWriter, message, code string) {
|
||||||
|
wire.WriteJSON(w, http.StatusConflict, map[string]any{"error": true, "message": message, "code": code})
|
||||||
|
}
|
||||||
|
|
||||||
|
// writeReview answers {data: data}, or maps err: the review conflicts are
|
||||||
|
// 409s with a code, ErrNotFound a 404, everything else as writeManaged.
|
||||||
|
func writeReview(w http.ResponseWriter, status int, data any, err error) {
|
||||||
|
switch {
|
||||||
|
case errors.Is(err, classes.ErrNoGraderScore):
|
||||||
|
reviewConflict(w, "The answer has no grader score to confirm; set the score instead.", "no_grader_score")
|
||||||
|
case errors.Is(err, classes.ErrAlreadyReviewed):
|
||||||
|
reviewConflict(w, "The answer is already reviewed; set the score instead.", "already_reviewed")
|
||||||
|
case errors.Is(err, classes.ErrGraderManual):
|
||||||
|
reviewConflict(w, "The quiz's grader is manual or not available, so nothing can be graded again.", "grader_manual")
|
||||||
|
case errors.Is(err, classes.ErrAttemptOpen):
|
||||||
|
reviewConflict(w, "The test attempt is still open; review its answers once it ends.", "attempt_open")
|
||||||
|
case errors.Is(err, classes.ErrNotFound):
|
||||||
|
wire.WriteJSON(w, http.StatusNotFound, map[string]any{"error": true, "message": "Open answer, attempt or quiz not found."})
|
||||||
|
default:
|
||||||
|
writeManaged(w, status, data, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// queryID reads an optional id query value: empty is 0, anything but a
|
||||||
|
// positive integer is a problem.
|
||||||
|
func queryID(q url.Values, name string) (uint, []string) {
|
||||||
|
raw := strings.TrimSpace(q.Get(name))
|
||||||
|
if raw == "" {
|
||||||
|
return 0, nil
|
||||||
|
}
|
||||||
|
id, err := strconv.ParseUint(raw, 10, 32)
|
||||||
|
if err != nil || id == 0 {
|
||||||
|
return 0, []string{name + " must be a positive integer"}
|
||||||
|
}
|
||||||
|
return uint(id), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// reviewID reads the {id} path value, the answer id: anything but a
|
||||||
|
// positive integer is the 404 of a missing answer.
|
||||||
|
func reviewID(w http.ResponseWriter, r *http.Request) (uint, bool) {
|
||||||
|
id, err := strconv.ParseUint(r.PathValue("id"), 10, 32)
|
||||||
|
if err != nil || id == 0 {
|
||||||
|
writeReview(w, 0, nil, classes.ErrNotFound)
|
||||||
|
return 0, false
|
||||||
|
}
|
||||||
|
return uint(id), true
|
||||||
|
}
|
||||||
|
|
||||||
|
// reviewer is the API token's user, who signs a review made over MCP.
|
||||||
|
func (h *Handlers) reviewer(w http.ResponseWriter, r *http.Request) (classes.Reviewer, bool) {
|
||||||
|
id, ok := h.user(w, r)
|
||||||
|
return classes.Reviewer{UserID: id}, ok
|
||||||
|
}
|
||||||
|
|
||||||
|
// ReviewList answers GET /api/v1/quiz-reviews?quiz=&status=&user_id=
|
||||||
|
// &attempt_id=&page=&per_page=: the open answers, oldest change first,
|
||||||
|
// paginated. status defaults to open (pending, graded and failed).
|
||||||
|
func (h *Handlers) ReviewList(w http.ResponseWriter, r *http.Request) {
|
||||||
|
q := r.URL.Query()
|
||||||
|
f := classes.ReviewFilter{QuizSlug: strings.TrimSpace(q.Get("quiz")), Status: strings.TrimSpace(q.Get("status"))}
|
||||||
|
_, problems := classes.CheckReviewStatus(f.Status)
|
||||||
|
var p []string
|
||||||
|
f.UserID, p = queryID(q, "user_id")
|
||||||
|
problems = append(problems, p...)
|
||||||
|
f.AttemptID, p = queryID(q, "attempt_id")
|
||||||
|
problems = append(problems, p...)
|
||||||
|
if refuse(w, problems) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
svc, ok := h.service(w)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
page := queryInt(r, "page", 1, 1, 100000)
|
||||||
|
perPage := queryInt(r, "per_page", 20, 1, 100)
|
||||||
|
rows, total, err := svc.ReviewQueue(r.Context(), f, page, perPage)
|
||||||
|
if err != nil {
|
||||||
|
writeReview(w, 0, nil, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
out := make([]reviewRowShape, 0, len(rows))
|
||||||
|
for _, row := range rows {
|
||||||
|
out = append(out, reviewRowJSON(row))
|
||||||
|
}
|
||||||
|
wire.WriteJSON(w, http.StatusOK, lagoon.Paginate(out, page, perPage, total))
|
||||||
|
}
|
||||||
|
|
||||||
|
// ReviewShow answers GET /api/v1/quiz-reviews/{id}: one open answer with
|
||||||
|
// its question, model answer, rubric, grading and review.
|
||||||
|
func (h *Handlers) ReviewShow(w http.ResponseWriter, r *http.Request) {
|
||||||
|
id, ok := reviewID(w, r)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
svc, ok := h.service(w)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
d, err := svc.ReviewItem(r.Context(), id)
|
||||||
|
answerReview(w, d, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ReviewConfirm answers POST /api/v1/quiz-reviews/{id}/confirm: the
|
||||||
|
// grader's score becomes final; 409 no_grader_score for a pending or
|
||||||
|
// failed answer.
|
||||||
|
func (h *Handlers) ReviewConfirm(w http.ResponseWriter, r *http.Request) {
|
||||||
|
id, ok := reviewID(w, r)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
by, ok := h.reviewer(w, r)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
svc, ok := h.service(w)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
d, err := svc.Confirm(r.Context(), id, by)
|
||||||
|
answerReview(w, d, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// answerReview answers one reviewed answer, or maps err.
|
||||||
|
func answerReview(w http.ResponseWriter, d *classes.ReviewDetail, err error) {
|
||||||
|
if err != nil {
|
||||||
|
writeReview(w, 0, nil, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
writeReview(w, http.StatusOK, reviewDetailJSON(*d), nil)
|
||||||
|
}
|
||||||
|
|
||||||
|
// setScoreBody is the POST /{id}/score body.
|
||||||
|
type setScoreBody struct {
|
||||||
|
Points *float64 `json:"points"`
|
||||||
|
Comment *string `json:"comment"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// ReviewSetScore answers POST /api/v1/quiz-reviews/{id}/score with
|
||||||
|
// {points, comment}: the owner's final score on any status, with an
|
||||||
|
// optional comment the student sees. Points outside 0..question points or
|
||||||
|
// off the 0.5 steps, and a comment over 2000 characters, are a 422.
|
||||||
|
func (h *Handlers) ReviewSetScore(w http.ResponseWriter, r *http.Request) {
|
||||||
|
id, ok := reviewID(w, r)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var body setScoreBody
|
||||||
|
if !readManaged(w, r, &body) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
comment, problems := classes.CheckReviewComment(body.Comment)
|
||||||
|
if body.Points == nil {
|
||||||
|
problems = append([]string{"points is required"}, problems...)
|
||||||
|
}
|
||||||
|
if refuse(w, problems) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
by, ok := h.reviewer(w, r)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
svc, ok := h.service(w)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
d, err := svc.SetScore(r.Context(), id, *body.Points, comment, by)
|
||||||
|
answerReview(w, d, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// confirmBulkBody is the POST /confirm body.
|
||||||
|
type confirmBulkBody struct {
|
||||||
|
Quiz string `json:"quiz"`
|
||||||
|
AttemptID uint `json:"attempt_id"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// ReviewConfirmBulk answers POST /api/v1/quiz-reviews/confirm with
|
||||||
|
// exactly one of {quiz} and {attempt_id}: every graded answer in scope is
|
||||||
|
// confirmed; it answers {confirmed: n}.
|
||||||
|
func (h *Handlers) ReviewConfirmBulk(w http.ResponseWriter, r *http.Request) {
|
||||||
|
var body confirmBulkBody
|
||||||
|
if !readManaged(w, r, &body) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
scope := classes.ReviewScope{AttemptID: body.AttemptID, QuizSlug: strings.TrimSpace(body.Quiz)}
|
||||||
|
if refuse(w, classes.CheckReviewScope(scope, false)) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
by, ok := h.reviewer(w, r)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
svc, ok := h.service(w)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
n, err := svc.ConfirmBulk(r.Context(), scope, by)
|
||||||
|
writeReview(w, http.StatusOK, map[string]any{"confirmed": n}, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// regradeBody is the POST /regrade body.
|
||||||
|
type regradeBody struct {
|
||||||
|
AnswerID uint `json:"answer_id"`
|
||||||
|
AttemptID uint `json:"attempt_id"`
|
||||||
|
Quiz string `json:"quiz"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// ReviewRegrade answers POST /api/v1/quiz-reviews/regrade with exactly one
|
||||||
|
// of {answer_id}, {attempt_id} and {quiz}: the unreviewed open answers in
|
||||||
|
// scope go back to the quiz's grader; it answers {regraded: n}. 409
|
||||||
|
// grader_manual when the quiz has no grader, already_reviewed for a single
|
||||||
|
// reviewed answer.
|
||||||
|
func (h *Handlers) ReviewRegrade(w http.ResponseWriter, r *http.Request) {
|
||||||
|
var body regradeBody
|
||||||
|
if !readManaged(w, r, &body) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
scope := classes.ReviewScope{AnswerID: body.AnswerID, AttemptID: body.AttemptID, QuizSlug: strings.TrimSpace(body.Quiz)}
|
||||||
|
if refuse(w, classes.CheckReviewScope(scope, true)) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
svc, ok := h.service(w)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
n, err := svc.Regrade(r.Context(), scope)
|
||||||
|
writeReview(w, http.StatusOK, map[string]any{"regraded": n}, err)
|
||||||
|
}
|
||||||
215
controllers/api/reviews_test.go
Normal file
215
controllers/api/reviews_test.go
Normal file
@@ -0,0 +1,215 @@
|
|||||||
|
package api
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
"unicode/utf8"
|
||||||
|
|
||||||
|
"git.golem15.com/golem15/sm-quizzes-plugin/classes"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/backpack"
|
||||||
|
)
|
||||||
|
|
||||||
|
func reviewRowFixture(text string) classes.ReviewRow {
|
||||||
|
at := time.Date(2026, 11, 9, 12, 0, 0, 0, time.UTC)
|
||||||
|
gp := 1.5
|
||||||
|
name := "Anna"
|
||||||
|
return classes.ReviewRow{
|
||||||
|
AnswerID: 41, Status: "graded",
|
||||||
|
QuizID: 3, QuizSlug: "pojecia", QuizTitle: "Pojęcia", QuizMode: "",
|
||||||
|
QuestionID: 7, QuestionText: "Czym jest odstraszanie?", QuestionPoints: 2,
|
||||||
|
AttemptID: 9, AttemptCompletedAt: &at,
|
||||||
|
UserID: 5, Email: "anna@example.test", Name: &name,
|
||||||
|
Text: text, GraderPoints: &gp, Points: 1.5, GradedAt: &at, UpdatedAt: at,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func marshalMap(t *testing.T, v any) (string, map[string]any) {
|
||||||
|
t.Helper()
|
||||||
|
raw, err := json.Marshal(v)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
var out map[string]any
|
||||||
|
if err := json.Unmarshal(raw, &out); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
return string(raw), out
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestReviewJSON: a queue row cuts the text to 300 runes and says so,
|
||||||
|
// keeps a short text whole, and names its keys in snake_case; the detail
|
||||||
|
// carries the whole text with the model answer, rubric and grading error.
|
||||||
|
func TestReviewJSON(t *testing.T) {
|
||||||
|
long := strings.Repeat("ż", 301)
|
||||||
|
_, out := marshalMap(t, reviewRowJSON(reviewRowFixture(long)))
|
||||||
|
if got := out["text"].(string); utf8.RuneCountInString(got) != 300 || out["text_truncated"] != true {
|
||||||
|
t.Errorf("long text = %d runes, truncated %v; want 300, true", utf8.RuneCountInString(got), out["text_truncated"])
|
||||||
|
}
|
||||||
|
|
||||||
|
short := strings.Repeat("a", 120)
|
||||||
|
raw, out := marshalMap(t, reviewRowJSON(reviewRowFixture(short)))
|
||||||
|
if out["text"] != short || out["text_truncated"] != false {
|
||||||
|
t.Errorf("short text = %v, truncated %v; want whole, false", out["text"], out["text_truncated"])
|
||||||
|
}
|
||||||
|
for _, key := range []string{"answer_id", "status", "quiz", "question", "attempt", "student", "text", "text_truncated", "grader_points", "points", "graded_at", "reviewed_at", "updated_at"} {
|
||||||
|
if _, ok := out[key]; !ok {
|
||||||
|
t.Errorf("row lacks %q: %s", key, raw)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if q := out["quiz"].(map[string]any); q["slug"] != "pojecia" || q["mode"] != "learning" {
|
||||||
|
t.Errorf("quiz = %v, want slug pojecia and mode learning", q)
|
||||||
|
}
|
||||||
|
if a := out["attempt"].(map[string]any); a["id"] != float64(9) || a["completed"] != true {
|
||||||
|
t.Errorf("attempt = %v, want id 9 completed", a)
|
||||||
|
}
|
||||||
|
if s := out["student"].(map[string]any); s["user_id"] != float64(5) || s["email"] != "anna@example.test" || s["name"] != "Anna" || s["surname"] != nil {
|
||||||
|
t.Errorf("student = %v", s)
|
||||||
|
}
|
||||||
|
for _, leak := range []string{"rubric", "answer_text", "grading_error"} {
|
||||||
|
if strings.Contains(raw, `"`+leak+`"`) {
|
||||||
|
t.Errorf("row carries %q: %s", leak, raw)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
model, rubric, failure := "model", "R-RUBRIC", "grader timed out"
|
||||||
|
d := classes.ReviewDetail{
|
||||||
|
ReviewRow: reviewRowFixture(long), AnswerText: &model, Rubric: &rubric, MaxLength: 2000,
|
||||||
|
GradingError: &failure, GradingAttempts: 3,
|
||||||
|
}
|
||||||
|
raw, out = marshalMap(t, reviewDetailJSON(d))
|
||||||
|
if got := out["text"].(string); got != long {
|
||||||
|
t.Errorf("detail text has %d runes, want the whole 301", utf8.RuneCountInString(got))
|
||||||
|
}
|
||||||
|
q := out["question"].(map[string]any)
|
||||||
|
if q["answer_text"] != "model" || q["rubric"] != "R-RUBRIC" || q["max_length"] != float64(2000) || q["points"] != float64(2) {
|
||||||
|
t.Errorf("detail question = %v", q)
|
||||||
|
}
|
||||||
|
for _, key := range []string{"grader", "grader_feedback", "grading_error", "grading_attempts", "is_correct", "review_comment", "reviewed_by", "reviewed_at"} {
|
||||||
|
if _, ok := out[key]; !ok {
|
||||||
|
t.Errorf("detail lacks %q: %s", key, raw)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if out["grading_error"] != failure || out["grading_attempts"] != float64(3) {
|
||||||
|
t.Errorf("detail grading = %v / %v", out["grading_error"], out["grading_attempts"])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestReviewErrorMapping: the review conflicts are 409s with a code, a
|
||||||
|
// missing answer a 404, invalid input a 422, other errors an opaque 500.
|
||||||
|
func TestReviewErrorMapping(t *testing.T) {
|
||||||
|
for name, tc := range map[string]struct {
|
||||||
|
err error
|
||||||
|
code int
|
||||||
|
key string
|
||||||
|
}{
|
||||||
|
"no grader score": {classes.ErrNoGraderScore, http.StatusConflict, "no_grader_score"},
|
||||||
|
"already reviewed": {classes.ErrAlreadyReviewed, http.StatusConflict, "already_reviewed"},
|
||||||
|
"grader manual": {classes.ErrGraderManual, http.StatusConflict, "grader_manual"},
|
||||||
|
"not found": {classes.ErrNotFound, http.StatusNotFound, ""},
|
||||||
|
"validation": {&classes.ValidationError{Problems: []string{"status must be one of"}}, http.StatusUnprocessableEntity, ""},
|
||||||
|
"other": {errors.New("boom"), http.StatusInternalServerError, ""},
|
||||||
|
} {
|
||||||
|
rec := httptest.NewRecorder()
|
||||||
|
writeReview(rec, 0, nil, tc.err)
|
||||||
|
if rec.Code != tc.code {
|
||||||
|
t.Errorf("%s = %d, want %d: %s", name, rec.Code, tc.code, rec.Body.String())
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if tc.key != "" {
|
||||||
|
var out map[string]any
|
||||||
|
_ = json.Unmarshal(rec.Body.Bytes(), &out)
|
||||||
|
if out["code"] != tc.key || out["error"] != true || out["message"] == "" {
|
||||||
|
t.Errorf("%s body = %v, want code %s", name, out, tc.key)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
rec := httptest.NewRecorder()
|
||||||
|
writeReview(rec, http.StatusOK, map[string]any{"x": 1}, nil)
|
||||||
|
if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), `"data"`) {
|
||||||
|
t.Errorf("success = %d %s", rec.Code, rec.Body.String())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestReviewHandlersBeforeDatabase: bad filters are a 422 and a bad id a
|
||||||
|
// 404 before the database; valid requests without one are a 503.
|
||||||
|
func TestReviewHandlersBeforeDatabase(t *testing.T) {
|
||||||
|
h := New(backpack.New(nil))
|
||||||
|
for target, want := range map[string]string{
|
||||||
|
"/?status=done": "status must be one of",
|
||||||
|
"/?user_id=abc": "user_id must be a positive integer",
|
||||||
|
"/?attempt_id=0": "attempt_id must be a positive integer",
|
||||||
|
"/?attempt_id=-3": "attempt_id must be a positive integer",
|
||||||
|
"/?user_id=99999999999": "user_id must be a positive integer",
|
||||||
|
} {
|
||||||
|
code, out := call(t, h.ReviewList, "GET", target, "", 7, nil)
|
||||||
|
if msg, _ := out["message"].(string); code != http.StatusUnprocessableEntity || !strings.Contains(msg, want) {
|
||||||
|
t.Errorf("list %s = %d %v, want 422 with %q", target, code, out, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, id := range []string{"", "0", "abc"} {
|
||||||
|
for name, fn := range map[string]http.HandlerFunc{"show": h.ReviewShow, "confirm": h.ReviewConfirm} {
|
||||||
|
code, _ := call(t, fn, "POST", "/", "", 7, map[string]string{"id": id})
|
||||||
|
if code != http.StatusNotFound {
|
||||||
|
t.Errorf("%s id %q = %d, want 404", name, id, code)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for name, fn := range map[string]http.HandlerFunc{"list": h.ReviewList, "show": h.ReviewShow, "confirm": h.ReviewConfirm} {
|
||||||
|
code, _ := call(t, fn, "GET", "/?status=graded", "", 7, map[string]string{"id": "3"})
|
||||||
|
if code != http.StatusServiceUnavailable {
|
||||||
|
t.Errorf("%s without a database = %d, want 503", name, code)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if code, _ := call(t, h.ReviewConfirm, "POST", "/", "", 0, map[string]string{"id": "3"}); code != http.StatusUnauthorized {
|
||||||
|
t.Errorf("confirm without a user = %d, want 401", code)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestReviewWritesBeforeDatabase: the bodies of set_score, confirm_bulk
|
||||||
|
// and regrade are checked before the database: unknown keys, a missing
|
||||||
|
// points, a long comment and a scope that is not exactly one key are 422s.
|
||||||
|
func TestReviewWritesBeforeDatabase(t *testing.T) {
|
||||||
|
h := New(backpack.New(nil))
|
||||||
|
long := strings.Repeat("x", 2001)
|
||||||
|
id := map[string]string{"id": "3"}
|
||||||
|
for name, tc := range map[string]struct {
|
||||||
|
fn http.HandlerFunc
|
||||||
|
body string
|
||||||
|
want string
|
||||||
|
}{
|
||||||
|
"score empty body": {h.ReviewSetScore, "", "invalid JSON"},
|
||||||
|
"score unknown key": {h.ReviewSetScore, `{"points":1,"status":"reviewed"}`, "invalid JSON"},
|
||||||
|
"score without points": {h.ReviewSetScore, `{"comment":"ok"}`, "points is required"},
|
||||||
|
"score long comment": {h.ReviewSetScore, `{"points":1,"comment":"` + long + `"}`, "comment must be at most 2000 characters"},
|
||||||
|
"bulk none": {h.ReviewConfirmBulk, `{}`, "exactly one of attempt_id and quiz is required"},
|
||||||
|
"bulk two": {h.ReviewConfirmBulk, `{"quiz":"q","attempt_id":4}`, "exactly one of attempt_id and quiz is required"},
|
||||||
|
"bulk answer_id": {h.ReviewConfirmBulk, `{"answer_id":4}`, "invalid JSON"},
|
||||||
|
"regrade none": {h.ReviewRegrade, `{}`, "exactly one of answer_id, attempt_id and quiz is required"},
|
||||||
|
"regrade two": {h.ReviewRegrade, `{"answer_id":3,"quiz":"q"}`, "exactly one of answer_id, attempt_id and quiz is required"},
|
||||||
|
} {
|
||||||
|
code, out := call(t, tc.fn, "POST", "/", tc.body, 7, id)
|
||||||
|
if msg, _ := out["message"].(string); code != http.StatusUnprocessableEntity || !strings.Contains(msg, tc.want) {
|
||||||
|
t.Errorf("%s = %d %v, want 422 with %q", name, code, out, tc.want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for name, tc := range map[string]struct {
|
||||||
|
fn http.HandlerFunc
|
||||||
|
body string
|
||||||
|
}{
|
||||||
|
"score": {h.ReviewSetScore, `{"points":1.5,"comment":null}`},
|
||||||
|
"bulk": {h.ReviewConfirmBulk, `{"quiz":"q"}`},
|
||||||
|
"regrade": {h.ReviewRegrade, `{"attempt_id":4}`},
|
||||||
|
} {
|
||||||
|
if code, _ := call(t, tc.fn, "POST", "/", tc.body, 7, id); code != http.StatusServiceUnavailable {
|
||||||
|
t.Errorf("%s without a database = %d, want 503", name, code)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if code, _ := call(t, h.ReviewSetScore, "POST", "/", `{"points":1}`, 7, map[string]string{"id": "x"}); code != http.StatusNotFound {
|
||||||
|
t.Errorf("score with a bad id = %d, want 404", code)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -3,6 +3,7 @@
|
|||||||
package controllers
|
package controllers
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"git.golem15.com/golem15/sm-quizzes-plugin/graders"
|
||||||
"git.golem15.com/golem15/sm-quizzes-plugin/models"
|
"git.golem15.com/golem15/sm-quizzes-plugin/models"
|
||||||
"git.golem15.com/golem15/summercms/modules/pact"
|
"git.golem15.com/golem15/summercms/modules/pact"
|
||||||
)
|
)
|
||||||
@@ -11,8 +12,17 @@ var (
|
|||||||
_ pact.AdminController = quizzesAdmin{}
|
_ pact.AdminController = quizzesAdmin{}
|
||||||
_ pact.AdminRecordSource = quizzesAdmin{}
|
_ pact.AdminRecordSource = quizzesAdmin{}
|
||||||
_ pact.AdminPermissioned = quizzesAdmin{}
|
_ pact.AdminPermissioned = quizzesAdmin{}
|
||||||
|
|
||||||
|
_ pact.DropdownOptionsProvider = quizzesAdmin{}
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// GraderOptions lists the grader dropdown choices: the registry golem15.quizzes
|
||||||
|
// built at boot. The plugin sets it at Boot; nil offers manual only.
|
||||||
|
//
|
||||||
|
// TODO: requires SummerCMS change. DropdownOptions receives neither a
|
||||||
|
// context nor the app, so the registry comes through a package-level hook.
|
||||||
|
var GraderOptions func() []graders.Option
|
||||||
|
|
||||||
// quizzesAdmin lists and edits quizzes. Questions have their own controller
|
// quizzesAdmin lists and edits quizzes. Questions have their own controller
|
||||||
// filtered by quiz.
|
// filtered by quiz.
|
||||||
//
|
//
|
||||||
@@ -33,5 +43,25 @@ func (quizzesAdmin) RequiredPermissions() []string {
|
|||||||
return []string{"golem15.quizzes.access_quizzes"}
|
return []string{"golem15.quizzes.access_quizzes"}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// DropdownOptions serves the grader dropdown (options: getGraderOptions):
|
||||||
|
// manual, then every grader an activated plugin registered. Other fields
|
||||||
|
// have no method-backed options.
|
||||||
|
func (quizzesAdmin) DropdownOptions(field string) []pact.Option {
|
||||||
|
if field != "grader" {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
opts := []graders.Option{{Code: graders.Manual, Label: graders.ManualLabel}}
|
||||||
|
if GraderOptions != nil {
|
||||||
|
if got := GraderOptions(); len(got) > 0 {
|
||||||
|
opts = got
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out := make([]pact.Option, 0, len(opts))
|
||||||
|
for _, o := range opts {
|
||||||
|
out = append(out, pact.Option{Value: o.Code, Label: o.Label})
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
// QuizzesController returns the golem15.quizzes.quizzes admin controller.
|
// QuizzesController returns the golem15.quizzes.quizzes admin controller.
|
||||||
func QuizzesController() pact.AdminController { return quizzesAdmin{} }
|
func QuizzesController() pact.AdminController { return quizzesAdmin{} }
|
||||||
|
|||||||
587
controllers/reviews.go
Normal file
587
controllers/reviews.go
Normal file
@@ -0,0 +1,587 @@
|
|||||||
|
package controllers
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"math"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
"unicode/utf8"
|
||||||
|
|
||||||
|
"git.golem15.com/golem15/sm-quizzes-plugin/classes"
|
||||||
|
"git.golem15.com/golem15/sm-quizzes-plugin/graders"
|
||||||
|
"git.golem15.com/golem15/sm-quizzes-plugin/models"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/bouncer"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/cabana"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/pact"
|
||||||
|
"gorm.io/gorm"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
_ pact.AdminController = reviewsAdmin{}
|
||||||
|
_ pact.AdminRecordSource = reviewsAdmin{}
|
||||||
|
_ pact.AdminPermissioned = reviewsAdmin{}
|
||||||
|
_ pact.ListExtendQuery = reviewsAdmin{}
|
||||||
|
_ pact.FormExtendQuery = reviewsAdmin{}
|
||||||
|
_ pact.FormRecordTitle = reviewsAdmin{}
|
||||||
|
_ pact.FormBeforeCreate = reviewsAdmin{}
|
||||||
|
_ pact.FormBeforeDelete = reviewsAdmin{}
|
||||||
|
_ pact.FormVirtualFields = reviewsAdmin{}
|
||||||
|
_ pact.FormRules = reviewsAdmin{}
|
||||||
|
_ pact.FormAfterUpdate = reviewsAdmin{}
|
||||||
|
_ pact.HasAdminBulkActions = reviewsAdmin{}
|
||||||
|
_ pact.HasAdminRecordActions = reviewsAdmin{}
|
||||||
|
_ pact.AdminPartialData = reviewsAdmin{}
|
||||||
|
)
|
||||||
|
|
||||||
|
// Reviews builds the review service of an admin request: over the request's
|
||||||
|
// write transaction (cabana.TxFromContext) when there is one, else over the
|
||||||
|
// application's database. The plugin sets it at Boot.
|
||||||
|
//
|
||||||
|
// TODO: requires SummerCMS change. Admin hooks receive no app, so, as
|
||||||
|
// models.FilterDB, the service comes through a package-level hook.
|
||||||
|
var Reviews func(ctx context.Context) *classes.Service
|
||||||
|
|
||||||
|
// reviewsLang prefixes the lang keys of the review screen.
|
||||||
|
const reviewsLang = "golem15.quizzes::lang.reviews."
|
||||||
|
|
||||||
|
// The virtual fields of the review form and its partial.
|
||||||
|
const (
|
||||||
|
fieldReviewPoints = "review_points"
|
||||||
|
fieldReviewComment = "review_comment"
|
||||||
|
partialReview = "review_context"
|
||||||
|
)
|
||||||
|
|
||||||
|
// errReviewsUnavailable is an admin request before the plugin booted.
|
||||||
|
var errReviewsUnavailable = errors.New("quizzes: the review service is not available")
|
||||||
|
|
||||||
|
// reviewsAdmin is the "Do oceny" screen: the open answers of every quiz,
|
||||||
|
// with the grader's result, the owner's score and comment, and the confirm
|
||||||
|
// and regrade actions. Answers come from students, so it never creates or
|
||||||
|
// deletes one; every write goes through the review service shared with the
|
||||||
|
// MCP review tools.
|
||||||
|
type reviewsAdmin struct{}
|
||||||
|
|
||||||
|
func (reviewsAdmin) ID() string { return "golem15.quizzes.reviews" }
|
||||||
|
func (reviewsAdmin) ModelName() string { return "Review" }
|
||||||
|
func (reviewsAdmin) ConfigDir() string { return "controllers/reviews" }
|
||||||
|
|
||||||
|
// NewRecord returns the model the generic admin handlers query.
|
||||||
|
func (reviewsAdmin) NewRecord() any { return &models.Review{} }
|
||||||
|
|
||||||
|
// RequiredPermissions is the quiz editors' permission (D-13): reviewing
|
||||||
|
// needs no permission of its own.
|
||||||
|
func (reviewsAdmin) RequiredPermissions() []string {
|
||||||
|
return []string{"golem15.quizzes.access_quizzes"}
|
||||||
|
}
|
||||||
|
|
||||||
|
// openAnswers keeps the rows of open questions: only they have a grading
|
||||||
|
// status.
|
||||||
|
func openAnswers(db *gorm.DB) *gorm.DB {
|
||||||
|
return db.Where("golem15_quizzes_attempt_answers.grading_status IS NOT NULL")
|
||||||
|
}
|
||||||
|
|
||||||
|
// ListExtendQuery lists open answers only.
|
||||||
|
func (reviewsAdmin) ListExtendQuery(_ context.Context, db *gorm.DB) *gorm.DB { return openAnswers(db) }
|
||||||
|
|
||||||
|
// FormExtendQuery opens open answers only. It preloads nothing: the admin
|
||||||
|
// save writes the loaded record back, and a preloaded question or attempt
|
||||||
|
// would be written with it.
|
||||||
|
func (reviewsAdmin) FormExtendQuery(_ context.Context, db *gorm.DB) *gorm.DB { return openAnswers(db) }
|
||||||
|
|
||||||
|
// FormRecordTitle names an answer by its quiz and student.
|
||||||
|
func (reviewsAdmin) FormRecordTitle(ctx context.Context, _ *gorm.DB, record any) (string, error) {
|
||||||
|
rec, ok := record.(*models.Review)
|
||||||
|
if !ok || rec == nil {
|
||||||
|
return "", nil
|
||||||
|
}
|
||||||
|
svc, err := reviewService(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return "#" + strconv.FormatUint(uint64(rec.ID), 10), nil
|
||||||
|
}
|
||||||
|
item, err := svc.ReviewItem(ctx, rec.ID)
|
||||||
|
if err != nil {
|
||||||
|
return "#" + strconv.FormatUint(uint64(rec.ID), 10), nil
|
||||||
|
}
|
||||||
|
return item.QuizTitle + " · " + item.Email, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// refusedWrite is the answer to a create or a delete: open answers come
|
||||||
|
// from students.
|
||||||
|
func refusedWrite() error {
|
||||||
|
return &cabana.ForbiddenError{Message: reviewsLang + "not_created"}
|
||||||
|
}
|
||||||
|
|
||||||
|
// FormBeforeCreate refuses: open answers come from students.
|
||||||
|
func (reviewsAdmin) FormBeforeCreate(context.Context, any) error { return refusedWrite() }
|
||||||
|
|
||||||
|
// FormBeforeDelete refuses: an answer is removed with its attempt or quiz.
|
||||||
|
func (reviewsAdmin) FormBeforeDelete(context.Context, any) error { return refusedWrite() }
|
||||||
|
|
||||||
|
// FormVirtualFields are the owner's score and comment.
|
||||||
|
func (reviewsAdmin) FormVirtualFields() []string {
|
||||||
|
return []string{fieldReviewPoints, fieldReviewComment}
|
||||||
|
}
|
||||||
|
|
||||||
|
// FormRules check the virtual fields; SetScore checks the points against
|
||||||
|
// the question.
|
||||||
|
func (reviewsAdmin) FormRules(context.Context, string) map[string]string {
|
||||||
|
return map[string]string{
|
||||||
|
fieldReviewPoints: "nullable|numeric|min:0",
|
||||||
|
fieldReviewComment: "nullable|max:" + strconv.Itoa(classes.MaxReviewComment),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// FormAfterUpdate stores the owner's score and comment through SetScore in
|
||||||
|
// the save transaction. An empty form saves nothing.
|
||||||
|
func (reviewsAdmin) FormAfterUpdate(ctx context.Context, model any) error {
|
||||||
|
values, _ := cabana.VirtualFieldsFromContext(ctx)
|
||||||
|
points, comment, err := reviewValues(values)
|
||||||
|
if err != nil || points == nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
rec, ok := model.(*models.Review)
|
||||||
|
if !ok || rec == nil {
|
||||||
|
return errors.New("quizzes: review form model is not a review")
|
||||||
|
}
|
||||||
|
svc, err := reviewService(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
_, err = svc.SetScore(ctx, rec.ID, *points, comment, classes.Reviewer{AdminID: adminID(ctx)})
|
||||||
|
return reviewError(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// reviewValues reads the virtual fields: review_points as a number or a
|
||||||
|
// numeric string (a decimal comma is accepted) and review_comment trimmed.
|
||||||
|
// No points and no comment is nothing to save (nil, nil, nil); a comment
|
||||||
|
// without points, or points that are not a number, is a
|
||||||
|
// *cabana.ValidationError on review_points.
|
||||||
|
func reviewValues(values map[string]any) (*float64, *string, error) {
|
||||||
|
var comment *string
|
||||||
|
if raw, ok := values[fieldReviewComment].(string); ok {
|
||||||
|
if c := strings.TrimSpace(raw); c != "" {
|
||||||
|
comment = &c
|
||||||
|
}
|
||||||
|
}
|
||||||
|
points, ok := numberValue(values[fieldReviewPoints])
|
||||||
|
if !ok {
|
||||||
|
return nil, nil, pointsError("points_invalid")
|
||||||
|
}
|
||||||
|
if points == nil {
|
||||||
|
if comment != nil {
|
||||||
|
return nil, nil, pointsError("points_required")
|
||||||
|
}
|
||||||
|
return nil, nil, nil
|
||||||
|
}
|
||||||
|
return points, comment, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// numberValue reads a submitted number: nil or "" is no value; a value
|
||||||
|
// that is not a finite number is false.
|
||||||
|
func numberValue(v any) (*float64, bool) {
|
||||||
|
var f float64
|
||||||
|
switch n := v.(type) {
|
||||||
|
case nil:
|
||||||
|
return nil, true
|
||||||
|
case float64:
|
||||||
|
f = n
|
||||||
|
case float32:
|
||||||
|
f = float64(n)
|
||||||
|
case int:
|
||||||
|
f = float64(n)
|
||||||
|
case int64:
|
||||||
|
f = float64(n)
|
||||||
|
case uint:
|
||||||
|
f = float64(n)
|
||||||
|
case uint64:
|
||||||
|
f = float64(n)
|
||||||
|
case json.Number:
|
||||||
|
parsed, err := n.Float64()
|
||||||
|
if err != nil {
|
||||||
|
return nil, false
|
||||||
|
}
|
||||||
|
f = parsed
|
||||||
|
case string:
|
||||||
|
s := strings.TrimSpace(n)
|
||||||
|
if s == "" {
|
||||||
|
return nil, true
|
||||||
|
}
|
||||||
|
parsed, err := strconv.ParseFloat(strings.Replace(s, ",", ".", 1), 64)
|
||||||
|
if err != nil {
|
||||||
|
return nil, false
|
||||||
|
}
|
||||||
|
f = parsed
|
||||||
|
default:
|
||||||
|
return nil, false
|
||||||
|
}
|
||||||
|
if math.IsNaN(f) || math.IsInf(f, 0) {
|
||||||
|
return nil, false
|
||||||
|
}
|
||||||
|
return &f, true
|
||||||
|
}
|
||||||
|
|
||||||
|
// pointsError is a validation error on review_points with a reviews lang
|
||||||
|
// key.
|
||||||
|
func pointsError(key string) error {
|
||||||
|
return &cabana.ValidationError{Details: map[string]any{fieldReviewPoints: []string{reviewsLang + key}}}
|
||||||
|
}
|
||||||
|
|
||||||
|
// reviewError maps the review service's refusals to admin answers: a
|
||||||
|
// rule broken by the score becomes a validation error on review_points,
|
||||||
|
// a state conflict a refusal with its message. Anything else passes.
|
||||||
|
func reviewError(err error) error {
|
||||||
|
if err == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
var invalid *classes.ValidationError
|
||||||
|
switch {
|
||||||
|
case errors.As(err, &invalid):
|
||||||
|
return pointsError("points_invalid")
|
||||||
|
case errors.Is(err, classes.ErrNoGraderScore):
|
||||||
|
return &cabana.ForbiddenError{Message: reviewsLang + "no_grader_score"}
|
||||||
|
case errors.Is(err, classes.ErrAlreadyReviewed):
|
||||||
|
return &cabana.ForbiddenError{Message: reviewsLang + "already_reviewed"}
|
||||||
|
case errors.Is(err, classes.ErrGraderManual):
|
||||||
|
return &cabana.ForbiddenError{Message: reviewsLang + "grader_manual"}
|
||||||
|
case errors.Is(err, classes.ErrAttemptOpen):
|
||||||
|
return &cabana.ForbiddenError{Message: reviewsLang + "attempt_open"}
|
||||||
|
case errors.Is(err, classes.ErrNotFound):
|
||||||
|
return &cabana.ForbiddenError{Message: reviewsLang + "not_found"}
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// reviewService is the review service of this request.
|
||||||
|
func reviewService(ctx context.Context) (*classes.Service, error) {
|
||||||
|
if Reviews == nil {
|
||||||
|
return nil, errReviewsUnavailable
|
||||||
|
}
|
||||||
|
svc := Reviews(ctx)
|
||||||
|
if svc == nil || svc.DB == nil {
|
||||||
|
return nil, errReviewsUnavailable
|
||||||
|
}
|
||||||
|
return svc, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// adminID is the signed-in administrator of an admin request.
|
||||||
|
func adminID(ctx context.Context) uint {
|
||||||
|
if p, ok := bouncer.User(ctx); ok && p != nil {
|
||||||
|
return p.ID
|
||||||
|
}
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
|
// reviewer is the administrator as a review's author.
|
||||||
|
func reviewer(ctx context.Context) classes.Reviewer {
|
||||||
|
return classes.Reviewer{AdminID: adminID(ctx)}
|
||||||
|
}
|
||||||
|
|
||||||
|
// AdminRecordActions are confirm (a graded answer's score becomes final)
|
||||||
|
// and regrade (the answer goes back to the quiz's grader).
|
||||||
|
func (reviewsAdmin) AdminRecordActions() []pact.AdminRecordAction {
|
||||||
|
return []pact.AdminRecordAction{
|
||||||
|
{
|
||||||
|
Name: "confirm",
|
||||||
|
Label: reviewsLang + "confirm",
|
||||||
|
Applies: func(_ context.Context, record any) (bool, error) {
|
||||||
|
rec, ok := record.(*models.Review)
|
||||||
|
return ok && rec != nil && rec.ReviewStatus() == models.GradingGraded, nil
|
||||||
|
},
|
||||||
|
Run: func(ctx context.Context, in pact.AdminRecordActionInput) (pact.AdminRecordActionResult, error) {
|
||||||
|
svc, err := reviewService(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return pact.AdminRecordActionResult{}, err
|
||||||
|
}
|
||||||
|
if _, err := svc.Confirm(ctx, uint(in.RecordID), reviewer(ctx)); err != nil {
|
||||||
|
return pact.AdminRecordActionResult{}, reviewError(err)
|
||||||
|
}
|
||||||
|
return pact.AdminRecordActionResult{Message: reviewsLang + "confirmed"}, nil
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Name: "regrade",
|
||||||
|
Label: reviewsLang + "regrade",
|
||||||
|
Confirm: reviewsLang + "regrade_confirm",
|
||||||
|
Applies: func(ctx context.Context, record any) (bool, error) {
|
||||||
|
rec, ok := record.(*models.Review)
|
||||||
|
if !ok || rec == nil {
|
||||||
|
return false, nil
|
||||||
|
}
|
||||||
|
switch rec.ReviewStatus() {
|
||||||
|
case models.GradingPending, models.GradingGraded, models.GradingFailed:
|
||||||
|
default:
|
||||||
|
return false, nil
|
||||||
|
}
|
||||||
|
return canRegrade(ctx, rec)
|
||||||
|
},
|
||||||
|
Run: func(ctx context.Context, in pact.AdminRecordActionInput) (pact.AdminRecordActionResult, error) {
|
||||||
|
svc, err := reviewService(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return pact.AdminRecordActionResult{}, err
|
||||||
|
}
|
||||||
|
if _, err := svc.Regrade(ctx, classes.ReviewScope{AnswerID: uint(in.RecordID)}); err != nil {
|
||||||
|
return pact.AdminRecordActionResult{}, reviewError(err)
|
||||||
|
}
|
||||||
|
return pact.AdminRecordActionResult{Message: reviewsLang + "regraded"}, nil
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// canRegrade reports whether the answer's quiz has a grader an activated
|
||||||
|
// plugin registered (not manual).
|
||||||
|
func canRegrade(ctx context.Context, rec *models.Review) (bool, error) {
|
||||||
|
svc, err := reviewService(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return false, nil
|
||||||
|
}
|
||||||
|
quiz := quizOf(rec)
|
||||||
|
if quiz == nil {
|
||||||
|
var q models.Quiz
|
||||||
|
err := svc.DB.WithContext(ctx).
|
||||||
|
Where("id = (SELECT quiz_id FROM golem15_quizzes_attempts WHERE id = ?)", rec.AttemptID).
|
||||||
|
Take(&q).Error
|
||||||
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||||
|
return false, nil
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return false, err
|
||||||
|
}
|
||||||
|
quiz = &q
|
||||||
|
}
|
||||||
|
_, ok := classes.GraderFor(svc.Graders, quiz)
|
||||||
|
return ok, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// quizOf is the record's quiz when it was loaded with it.
|
||||||
|
func quizOf(rec *models.Review) *models.Quiz {
|
||||||
|
if rec.Attempt != nil && rec.Attempt.Quiz != nil {
|
||||||
|
return rec.Attempt.Quiz
|
||||||
|
}
|
||||||
|
if rec.Question != nil && rec.Question.Quiz != nil {
|
||||||
|
return rec.Question.Quiz
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// AdminBulkActions is confirm: every selected graded answer gets its
|
||||||
|
// grader's score as final; other statuses are skipped.
|
||||||
|
func (reviewsAdmin) AdminBulkActions() []pact.AdminBulkAction {
|
||||||
|
return []pact.AdminBulkAction{{
|
||||||
|
Name: "confirm",
|
||||||
|
Label: reviewsLang + "confirm_selected",
|
||||||
|
Run: func(ctx context.Context, in pact.AdminBulkActionInput) (pact.AdminBulkActionResult, error) {
|
||||||
|
svc, err := reviewService(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return pact.AdminBulkActionResult{}, err
|
||||||
|
}
|
||||||
|
by := reviewer(ctx)
|
||||||
|
affected := 0
|
||||||
|
for _, record := range in.Records {
|
||||||
|
rec, ok := record.(*models.Review)
|
||||||
|
if !ok || rec == nil || rec.ReviewStatus() != models.GradingGraded {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if _, err := svc.Confirm(ctx, rec.ID, by); err != nil {
|
||||||
|
return pact.AdminBulkActionResult{}, reviewError(err)
|
||||||
|
}
|
||||||
|
affected++
|
||||||
|
}
|
||||||
|
return pact.AdminBulkActionResult{Affected: affected}, nil
|
||||||
|
},
|
||||||
|
}}
|
||||||
|
}
|
||||||
|
|
||||||
|
// reviewContextView is the view model of the _review_context partial: plain
|
||||||
|
// strings, numbers and booleans only, so the template's escaping covers
|
||||||
|
// every value (the student's text and the grader's feedback are untrusted).
|
||||||
|
type reviewContextView struct {
|
||||||
|
QuizTitle string
|
||||||
|
StudentEmail string
|
||||||
|
StudentName string
|
||||||
|
QuestionText string
|
||||||
|
QuestionPoints int
|
||||||
|
ModelAnswer string
|
||||||
|
Rubric string
|
||||||
|
MaxLength int
|
||||||
|
Text string
|
||||||
|
Status string
|
||||||
|
StatusLabel string
|
||||||
|
Grader string
|
||||||
|
GraderLabel string
|
||||||
|
HasGraderPoints bool
|
||||||
|
GraderPoints float64
|
||||||
|
GraderFeedback string
|
||||||
|
GradingError string
|
||||||
|
GradingAttempts int
|
||||||
|
GradedAt string
|
||||||
|
Points float64
|
||||||
|
ReviewComment string
|
||||||
|
Reviewed bool
|
||||||
|
ReviewedAt string
|
||||||
|
// TextCut and Cut tell that the student's text, or another long text,
|
||||||
|
// was shortened to fit cabana's partial size cap (see fitEscaped).
|
||||||
|
TextCut bool
|
||||||
|
Cut bool
|
||||||
|
}
|
||||||
|
|
||||||
|
// Escaped-byte budgets of the partial's long texts. cabana refuses a
|
||||||
|
// partial that renders to more than 64 KiB, and html/template turns one
|
||||||
|
// character into up to 5 bytes, so each text is cut to its budget measured
|
||||||
|
// as escaped (fitEscaped). Their sum leaves room for the markup and the
|
||||||
|
// translated labels; a long but ordinary answer (max_length up to 20000)
|
||||||
|
// fits whole, only pathological texts are cut.
|
||||||
|
const (
|
||||||
|
budgetText = 32 << 10
|
||||||
|
budgetQuestionText = 4 << 10
|
||||||
|
budgetModelAnswer = 6 << 10
|
||||||
|
budgetRubric = 6 << 10
|
||||||
|
budgetFeedback = 4 << 10
|
||||||
|
budgetComment = 4 << 10
|
||||||
|
budgetError = 1 << 10
|
||||||
|
budgetShort = 512
|
||||||
|
)
|
||||||
|
|
||||||
|
// fitEscaped cuts s so that it takes at most budget bytes once escaped by
|
||||||
|
// html/template, ending it with "…" when cut, and reports whether it cut.
|
||||||
|
func fitEscaped(s string, budget int) (string, bool) {
|
||||||
|
total := 0
|
||||||
|
for _, r := range s {
|
||||||
|
total += escapedLen(r)
|
||||||
|
}
|
||||||
|
if total <= budget {
|
||||||
|
return s, false
|
||||||
|
}
|
||||||
|
used := 0
|
||||||
|
for i, r := range s {
|
||||||
|
used += escapedLen(r)
|
||||||
|
if used > budget-len("…") {
|
||||||
|
return s[:i] + "…", true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return s, false
|
||||||
|
}
|
||||||
|
|
||||||
|
// escapedLen is the most bytes html/template writes for r in text.
|
||||||
|
func escapedLen(r rune) int {
|
||||||
|
switch r {
|
||||||
|
case '"', '&', '\'', '+', '<', '>':
|
||||||
|
return 5
|
||||||
|
case 0:
|
||||||
|
return len("\uFFFD")
|
||||||
|
}
|
||||||
|
if n := utf8.RuneLen(r); n > 0 {
|
||||||
|
return n
|
||||||
|
}
|
||||||
|
return 3
|
||||||
|
}
|
||||||
|
|
||||||
|
// PartialData builds the review context of an answer from the review
|
||||||
|
// service; an unknown partial is an error.
|
||||||
|
func (reviewsAdmin) PartialData(ctx context.Context, name string, record any) (any, error) {
|
||||||
|
if name != partialReview {
|
||||||
|
return nil, errors.New("quizzes: unknown partial " + name)
|
||||||
|
}
|
||||||
|
rec, ok := record.(*models.Review)
|
||||||
|
if !ok || rec == nil || rec.ID == 0 {
|
||||||
|
return reviewContextView{}, nil
|
||||||
|
}
|
||||||
|
svc, err := reviewService(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
item, err := svc.ReviewItem(ctx, rec.ID)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return newReviewContextView(item, svc.Graders), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// newReviewContextView copies a review detail into the partial's view
|
||||||
|
// model, each long text cut to its escaped-byte budget so the partial
|
||||||
|
// always fits cabana's size cap.
|
||||||
|
func newReviewContextView(item *classes.ReviewDetail, reg *graders.Registry) reviewContextView {
|
||||||
|
v := reviewContextView{
|
||||||
|
QuizTitle: item.QuizTitle,
|
||||||
|
StudentEmail: item.Email,
|
||||||
|
StudentName: strings.TrimSpace(deref(item.Name) + " " + deref(item.Surname)),
|
||||||
|
QuestionText: item.QuestionText,
|
||||||
|
QuestionPoints: item.QuestionPoints,
|
||||||
|
ModelAnswer: deref(item.AnswerText),
|
||||||
|
Rubric: deref(item.Rubric),
|
||||||
|
MaxLength: item.MaxLength,
|
||||||
|
Text: item.Text,
|
||||||
|
Status: item.Status,
|
||||||
|
StatusLabel: reviewsLang + "status_" + item.Status,
|
||||||
|
Grader: deref(item.Grader),
|
||||||
|
GraderFeedback: deref(item.GraderFeedback),
|
||||||
|
GradingError: deref(item.GradingError),
|
||||||
|
GradingAttempts: item.GradingAttempts,
|
||||||
|
GradedAt: formatTime(item.GradedAt),
|
||||||
|
Points: item.Points,
|
||||||
|
ReviewComment: deref(item.ReviewComment),
|
||||||
|
Reviewed: item.Status == models.GradingReviewed,
|
||||||
|
ReviewedAt: formatTime(item.ReviewedAt),
|
||||||
|
}
|
||||||
|
if item.GraderPoints != nil {
|
||||||
|
v.HasGraderPoints, v.GraderPoints = true, *item.GraderPoints
|
||||||
|
}
|
||||||
|
v.GraderLabel = graderLabel(reg, v.Grader)
|
||||||
|
v.Text, v.TextCut = fitEscaped(v.Text, budgetText)
|
||||||
|
for _, f := range []struct {
|
||||||
|
s *string
|
||||||
|
budget int
|
||||||
|
}{
|
||||||
|
{&v.QuizTitle, budgetShort},
|
||||||
|
{&v.StudentEmail, budgetShort},
|
||||||
|
{&v.StudentName, budgetShort},
|
||||||
|
{&v.QuestionText, budgetQuestionText},
|
||||||
|
{&v.ModelAnswer, budgetModelAnswer},
|
||||||
|
{&v.Rubric, budgetRubric},
|
||||||
|
{&v.GraderFeedback, budgetFeedback},
|
||||||
|
{&v.GradingError, budgetError},
|
||||||
|
{&v.ReviewComment, budgetComment},
|
||||||
|
} {
|
||||||
|
var cut bool
|
||||||
|
*f.s, cut = fitEscaped(*f.s, f.budget)
|
||||||
|
v.Cut = v.Cut || cut
|
||||||
|
}
|
||||||
|
return v
|
||||||
|
}
|
||||||
|
|
||||||
|
// graderLabel is the lang key or name of a grader code: Manual's label, a
|
||||||
|
// registered grader's label, else the code itself.
|
||||||
|
func graderLabel(reg *graders.Registry, code string) string {
|
||||||
|
if code == "" {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
if code == graders.Manual {
|
||||||
|
return graders.ManualLabel
|
||||||
|
}
|
||||||
|
if g, ok := reg.Get(code); ok {
|
||||||
|
if label := g.Label(); label != "" {
|
||||||
|
return label
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return code
|
||||||
|
}
|
||||||
|
|
||||||
|
func deref(s *string) string {
|
||||||
|
if s == nil {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
return *s
|
||||||
|
}
|
||||||
|
|
||||||
|
func formatTime(t *time.Time) string {
|
||||||
|
if t == nil {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
return t.Local().Format("2006-01-02 15:04")
|
||||||
|
}
|
||||||
|
|
||||||
|
// ReviewsController returns the golem15.quizzes.reviews admin controller.
|
||||||
|
func ReviewsController() pact.AdminController { return reviewsAdmin{} }
|
||||||
51
controllers/reviews/_review_context.htm
Normal file
51
controllers/reviews/_review_context.htm
Normal file
@@ -0,0 +1,51 @@
|
|||||||
|
<div class="quizzes-review">
|
||||||
|
{{with .Data}}
|
||||||
|
{{if .Cut}}
|
||||||
|
<p class="help-block">{{trans "golem15.quizzes::lang.reviews.cut"}}</p>
|
||||||
|
{{end}}
|
||||||
|
<dl>
|
||||||
|
<dt>{{trans "golem15.quizzes::lang.reviews.quiz"}}</dt>
|
||||||
|
<dd>{{.QuizTitle}}</dd>
|
||||||
|
<dt>{{trans "golem15.quizzes::lang.reviews.student"}}</dt>
|
||||||
|
<dd>{{if .StudentName}}{{.StudentName}} <span class="help-block">{{.StudentEmail}}</span>{{else}}{{.StudentEmail}}{{end}}</dd>
|
||||||
|
<dt>{{trans "golem15.quizzes::lang.reviews.question"}} ({{.QuestionPoints}} {{trans "golem15.quizzes::lang.reviews.points_short"}})</dt>
|
||||||
|
<dd><p class="whitespace-pre-wrap">{{.QuestionText}}</p></dd>
|
||||||
|
{{if .ModelAnswer}}
|
||||||
|
<dt>{{trans "golem15.quizzes::lang.reviews.model_answer"}}</dt>
|
||||||
|
<dd><p class="whitespace-pre-wrap">{{.ModelAnswer}}</p></dd>
|
||||||
|
{{end}}
|
||||||
|
{{if .Rubric}}
|
||||||
|
<dt>{{trans "golem15.quizzes::lang.reviews.rubric"}}</dt>
|
||||||
|
<dd><p class="whitespace-pre-wrap">{{.Rubric}}</p></dd>
|
||||||
|
{{end}}
|
||||||
|
<dt>{{trans "golem15.quizzes::lang.reviews.text"}} <span class="help-block">{{trans "golem15.quizzes::lang.reviews.max_length"}}: {{.MaxLength}}</span></dt>
|
||||||
|
<dd><blockquote class="whitespace-pre-wrap">{{.Text}}</blockquote>{{if .TextCut}}<p class="help-block">{{trans "golem15.quizzes::lang.reviews.text_cut"}}</p>{{end}}</dd>
|
||||||
|
<dt>{{trans "golem15.quizzes::lang.reviews.status"}}</dt>
|
||||||
|
<dd><strong>{{trans .StatusLabel}}</strong></dd>
|
||||||
|
{{if .Grader}}
|
||||||
|
<dt>{{trans "golem15.quizzes::lang.reviews.grader"}}</dt>
|
||||||
|
<dd>{{trans .GraderLabel}} <span class="help-block">{{trans "golem15.quizzes::lang.reviews.grading_attempts"}}: {{.GradingAttempts}}{{if .GradedAt}} · {{trans "golem15.quizzes::lang.reviews.graded_at"}}: {{.GradedAt}}{{end}}</span></dd>
|
||||||
|
{{end}}
|
||||||
|
{{if .HasGraderPoints}}
|
||||||
|
<dt>{{trans "golem15.quizzes::lang.reviews.grader_points"}}</dt>
|
||||||
|
<dd>{{.GraderPoints}}</dd>
|
||||||
|
{{end}}
|
||||||
|
{{if .GraderFeedback}}
|
||||||
|
<dt>{{trans "golem15.quizzes::lang.reviews.grader_feedback"}}</dt>
|
||||||
|
<dd><p class="whitespace-pre-wrap">{{.GraderFeedback}}</p></dd>
|
||||||
|
{{end}}
|
||||||
|
{{if .GradingError}}
|
||||||
|
<dt>{{trans "golem15.quizzes::lang.reviews.grading_error"}}</dt>
|
||||||
|
<dd><p class="whitespace-pre-wrap">{{.GradingError}}</p></dd>
|
||||||
|
{{end}}
|
||||||
|
{{if .Reviewed}}
|
||||||
|
<dt>{{trans "golem15.quizzes::lang.reviews.points"}}</dt>
|
||||||
|
<dd><strong>{{.Points}}</strong> / {{.QuestionPoints}}{{if .ReviewedAt}} <span class="help-block">{{trans "golem15.quizzes::lang.reviews.reviewed_at"}}: {{.ReviewedAt}}</span>{{end}}</dd>
|
||||||
|
{{end}}
|
||||||
|
{{if .ReviewComment}}
|
||||||
|
<dt>{{trans "golem15.quizzes::lang.reviews.review_comment"}}</dt>
|
||||||
|
<dd><p class="whitespace-pre-wrap">{{.ReviewComment}}</p></dd>
|
||||||
|
{{end}}
|
||||||
|
</dl>
|
||||||
|
{{end}}
|
||||||
|
</div>
|
||||||
16
controllers/reviews/config_filter.yaml
Normal file
16
controllers/reviews/config_filter.yaml
Normal file
@@ -0,0 +1,16 @@
|
|||||||
|
scopes:
|
||||||
|
quiz:
|
||||||
|
label: golem15.quizzes::lang.reviews.quiz
|
||||||
|
modelClass: Quiz
|
||||||
|
nameFrom: title
|
||||||
|
scope: filterByQuiz
|
||||||
|
status:
|
||||||
|
label: golem15.quizzes::lang.reviews.status
|
||||||
|
modelClass: Review
|
||||||
|
nameFrom: grading_status
|
||||||
|
scope: filterByStatus
|
||||||
|
student:
|
||||||
|
label: golem15.quizzes::lang.reviews.student
|
||||||
|
modelClass: Review
|
||||||
|
nameFrom: grading_status
|
||||||
|
scope: filterByStudent
|
||||||
15
controllers/reviews/config_form.yaml
Normal file
15
controllers/reviews/config_form.yaml
Normal file
@@ -0,0 +1,15 @@
|
|||||||
|
name: golem15.quizzes::lang.reviews.answer
|
||||||
|
form: ~/plugins/golem15/quizzes/models/reviews/fields.yaml
|
||||||
|
modelClass: Review
|
||||||
|
defaultRedirect: golem15/quizzes/reviews
|
||||||
|
|
||||||
|
# Open answers come from students: there is no create. Saving the form
|
||||||
|
# stores the owner's score and comment, then returns to the preview.
|
||||||
|
update:
|
||||||
|
redirect: golem15/quizzes/reviews/preview/:id
|
||||||
|
redirectClose: golem15/quizzes/reviews
|
||||||
|
|
||||||
|
# The preview screen shows the answer and offers the record actions.
|
||||||
|
preview: {}
|
||||||
|
|
||||||
|
recordActions: [confirm, regrade]
|
||||||
16
controllers/reviews/config_list.yaml
Normal file
16
controllers/reviews/config_list.yaml
Normal file
@@ -0,0 +1,16 @@
|
|||||||
|
list: ~/plugins/golem15/quizzes/models/reviews/columns.yaml
|
||||||
|
modelClass: Review
|
||||||
|
title: golem15.quizzes::lang.reviews.title
|
||||||
|
recordUrl: golem15/quizzes/reviews/preview/:id
|
||||||
|
recordsPerPage: 50
|
||||||
|
perPageOptions: [20, 50, 100]
|
||||||
|
showCheckboxes: true
|
||||||
|
defaultSort:
|
||||||
|
column: updated_at
|
||||||
|
direction: asc
|
||||||
|
filter: config_filter.yaml
|
||||||
|
bulkActions: [confirm]
|
||||||
|
toolbar:
|
||||||
|
buttons: []
|
||||||
|
search:
|
||||||
|
prompt: backend::lang.list.search_prompt
|
||||||
266
controllers/reviews_test.go
Normal file
266
controllers/reviews_test.go
Normal file
@@ -0,0 +1,266 @@
|
|||||||
|
package controllers
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"errors"
|
||||||
|
"html/template"
|
||||||
|
"os"
|
||||||
|
"reflect"
|
||||||
|
"slices"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"git.golem15.com/golem15/sm-quizzes-plugin/classes"
|
||||||
|
"git.golem15.com/golem15/sm-quizzes-plugin/graders"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/cabana"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/pact"
|
||||||
|
)
|
||||||
|
|
||||||
|
func pointsDetail(t *testing.T, err error) string {
|
||||||
|
t.Helper()
|
||||||
|
var invalid *cabana.ValidationError
|
||||||
|
if !errors.As(err, &invalid) {
|
||||||
|
t.Fatalf("err = %v, want a cabana.ValidationError", err)
|
||||||
|
}
|
||||||
|
msgs, _ := invalid.Details[fieldReviewPoints].([]string)
|
||||||
|
if len(msgs) != 1 {
|
||||||
|
t.Fatalf("details = %v, want one message on review_points", invalid.Details)
|
||||||
|
}
|
||||||
|
return msgs[0]
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestReviewValues(t *testing.T) {
|
||||||
|
points, comment, err := reviewValues(map[string]any{"review_points": "1.5", "review_comment": " dobrze "})
|
||||||
|
if err != nil || points == nil || *points != 1.5 || comment == nil || *comment != "dobrze" {
|
||||||
|
t.Errorf("1.5 + comment = %v, %v, %v", points, comment, err)
|
||||||
|
}
|
||||||
|
if points, _, err := reviewValues(map[string]any{"review_points": float64(2)}); err != nil || points == nil || *points != 2 {
|
||||||
|
t.Errorf("number 2 = %v, %v", points, err)
|
||||||
|
}
|
||||||
|
if points, _, err := reviewValues(map[string]any{"review_points": 2}); err != nil || points == nil || *points != 2 {
|
||||||
|
t.Errorf("int 2 = %v, %v", points, err)
|
||||||
|
}
|
||||||
|
if points, _, err := reviewValues(map[string]any{"review_points": "1,5"}); err != nil || points == nil || *points != 1.5 {
|
||||||
|
t.Errorf("decimal comma = %v, %v", points, err)
|
||||||
|
}
|
||||||
|
if points, comment, err := reviewValues(map[string]any{"review_points": 0.0, "review_comment": " "}); err != nil || points == nil || *points != 0 || comment != nil {
|
||||||
|
t.Errorf("zero without comment = %v, %v, %v", points, comment, err)
|
||||||
|
}
|
||||||
|
for _, values := range []map[string]any{nil, {}, {"review_points": "", "review_comment": ""}, {"review_points": nil}} {
|
||||||
|
if points, comment, err := reviewValues(values); points != nil || comment != nil || err != nil {
|
||||||
|
t.Errorf("%v = %v, %v, %v, want nothing to save", values, points, comment, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_, _, err = reviewValues(map[string]any{"review_comment": "bez punktów"})
|
||||||
|
if got := pointsDetail(t, err); got != reviewsLang+"points_required" {
|
||||||
|
t.Errorf("comment without points = %q", got)
|
||||||
|
}
|
||||||
|
for _, bad := range []any{"abc", "NaN", "Inf", true} {
|
||||||
|
_, _, err := reviewValues(map[string]any{"review_points": bad})
|
||||||
|
if got := pointsDetail(t, err); got != reviewsLang+"points_invalid" {
|
||||||
|
t.Errorf("%v = %q", bad, got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestReviewErrorMapping(t *testing.T) {
|
||||||
|
if got := pointsDetail(t, reviewError(&classes.ValidationError{Problems: []string{"points"}})); got != reviewsLang+"points_invalid" {
|
||||||
|
t.Errorf("validation = %q", got)
|
||||||
|
}
|
||||||
|
for err, key := range map[error]string{
|
||||||
|
classes.ErrNoGraderScore: "no_grader_score",
|
||||||
|
classes.ErrAlreadyReviewed: "already_reviewed",
|
||||||
|
classes.ErrGraderManual: "grader_manual",
|
||||||
|
classes.ErrNotFound: "not_found",
|
||||||
|
} {
|
||||||
|
var refused *cabana.ForbiddenError
|
||||||
|
if !errors.As(reviewError(err), &refused) || refused.Message != reviewsLang+key {
|
||||||
|
t.Errorf("%v = %v, want refusal %s", err, reviewError(err), key)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
other := errors.New("db down")
|
||||||
|
if got := reviewError(other); got != other {
|
||||||
|
t.Errorf("other error = %v", got)
|
||||||
|
}
|
||||||
|
if reviewError(nil) != nil {
|
||||||
|
t.Error("nil error mapped")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestGraderDropdown(t *testing.T) {
|
||||||
|
saved := GraderOptions
|
||||||
|
t.Cleanup(func() { GraderOptions = saved })
|
||||||
|
|
||||||
|
GraderOptions = nil
|
||||||
|
want := []pact.Option{{Value: graders.Manual, Label: "golem15.quizzes::lang.graders.manual"}}
|
||||||
|
if got := (quizzesAdmin{}).DropdownOptions("grader"); !slices.Equal(got, want) {
|
||||||
|
t.Errorf("no hook = %v, want %v", got, want)
|
||||||
|
}
|
||||||
|
|
||||||
|
GraderOptions = func() []graders.Option {
|
||||||
|
return []graders.Option{{Code: graders.Manual, Label: graders.ManualLabel}, {Code: "ai", Label: "vendor.plugin::lang.grader"}}
|
||||||
|
}
|
||||||
|
want = []pact.Option{{Value: "manual", Label: graders.ManualLabel}, {Value: "ai", Label: "vendor.plugin::lang.grader"}}
|
||||||
|
if got := (quizzesAdmin{}).DropdownOptions("grader"); !slices.Equal(got, want) {
|
||||||
|
t.Errorf("hook = %v, want %v", got, want)
|
||||||
|
}
|
||||||
|
if got := (quizzesAdmin{}).DropdownOptions("mode"); got != nil {
|
||||||
|
t.Errorf("mode = %v, want nil", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestReviewContextViewIsPlain(t *testing.T) {
|
||||||
|
typ := reflect.TypeOf(reviewContextView{})
|
||||||
|
for i := range typ.NumField() {
|
||||||
|
f := typ.Field(i)
|
||||||
|
switch f.Type.Kind() {
|
||||||
|
case reflect.String, reflect.Bool,
|
||||||
|
reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
|
||||||
|
reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64,
|
||||||
|
reflect.Float32, reflect.Float64:
|
||||||
|
default:
|
||||||
|
t.Errorf("field %s is %s; the view model holds strings, numbers and booleans only", f.Name, f.Type)
|
||||||
|
}
|
||||||
|
if f.Type.PkgPath() != "" {
|
||||||
|
t.Errorf("field %s has the named type %s", f.Name, f.Type)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
name, surname := "Anna", "Nowak"
|
||||||
|
grader, feedback := "ai", "<b>ok</b>"
|
||||||
|
gp := 1.5
|
||||||
|
v := newReviewContextView(&classes.ReviewDetail{
|
||||||
|
ReviewRow: classes.ReviewRow{Status: "graded", QuizTitle: "Q", Email: "a@example.com", Name: &name, Surname: &surname, Text: "<script>x</script>", GraderPoints: &gp},
|
||||||
|
Grader: &grader,
|
||||||
|
GraderFeedback: &feedback,
|
||||||
|
}, nil)
|
||||||
|
if v.StudentName != "Anna Nowak" || v.StatusLabel != reviewsLang+"status_graded" || !v.HasGraderPoints || v.GraderPoints != 1.5 {
|
||||||
|
t.Errorf("view = %+v", v)
|
||||||
|
}
|
||||||
|
if v.GraderLabel != "ai" {
|
||||||
|
t.Errorf("unregistered grader label = %q, want the code", v.GraderLabel)
|
||||||
|
}
|
||||||
|
if v.Text != "<script>x</script>" || v.GraderFeedback != "<b>ok</b>" {
|
||||||
|
t.Errorf("texts are copied raw for the template to escape: %+v", v)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestReviewsControllerShape(t *testing.T) {
|
||||||
|
c := reviewsAdmin{}
|
||||||
|
if c.ID() != "golem15.quizzes.reviews" || c.ConfigDir() != "controllers/reviews" {
|
||||||
|
t.Errorf("controller = %s %s", c.ID(), c.ConfigDir())
|
||||||
|
}
|
||||||
|
if !slices.Equal(c.RequiredPermissions(), []string{"golem15.quizzes.access_quizzes"}) {
|
||||||
|
t.Errorf("permissions = %v", c.RequiredPermissions())
|
||||||
|
}
|
||||||
|
if !slices.Equal(c.FormVirtualFields(), []string{"review_points", "review_comment"}) {
|
||||||
|
t.Errorf("virtual fields = %v", c.FormVirtualFields())
|
||||||
|
}
|
||||||
|
var refused *cabana.ForbiddenError
|
||||||
|
if err := c.FormBeforeCreate(t.Context(), nil); !errors.As(err, &refused) {
|
||||||
|
t.Errorf("create = %v, want a refusal", err)
|
||||||
|
}
|
||||||
|
if err := c.FormBeforeDelete(t.Context(), nil); !errors.As(err, &refused) {
|
||||||
|
t.Errorf("delete = %v, want a refusal", err)
|
||||||
|
}
|
||||||
|
var names []string
|
||||||
|
for _, a := range c.AdminRecordActions() {
|
||||||
|
names = append(names, a.Name)
|
||||||
|
}
|
||||||
|
if !slices.Equal(names, []string{"confirm", "regrade"}) {
|
||||||
|
t.Errorf("record actions = %v", names)
|
||||||
|
}
|
||||||
|
if bulk := c.AdminBulkActions(); len(bulk) != 1 || bulk[0].Name != "confirm" {
|
||||||
|
t.Errorf("bulk actions = %+v", bulk)
|
||||||
|
}
|
||||||
|
if _, err := c.PartialData(t.Context(), "other", nil); err == nil {
|
||||||
|
t.Error("unknown partial gave no error")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestReviewContextEscapes(t *testing.T) {
|
||||||
|
src, err := os.ReadFile("reviews/_review_context.htm")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if strings.Contains(string(src), "safe") || strings.Contains(string(src), "style=") {
|
||||||
|
t.Error("the partial must not mark text as safe or use inline styles")
|
||||||
|
}
|
||||||
|
tpl, err := template.New("review_context").Funcs(template.FuncMap{"trans": func(k string) string { return k }}).Parse(string(src))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("parse: %v", err)
|
||||||
|
}
|
||||||
|
var out bytes.Buffer
|
||||||
|
view := reviewContextView{
|
||||||
|
Text: "<script>alert(1)</script>", GraderFeedback: "<img src=x onerror=alert(1)>",
|
||||||
|
ReviewComment: "<b>c</b>", Rubric: "<i>r</i>", Grader: "ai", GraderLabel: "ai", Reviewed: true,
|
||||||
|
StatusLabel: reviewsLang + "status_reviewed",
|
||||||
|
}
|
||||||
|
if err := tpl.Execute(&out, map[string]any{"Data": view}); err != nil {
|
||||||
|
t.Fatalf("execute: %v", err)
|
||||||
|
}
|
||||||
|
html := out.String()
|
||||||
|
for _, raw := range []string{"<script>", "<img", "<b>c</b>", "<i>r</i>"} {
|
||||||
|
if strings.Contains(html, raw) {
|
||||||
|
t.Errorf("output carries %q unescaped", raw)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !strings.Contains(html, "<script>") {
|
||||||
|
t.Errorf("student text not escaped: %s", html)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestFitEscaped(t *testing.T) {
|
||||||
|
if s, cut := fitEscaped("zażółć", 12); s != "zażółć" || cut {
|
||||||
|
t.Errorf("a text within budget = %q, %v", s, cut)
|
||||||
|
}
|
||||||
|
s, cut := fitEscaped(strings.Repeat(`"`, 10), 23)
|
||||||
|
if !cut || s != `""""`+"…" {
|
||||||
|
t.Errorf("quotes cut = %q, %v; want four quotes and an ellipsis", s, cut)
|
||||||
|
}
|
||||||
|
if s, cut := fitEscaped("abc", 0); !cut || s != "…" {
|
||||||
|
t.Errorf("zero budget = %q, %v", s, cut)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestReviewContextFitsPartialCap renders the partial with every text at
|
||||||
|
// its worst case (characters html/template turns into 5 bytes) and checks
|
||||||
|
// the output stays under cabana's 64 KiB partial cap.
|
||||||
|
func TestReviewContextFitsPartialCap(t *testing.T) {
|
||||||
|
src, err := os.ReadFile("reviews/_review_context.htm")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
// A translation longer than any real label.
|
||||||
|
long := strings.Repeat("ą", 100)
|
||||||
|
tpl, err := template.New("review_context").Funcs(template.FuncMap{"trans": func(string) string { return long }}).Parse(string(src))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("parse: %v", err)
|
||||||
|
}
|
||||||
|
worst := func(n int) *string { s := strings.Repeat(`"&'`, n); return &s }
|
||||||
|
grader := "ai"
|
||||||
|
gp := 1.5
|
||||||
|
v := newReviewContextView(&classes.ReviewDetail{
|
||||||
|
ReviewRow: classes.ReviewRow{
|
||||||
|
Status: "reviewed", QuizTitle: *worst(300), Email: *worst(300), Name: worst(300), Surname: worst(300),
|
||||||
|
QuestionText: *worst(10000), Text: *worst(20000), GraderPoints: &gp,
|
||||||
|
},
|
||||||
|
AnswerText: worst(10000), Rubric: worst(10000), Grader: &grader,
|
||||||
|
GraderFeedback: worst(2000), GradingError: worst(500), ReviewComment: worst(2000),
|
||||||
|
}, nil)
|
||||||
|
if !v.TextCut || !v.Cut {
|
||||||
|
t.Fatalf("worst-case texts not cut: TextCut=%v Cut=%v", v.TextCut, v.Cut)
|
||||||
|
}
|
||||||
|
var out bytes.Buffer
|
||||||
|
if err := tpl.Execute(&out, map[string]any{"Data": v}); err != nil {
|
||||||
|
t.Fatalf("execute: %v", err)
|
||||||
|
}
|
||||||
|
if n := out.Len(); n > 64<<10 {
|
||||||
|
t.Errorf("partial renders to %d bytes, over the 64 KiB cap", n)
|
||||||
|
}
|
||||||
|
|
||||||
|
plain := strings.Repeat("Długa, zwykła odpowiedź studenta. ", 580)
|
||||||
|
if v := newReviewContextView(&classes.ReviewDetail{ReviewRow: classes.ReviewRow{Text: plain}}, nil); v.TextCut || v.Text != plain {
|
||||||
|
t.Error("an ordinary answer near 20000 characters was cut")
|
||||||
|
}
|
||||||
|
}
|
||||||
62
events/events.go
Normal file
62
events/events.go
Normal file
@@ -0,0 +1,62 @@
|
|||||||
|
// Package events holds the plugin events of golem15.quizzes that other
|
||||||
|
// plugins listen to with app.Events.Listen. Every event fires after the
|
||||||
|
// write it announces has committed, so a listener never sees a score that
|
||||||
|
// was rolled back; a listener error is logged and never undoes the write.
|
||||||
|
// The package imports nothing from golem15.quizzes, so a listener can
|
||||||
|
// depend on it alone.
|
||||||
|
package events
|
||||||
|
|
||||||
|
// Event names, for logs and documentation; the bus itself is keyed by type.
|
||||||
|
const (
|
||||||
|
AnswerGradedEventName = "quizzes.AnswerGraded"
|
||||||
|
AnswerReviewedEventName = "quizzes.AnswerReviewed"
|
||||||
|
AttemptReviewedEventName = "quizzes.AttemptReviewed"
|
||||||
|
)
|
||||||
|
|
||||||
|
// AnswerGradedEvent is fired as *AnswerGradedEvent after a grader's score
|
||||||
|
// of an open answer is stored (grading_status graded). The owner has not
|
||||||
|
// confirmed it yet. MaxPoints is the question's points.
|
||||||
|
type AnswerGradedEvent struct {
|
||||||
|
QuizID uint
|
||||||
|
QuestionID uint
|
||||||
|
AttemptID uint
|
||||||
|
AnswerID uint
|
||||||
|
UserID uint
|
||||||
|
Grader string
|
||||||
|
Points float64
|
||||||
|
MaxPoints int
|
||||||
|
Feedback string
|
||||||
|
}
|
||||||
|
|
||||||
|
// AnswerReviewedEvent is fired as *AnswerReviewedEvent after the owner
|
||||||
|
// confirms or sets the score of an open answer (grading_status reviewed).
|
||||||
|
// GraderPoints is the grader's score when there was one; Comment is the
|
||||||
|
// owner's comment to the student. The reviewer is a frontend user
|
||||||
|
// (ReviewerUserID, over MCP) or a backend administrator (ReviewerAdminID).
|
||||||
|
type AnswerReviewedEvent struct {
|
||||||
|
QuizID uint
|
||||||
|
QuestionID uint
|
||||||
|
AttemptID uint
|
||||||
|
AnswerID uint
|
||||||
|
UserID uint
|
||||||
|
Points float64
|
||||||
|
MaxPoints int
|
||||||
|
GraderPoints *float64
|
||||||
|
Comment *string
|
||||||
|
ReviewerUserID *uint
|
||||||
|
ReviewerAdminID *uint
|
||||||
|
}
|
||||||
|
|
||||||
|
// AttemptReviewedEvent is fired as *AttemptReviewedEvent once every open
|
||||||
|
// answer of a completed attempt is reviewed, with the attempt's final
|
||||||
|
// score. MaxPoints is the attempt's stored maximum; Passed compares
|
||||||
|
// ScorePercent with the quiz's passing score.
|
||||||
|
type AttemptReviewedEvent struct {
|
||||||
|
QuizID uint
|
||||||
|
AttemptID uint
|
||||||
|
UserID uint
|
||||||
|
ScorePoints float64
|
||||||
|
MaxPoints int
|
||||||
|
ScorePercent *float64
|
||||||
|
Passed bool
|
||||||
|
}
|
||||||
62
graders/graders.go
Normal file
62
graders/graders.go
Normal file
@@ -0,0 +1,62 @@
|
|||||||
|
// Package graders is the grader registry of golem15.quizzes. A plugin that
|
||||||
|
// grades open answers implements HasGraders, and golem15.quizzes collects
|
||||||
|
// its graders at boot. Manual is built in and is never called: an answer of
|
||||||
|
// a manual quiz waits for the owner. The package imports only the standard
|
||||||
|
// library, so a grading plugin can depend on it without pulling in the rest
|
||||||
|
// of golem15.quizzes.
|
||||||
|
package graders
|
||||||
|
|
||||||
|
import "context"
|
||||||
|
|
||||||
|
// Manual is the built-in grader code: the owner grades every open answer.
|
||||||
|
const Manual = "manual"
|
||||||
|
|
||||||
|
// ManualLabel is the lang key of Manual in the admin grader dropdown.
|
||||||
|
const ManualLabel = "golem15.quizzes::lang.graders.manual"
|
||||||
|
|
||||||
|
// Input is one open answer to grade.
|
||||||
|
type Input struct {
|
||||||
|
QuizID uint
|
||||||
|
QuestionID uint
|
||||||
|
AttemptID uint
|
||||||
|
AnswerID uint
|
||||||
|
UserID uint
|
||||||
|
// Question is the owner-authored question text.
|
||||||
|
Question string
|
||||||
|
// ModelAnswer is the owner-authored model answer; it may be empty.
|
||||||
|
ModelAnswer string
|
||||||
|
// Rubric is the owner-authored grading rubric; it may be empty and is
|
||||||
|
// owner-only: it must never reach the student.
|
||||||
|
Rubric string
|
||||||
|
// Answer is the student's text. It is untrusted input.
|
||||||
|
Answer string
|
||||||
|
// Points is the full value of the question.
|
||||||
|
Points int
|
||||||
|
}
|
||||||
|
|
||||||
|
// Result is a grader's verdict. golem15.quizzes clamps Points to
|
||||||
|
// 0..Input.Points in steps of 0.5 and refuses a value that is not a finite
|
||||||
|
// number.
|
||||||
|
type Result struct {
|
||||||
|
Points float64
|
||||||
|
Feedback string
|
||||||
|
}
|
||||||
|
|
||||||
|
// Grader grades open answers. Grade runs in a background job with no
|
||||||
|
// transaction open, so it may take seconds; an error is retried a few times
|
||||||
|
// and then leaves the answer failed for the owner to grade.
|
||||||
|
type Grader interface {
|
||||||
|
// Code identifies the grader in a quiz's grader field, such as "ai".
|
||||||
|
// It must match ^[a-z][a-z0-9_]{0,63}$ and must not be Manual.
|
||||||
|
Code() string
|
||||||
|
// Label is the lang key or text the admin grader dropdown shows.
|
||||||
|
Label() string
|
||||||
|
// Grade scores one answer.
|
||||||
|
Grade(ctx context.Context, in Input) (Result, error)
|
||||||
|
}
|
||||||
|
|
||||||
|
// HasGraders is implemented by a plugin that provides graders.
|
||||||
|
// golem15.quizzes calls it once at boot.
|
||||||
|
type HasGraders interface {
|
||||||
|
QuizGraders() []Grader
|
||||||
|
}
|
||||||
137
graders/registry.go
Normal file
137
graders/registry.go
Normal file
@@ -0,0 +1,137 @@
|
|||||||
|
package graders
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"regexp"
|
||||||
|
"sync"
|
||||||
|
)
|
||||||
|
|
||||||
|
// ErrDuplicateCode reports two graders published with the same code.
|
||||||
|
var ErrDuplicateCode = errors.New("quizzes: duplicate grader code")
|
||||||
|
|
||||||
|
// ErrReservedCode reports a grader that claims the built-in Manual code.
|
||||||
|
var ErrReservedCode = errors.New("quizzes: grader code manual is built in")
|
||||||
|
|
||||||
|
// codePattern is the shape of a grader code: it is stored in the quiz's
|
||||||
|
// grader column (VARCHAR(64)).
|
||||||
|
var codePattern = regexp.MustCompile(`^[a-z][a-z0-9_]{0,63}$`)
|
||||||
|
|
||||||
|
// ValidCode reports whether code has the shape of a grader code: lowercase
|
||||||
|
// letters, digits and _, starting with a letter, at most 64 characters.
|
||||||
|
// It says nothing about whether a plugin registered it.
|
||||||
|
func ValidCode(code string) bool { return codePattern.MatchString(code) }
|
||||||
|
|
||||||
|
// Option is one choice of the admin grader dropdown.
|
||||||
|
type Option struct {
|
||||||
|
Code string
|
||||||
|
Label string
|
||||||
|
}
|
||||||
|
|
||||||
|
// Registry is the ordered set of graders collected at boot: Manual first,
|
||||||
|
// then every activated plugin's graders in activation order. golem15.quizzes
|
||||||
|
// publishes it on the app as *graders.Registry. Every method is safe on a
|
||||||
|
// nil *Registry, which knows only Manual.
|
||||||
|
type Registry struct {
|
||||||
|
mu sync.RWMutex
|
||||||
|
order []string
|
||||||
|
byCode map[string]entry
|
||||||
|
}
|
||||||
|
|
||||||
|
type entry struct {
|
||||||
|
grader Grader
|
||||||
|
pluginID string
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewRegistry returns a registry that knows only Manual.
|
||||||
|
func NewRegistry() *Registry {
|
||||||
|
return &Registry{byCode: map[string]entry{}}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Add registers g as published by pluginID. A nil grader, an empty or
|
||||||
|
// malformed code, Manual (ErrReservedCode) and a code already registered
|
||||||
|
// (ErrDuplicateCode, naming both plugins) are errors.
|
||||||
|
func (r *Registry) Add(pluginID string, g Grader) error {
|
||||||
|
if r == nil {
|
||||||
|
return fmt.Errorf("quizzes: grader registry is nil")
|
||||||
|
}
|
||||||
|
if g == nil {
|
||||||
|
return fmt.Errorf("quizzes: plugin %s published a nil grader", pluginID)
|
||||||
|
}
|
||||||
|
code := g.Code()
|
||||||
|
switch {
|
||||||
|
case code == "":
|
||||||
|
return fmt.Errorf("quizzes: plugin %s published a grader without a code", pluginID)
|
||||||
|
case code == Manual:
|
||||||
|
return fmt.Errorf("%w: published by %s", ErrReservedCode, pluginID)
|
||||||
|
case !codePattern.MatchString(code):
|
||||||
|
return fmt.Errorf("quizzes: plugin %s published grader code %q; want lowercase letters, digits and _ (at most 64)", pluginID, code)
|
||||||
|
}
|
||||||
|
r.mu.Lock()
|
||||||
|
defer r.mu.Unlock()
|
||||||
|
if r.byCode == nil {
|
||||||
|
r.byCode = map[string]entry{}
|
||||||
|
}
|
||||||
|
if existing, ok := r.byCode[code]; ok {
|
||||||
|
return fmt.Errorf("%w: %q is published by %s and %s", ErrDuplicateCode, code, existing.pluginID, pluginID)
|
||||||
|
}
|
||||||
|
r.byCode[code] = entry{grader: g, pluginID: pluginID}
|
||||||
|
r.order = append(r.order, code)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get returns the grader with code. Manual and unknown codes are false:
|
||||||
|
// there is nothing to call, the owner grades.
|
||||||
|
func (r *Registry) Get(code string) (Grader, bool) {
|
||||||
|
if r == nil || code == Manual {
|
||||||
|
return nil, false
|
||||||
|
}
|
||||||
|
r.mu.RLock()
|
||||||
|
defer r.mu.RUnlock()
|
||||||
|
e, ok := r.byCode[code]
|
||||||
|
if !ok {
|
||||||
|
return nil, false
|
||||||
|
}
|
||||||
|
return e.grader, true
|
||||||
|
}
|
||||||
|
|
||||||
|
// Codes lists Manual and then every registered code in registration order.
|
||||||
|
func (r *Registry) Codes() []string {
|
||||||
|
out := []string{Manual}
|
||||||
|
if r == nil {
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
r.mu.RLock()
|
||||||
|
defer r.mu.RUnlock()
|
||||||
|
return append(out, r.order...)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Options lists the admin dropdown choices: Manual with ManualLabel, then
|
||||||
|
// every registered grader with its Label.
|
||||||
|
func (r *Registry) Options() []Option {
|
||||||
|
out := []Option{{Code: Manual, Label: ManualLabel}}
|
||||||
|
if r == nil {
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
r.mu.RLock()
|
||||||
|
defer r.mu.RUnlock()
|
||||||
|
for _, code := range r.order {
|
||||||
|
out = append(out, Option{Code: code, Label: r.byCode[code].grader.Label()})
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
// PluginID returns the id of the plugin that published code. Manual is
|
||||||
|
// golem15.quizzes' own.
|
||||||
|
func (r *Registry) PluginID(code string) (string, bool) {
|
||||||
|
if code == Manual {
|
||||||
|
return "golem15.quizzes", true
|
||||||
|
}
|
||||||
|
if r == nil {
|
||||||
|
return "", false
|
||||||
|
}
|
||||||
|
r.mu.RLock()
|
||||||
|
defer r.mu.RUnlock()
|
||||||
|
e, ok := r.byCode[code]
|
||||||
|
return e.pluginID, ok
|
||||||
|
}
|
||||||
79
graders/registry_test.go
Normal file
79
graders/registry_test.go
Normal file
@@ -0,0 +1,79 @@
|
|||||||
|
package graders_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"slices"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"git.golem15.com/golem15/sm-quizzes-plugin/graders"
|
||||||
|
)
|
||||||
|
|
||||||
|
type fake struct{ code, label string }
|
||||||
|
|
||||||
|
func (f fake) Code() string { return f.code }
|
||||||
|
func (f fake) Label() string { return f.label }
|
||||||
|
func (f fake) Grade(context.Context, graders.Input) (graders.Result, error) {
|
||||||
|
return graders.Result{}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestGradersRegistry(t *testing.T) {
|
||||||
|
reg := graders.NewRegistry()
|
||||||
|
if got := reg.Codes(); !slices.Equal(got, []string{graders.Manual}) {
|
||||||
|
t.Fatalf("empty Codes = %v, want [manual]", got)
|
||||||
|
}
|
||||||
|
if err := reg.Add("acme.one", fake{"x", "X grader"}); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if got := reg.Codes(); !slices.Equal(got, []string{graders.Manual, "x"}) {
|
||||||
|
t.Errorf("Codes = %v, want [manual x]", got)
|
||||||
|
}
|
||||||
|
if g, ok := reg.Get("x"); !ok || g.Code() != "x" {
|
||||||
|
t.Errorf("Get(x) = %v, %v", g, ok)
|
||||||
|
}
|
||||||
|
for _, code := range []string{graders.Manual, "zzz", ""} {
|
||||||
|
if _, ok := reg.Get(code); ok {
|
||||||
|
t.Errorf("Get(%q) = true, want false", code)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if id, ok := reg.PluginID("x"); !ok || id != "acme.one" {
|
||||||
|
t.Errorf("PluginID(x) = %q, %v", id, ok)
|
||||||
|
}
|
||||||
|
|
||||||
|
err := reg.Add("acme.two", fake{"x", "Other"})
|
||||||
|
if !errors.Is(err, graders.ErrDuplicateCode) || !strings.Contains(err.Error(), "acme.one") || !strings.Contains(err.Error(), "acme.two") {
|
||||||
|
t.Errorf("duplicate Add = %v, want ErrDuplicateCode naming both plugins", err)
|
||||||
|
}
|
||||||
|
if err := reg.Add("acme.two", fake{graders.Manual, "M"}); !errors.Is(err, graders.ErrReservedCode) {
|
||||||
|
t.Errorf("manual Add = %v, want ErrReservedCode", err)
|
||||||
|
}
|
||||||
|
for _, g := range []graders.Grader{nil, fake{"", "E"}, fake{"Bad Code", "B"}, fake{"9lives", "N"}, fake{strings.Repeat("a", 65), "L"}} {
|
||||||
|
if err := reg.Add("acme.two", g); err == nil {
|
||||||
|
t.Errorf("Add(%v) = nil, want an error", g)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if got := reg.Codes(); !slices.Equal(got, []string{graders.Manual, "x"}) {
|
||||||
|
t.Errorf("rejected Adds changed Codes: %v", got)
|
||||||
|
}
|
||||||
|
|
||||||
|
opts := reg.Options()
|
||||||
|
want := []graders.Option{{Code: graders.Manual, Label: graders.ManualLabel}, {Code: "x", Label: "X grader"}}
|
||||||
|
if !slices.Equal(opts, want) {
|
||||||
|
t.Errorf("Options = %v, want %v", opts, want)
|
||||||
|
}
|
||||||
|
|
||||||
|
var none *graders.Registry
|
||||||
|
if got := none.Codes(); !slices.Equal(got, []string{graders.Manual}) {
|
||||||
|
t.Errorf("nil Codes = %v", got)
|
||||||
|
}
|
||||||
|
if _, ok := none.Get("x"); ok {
|
||||||
|
t.Error("nil Get = true")
|
||||||
|
}
|
||||||
|
if got := none.Options(); len(got) != 1 || got[0].Code != graders.Manual {
|
||||||
|
t.Errorf("nil Options = %v", got)
|
||||||
|
}
|
||||||
|
if err := none.Add("acme.one", fake{"y", "Y"}); err == nil {
|
||||||
|
t.Error("nil Add = nil, want an error")
|
||||||
|
}
|
||||||
|
}
|
||||||
65
graders_boot_test.go
Normal file
65
graders_boot_test.go
Normal file
@@ -0,0 +1,65 @@
|
|||||||
|
package quizzes_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"slices"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"git.golem15.com/golem15/sm-quizzes-plugin/graders"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/backpack"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/party"
|
||||||
|
)
|
||||||
|
|
||||||
|
// fixtureGrader is the grader both fixture plugins publish, under the same
|
||||||
|
// code.
|
||||||
|
type fixtureGrader struct{}
|
||||||
|
|
||||||
|
func (fixtureGrader) Code() string { return "fixture" }
|
||||||
|
func (fixtureGrader) Label() string { return "Fixture" }
|
||||||
|
func (fixtureGrader) Grade(context.Context, graders.Input) (graders.Result, error) {
|
||||||
|
return graders.Result{}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// graderPlugin is a test-only plugin that provides fixtureGrader. It is
|
||||||
|
// registered here and activated only by the tests that name it.
|
||||||
|
type graderPlugin struct{ id string }
|
||||||
|
|
||||||
|
func (p *graderPlugin) ID() string { return p.id }
|
||||||
|
func (p *graderPlugin) Requires() []string { return []string{"golem15.quizzes"} }
|
||||||
|
func (p *graderPlugin) Register(*backpack.App) error { return nil }
|
||||||
|
func (p *graderPlugin) Boot(*backpack.App) error { return nil }
|
||||||
|
func (p *graderPlugin) QuizGraders() []graders.Grader { return []graders.Grader{fixtureGrader{}} }
|
||||||
|
|
||||||
|
func init() {
|
||||||
|
party.Register(&graderPlugin{id: "acme.gradersone"})
|
||||||
|
party.Register(&graderPlugin{id: "acme.graderstwo"})
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestGradersCollectedAtBoot(t *testing.T) {
|
||||||
|
app := backpack.New(testConfig(t))
|
||||||
|
if _, err := party.Activate(app, []string{"golem15.user", "golem15.quizzes", "acme.gradersone"}); err != nil {
|
||||||
|
t.Fatalf("Activate: %v", err)
|
||||||
|
}
|
||||||
|
reg, ok := app.Lookup[*graders.Registry]()
|
||||||
|
if !ok || reg == nil {
|
||||||
|
t.Fatal("no *graders.Registry published")
|
||||||
|
}
|
||||||
|
if got := reg.Codes(); !slices.Equal(got, []string{graders.Manual, "fixture"}) {
|
||||||
|
t.Errorf("Codes = %v, want [manual fixture]", got)
|
||||||
|
}
|
||||||
|
if id, _ := reg.PluginID("fixture"); id != "acme.gradersone" {
|
||||||
|
t.Errorf("PluginID(fixture) = %q", id)
|
||||||
|
}
|
||||||
|
|
||||||
|
plain, _ := activate(t, nil, nil)
|
||||||
|
if reg, ok := plain.Lookup[*graders.Registry](); !ok || !slices.Equal(reg.Codes(), []string{graders.Manual}) {
|
||||||
|
t.Errorf("without grading plugins the registry should hold manual only")
|
||||||
|
}
|
||||||
|
|
||||||
|
dup := backpack.New(testConfig(t))
|
||||||
|
_, err := party.Activate(dup, []string{"golem15.user", "golem15.quizzes", "acme.gradersone", "acme.graderstwo"})
|
||||||
|
if !errors.Is(err, graders.ErrDuplicateCode) {
|
||||||
|
t.Errorf("Activate with two fixture plugins = %v, want ErrDuplicateCode", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
19
jobs/grade_answer.go
Normal file
19
jobs/grade_answer.go
Normal file
@@ -0,0 +1,19 @@
|
|||||||
|
package jobs
|
||||||
|
|
||||||
|
// Queue is the River queue of the grading jobs, so an app can cap how many
|
||||||
|
// answers are graded at once (config/queue.yaml).
|
||||||
|
const Queue = "quizzes_grading"
|
||||||
|
|
||||||
|
// Kind is the River kind of GradeAnswerArgs.
|
||||||
|
const Kind = "golem15.quizzes.grade_answer"
|
||||||
|
|
||||||
|
// GradeAnswerArgs asks the quiz's grader to score one open answer. Seq is
|
||||||
|
// the answer's grading_seq when the job was enqueued: a job whose Seq no
|
||||||
|
// longer matches, or whose answer is no longer pending, does nothing.
|
||||||
|
type GradeAnswerArgs struct {
|
||||||
|
AnswerID uint `json:"answer_id"`
|
||||||
|
Seq int `json:"seq"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Kind implements pact.JobArgs.
|
||||||
|
func (GradeAnswerArgs) Kind() string { return Kind }
|
||||||
@@ -12,6 +12,13 @@ api:
|
|||||||
single_one_answer: Choose exactly one answer for this question.
|
single_one_answer: Choose exactly one answer for this question.
|
||||||
known_required: The known field is required for this question.
|
known_required: The known field is required for this question.
|
||||||
unknown_category: The quiz has no questions in this category.
|
unknown_category: The quiz has no questions in this category.
|
||||||
|
attempt_limit_reached: All attempts at this test have been used.
|
||||||
|
answer_locked: An answer in this test cannot be changed.
|
||||||
|
category_not_allowed: A test covers the whole quiz; a category cannot be chosen.
|
||||||
|
text_required: Write an answer to this question.
|
||||||
|
text_too_long: The answer is longer than this question allows.
|
||||||
|
graders:
|
||||||
|
manual: Manual (the owner grades)
|
||||||
permissions:
|
permissions:
|
||||||
access_quizzes: Manage quizzes, questions and answers
|
access_quizzes: Manage quizzes, questions and answers
|
||||||
access_attempts: View quiz attempts
|
access_attempts: View quiz attempts
|
||||||
@@ -34,6 +41,18 @@ quizzes:
|
|||||||
round_size: Round size
|
round_size: Round size
|
||||||
round_size_comment: Clients may present the questions in rounds of this many.
|
round_size_comment: Clients may present the questions in rounds of this many.
|
||||||
shuffle_questions: Shuffle questions
|
shuffle_questions: Shuffle questions
|
||||||
|
mode: Mode
|
||||||
|
mode_learning: Learning
|
||||||
|
mode_test: Test
|
||||||
|
mode_comment: A test hides the correct answers and explanations until the attempt is finished.
|
||||||
|
navigation: Test navigation
|
||||||
|
navigation_free: Free (go back and change answers)
|
||||||
|
navigation_one_way: One way (an answer is final)
|
||||||
|
navigation_comment: Applies to tests only.
|
||||||
|
max_attempts: Attempt limit
|
||||||
|
max_attempts_comment: Tests only. Leave empty for no limit.
|
||||||
|
grader: Grading of open questions
|
||||||
|
grader_comment: "Manual: you grade every answer yourself. Installed plugins add other options."
|
||||||
questions:
|
questions:
|
||||||
title: Questions
|
title: Questions
|
||||||
question: Question
|
question: Question
|
||||||
@@ -42,11 +61,16 @@ questions:
|
|||||||
type: Type
|
type: Type
|
||||||
type_single: Single choice
|
type_single: Single choice
|
||||||
type_multiple: Multiple choice
|
type_multiple: Multiple choice
|
||||||
|
type_open: Open question
|
||||||
type_self_check: Self-check (flashcard)
|
type_self_check: Self-check (flashcard)
|
||||||
category: Category
|
category: Category
|
||||||
points: Points
|
points: Points
|
||||||
answer_text: Model answer
|
answer_text: Model answer
|
||||||
answer_text_comment: Revealed for self-check questions.
|
answer_text_comment: Revealed for self-check questions. For an open question it is the model answer.
|
||||||
|
rubric: Grading criteria (for the grader only)
|
||||||
|
rubric_comment: Only the grader sees it, never the student. Applies to open questions.
|
||||||
|
max_length: Max. answer length
|
||||||
|
max_length_comment: Characters; empty means 2000. Applies to open questions.
|
||||||
explanation: Explanation
|
explanation: Explanation
|
||||||
answers:
|
answers:
|
||||||
title: Answers
|
title: Answers
|
||||||
@@ -64,3 +88,48 @@ attempts:
|
|||||||
score_points: Points
|
score_points: Points
|
||||||
max_points: Max points
|
max_points: Max points
|
||||||
score_percent: Score (%)
|
score_percent: Score (%)
|
||||||
|
reviews:
|
||||||
|
title: To review
|
||||||
|
answer: Open answer
|
||||||
|
context: Answer
|
||||||
|
quiz: Quiz
|
||||||
|
question: Question
|
||||||
|
student: Student
|
||||||
|
text: Student's answer
|
||||||
|
max_length: Character limit
|
||||||
|
status: Status
|
||||||
|
status_pending: waiting for a grade
|
||||||
|
status_graded: to be verified
|
||||||
|
status_failed: grading failed
|
||||||
|
status_reviewed: verified
|
||||||
|
grader: Grader
|
||||||
|
grader_points: Grader's points
|
||||||
|
grader_feedback: Grader's feedback
|
||||||
|
grading_error: Grading error
|
||||||
|
grading_attempts: Grading attempts
|
||||||
|
points: Points
|
||||||
|
points_short: pts
|
||||||
|
graded_at: Graded
|
||||||
|
reviewed_at: Verified
|
||||||
|
model_answer: Model answer
|
||||||
|
rubric: Grading criteria
|
||||||
|
review_points: Points (final)
|
||||||
|
review_points_comment: From 0 to the question's points, in steps of 0.5.
|
||||||
|
review_comment: Comment to the student
|
||||||
|
review_comment_comment: The student sees it with their answer. Saving points replaces an earlier comment.
|
||||||
|
confirm: Confirm the grade
|
||||||
|
confirm_selected: Confirm selected
|
||||||
|
confirmed: Grade confirmed.
|
||||||
|
regrade: Grade again
|
||||||
|
regrade_confirm: The answer goes back to grading and loses the grader's current result.
|
||||||
|
regraded: The answer was sent to be graded again.
|
||||||
|
points_required: Enter the points to save a grade.
|
||||||
|
points_invalid: Points must be from 0 to the question's points, in steps of 0.5.
|
||||||
|
no_grader_score: This answer has no grader's score yet; enter the points yourself.
|
||||||
|
already_reviewed: This answer is already verified.
|
||||||
|
grader_manual: This quiz is graded manually; nothing can grade the answer again.
|
||||||
|
attempt_open: The test is still in progress; review this answer once it ends.
|
||||||
|
text_cut: The answer is too long to show here in full; the quizzes_review_show tool shows all of it.
|
||||||
|
cut: Some long texts are shortened on this screen; the quizzes_review_show tool shows them in full.
|
||||||
|
not_found: This answer was not found.
|
||||||
|
not_created: Open answers come from students; they cannot be added or deleted here.
|
||||||
|
|||||||
@@ -12,6 +12,13 @@ api:
|
|||||||
single_one_answer: Wybierz dokładnie jedną odpowiedź.
|
single_one_answer: Wybierz dokładnie jedną odpowiedź.
|
||||||
known_required: Zaznacz, czy znasz odpowiedź.
|
known_required: Zaznacz, czy znasz odpowiedź.
|
||||||
unknown_category: Quiz nie ma pytań w tej kategorii.
|
unknown_category: Quiz nie ma pytań w tej kategorii.
|
||||||
|
attempt_limit_reached: Wykorzystano już wszystkie podejścia do tego testu.
|
||||||
|
answer_locked: W tym teście nie można zmienić udzielonej odpowiedzi.
|
||||||
|
category_not_allowed: Test obejmuje cały quiz; nie można wybrać kategorii.
|
||||||
|
text_required: Wpisz odpowiedź na to pytanie.
|
||||||
|
text_too_long: Odpowiedź jest dłuższa, niż pozwala to pytanie.
|
||||||
|
graders:
|
||||||
|
manual: Ręcznie (ocenia właściciel)
|
||||||
permissions:
|
permissions:
|
||||||
access_quizzes: Zarządzanie quizami, pytaniami i odpowiedziami
|
access_quizzes: Zarządzanie quizami, pytaniami i odpowiedziami
|
||||||
access_attempts: Podgląd podejść do quizów
|
access_attempts: Podgląd podejść do quizów
|
||||||
@@ -34,6 +41,18 @@ quizzes:
|
|||||||
round_size: Wielkość rundy
|
round_size: Wielkość rundy
|
||||||
round_size_comment: Klient może pokazywać pytania w rundach po tyle pytań.
|
round_size_comment: Klient może pokazywać pytania w rundach po tyle pytań.
|
||||||
shuffle_questions: Losowa kolejność pytań
|
shuffle_questions: Losowa kolejność pytań
|
||||||
|
mode: Tryb
|
||||||
|
mode_learning: Nauka
|
||||||
|
mode_test: Test
|
||||||
|
mode_comment: Test ukrywa poprawne odpowiedzi i wyjaśnienia do zakończenia podejścia.
|
||||||
|
navigation: Nawigacja w teście
|
||||||
|
navigation_free: Swobodna (można wracać i zmieniać odpowiedzi)
|
||||||
|
navigation_one_way: Jednokierunkowa (odpowiedź jest ostateczna)
|
||||||
|
navigation_comment: Dotyczy tylko testów.
|
||||||
|
max_attempts: Limit podejść
|
||||||
|
max_attempts_comment: Tylko dla testów. Zostaw puste, aby nie ograniczać.
|
||||||
|
grader: Ocenianie pytań otwartych
|
||||||
|
grader_comment: "Ręcznie: każdą odpowiedź oceniasz sam. Inne opcje dodają zainstalowane wtyczki."
|
||||||
questions:
|
questions:
|
||||||
title: Pytania
|
title: Pytania
|
||||||
question: Pytanie
|
question: Pytanie
|
||||||
@@ -43,10 +62,15 @@ questions:
|
|||||||
type_single: Jednokrotny wybór
|
type_single: Jednokrotny wybór
|
||||||
type_multiple: Wielokrotny wybór
|
type_multiple: Wielokrotny wybór
|
||||||
type_self_check: Fiszka (samoocena)
|
type_self_check: Fiszka (samoocena)
|
||||||
|
type_open: Pytanie otwarte
|
||||||
category: Kategoria
|
category: Kategoria
|
||||||
points: Punkty
|
points: Punkty
|
||||||
answer_text: Wzorcowa odpowiedź
|
answer_text: Wzorcowa odpowiedź
|
||||||
answer_text_comment: Pokazywana w fiszkach po odsłonięciu.
|
answer_text_comment: Pokazywana w fiszkach po odsłonięciu. W pytaniu otwartym to odpowiedź wzorcowa.
|
||||||
|
rubric: Kryteria oceny (tylko dla oceniającego)
|
||||||
|
rubric_comment: Widzi je tylko oceniający, nigdy student. Dotyczy pytań otwartych.
|
||||||
|
max_length: Maks. długość odpowiedzi
|
||||||
|
max_length_comment: Liczba znaków; puste oznacza 2000. Dotyczy pytań otwartych.
|
||||||
explanation: Wyjaśnienie
|
explanation: Wyjaśnienie
|
||||||
answers:
|
answers:
|
||||||
title: Odpowiedzi
|
title: Odpowiedzi
|
||||||
@@ -64,3 +88,48 @@ attempts:
|
|||||||
score_points: Punkty
|
score_points: Punkty
|
||||||
max_points: Maks. punktów
|
max_points: Maks. punktów
|
||||||
score_percent: Wynik (%)
|
score_percent: Wynik (%)
|
||||||
|
reviews:
|
||||||
|
title: Do oceny
|
||||||
|
answer: Odpowiedź otwarta
|
||||||
|
context: Odpowiedź
|
||||||
|
quiz: Quiz
|
||||||
|
question: Pytanie
|
||||||
|
student: Student
|
||||||
|
text: Odpowiedź studenta
|
||||||
|
max_length: Limit znaków
|
||||||
|
status: Status
|
||||||
|
status_pending: czeka na ocenę
|
||||||
|
status_graded: do weryfikacji
|
||||||
|
status_failed: błąd oceniania
|
||||||
|
status_reviewed: zweryfikowano
|
||||||
|
grader: Oceniający
|
||||||
|
grader_points: Punkty oceniającego
|
||||||
|
grader_feedback: Uwagi oceniającego
|
||||||
|
grading_error: Błąd oceniania
|
||||||
|
grading_attempts: Próby oceny
|
||||||
|
points: Punkty
|
||||||
|
points_short: pkt
|
||||||
|
graded_at: Oceniono
|
||||||
|
reviewed_at: Zweryfikowano
|
||||||
|
model_answer: Odpowiedź wzorcowa
|
||||||
|
rubric: Kryteria oceny
|
||||||
|
review_points: Punkty (ostateczne)
|
||||||
|
review_points_comment: Od 0 do liczby punktów pytania, co 0,5.
|
||||||
|
review_comment: Komentarz dla studenta
|
||||||
|
review_comment_comment: Student zobaczy go przy swojej odpowiedzi. Zapisanie punktów zastępuje wcześniejszy komentarz.
|
||||||
|
confirm: Zatwierdź ocenę
|
||||||
|
confirm_selected: Zatwierdź zaznaczone
|
||||||
|
confirmed: Ocena zatwierdzona.
|
||||||
|
regrade: Oceń ponownie
|
||||||
|
regrade_confirm: Odpowiedź wróci do oceniania i straci obecny wynik oceniającego.
|
||||||
|
regraded: Odpowiedź wysłana do ponownej oceny.
|
||||||
|
points_required: Podaj punkty, aby zapisać ocenę.
|
||||||
|
points_invalid: Punkty muszą mieścić się w zakresie od 0 do liczby punktów pytania, co 0,5.
|
||||||
|
no_grader_score: Ta odpowiedź nie ma jeszcze wyniku oceniającego; wpisz punkty sam.
|
||||||
|
already_reviewed: Ta odpowiedź jest już zweryfikowana.
|
||||||
|
grader_manual: Ten quiz jest oceniany ręcznie; nie ma kto ocenić odpowiedzi ponownie.
|
||||||
|
attempt_open: Test wciąż trwa; oceń tę odpowiedź po jego zakończeniu.
|
||||||
|
text_cut: Odpowiedź jest zbyt długa, by pokazać ją tu w całości; całą pokazuje narzędzie quizzes_review_show.
|
||||||
|
cut: Część długich tekstów jest tu skrócona; w całości pokazuje je narzędzie quizzes_review_show.
|
||||||
|
not_found: Nie znaleziono tej odpowiedzi.
|
||||||
|
not_created: Odpowiedzi otwarte pochodzą od studentów; tutaj nie można ich dodawać ani usuwać.
|
||||||
|
|||||||
284
manage_api_postgres_test.go
Normal file
284
manage_api_postgres_test.go
Normal file
@@ -0,0 +1,284 @@
|
|||||||
|
package quizzes_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"net/http"
|
||||||
|
"os"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"git.golem15.com/golem15/sm-quizzes-plugin/models"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/surf"
|
||||||
|
)
|
||||||
|
|
||||||
|
// TestManageAPIAgainstDatabase covers the owner manage routes the MCP quiz
|
||||||
|
// tools bind (D-13..D-16): access, quiz CRUD, publish, show with
|
||||||
|
// solutions, stats with the lazy close of expired test attempts, delete
|
||||||
|
// with confirm and the import route. Skipped under -short.
|
||||||
|
func TestManageAPIAgainstDatabase(t *testing.T) {
|
||||||
|
app, plugins, gdb := migrated(t)
|
||||||
|
h, err := surf.Assemble(app, plugins)
|
||||||
|
must(t, err)
|
||||||
|
c := &client{t: t, h: h}
|
||||||
|
const prefix = "/api/v1/quizzes"
|
||||||
|
|
||||||
|
editor, _ := newUser(t, gdb, "ala@example.com")
|
||||||
|
stranger, _ := newUser(t, gdb, "ola@example.com")
|
||||||
|
var groupID uint
|
||||||
|
must(t, gdb.Raw(`INSERT INTO user_groups (name, code, permissions, created_at, updated_at)
|
||||||
|
VALUES ('Editors', 'editors', '{"golem15.quizzes.access_quizzes":1}', NOW(), NOW()) RETURNING id`).Scan(&groupID).Error)
|
||||||
|
must(t, gdb.Exec(`INSERT INTO users_groups (user_id, user_group_id) VALUES (?, ?)`, editor.ID, groupID).Error)
|
||||||
|
token := apiToken(t, gdb, editor.ID, "read", "write")
|
||||||
|
readOnly := apiToken(t, gdb, editor.ID, "read")
|
||||||
|
|
||||||
|
t.Run("access", func(t *testing.T) {
|
||||||
|
for name, tc := range map[string]struct {
|
||||||
|
method, path, token string
|
||||||
|
want int
|
||||||
|
}{
|
||||||
|
"no token": {"GET", prefix, "", http.StatusUnauthorized},
|
||||||
|
"read token on a write": {"POST", prefix, readOnly, http.StatusForbidden},
|
||||||
|
"user without permission": {"GET", prefix, apiToken(t, gdb, stranger.ID, "read", "write"), http.StatusForbidden},
|
||||||
|
} {
|
||||||
|
if code, _ := c.do(tc.method, tc.path, tc.token, `{"title":"X"}`); code != tc.want {
|
||||||
|
t.Errorf("%s: %s %s = %d, want %d", name, tc.method, tc.path, code, tc.want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if code, _ := c.do("GET", prefix, readOnly, ""); code != http.StatusOK {
|
||||||
|
t.Errorf("read token on a read = %d, want 200", code)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("create, update, publish and list", func(t *testing.T) {
|
||||||
|
out := data(c.ok(http.StatusCreated, "POST", prefix, token, `{"title":"Pojęcia bezpieczeństwa","context":"BM2","mode":"test","max_attempts":2}`))
|
||||||
|
if out["slug"] != "pojecia-bezpieczenstwa" || out["is_published"] != false || out["mode"] != "test" || out["max_attempts"] != float64(2) || out["passing_score"] != float64(50) {
|
||||||
|
t.Fatalf("created = %v", out)
|
||||||
|
}
|
||||||
|
if code, _ := c.do("POST", prefix, token, `{"title":"Inny","slug":"pojecia-bezpieczenstwa"}`); code != http.StatusConflict {
|
||||||
|
t.Errorf("taken slug = %d, want 409", code)
|
||||||
|
}
|
||||||
|
out = data(c.ok(http.StatusOK, "PATCH", prefix+"/pojecia-bezpieczenstwa", token, `{"max_attempts":0,"description":"Opis"}`))
|
||||||
|
if out["max_attempts"] != nil || out["description"] != "Opis" || out["mode"] != "test" {
|
||||||
|
t.Errorf("update clearing max_attempts = %v", out)
|
||||||
|
}
|
||||||
|
out = data(c.ok(http.StatusOK, "PATCH", prefix+"/pojecia-bezpieczenstwa", token, `{"description":""}`))
|
||||||
|
if out["description"] != nil {
|
||||||
|
t.Errorf("empty description = %v, want null", out["description"])
|
||||||
|
}
|
||||||
|
if code, _ := c.do("PATCH", prefix+"/pojecia-bezpieczenstwa", token, `{"is_published":true}`); code != http.StatusUnprocessableEntity {
|
||||||
|
t.Errorf("update with is_published = %d, want 422", code)
|
||||||
|
}
|
||||||
|
for range 2 {
|
||||||
|
if out := data(c.ok(http.StatusOK, "POST", prefix+"/pojecia-bezpieczenstwa/publish", token, "")); out["is_published"] != true {
|
||||||
|
t.Errorf("publish = %v", out)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
data(c.ok(http.StatusOK, "POST", prefix+"/pojecia-bezpieczenstwa/unpublish", token, ""))
|
||||||
|
c.ok(http.StatusCreated, "POST", prefix, token, `{"title":"Drugi"}`)
|
||||||
|
rows := list(c.ok(http.StatusOK, "GET", prefix, token, ""))
|
||||||
|
if len(rows) != 2 || rows[0].(map[string]any)["context"] != "BM2" || rows[0].(map[string]any)["is_published"] != false {
|
||||||
|
t.Errorf("list = %v, want two unpublished quizzes, BM2 first", rows)
|
||||||
|
}
|
||||||
|
if rows := list(c.ok(http.StatusOK, "GET", prefix+"?context=BM2", token, "")); len(rows) != 1 {
|
||||||
|
t.Errorf("context filter = %v", rows)
|
||||||
|
}
|
||||||
|
if code, _ := c.do("GET", prefix+"/nie-ma", token, ""); code != http.StatusNotFound {
|
||||||
|
t.Errorf("missing quiz = %d, want 404", code)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
f := seedQuiz(t, gdb, "statystyka", func(q *models.Quiz) { q.PassingScore = 60 })
|
||||||
|
|
||||||
|
t.Run("show includes the solutions", func(t *testing.T) {
|
||||||
|
out := data(c.ok(http.StatusOK, "GET", prefix+"/statystyka", token, ""))
|
||||||
|
qs, _ := out["questions"].([]any)
|
||||||
|
if len(qs) != 3 || out["question_count"] != float64(3) {
|
||||||
|
t.Fatalf("show = %v", out)
|
||||||
|
}
|
||||||
|
first := qs[0].(map[string]any)
|
||||||
|
if first["explanation"] != "Warszawa od 1596." {
|
||||||
|
t.Errorf("question explanation = %v", first["explanation"])
|
||||||
|
}
|
||||||
|
answers := first["answers"].([]any)
|
||||||
|
if answers[0].(map[string]any)["is_correct"] != true || answers[1].(map[string]any)["explanation"] != "Dawna stolica." {
|
||||||
|
t.Errorf("answers = %v", answers)
|
||||||
|
}
|
||||||
|
if qs[2].(map[string]any)["answer_text"] != "Zdolność społeczeństwa do..." {
|
||||||
|
t.Errorf("self_check answer_text = %v", qs[2])
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("stats", func(t *testing.T) {
|
||||||
|
finish := func(email string, answers ...string) {
|
||||||
|
t.Helper()
|
||||||
|
_, jwt := newUser(t, gdb, email)
|
||||||
|
att := data(c.ok(http.StatusCreated, "POST", apiPrefix+"/quizzes/statystyka/attempts", jwt, ""))
|
||||||
|
path := fmt.Sprintf("%s/attempts/%d", apiPrefix, int(att["id"].(float64)))
|
||||||
|
for _, body := range answers {
|
||||||
|
c.ok(http.StatusOK, "POST", path+"/answers", jwt, body)
|
||||||
|
}
|
||||||
|
c.ok(http.StatusOK, "POST", path+"/finish", jwt, "")
|
||||||
|
}
|
||||||
|
right := fmt.Sprintf(`{"question_id":%d,"answer_ids":[%d]}`, f.single.ID, f.singleRight.ID)
|
||||||
|
wrong := fmt.Sprintf(`{"question_id":%d,"answer_ids":[%d]}`, f.single.ID, f.singleNo.ID)
|
||||||
|
multiWrong := fmt.Sprintf(`{"question_id":%d,"answer_ids":[%d,%d]}`, f.multi.ID, f.multiA.ID, f.multiC.ID)
|
||||||
|
known := fmt.Sprintf(`{"question_id":%d,"known":true}`, f.selfQ.ID)
|
||||||
|
finish("s1@example.com", right, multiWrong, known)
|
||||||
|
finish("s2@example.com", wrong)
|
||||||
|
finish("s3@example.com", right)
|
||||||
|
|
||||||
|
out := data(c.ok(http.StatusOK, "GET", prefix+"/statystyka/stats", token, ""))
|
||||||
|
students := out["students"].([]any)
|
||||||
|
if len(students) != 3 {
|
||||||
|
t.Fatalf("students = %v", students)
|
||||||
|
}
|
||||||
|
for _, s := range students {
|
||||||
|
s := s.(map[string]any)
|
||||||
|
if s["attempts"] != float64(1) || s["best_score_percent"] == nil || s["last_completed_at"] == nil {
|
||||||
|
t.Errorf("student row = %v", s)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
qs := out["questions"].([]any)
|
||||||
|
single := qs[0].(map[string]any)
|
||||||
|
if single["answered"] != float64(3) || single["correct"] != float64(2) || single["correct_percent"] != 66.7 {
|
||||||
|
t.Errorf("single question = %v", single)
|
||||||
|
}
|
||||||
|
if w, _ := single["most_chosen_wrong"].(map[string]any); w == nil || w["answer_id"] != float64(f.singleNo.ID) || w["count"] != float64(1) {
|
||||||
|
t.Errorf("single most_chosen_wrong = %v", single["most_chosen_wrong"])
|
||||||
|
}
|
||||||
|
if w, _ := qs[1].(map[string]any)["most_chosen_wrong"].(map[string]any); w == nil || w["answer_id"] != float64(f.multiC.ID) {
|
||||||
|
t.Errorf("multiple most_chosen_wrong = %v", qs[1])
|
||||||
|
}
|
||||||
|
if self := qs[2].(map[string]any); self["most_chosen_wrong"] != nil || self["correct"] != float64(1) {
|
||||||
|
t.Errorf("self_check stats = %v", self)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("stats closes an expired test attempt", func(t *testing.T) {
|
||||||
|
tq := seedQuiz(t, gdb, "test-wygasly", func(q *models.Quiz) { q.Mode = models.ModeTest; q.TimeLimitSeconds = intPtr(60) })
|
||||||
|
student, _ := newUser(t, gdb, "late@example.com")
|
||||||
|
started := time.Now().UTC().Add(-10 * time.Minute).Truncate(time.Second)
|
||||||
|
attempt := models.Attempt{QuizID: tq.quiz.ID, UserID: student.ID, StartedAt: started, MaxPoints: 4}
|
||||||
|
must(t, gdb.Create(&attempt).Error)
|
||||||
|
out := data(c.ok(http.StatusOK, "GET", prefix+"/test-wygasly/stats", token, ""))
|
||||||
|
var closed models.Attempt
|
||||||
|
must(t, gdb.Take(&closed, attempt.ID).Error)
|
||||||
|
if closed.CompletedAt == nil || !closed.CompletedAt.Equal(started.Add(time.Minute)) {
|
||||||
|
t.Errorf("expired attempt completed_at = %v, want the deadline %v", closed.CompletedAt, started.Add(time.Minute))
|
||||||
|
}
|
||||||
|
if students := out["students"].([]any); len(students) != 1 || students[0].(map[string]any)["passed"] != false {
|
||||||
|
t.Errorf("students after lazy close = %v", students)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("delete", func(t *testing.T) {
|
||||||
|
code, body := c.do("DELETE", prefix+"/statystyka?confirm=inny", token, "")
|
||||||
|
if code != http.StatusUnprocessableEntity || !strings.Contains(fmt.Sprint(body["message"]), "confirm") {
|
||||||
|
t.Errorf("wrong confirm = %d %v", code, body)
|
||||||
|
}
|
||||||
|
out := data(c.ok(http.StatusOK, "DELETE", prefix+"/statystyka?confirm=statystyka", token, ""))
|
||||||
|
if out["slug"] != "statystyka" || out["questions"] != float64(3) || out["attempts"] != float64(3) {
|
||||||
|
t.Errorf("delete = %v", out)
|
||||||
|
}
|
||||||
|
var n int64
|
||||||
|
must(t, gdb.Model(&models.Attempt{}).Where("quiz_id = ?", f.quiz.ID).Count(&n).Error)
|
||||||
|
if n != 0 {
|
||||||
|
t.Errorf("attempts after delete = %d", n)
|
||||||
|
}
|
||||||
|
if code, _ := c.do("GET", prefix+"/statystyka", token, ""); code != http.StatusNotFound {
|
||||||
|
t.Errorf("deleted quiz = %d, want 404", code)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("questions", func(t *testing.T) {
|
||||||
|
const qp = prefix + "/pytania/questions"
|
||||||
|
c.ok(http.StatusCreated, "POST", prefix, token, `{"title":"Pytania"}`)
|
||||||
|
single := data(c.ok(http.StatusCreated, "POST", qp, token,
|
||||||
|
`{"text":"Stolica?","type":"single","points":2,"answers":[{"text":"Warszawa","is_correct":true},{"text":"Kraków"},{"text":"Gdańsk"}]}`))
|
||||||
|
card := data(c.ok(http.StatusCreated, "POST", qp, token, `{"text":"Odporność?","type":"self_check","answer_text":"Zdolność"}`))
|
||||||
|
if single["sort_order"] != float64(1) || card["sort_order"] != float64(2) || len(single["answers"].([]any)) != 3 {
|
||||||
|
t.Fatalf("created questions = %v %v", single, card)
|
||||||
|
}
|
||||||
|
if code, _ := c.do("POST", qp, token, `{"text":"Zła","type":"single","answers":[{"text":"a"},{"text":"b"}]}`); code != http.StatusUnprocessableEntity {
|
||||||
|
t.Errorf("single without a correct answer = %d, want 422", code)
|
||||||
|
}
|
||||||
|
singleID := uint(single["id"].(float64))
|
||||||
|
cardID := uint(card["id"].(float64))
|
||||||
|
ans := single["answers"].([]any)
|
||||||
|
warszawa := uint(ans[0].(map[string]any)["id"].(float64))
|
||||||
|
krakow := uint(ans[1].(map[string]any)["id"].(float64))
|
||||||
|
gdansk := uint(ans[2].(map[string]any)["id"].(float64))
|
||||||
|
|
||||||
|
// A student finishes an attempt with the right answer.
|
||||||
|
c.ok(http.StatusOK, "POST", prefix+"/pytania/publish", token, "")
|
||||||
|
_, jwt := newUser(t, gdb, "student@example.com")
|
||||||
|
att := data(c.ok(http.StatusCreated, "POST", apiPrefix+"/quizzes/pytania/attempts", jwt, ""))
|
||||||
|
attPath := fmt.Sprintf("%s/attempts/%d", apiPrefix, int(att["id"].(float64)))
|
||||||
|
c.ok(http.StatusOK, "POST", attPath+"/answers", jwt, fmt.Sprintf(`{"question_id":%d,"answer_ids":[%d]}`, singleID, warszawa))
|
||||||
|
c.ok(http.StatusOK, "POST", attPath+"/answers", jwt, fmt.Sprintf(`{"question_id":%d,"known":true}`, cardID))
|
||||||
|
c.ok(http.StatusOK, "POST", attPath+"/finish", jwt, "")
|
||||||
|
var before models.Attempt
|
||||||
|
must(t, gdb.Take(&before, int(att["id"].(float64))).Error)
|
||||||
|
|
||||||
|
// Kraków becomes the correct answer: Warszawa is kept (same id),
|
||||||
|
// Gdańsk is deleted, Poznań is created.
|
||||||
|
body := fmt.Sprintf(`{"text":"Stolica Małopolski?","answers":[{"id":%d,"text":"Kraków","is_correct":true},{"id":%d,"text":"Warszawa"},{"text":"Poznań"}]}`, krakow, warszawa)
|
||||||
|
upd := data(c.ok(http.StatusOK, "PATCH", fmt.Sprintf("%s/%d", qp, singleID), token, body))
|
||||||
|
got := upd["answers"].([]any)
|
||||||
|
if len(got) != 3 || got[0].(map[string]any)["id"] != float64(krakow) || got[1].(map[string]any)["id"] != float64(warszawa) || got[2].(map[string]any)["id"] == float64(gdansk) {
|
||||||
|
t.Errorf("updated answers = %v", got)
|
||||||
|
}
|
||||||
|
var n int64
|
||||||
|
must(t, gdb.Model(&models.Answer{}).Where("id = ?", gdansk).Count(&n).Error)
|
||||||
|
if n != 0 {
|
||||||
|
t.Errorf("Gdańsk was not deleted")
|
||||||
|
}
|
||||||
|
var after models.Attempt
|
||||||
|
must(t, gdb.Take(&after, before.ID).Error)
|
||||||
|
if after.ScorePoints != before.ScorePoints || *after.ScorePercent != *before.ScorePercent {
|
||||||
|
t.Errorf("attempt score changed by an edit: %v -> %v", before.ScorePoints, after.ScorePoints)
|
||||||
|
}
|
||||||
|
foreign := fmt.Sprintf(`{"answers":[{"id":%d,"text":"x","is_correct":true},{"text":"y"}]}`, gdansk)
|
||||||
|
if code, _ := c.do("PATCH", fmt.Sprintf("%s/%d", qp, singleID), token, foreign); code != http.StatusUnprocessableEntity {
|
||||||
|
t.Errorf("foreign answer id = %d, want 422", code)
|
||||||
|
}
|
||||||
|
if code, _ := c.do("PATCH", fmt.Sprintf("%s/%d", qp, 999999), token, `{"text":"x"}`); code != http.StatusNotFound {
|
||||||
|
t.Errorf("missing question = %d, want 404", code)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Reorder refuses a partial list and sets the order.
|
||||||
|
if code, _ := c.do("PUT", qp+"/order", token, fmt.Sprintf(`{"question_ids":[%d]}`, cardID)); code != http.StatusUnprocessableEntity {
|
||||||
|
t.Errorf("partial reorder = %d, want 422", code)
|
||||||
|
}
|
||||||
|
out := data(c.ok(http.StatusOK, "PUT", qp+"/order", token, fmt.Sprintf(`{"question_ids":[%d,%d]}`, cardID, singleID)))
|
||||||
|
qs := out["questions"].([]any)
|
||||||
|
if qs[0].(map[string]any)["id"] != float64(cardID) || qs[0].(map[string]any)["sort_order"] != float64(1) {
|
||||||
|
t.Errorf("reordered = %v", qs)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Deleting a question removes the attempt answers given to it; the
|
||||||
|
// attempt keeps its score.
|
||||||
|
del := data(c.ok(http.StatusOK, "DELETE", fmt.Sprintf("%s/%d", qp, cardID), token, ""))
|
||||||
|
if del["quiz_slug"] != "pytania" {
|
||||||
|
t.Errorf("delete question = %v", del)
|
||||||
|
}
|
||||||
|
must(t, gdb.Model(&models.AttemptAnswer{}).Where("question_id = ?", cardID).Count(&n).Error)
|
||||||
|
if n != 0 {
|
||||||
|
t.Errorf("attempt answers of the deleted question = %d", n)
|
||||||
|
}
|
||||||
|
must(t, gdb.Take(&after, before.ID).Error)
|
||||||
|
if after.ScorePoints != before.ScorePoints {
|
||||||
|
t.Errorf("attempt score changed by a delete: %v -> %v", before.ScorePoints, after.ScorePoints)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("import still works", func(t *testing.T) {
|
||||||
|
raw, err := os.ReadFile("testdata/quiz.json")
|
||||||
|
must(t, err)
|
||||||
|
c.ok(http.StatusOK, "POST", prefix+"/import", token, string(raw))
|
||||||
|
if out := data(c.ok(http.StatusOK, "POST", prefix+"/import?replace=true", token, string(raw))); out["created"] != false {
|
||||||
|
t.Errorf("import with replace=true = %v", out)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
15
mcp.go
Normal file
15
mcp.go
Normal file
@@ -0,0 +1,15 @@
|
|||||||
|
package quizzes
|
||||||
|
|
||||||
|
import "git.golem15.com/golem15/summercms/modules/pact"
|
||||||
|
|
||||||
|
var _ pact.HasMCP = (*Plugin)(nil)
|
||||||
|
|
||||||
|
// MCP declares the owner's quiz tools (exposed as quizzes_*) and the
|
||||||
|
// review tools of the open-answer queue (quizzes_review_*). Every tool
|
||||||
|
// lists the golem15.quizzes.access_quizzes permission, so a user whose
|
||||||
|
// groups lack it never lists them, and every route the tools bind checks
|
||||||
|
// it again (D-13). The plugin still requires only golem15.user and names
|
||||||
|
// no OAuth server.
|
||||||
|
func (p *Plugin) MCP() pact.MCP {
|
||||||
|
return pact.MCP{Tools: append(quizTools(), reviewTools()...)}
|
||||||
|
}
|
||||||
298
mcp_quizzes.go
Normal file
298
mcp_quizzes.go
Normal file
@@ -0,0 +1,298 @@
|
|||||||
|
package quizzes
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
|
||||||
|
"git.golem15.com/golem15/summercms/modules/pact"
|
||||||
|
)
|
||||||
|
|
||||||
|
// The sentences every quiz tool description ends with (D-13).
|
||||||
|
const (
|
||||||
|
needsRead = " Needs scope read and the golem15.quizzes.access_quizzes permission."
|
||||||
|
needsWrite = " Needs scope write and the golem15.quizzes.access_quizzes permission."
|
||||||
|
)
|
||||||
|
|
||||||
|
// quizPermissions filters the listing: only users whose groups grant the
|
||||||
|
// quizzes permission see the quiz tools.
|
||||||
|
var quizPermissions = []string{permQuizzes}
|
||||||
|
|
||||||
|
// yes is the true the tool annotations point at.
|
||||||
|
var yes = true
|
||||||
|
|
||||||
|
// listQuizzesInput is the input of quizzes_list_quizzes.
|
||||||
|
type listQuizzesInput struct {
|
||||||
|
Context string `json:"context,omitempty" query:"context" jsonschema:"only quizzes whose context label equals this value exactly; leave out for every quiz"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// showQuizInput is the input of quizzes_show_quiz.
|
||||||
|
type showQuizInput struct {
|
||||||
|
Slug string `json:"slug" path:"slug" jsonschema:"the quiz slug (lowercase letters, digits and hyphens), as listed by quizzes_list_quizzes"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// The quiz fields a create or an update may send.
|
||||||
|
type createQuizInput struct {
|
||||||
|
Title string `json:"title" jsonschema:"the quiz title, 1-255 characters"`
|
||||||
|
Slug string `json:"slug,omitempty" jsonschema:"the slug (lowercase letters, digits and hyphens; normalised); default: made from the title; 409 when taken"`
|
||||||
|
Description *string `json:"description,omitempty" jsonschema:"a description shown above the quiz"`
|
||||||
|
Context *string `json:"context,omitempty" jsonschema:"a free context label (at most 255 characters) the student app groups quizzes by, such as a course code"`
|
||||||
|
Mode *string `json:"mode,omitempty" jsonschema:"learning (default: solutions after each answer) or test (solutions only after finishing)"`
|
||||||
|
Navigation *string `json:"navigation,omitempty" jsonschema:"for a test: free (default; answers can change) or one_way (an answer is final)"`
|
||||||
|
MaxAttempts *int `json:"max_attempts,omitempty" jsonschema:"for a test: attempts per student, at least 1; leave out for unlimited"`
|
||||||
|
TimeLimitSeconds *int `json:"time_limit_seconds,omitempty" jsonschema:"time limit of an attempt in seconds, at least 1; leave out for none"`
|
||||||
|
PassingScore *int `json:"passing_score,omitempty" jsonschema:"percent needed to pass, 0-100; default 50"`
|
||||||
|
ShuffleQuestions *bool `json:"shuffle_questions,omitempty" jsonschema:"true to shuffle the question order"`
|
||||||
|
RoundSize *int `json:"round_size,omitempty" jsonschema:"for learning: questions per round, at least 1; leave out for all"`
|
||||||
|
Grader *string `json:"grader,omitempty" jsonschema:"how open answers are graded: manual (default; the owner grades) or a grader code an installed plugin registers; an unknown code is refused with the valid list"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// updateQuizInput is the input of quizzes_update_quiz: only sent fields
|
||||||
|
// change.
|
||||||
|
type updateQuizInput struct {
|
||||||
|
Slug string `json:"slug" path:"slug" jsonschema:"the quiz slug, as listed by quizzes_list_quizzes; it cannot be changed"`
|
||||||
|
Title *string `json:"title,omitempty" jsonschema:"the new title, 1-255 characters"`
|
||||||
|
Description *string `json:"description,omitempty" jsonschema:"the new description; an empty string clears it"`
|
||||||
|
Context *string `json:"context,omitempty" jsonschema:"the new context label (at most 255 characters); an empty string clears it"`
|
||||||
|
Mode *string `json:"mode,omitempty" jsonschema:"learning or test"`
|
||||||
|
Navigation *string `json:"navigation,omitempty" jsonschema:"free or one_way (tests only)"`
|
||||||
|
MaxAttempts *int `json:"max_attempts,omitempty" jsonschema:"attempts per student in a test; 0 clears it (unlimited)"`
|
||||||
|
TimeLimitSeconds *int `json:"time_limit_seconds,omitempty" jsonschema:"time limit in seconds; 0 clears it (none)"`
|
||||||
|
PassingScore *int `json:"passing_score,omitempty" jsonschema:"percent needed to pass, 0-100"`
|
||||||
|
ShuffleQuestions *bool `json:"shuffle_questions,omitempty" jsonschema:"true to shuffle the question order"`
|
||||||
|
RoundSize *int `json:"round_size,omitempty" jsonschema:"questions per learning round; 0 clears it (all)"`
|
||||||
|
Grader *string `json:"grader,omitempty" jsonschema:"how open answers are graded: manual (default; the owner grades) or a grader code an installed plugin registers; an unknown code is refused with the valid list"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// deleteQuizInput is the input of quizzes_delete_quiz.
|
||||||
|
type deleteQuizInput struct {
|
||||||
|
Slug string `json:"slug" path:"slug" jsonschema:"the quiz slug"`
|
||||||
|
Confirm string `json:"confirm" query:"confirm" jsonschema:"must repeat the slug exactly, or the delete is refused"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// publishInput is the input of quizzes_publish and quizzes_unpublish.
|
||||||
|
type publishInput struct {
|
||||||
|
Slug string `json:"slug" path:"slug" jsonschema:"the quiz slug"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// statsInput is the input of quizzes_quiz_stats.
|
||||||
|
type statsInput struct {
|
||||||
|
Slug string `json:"slug" path:"slug" jsonschema:"the quiz slug"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// importQuizInput is the input of quizzes_import_quiz: the quizzes:import
|
||||||
|
// document. The keys match classes.ImportQuiz exactly, because the
|
||||||
|
// importer refuses unknown keys.
|
||||||
|
type importQuizInput struct {
|
||||||
|
Replace bool `json:"replace,omitempty" query:"replace" jsonschema:"true to replace an existing quiz with this slug (its fields, and all its questions are deleted and recreated); without it a taken slug is a 409"`
|
||||||
|
Title string `json:"title" jsonschema:"the quiz title"`
|
||||||
|
Slug string `json:"slug,omitempty" jsonschema:"the slug; default: made from the title"`
|
||||||
|
Description *string `json:"description,omitempty" jsonschema:"a description"`
|
||||||
|
Context *string `json:"context,omitempty" jsonschema:"a free context label, such as a course code"`
|
||||||
|
IsPublished *bool `json:"is_published,omitempty" jsonschema:"true to publish the quiz at once"`
|
||||||
|
Mode *string `json:"mode,omitempty" jsonschema:"learning or test"`
|
||||||
|
Navigation *string `json:"navigation,omitempty" jsonschema:"free or one_way (tests only)"`
|
||||||
|
MaxAttempts *int `json:"max_attempts,omitempty" jsonschema:"attempts per student in a test, at least 1"`
|
||||||
|
TimeLimitSeconds *int `json:"time_limit_seconds,omitempty" jsonschema:"time limit in seconds, at least 1"`
|
||||||
|
PassingScore *int `json:"passing_score,omitempty" jsonschema:"percent needed to pass, 0-100; default 50"`
|
||||||
|
ShuffleQuestions *bool `json:"shuffle_questions,omitempty" jsonschema:"true to shuffle the question order"`
|
||||||
|
RoundSize *int `json:"round_size,omitempty" jsonschema:"questions per learning round, at least 1"`
|
||||||
|
Grader *string `json:"grader,omitempty" jsonschema:"how open answers are graded: manual (default) or a grader code; a code no installed plugin registers grades as manual"`
|
||||||
|
Questions []importQuestionInput `json:"questions" jsonschema:"the questions in order; at least one"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// importQuestionInput is one question of an import document.
|
||||||
|
type importQuestionInput struct {
|
||||||
|
Text string `json:"text" jsonschema:"the question"`
|
||||||
|
Type string `json:"type" jsonschema:"single (exactly one correct answer), multiple (one or more correct), self_check (a flashcard with answer_text and no answers) or open (a free-text answer graded later; no answers, answer_text is the model answer)"`
|
||||||
|
Category *string `json:"category,omitempty" jsonschema:"a category for learning rounds"`
|
||||||
|
AnswerText *string `json:"answer_text,omitempty" jsonschema:"the answer a self_check card reveals, or an open question's model answer"`
|
||||||
|
Explanation *string `json:"explanation,omitempty" jsonschema:"shown with the solution"`
|
||||||
|
Points *int `json:"points,omitempty" jsonschema:"points, zero or more; default 1"`
|
||||||
|
Rubric *string `json:"rubric,omitempty" jsonschema:"open questions: owner-only grading notes for the grader, never shown to students"`
|
||||||
|
MaxLength *int `json:"max_length,omitempty" jsonschema:"open questions: the longest answer in characters, 1-20000; default 2000"`
|
||||||
|
Answers []importAnswerInput `json:"answers,omitempty" jsonschema:"the choices of a single or multiple question, at least two"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// importAnswerInput is one answer of an import question.
|
||||||
|
type importAnswerInput struct {
|
||||||
|
Text string `json:"text" jsonschema:"the answer text"`
|
||||||
|
IsCorrect bool `json:"is_correct,omitempty" jsonschema:"true for a correct answer"`
|
||||||
|
Explanation *string `json:"explanation,omitempty" jsonschema:"shown with the solution"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// answerInput is one answer of quizzes_update_question's answers list.
|
||||||
|
type answerInput struct {
|
||||||
|
ID *uint `json:"id,omitempty" jsonschema:"the id of an existing answer to keep; leave out to create one"`
|
||||||
|
Text string `json:"text" jsonschema:"the answer text"`
|
||||||
|
IsCorrect bool `json:"is_correct,omitempty" jsonschema:"true for a correct answer"`
|
||||||
|
Explanation *string `json:"explanation,omitempty" jsonschema:"shown with the solution; left out keeps a kept answer's explanation, an empty string clears it"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// createQuestionInput is the input of quizzes_create_question.
|
||||||
|
type createQuestionInput struct {
|
||||||
|
Slug string `json:"slug" path:"slug" jsonschema:"the quiz slug"`
|
||||||
|
Text string `json:"text" jsonschema:"the question"`
|
||||||
|
Type string `json:"type" jsonschema:"single (exactly one correct answer), multiple (one or more correct), self_check (a flashcard with answer_text and no answers) or open (a free-text answer graded later; no answers, answer_text is the model answer)"`
|
||||||
|
Category *string `json:"category,omitempty" jsonschema:"a category for learning rounds"`
|
||||||
|
AnswerText *string `json:"answer_text,omitempty" jsonschema:"the answer a self_check card reveals, or an open question's model answer"`
|
||||||
|
Explanation *string `json:"explanation,omitempty" jsonschema:"shown with the solution"`
|
||||||
|
Points *int `json:"points,omitempty" jsonschema:"points, zero or more; default 1"`
|
||||||
|
SortOrder *int `json:"sort_order,omitempty" jsonschema:"position, at least 1; default: after the last question"`
|
||||||
|
Rubric *string `json:"rubric,omitempty" jsonschema:"open questions: owner-only grading notes for the grader, never shown to students"`
|
||||||
|
MaxLength *int `json:"max_length,omitempty" jsonschema:"open questions: the longest answer in characters, 1-20000; default 2000"`
|
||||||
|
Answers []importAnswerInput `json:"answers,omitempty" jsonschema:"the choices of a single or multiple question in order, at least two"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// updateQuestionInput is the input of quizzes_update_question.
|
||||||
|
type updateQuestionInput struct {
|
||||||
|
Slug string `json:"slug" path:"slug" jsonschema:"the quiz slug"`
|
||||||
|
ID uint `json:"id" path:"id" jsonschema:"the question id, as listed by quizzes_show_quiz"`
|
||||||
|
Text *string `json:"text,omitempty" jsonschema:"the new question text"`
|
||||||
|
Type *string `json:"type,omitempty" jsonschema:"single, multiple, self_check or open"`
|
||||||
|
Category *string `json:"category,omitempty" jsonschema:"the new category; an empty string clears it"`
|
||||||
|
AnswerText *string `json:"answer_text,omitempty" jsonschema:"the new self_check answer or open model answer; an empty string clears it"`
|
||||||
|
Explanation *string `json:"explanation,omitempty" jsonschema:"the new explanation; an empty string clears it"`
|
||||||
|
Points *int `json:"points,omitempty" jsonschema:"points, zero or more"`
|
||||||
|
SortOrder *int `json:"sort_order,omitempty" jsonschema:"position, at least 1"`
|
||||||
|
Rubric *string `json:"rubric,omitempty" jsonschema:"open questions: the new owner-only grading notes, never shown to students; an empty string clears them"`
|
||||||
|
MaxLength *int `json:"max_length,omitempty" jsonschema:"open questions: the longest answer in characters, 1-20000; 0 clears it (default 2000)"`
|
||||||
|
Answers *[]answerInput `json:"answers,omitempty" jsonschema:"the full new answer list in order: answers with an id are kept and updated, answers without an id are created, answers missing from the list are deleted; leave out to keep the answers"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// deleteQuestionInput is the input of quizzes_delete_question.
|
||||||
|
type deleteQuestionInput struct {
|
||||||
|
Slug string `json:"slug" path:"slug" jsonschema:"the quiz slug"`
|
||||||
|
ID uint `json:"id" path:"id" jsonschema:"the question id"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// reorderInput is the input of quizzes_reorder_questions.
|
||||||
|
type reorderInput struct {
|
||||||
|
Slug string `json:"slug" path:"slug" jsonschema:"the quiz slug"`
|
||||||
|
QuestionIDs []uint `json:"question_ids" jsonschema:"every question id of the quiz exactly once, in the new order"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func quizTools() []pact.MCPTool {
|
||||||
|
return []pact.MCPTool{
|
||||||
|
{
|
||||||
|
Name: "list_quizzes",
|
||||||
|
Title: "List quizzes",
|
||||||
|
Description: "Lists every quiz, published or not, ordered by context (quizzes without one last) and title: id, slug, title, description, context, mode (learning or test), navigation (free or one_way), max_attempts, time_limit_seconds, passing_score, shuffle_questions, round_size, grader (how open answers are graded), is_published, question_count, attempts_count (completed attempts of all students), created_at and updated_at. context filters by the exact context label." + needsRead,
|
||||||
|
Method: http.MethodGet,
|
||||||
|
Path: ManagePrefix,
|
||||||
|
Input: listQuizzesInput{},
|
||||||
|
Permissions: quizPermissions,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Name: "show_quiz",
|
||||||
|
Title: "Show a quiz with its solutions",
|
||||||
|
Description: "Returns one quiz with the fields of quizzes_list_quizzes and its questions in order: id, text, type (single, multiple, self_check or open), category, answer_text (an open question's model answer), explanation, points, sort_order, rubric and max_length (open questions; null otherwise) and answers [{id, text, is_correct, explanation, sort_order}]. This is the owner view: it includes the solutions (is_correct, explanations and answer_text), which students only see after answering or finishing, and the rubric, which students never see." + needsRead,
|
||||||
|
Method: http.MethodGet,
|
||||||
|
Path: ManagePrefix + "/{slug}",
|
||||||
|
Input: showQuizInput{},
|
||||||
|
Permissions: quizPermissions,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Name: "create_quiz",
|
||||||
|
Title: "Create a quiz",
|
||||||
|
Description: "Creates a quiz without questions and returns it with the fields of quizzes_list_quizzes. title is required; slug defaults to one made from the title, and a taken slug is refused with 409. Optional: description, context, mode (learning or test), navigation (free or one_way), max_attempts, time_limit_seconds, passing_score (default 50), shuffle_questions, round_size, grader (manual by default, or a code an installed grader plugin registers; an unknown code is refused with the valid list). The quiz starts unpublished; add questions with quizzes_create_question, then use quizzes_publish. To create a quiz with all its questions in one call use quizzes_import_quiz." + needsWrite,
|
||||||
|
Method: http.MethodPost,
|
||||||
|
Path: ManagePrefix,
|
||||||
|
Input: createQuizInput{},
|
||||||
|
Permissions: quizPermissions,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Name: "update_quiz",
|
||||||
|
Title: "Change quiz fields",
|
||||||
|
Description: "Changes only the quiz fields you send: title, description, context, mode, navigation, max_attempts, time_limit_seconds, passing_score, shuffle_questions, round_size, grader (refused unless manual or registered). 0 clears time_limit_seconds, max_attempts and round_size; an empty string clears description and context. It cannot publish or unpublish (use quizzes_publish / quizzes_unpublish) and cannot change the slug. Returns the quiz with the fields of quizzes_list_quizzes. Finished attempts keep their scores." + needsWrite,
|
||||||
|
Method: http.MethodPatch,
|
||||||
|
Path: ManagePrefix + "/{slug}",
|
||||||
|
Input: updateQuizInput{},
|
||||||
|
Permissions: quizPermissions,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Name: "delete_quiz",
|
||||||
|
Title: "Delete a quiz",
|
||||||
|
Description: "Deletes a quiz for good, with every question, answer and student attempt. Refused unless confirm repeats the slug. Returns id, slug, title and the number of questions and attempts removed. To hide a quiz without deleting it use quizzes_unpublish." + needsWrite,
|
||||||
|
Method: http.MethodDelete,
|
||||||
|
Path: ManagePrefix + "/{slug}",
|
||||||
|
Input: deleteQuizInput{},
|
||||||
|
Permissions: quizPermissions,
|
||||||
|
Destructive: &yes,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Name: "publish",
|
||||||
|
Title: "Publish a quiz",
|
||||||
|
Description: "Publishes the quiz so students see it in their quiz list; publishing a published quiz changes nothing. Returns the quiz with the fields of quizzes_list_quizzes." + needsWrite,
|
||||||
|
Method: http.MethodPost,
|
||||||
|
Path: ManagePrefix + "/{slug}/publish",
|
||||||
|
Input: publishInput{},
|
||||||
|
Permissions: quizPermissions,
|
||||||
|
Idempotent: &yes,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Name: "unpublish",
|
||||||
|
Title: "Unpublish a quiz",
|
||||||
|
Description: "Hides the quiz from students; their finished attempts and scores stay. Unpublishing an unpublished quiz changes nothing. Returns the quiz with the fields of quizzes_list_quizzes." + needsWrite,
|
||||||
|
Method: http.MethodPost,
|
||||||
|
Path: ManagePrefix + "/{slug}/unpublish",
|
||||||
|
Input: publishInput{},
|
||||||
|
Permissions: quizPermissions,
|
||||||
|
Idempotent: &yes,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Name: "import_quiz",
|
||||||
|
Title: "Import a whole quiz",
|
||||||
|
Description: "Creates a quiz with all its questions and answers from one quizzes:import document: title, slug, description, context, is_published, mode, navigation, max_attempts, time_limit_seconds, passing_score, shuffle_questions, round_size, grader and questions [{text, type, category, answer_text, explanation, points, rubric, max_length, answers [{text, is_correct, explanation}]}]. A taken slug is a 409 unless replace is true: then the quiz fields are updated and all its questions are deleted and recreated, which deletes the attempt answers given to them, open answers with their grades and reviews. Finished attempts keep their scores, but their reviews lose those questions; on a quiz with attempts prefer the per-question tools. An invalid document is a 422 and writes nothing. Returns id, slug, created and the number of questions and answers." + needsWrite,
|
||||||
|
Method: http.MethodPost,
|
||||||
|
Path: ManagePrefix + "/import",
|
||||||
|
Input: importQuizInput{},
|
||||||
|
Permissions: quizPermissions,
|
||||||
|
Destructive: &yes,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Name: "quiz_stats",
|
||||||
|
Title: "Quiz results",
|
||||||
|
Description: "Reports on one quiz. Expired open test attempts are closed at their deadline first. students [{user_id, email, name, surname, attempts, best_score_percent, last_score_percent, last_completed_at, passed}] counts each student's completed whole-quiz attempts (learning rounds of one category are left out); passed is best_score_percent >= passing_score. questions [{id, text, type, answered, correct, correct_percent, most_chosen_wrong {answer_id, text, count} or null, unreviewed, average_points}] counts the answers of every completed attempt; correct_percent is null when nobody answered, and for self_check correct counts the cards marked known. For open questions unreviewed counts the answers still pending, graded or failed and average_points is the mean of the scored ones (null otherwise); the top-level unreviewed is their sum. It shows student emails and names." + needsRead,
|
||||||
|
Method: http.MethodGet,
|
||||||
|
Path: ManagePrefix + "/{slug}/stats",
|
||||||
|
Input: statsInput{},
|
||||||
|
Permissions: quizPermissions,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Name: "create_question",
|
||||||
|
Title: "Add a question",
|
||||||
|
Description: "Adds a question to a quiz: text and type (single, multiple, self_check or open) are required; category, answer_text (the self_check answer or the open model answer), explanation, points (default 1), sort_order (default: after the last question), rubric and max_length (open only) and answers [{text, is_correct, explanation}] are optional. A single question needs at least two answers and exactly one correct, a multiple question at least two and one or more correct, a self_check and an open question none. An open question takes a free-text answer of at most max_length characters (default 2000) that the quiz's grader or the owner scores; its rubric guides grading and is never shown to students. Returns the question with its answer ids." + needsWrite,
|
||||||
|
Method: http.MethodPost,
|
||||||
|
Path: ManagePrefix + "/{slug}/questions",
|
||||||
|
Input: createQuestionInput{},
|
||||||
|
Permissions: quizPermissions,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Name: "update_question",
|
||||||
|
Title: "Change one question",
|
||||||
|
Description: "Changes only the fields you send on one question: text, type, category, answer_text, explanation, points, sort_order, rubric, max_length; an empty string clears category, answer_text, explanation and rubric, max_length 0 clears it (default 2000), and rubric and max_length apply to open questions only. answers, when sent, is the full new list: answers with an id are kept and updated (they keep their ids), answers without an id are created, answers missing from the list are deleted; an id of another question is refused. The changed question must pass the same rules as quizzes_create_question. Editing a question of a quiz with attempts is allowed: finished attempts keep their scores and their reviews show the current question." + needsWrite,
|
||||||
|
Method: http.MethodPatch,
|
||||||
|
Path: ManagePrefix + "/{slug}/questions/{id}",
|
||||||
|
Input: updateQuestionInput{},
|
||||||
|
Permissions: quizPermissions,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Name: "delete_question",
|
||||||
|
Title: "Delete a question",
|
||||||
|
Description: "Deletes one question for good, with its answers and the attempt answers students gave to it. Finished attempts keep their scores, but their reviews lose the question. Returns id and quiz_slug." + needsWrite,
|
||||||
|
Method: http.MethodDelete,
|
||||||
|
Path: ManagePrefix + "/{slug}/questions/{id}",
|
||||||
|
Input: deleteQuestionInput{},
|
||||||
|
Permissions: quizPermissions,
|
||||||
|
Destructive: &yes,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Name: "reorder_questions",
|
||||||
|
Title: "Reorder questions",
|
||||||
|
Description: "Sets the question order of a quiz: question_ids must list every question of the quiz exactly once, or the call is refused; the first id gets sort_order 1. Returns the quiz with its questions as quizzes_show_quiz does." + needsWrite,
|
||||||
|
Method: http.MethodPut,
|
||||||
|
Path: ManagePrefix + "/{slug}/questions/order",
|
||||||
|
Input: reorderInput{},
|
||||||
|
Permissions: quizPermissions,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
108
mcp_reviews.go
Normal file
108
mcp_reviews.go
Normal file
@@ -0,0 +1,108 @@
|
|||||||
|
package quizzes
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
|
||||||
|
"git.golem15.com/golem15/summercms/modules/pact"
|
||||||
|
)
|
||||||
|
|
||||||
|
// reviewListInput is the input of quizzes_review_list.
|
||||||
|
type reviewListInput struct {
|
||||||
|
Quiz string `json:"quiz,omitempty" query:"quiz" jsonschema:"only answers to this quiz, by slug"`
|
||||||
|
Status string `json:"status,omitempty" query:"status" jsonschema:"open (the default: pending, graded and failed, everything not reviewed yet), pending, graded, failed, reviewed or all"`
|
||||||
|
UserID uint `json:"user_id,omitempty" query:"user_id" jsonschema:"only answers of this student (user id)"`
|
||||||
|
AttemptID uint `json:"attempt_id,omitempty" query:"attempt_id" jsonschema:"only answers of this attempt"`
|
||||||
|
Page int `json:"page,omitempty" query:"page" jsonschema:"page number, from 1"`
|
||||||
|
PerPage int `json:"per_page,omitempty" query:"per_page" jsonschema:"rows per page, 1-100; default 20"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// reviewAnswerInput is the input of the tools that act on one answer.
|
||||||
|
type reviewAnswerInput struct {
|
||||||
|
ID uint `json:"id" path:"id" jsonschema:"the answer_id, as listed by quizzes_review_list"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// reviewSetScoreInput is the input of quizzes_review_set_score.
|
||||||
|
type reviewSetScoreInput struct {
|
||||||
|
ID uint `json:"id" path:"id" jsonschema:"the answer_id, as listed by quizzes_review_list"`
|
||||||
|
Points float64 `json:"points" jsonschema:"0 up to the question's points, in steps of 0.5"`
|
||||||
|
Comment *string `json:"comment,omitempty" jsonschema:"optional comment the student sees, at most 2000 characters; leaving it out clears an earlier comment"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// reviewConfirmBulkInput is the input of quizzes_review_confirm_bulk.
|
||||||
|
type reviewConfirmBulkInput struct {
|
||||||
|
Quiz string `json:"quiz,omitempty" jsonschema:"confirm the graded answers of this quiz (its slug); give either quiz or attempt_id"`
|
||||||
|
AttemptID uint `json:"attempt_id,omitempty" jsonschema:"confirm the graded answers of this attempt; give either quiz or attempt_id"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// reviewRegradeInput is the input of quizzes_review_regrade.
|
||||||
|
type reviewRegradeInput struct {
|
||||||
|
AnswerID uint `json:"answer_id,omitempty" jsonschema:"grade this one answer again; give exactly one of answer_id, attempt_id and quiz"`
|
||||||
|
AttemptID uint `json:"attempt_id,omitempty" jsonschema:"grade the unreviewed answers of this attempt again"`
|
||||||
|
Quiz string `json:"quiz,omitempty" jsonschema:"grade the unreviewed answers of this quiz (its slug) again"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// reviewTools are the owner's tools over the review queue of open answers
|
||||||
|
// (D-11). They bind the routes under ReviewPrefix, which check the same
|
||||||
|
// permission as the quiz tools (D-13).
|
||||||
|
func reviewTools() []pact.MCPTool {
|
||||||
|
return []pact.MCPTool{
|
||||||
|
{
|
||||||
|
Name: "review_list",
|
||||||
|
Title: "List open answers to review",
|
||||||
|
Description: "Lists the answers students wrote to open questions, oldest change first, for you to review. status: open (default: pending, graded and failed, everything not reviewed yet, except answers of a test attempt still in progress), pending (waiting for the grader or for you), graded (the grader gave a score you have not confirmed), failed (the grader could not score it; set the score yourself), reviewed or all. Filters: quiz (slug), user_id, attempt_id; page and per_page (1-100, default 20). Each row: answer_id, status, quiz {id, slug, title, mode}, question {id, text, points}, attempt {id, completed, completed_at}, student {user_id, email, name, surname}, text (the first 300 characters, text_truncated when cut), grader_points, points, graded_at, reviewed_at, updated_at. Read one answer in full with quizzes_review_show. It shows student emails, names and answers." + needsRead,
|
||||||
|
Method: http.MethodGet,
|
||||||
|
Path: ReviewPrefix,
|
||||||
|
Input: reviewListInput{},
|
||||||
|
Permissions: quizPermissions,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Name: "review_show",
|
||||||
|
Title: "Show one open answer for review",
|
||||||
|
Description: "Shows one open answer for review, owner view with the solution: question {id, text, points, answer_text (the model answer), rubric (the grading rules), max_length}, the student's full text, quiz, attempt, student, status, grader (the grader code), grader_points and grader_feedback (the grader's score and note, final only once status is reviewed), grading_error (why the grader failed, or that its feedback was withheld for repeating the rubric), grading_attempts, points (what counts in the attempt's score now), is_correct, review_comment (shown to the student), reviewed_at and reviewed_by {user_id, admin_id}. Never pass the rubric or the model answer to a student." + needsRead,
|
||||||
|
Method: http.MethodGet,
|
||||||
|
Path: ReviewPrefix + "/{id}",
|
||||||
|
Input: reviewAnswerInput{},
|
||||||
|
Permissions: quizPermissions,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Name: "review_confirm",
|
||||||
|
Title: "Confirm the grader's score",
|
||||||
|
Description: "Confirms the grader's score of one graded answer: status becomes reviewed and points become grader_points, final over any later grading, and a finished attempt's score is recalculated. A pending or failed answer has no score to confirm and is refused with 409 code no_grader_score (set the score with quizzes_review_set_score instead); confirming a reviewed answer changes nothing. An answer of a test attempt still in progress is refused with 409 code attempt_open. Returns the answer as quizzes_review_show does." + needsWrite,
|
||||||
|
Method: http.MethodPost,
|
||||||
|
Path: ReviewPrefix + "/{id}/confirm",
|
||||||
|
Input: reviewAnswerInput{},
|
||||||
|
Permissions: quizPermissions,
|
||||||
|
Idempotent: &yes,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Name: "review_set_score",
|
||||||
|
Title: "Set the score of an open answer",
|
||||||
|
Description: "Sets your own final score on one open answer, whatever its status (pending, graded, failed or reviewed): points from 0 up to the question's points in steps of 0.5 (anything else is refused with 422), and an optional comment of at most 2000 characters that the student sees with the answer; leaving the comment out clears an earlier one. status becomes reviewed and the score is final over any later grading; the grader's score and feedback stay for the record, and a finished attempt's score is recalculated. An answer of a test attempt still in progress is refused with 409 code attempt_open. Returns the answer as quizzes_review_show does." + needsWrite,
|
||||||
|
Method: http.MethodPost,
|
||||||
|
Path: ReviewPrefix + "/{id}/score",
|
||||||
|
Input: reviewSetScoreInput{},
|
||||||
|
Permissions: quizPermissions,
|
||||||
|
Idempotent: &yes,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Name: "review_confirm_bulk",
|
||||||
|
Title: "Confirm grader scores in bulk",
|
||||||
|
Description: "Confirms the grader's score of every graded answer of one quiz (quiz, its slug) or of one attempt (attempt_id); give exactly one of the two. Each becomes reviewed with points = grader_points, as quizzes_review_confirm does; pending, failed and reviewed answers are left alone, so check failed ones with quizzes_review_list first. Answers of test attempts still in progress are skipped (an attempt_id of one is refused with 409 code attempt_open). Finished attempts are recalculated. Returns {confirmed: the number of answers confirmed}; a second call confirms nothing new." + needsWrite,
|
||||||
|
Method: http.MethodPost,
|
||||||
|
Path: ReviewPrefix + "/confirm",
|
||||||
|
Input: reviewConfirmBulkInput{},
|
||||||
|
Permissions: quizPermissions,
|
||||||
|
Idempotent: &yes,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Name: "review_regrade",
|
||||||
|
Title: "Grade open answers again",
|
||||||
|
Description: "Re-runs the quiz's grader on one answer (answer_id), one attempt (attempt_id) or a whole quiz (quiz, its slug); give exactly one. Use it after changing a rubric or when the grader failed. Every pending, graded or failed answer in scope goes back to pending: the current grader scores, feedback and errors are discarded and the points drop to 0 until the grader scores it again (a finished attempt's score is recalculated). Answers of a test attempt that is still open are graded when it ends. Reviewed answers are skipped, and a single reviewed answer is refused with 409 code already_reviewed. Refused with 409 code grader_manual when the quiz's grader is manual or not available. Returns {regraded: the number of answers sent back}." + needsWrite,
|
||||||
|
Method: http.MethodPost,
|
||||||
|
Path: ReviewPrefix + "/regrade",
|
||||||
|
Input: reviewRegradeInput{},
|
||||||
|
Permissions: quizPermissions,
|
||||||
|
Destructive: &yes,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
281
mcp_test.go
Normal file
281
mcp_test.go
Normal file
@@ -0,0 +1,281 @@
|
|||||||
|
package quizzes
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"reflect"
|
||||||
|
"slices"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"unicode/utf8"
|
||||||
|
|
||||||
|
_ "git.golem15.com/golem15/sm-user-plugin"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/backpack"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/compass"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/pact"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/party"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/pier"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/surf"
|
||||||
|
)
|
||||||
|
|
||||||
|
// mountHost adapts a built surf router to pier.Host for a compile-only
|
||||||
|
// mount: pier compiles every declared tool against the real route table.
|
||||||
|
type mountHost struct{ r *surf.Router }
|
||||||
|
|
||||||
|
func (h mountHost) Routes() []pier.RouteInfo {
|
||||||
|
var out []pier.RouteInfo
|
||||||
|
for _, ri := range h.r.Routes() {
|
||||||
|
out = append(out, pier.RouteInfo{Method: ri.Method, Pattern: ri.Pattern, PluginID: ri.PluginID, Middleware: ri.Middleware})
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
func (h mountHost) Handler(method, pattern string) (http.Handler, bool) {
|
||||||
|
return h.r.Handler(method, pattern)
|
||||||
|
}
|
||||||
|
func (mountHost) MountStream(string, string, http.Handler, ...string) error { return nil }
|
||||||
|
func (mountHost) MountJSON(string, string, http.Handler) error { return nil }
|
||||||
|
func (h mountHost) Owner(method, path string) (string, bool) {
|
||||||
|
for _, ri := range h.r.Routes() {
|
||||||
|
if ri.Method == method && ri.Pattern == path {
|
||||||
|
return ri.PluginID, true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return "", false
|
||||||
|
}
|
||||||
|
|
||||||
|
// mcpTestApp boots golem15.user and golem15.quizzes on a config without a
|
||||||
|
// database.
|
||||||
|
func mcpTestApp(t *testing.T) (*backpack.App, []party.Plugin) {
|
||||||
|
t.Helper()
|
||||||
|
dir := t.TempDir()
|
||||||
|
files := map[string]string{
|
||||||
|
"app.yaml": "name: quizzes-mcp\nlocale: en\nfallback_locale: en\nurl: https://quizzes.example.test\n",
|
||||||
|
"http.yaml": "body_limits:\n default_bytes: 1048576\n upload_bytes: 10485760\n",
|
||||||
|
}
|
||||||
|
for name, body := range files {
|
||||||
|
if err := os.WriteFile(filepath.Join(dir, name), []byte(body), 0o644); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
cfg, err := compass.Open(compass.Options{Dir: dir, Environ: []string{
|
||||||
|
"SUMMER_ENV=testing",
|
||||||
|
"SUMMER_GOLEM15__USER__JWT__SECRET=quizzes-test-only-user-jwt-secret-with-32",
|
||||||
|
"SUMMER_ADMIN__JWT__SECRET=quizzes-test-only-admin-jwt-secret-with-32",
|
||||||
|
}})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
app := backpack.New(cfg)
|
||||||
|
plugins, err := party.Activate(app, []string{"golem15.user", "golem15.quizzes"})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Activate: %v", err)
|
||||||
|
}
|
||||||
|
return app, plugins
|
||||||
|
}
|
||||||
|
|
||||||
|
// pinnedTools is the sorted tool list of golem15.user plus this plugin.
|
||||||
|
var pinnedTools = []string{
|
||||||
|
"quizzes_create_question",
|
||||||
|
"quizzes_create_quiz",
|
||||||
|
"quizzes_delete_question",
|
||||||
|
"quizzes_delete_quiz",
|
||||||
|
"quizzes_import_quiz",
|
||||||
|
"quizzes_list_quizzes",
|
||||||
|
"quizzes_publish",
|
||||||
|
"quizzes_quiz_stats",
|
||||||
|
"quizzes_reorder_questions",
|
||||||
|
"quizzes_review_confirm",
|
||||||
|
"quizzes_review_confirm_bulk",
|
||||||
|
"quizzes_review_list",
|
||||||
|
"quizzes_review_regrade",
|
||||||
|
"quizzes_review_set_score",
|
||||||
|
"quizzes_review_show",
|
||||||
|
"quizzes_show_quiz",
|
||||||
|
"quizzes_unpublish",
|
||||||
|
"quizzes_update_question",
|
||||||
|
"quizzes_update_quiz",
|
||||||
|
"user_me",
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestQuizzesMCP (D-13, D-14) mounts pier against golem15.user and
|
||||||
|
// golem15.quizzes and pins the compiled tools; every quiz tool lists the
|
||||||
|
// quizzes permission and says so, GET and DELETE tools carry no body, and
|
||||||
|
// only import_quiz can carry is_published. Runs under -short.
|
||||||
|
func TestQuizzesMCP(t *testing.T) {
|
||||||
|
tools := (&Plugin{}).MCP().Tools
|
||||||
|
|
||||||
|
t.Run("compiles", func(t *testing.T) {
|
||||||
|
app, plugins := mcpTestApp(t)
|
||||||
|
router, err := surf.BuildRouter(app, plugins)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("BuildRouter: %v", err)
|
||||||
|
}
|
||||||
|
if err := app.Config.Set(pier.EnabledKey, true); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := pier.Mount(mountHost{r: router}, app, plugins); err != nil {
|
||||||
|
t.Fatalf("pier.Mount: %v", err)
|
||||||
|
}
|
||||||
|
p, ok := app.Lookup[*pier.Pier]()
|
||||||
|
if !ok {
|
||||||
|
t.Fatal("pier was not mounted")
|
||||||
|
}
|
||||||
|
if got := p.ToolNames(); !slices.Equal(got, pinnedTools) {
|
||||||
|
t.Fatalf("compiled tools %v, want %v", got, pinnedTools)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("permissions", func(t *testing.T) {
|
||||||
|
for _, tool := range tools {
|
||||||
|
if !slices.Contains(tool.Permissions, permQuizzes) {
|
||||||
|
t.Errorf("%s: Permissions %v lack %s", tool.Name, tool.Permissions, permQuizzes)
|
||||||
|
}
|
||||||
|
if !strings.Contains(tool.Description, "Needs scope") || !strings.Contains(tool.Description, "golem15.quizzes.access_quizzes") {
|
||||||
|
t.Errorf("%s: description does not name its scope and permission: %q", tool.Name, tool.Description)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("inputs", func(t *testing.T) {
|
||||||
|
for _, tool := range tools {
|
||||||
|
rt := reflect.TypeOf(tool.Input)
|
||||||
|
for rt.Kind() == reflect.Pointer {
|
||||||
|
rt = rt.Elem()
|
||||||
|
}
|
||||||
|
for i := 0; i < rt.NumField(); i++ {
|
||||||
|
f := rt.Field(i)
|
||||||
|
switch {
|
||||||
|
case f.Tag.Get("path") != "":
|
||||||
|
if !strings.Contains(tool.Path, "{"+f.Tag.Get("path")+"}") {
|
||||||
|
t.Errorf("%s.%s: path tag %q not in %s", tool.Name, f.Name, f.Tag.Get("path"), tool.Path)
|
||||||
|
}
|
||||||
|
case f.Tag.Get("query") != "":
|
||||||
|
default:
|
||||||
|
if tool.Method == http.MethodGet || tool.Method == http.MethodDelete {
|
||||||
|
t.Errorf("%s.%s: a %s tool carries a body field", tool.Name, f.Name, tool.Method)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
key, found := jsonKeyIn(rt, "is_published")
|
||||||
|
if found != (tool.Name == "import_quiz") {
|
||||||
|
t.Errorf("%s: has a field named %s = %v, want %v", tool.Name, key, found, tool.Name == "import_quiz")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("open authoring", func(t *testing.T) {
|
||||||
|
byName := map[string]pact.MCPTool{}
|
||||||
|
for _, tool := range tools {
|
||||||
|
byName[tool.Name] = tool
|
||||||
|
}
|
||||||
|
for name, keys := range map[string][]string{
|
||||||
|
"create_quiz": {"grader"},
|
||||||
|
"update_quiz": {"grader"},
|
||||||
|
"import_quiz": {"grader", "rubric", "max_length"},
|
||||||
|
"create_question": {"rubric", "max_length"},
|
||||||
|
"update_question": {"rubric", "max_length"},
|
||||||
|
} {
|
||||||
|
tool, ok := byName[name]
|
||||||
|
if !ok {
|
||||||
|
t.Errorf("no tool %s", name)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
for _, key := range keys {
|
||||||
|
if _, found := jsonKeyIn(reflect.TypeOf(tool.Input), key); !found {
|
||||||
|
t.Errorf("%s has no input %s", name, key)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if d := byName["import_quiz"].Description; !strings.Contains(d, "grades and reviews") {
|
||||||
|
t.Errorf("import_quiz does not warn that replace deletes reviews: %q", d)
|
||||||
|
}
|
||||||
|
for _, name := range []string{"show_quiz", "list_quizzes"} {
|
||||||
|
if !strings.Contains(byName[name].Description, "grader") && !strings.Contains(byName[name].Description, "rubric") {
|
||||||
|
t.Errorf("%s does not name the open-question fields", name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if d := byName["quiz_stats"].Description; !strings.Contains(d, "unreviewed") || !strings.Contains(d, "average_points") {
|
||||||
|
t.Errorf("quiz_stats does not name unreviewed and average_points: %q", d)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("review annotations", func(t *testing.T) {
|
||||||
|
destructive := map[string]bool{"review_regrade": true}
|
||||||
|
idempotent := map[string]bool{"review_confirm": true, "review_set_score": true, "review_confirm_bulk": true}
|
||||||
|
n := 0
|
||||||
|
for _, tool := range tools {
|
||||||
|
if !strings.HasPrefix(tool.Name, "review_") {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
n++
|
||||||
|
if !strings.HasPrefix(tool.Path, ReviewPrefix) {
|
||||||
|
t.Errorf("%s: path %s is not under %s", tool.Name, tool.Path, ReviewPrefix)
|
||||||
|
}
|
||||||
|
if got := tool.Destructive != nil && *tool.Destructive; got != destructive[tool.Name] {
|
||||||
|
t.Errorf("%s: Destructive = %v, want %v", tool.Name, got, destructive[tool.Name])
|
||||||
|
}
|
||||||
|
if got := tool.Idempotent != nil && *tool.Idempotent; got != idempotent[tool.Name] {
|
||||||
|
t.Errorf("%s: Idempotent = %v, want %v", tool.Name, got, idempotent[tool.Name])
|
||||||
|
}
|
||||||
|
suffix := needsWrite
|
||||||
|
if tool.Method == http.MethodGet {
|
||||||
|
suffix = needsRead
|
||||||
|
}
|
||||||
|
if !strings.HasSuffix(tool.Description, suffix) {
|
||||||
|
t.Errorf("%s: description does not end with %q", tool.Name, suffix)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if n != 6 {
|
||||||
|
t.Errorf("%d review tools, want 6", n)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("no vendor names", func(t *testing.T) {
|
||||||
|
for _, tool := range tools {
|
||||||
|
// The golem15 namespace of the permission is not the bridge.
|
||||||
|
text := strings.ReplaceAll(strings.ToLower(tool.Name+" "+tool.Title+" "+tool.Description+" "+tool.Path), "golem15.", "")
|
||||||
|
for _, word := range []string{" ai ", "ai.", "openai", "anthropic", "claude", "gpt", "gemini", "llm", "language model", "bridge", "golem"} {
|
||||||
|
if strings.Contains(" "+text+" ", word) {
|
||||||
|
t.Errorf("%s mentions %q", tool.Name, word)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("descriptions", func(t *testing.T) {
|
||||||
|
for _, tool := range tools {
|
||||||
|
if n := utf8.RuneCountInString(tool.Description); n > pier.MaxDescriptionRunes {
|
||||||
|
t.Errorf("%s: description has %d runes, more than %d", tool.Name, n, pier.MaxDescriptionRunes)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// jsonKeyIn reports whether rt, or a struct it contains (through pointers,
|
||||||
|
// slices and nested structs), has a field with the given JSON key.
|
||||||
|
func jsonKeyIn(rt reflect.Type, key string) (string, bool) {
|
||||||
|
seen := map[reflect.Type]bool{}
|
||||||
|
var walk func(reflect.Type) bool
|
||||||
|
walk = func(t reflect.Type) bool {
|
||||||
|
for t.Kind() == reflect.Pointer || t.Kind() == reflect.Slice || t.Kind() == reflect.Array {
|
||||||
|
t = t.Elem()
|
||||||
|
}
|
||||||
|
if t.Kind() != reflect.Struct || seen[t] {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
seen[t] = true
|
||||||
|
for i := 0; i < t.NumField(); i++ {
|
||||||
|
f := t.Field(i)
|
||||||
|
name, _, _ := strings.Cut(f.Tag.Get("json"), ",")
|
||||||
|
if name == key || (name == "" && strings.EqualFold(f.Name, strings.ReplaceAll(key, "_", ""))) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
if walk(f.Type) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
return key, walk(rt)
|
||||||
|
}
|
||||||
@@ -8,8 +8,31 @@ import (
|
|||||||
"git.golem15.com/golem15/summercms/modules/lagoon"
|
"git.golem15.com/golem15/summercms/modules/lagoon"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// Grading states of an open answer (AttemptAnswer.GradingStatus).
|
||||||
|
const (
|
||||||
|
// GradingPending waits for a grader or for the owner.
|
||||||
|
GradingPending = "pending"
|
||||||
|
// GradingGraded holds a grader's score the owner has not confirmed.
|
||||||
|
GradingGraded = "graded"
|
||||||
|
// GradingFailed is an answer the grader could not score; the owner
|
||||||
|
// grades it.
|
||||||
|
GradingFailed = "failed"
|
||||||
|
// GradingReviewed is final: the owner confirmed or set the score.
|
||||||
|
GradingReviewed = "reviewed"
|
||||||
|
)
|
||||||
|
|
||||||
|
// GradingStatuses lists the valid values of AttemptAnswer.GradingStatus.
|
||||||
|
var GradingStatuses = []string{GradingPending, GradingGraded, GradingFailed, GradingReviewed}
|
||||||
|
|
||||||
// AttemptAnswer is the user's answer to one question of an attempt. There is
|
// AttemptAnswer is the user's answer to one question of an attempt. There is
|
||||||
// one row per attempt and question; answering again overwrites it.
|
// one row per attempt and question; answering again overwrites it.
|
||||||
|
//
|
||||||
|
// TextAnswer and the grading fields belong to open questions only:
|
||||||
|
// GradingStatus is NULL for every other row. GradingSeq grows with every new
|
||||||
|
// text, so a grading job for an older text is ignored; GradingAttempts counts
|
||||||
|
// the grader runs for the current text. The review fields record the owner's
|
||||||
|
// decision: ReviewedByUserID for a frontend user (MCP), ReviewedByAdminID for
|
||||||
|
// a backend administrator.
|
||||||
type AttemptAnswer struct {
|
type AttemptAnswer struct {
|
||||||
ID uint `gorm:"column:id;primaryKey"`
|
ID uint `gorm:"column:id;primaryKey"`
|
||||||
AttemptID uint `gorm:"column:attempt_id"`
|
AttemptID uint `gorm:"column:attempt_id"`
|
||||||
@@ -20,6 +43,20 @@ type AttemptAnswer struct {
|
|||||||
Points float64 `gorm:"column:points"`
|
Points float64 `gorm:"column:points"`
|
||||||
CreatedAt time.Time `gorm:"column:created_at"`
|
CreatedAt time.Time `gorm:"column:created_at"`
|
||||||
UpdatedAt time.Time `gorm:"column:updated_at"`
|
UpdatedAt time.Time `gorm:"column:updated_at"`
|
||||||
|
|
||||||
|
TextAnswer *string `gorm:"column:text_answer"`
|
||||||
|
GradingStatus *string `gorm:"column:grading_status"`
|
||||||
|
GradingSeq int `gorm:"column:grading_seq"`
|
||||||
|
GradingAttempts int `gorm:"column:grading_attempts"`
|
||||||
|
Grader *string `gorm:"column:grader"`
|
||||||
|
GraderPoints *float64 `gorm:"column:grader_points"`
|
||||||
|
GraderFeedback *string `gorm:"column:grader_feedback"`
|
||||||
|
GradingError *string `gorm:"column:grading_error"`
|
||||||
|
GradedAt *time.Time `gorm:"column:graded_at"`
|
||||||
|
ReviewComment *string `gorm:"column:review_comment"`
|
||||||
|
ReviewedAt *time.Time `gorm:"column:reviewed_at"`
|
||||||
|
ReviewedByUserID *uint `gorm:"column:reviewed_by_user_id"`
|
||||||
|
ReviewedByAdminID *uint `gorm:"column:reviewed_by_admin_id"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// TableName is the plugin-prefixed table.
|
// TableName is the plugin-prefixed table.
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ package models
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"encoding/hex"
|
"encoding/hex"
|
||||||
|
"slices"
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
@@ -22,6 +23,8 @@ const (
|
|||||||
ScopeByQuiz = "filterByQuiz"
|
ScopeByQuiz = "filterByQuiz"
|
||||||
ScopeByCategory = "filterByCategory"
|
ScopeByCategory = "filterByCategory"
|
||||||
ScopeByType = "filterByType"
|
ScopeByType = "filterByType"
|
||||||
|
ScopeByStatus = "filterByStatus"
|
||||||
|
ScopeByStudent = "filterByStudent"
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
@@ -31,6 +34,8 @@ var (
|
|||||||
_ pact.FilterOptions = Answer{}
|
_ pact.FilterOptions = Answer{}
|
||||||
_ pact.FilterScope = Attempt{}
|
_ pact.FilterScope = Attempt{}
|
||||||
_ pact.FilterOptions = Attempt{}
|
_ pact.FilterOptions = Attempt{}
|
||||||
|
_ pact.FilterScope = Review{}
|
||||||
|
_ pact.FilterOptions = Review{}
|
||||||
)
|
)
|
||||||
|
|
||||||
// FilterScopes lists the admin list scopes of questions.
|
// FilterScopes lists the admin list scopes of questions.
|
||||||
@@ -75,6 +80,7 @@ func (Question) FilterOptions(scope string) []pact.Option {
|
|||||||
{Value: TypeSingle, Label: "golem15.quizzes::lang.questions.type_single"},
|
{Value: TypeSingle, Label: "golem15.quizzes::lang.questions.type_single"},
|
||||||
{Value: TypeMultiple, Label: "golem15.quizzes::lang.questions.type_multiple"},
|
{Value: TypeMultiple, Label: "golem15.quizzes::lang.questions.type_multiple"},
|
||||||
{Value: TypeSelfCheck, Label: "golem15.quizzes::lang.questions.type_self_check"},
|
{Value: TypeSelfCheck, Label: "golem15.quizzes::lang.questions.type_self_check"},
|
||||||
|
{Value: TypeOpen, Label: "golem15.quizzes::lang.questions.type_open"},
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
@@ -121,6 +127,54 @@ func (Attempt) FilterOptions(scope string) []pact.Option {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// FilterScopes lists the admin list scopes of the review screen.
|
||||||
|
func (Review) FilterScopes() []string { return []string{ScopeByQuiz, ScopeByStatus, ScopeByStudent} }
|
||||||
|
|
||||||
|
// FilterScope narrows the review list to the open answers of the chosen
|
||||||
|
// quizzes, grading statuses or students.
|
||||||
|
func (Review) FilterScope(name string, db *gorm.DB, value any) *gorm.DB {
|
||||||
|
values := filterValues(value)
|
||||||
|
if db == nil || len(values) == 0 {
|
||||||
|
return db
|
||||||
|
}
|
||||||
|
switch name {
|
||||||
|
case ScopeByQuiz:
|
||||||
|
return db.Where("golem15_quizzes_attempt_answers.question_id IN (SELECT id FROM golem15_quizzes_questions WHERE quiz_id IN ?)", ids(values))
|
||||||
|
case ScopeByStatus:
|
||||||
|
statuses := make([]string, 0, len(values))
|
||||||
|
for _, v := range values {
|
||||||
|
if slices.Contains(GradingStatuses, v) {
|
||||||
|
statuses = append(statuses, v)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(statuses) == 0 {
|
||||||
|
return db.Where("1 = 0")
|
||||||
|
}
|
||||||
|
return db.Where("golem15_quizzes_attempt_answers.grading_status IN ?", statuses)
|
||||||
|
case ScopeByStudent:
|
||||||
|
return db.Where("golem15_quizzes_attempt_answers.attempt_id IN (SELECT id FROM golem15_quizzes_attempts WHERE user_id IN ?)", ids(values))
|
||||||
|
}
|
||||||
|
return db
|
||||||
|
}
|
||||||
|
|
||||||
|
// FilterOptions serves the quizzes, the grading statuses and the students
|
||||||
|
// who have open answers.
|
||||||
|
func (Review) FilterOptions(scope string) []pact.Option {
|
||||||
|
switch scope {
|
||||||
|
case ScopeByQuiz:
|
||||||
|
return quizOptions()
|
||||||
|
case ScopeByStatus:
|
||||||
|
out := make([]pact.Option, 0, len(GradingStatuses))
|
||||||
|
for _, status := range GradingStatuses {
|
||||||
|
out = append(out, pact.Option{Value: status, Label: "golem15.quizzes::lang.reviews.status_" + status})
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
case ScopeByStudent:
|
||||||
|
return studentOptions()
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
func filterDB() *gorm.DB {
|
func filterDB() *gorm.DB {
|
||||||
if FilterDB == nil {
|
if FilterDB == nil {
|
||||||
return nil
|
return nil
|
||||||
@@ -144,6 +198,32 @@ func quizOptions() []pact.Option {
|
|||||||
return out
|
return out
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// studentOptions lists the users with at least one open answer, by email.
|
||||||
|
func studentOptions() []pact.Option {
|
||||||
|
db := filterDB()
|
||||||
|
if db == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
var rows []struct {
|
||||||
|
ID uint
|
||||||
|
Email string
|
||||||
|
}
|
||||||
|
err := db.Raw(`SELECT DISTINCT u.id AS id, COALESCE(u.email, '') AS email
|
||||||
|
FROM users u
|
||||||
|
JOIN golem15_quizzes_attempts a ON a.user_id = u.id
|
||||||
|
JOIN golem15_quizzes_attempt_answers aa ON aa.attempt_id = a.id
|
||||||
|
WHERE aa.grading_status IS NOT NULL
|
||||||
|
ORDER BY email, id`).Scan(&rows).Error
|
||||||
|
if err != nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
out := make([]pact.Option, 0, len(rows))
|
||||||
|
for _, r := range rows {
|
||||||
|
out = append(out, pact.Option{Value: strconv.FormatUint(uint64(r.ID), 10), Label: r.Email})
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
func categoryOptions() []pact.Option {
|
func categoryOptions() []pact.Option {
|
||||||
db := filterDB()
|
db := filterDB()
|
||||||
if db == nil {
|
if db == nil {
|
||||||
|
|||||||
@@ -9,13 +9,25 @@ const (
|
|||||||
TypeSingle = "single"
|
TypeSingle = "single"
|
||||||
TypeMultiple = "multiple"
|
TypeMultiple = "multiple"
|
||||||
TypeSelfCheck = "self_check"
|
TypeSelfCheck = "self_check"
|
||||||
|
TypeOpen = "open"
|
||||||
)
|
)
|
||||||
|
|
||||||
// QuestionTypes lists the valid values of Question.Type.
|
// QuestionTypes lists the valid values of Question.Type.
|
||||||
var QuestionTypes = []string{TypeSingle, TypeMultiple, TypeSelfCheck}
|
var QuestionTypes = []string{TypeSingle, TypeMultiple, TypeSelfCheck, TypeOpen}
|
||||||
|
|
||||||
|
// Limits of the answer length of an open question, in characters.
|
||||||
|
const (
|
||||||
|
// DefaultMaxLength applies when MaxLength is nil.
|
||||||
|
DefaultMaxLength = 2000
|
||||||
|
// MaxMaxLength is the largest MaxLength the column accepts.
|
||||||
|
MaxMaxLength = 20000
|
||||||
|
)
|
||||||
|
|
||||||
// Question is one question of a quiz. A self_check question is a flashcard:
|
// Question is one question of a quiz. A self_check question is a flashcard:
|
||||||
// the user reveals AnswerText and marks whether they knew it.
|
// the user reveals AnswerText and marks whether they knew it. An open
|
||||||
|
// question is answered in free text and graded against AnswerText (the
|
||||||
|
// model answer) and the owner-only Rubric; MaxLength caps the answer
|
||||||
|
// (DefaultMaxLength when nil).
|
||||||
type Question struct {
|
type Question struct {
|
||||||
ID uint `gorm:"column:id;primaryKey"`
|
ID uint `gorm:"column:id;primaryKey"`
|
||||||
QuizID uint `gorm:"column:quiz_id"`
|
QuizID uint `gorm:"column:quiz_id"`
|
||||||
@@ -24,6 +36,8 @@ type Question struct {
|
|||||||
Category *string `gorm:"column:category"`
|
Category *string `gorm:"column:category"`
|
||||||
AnswerText *string `gorm:"column:answer_text"`
|
AnswerText *string `gorm:"column:answer_text"`
|
||||||
Explanation *string `gorm:"column:explanation"`
|
Explanation *string `gorm:"column:explanation"`
|
||||||
|
Rubric *string `gorm:"column:rubric"`
|
||||||
|
MaxLength *int `gorm:"column:max_length"`
|
||||||
SortOrder int `gorm:"column:sort_order"`
|
SortOrder int `gorm:"column:sort_order"`
|
||||||
Points int `gorm:"column:points"`
|
Points int `gorm:"column:points"`
|
||||||
CreatedAt time.Time `gorm:"column:created_at"`
|
CreatedAt time.Time `gorm:"column:created_at"`
|
||||||
@@ -37,7 +51,7 @@ func (Question) TableName() string { return "golem15_quizzes_questions" }
|
|||||||
|
|
||||||
// Fillable lists the columns mass assignment may set.
|
// Fillable lists the columns mass assignment may set.
|
||||||
func (Question) Fillable() []string {
|
func (Question) Fillable() []string {
|
||||||
return []string{"quiz_id", "text", "type", "category", "answer_text", "explanation", "sort_order", "points"}
|
return []string{"quiz_id", "text", "type", "category", "answer_text", "explanation", "sort_order", "points", "rubric", "max_length"}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Rules are checked by the admin API on every save.
|
// Rules are checked by the admin API on every save.
|
||||||
@@ -45,9 +59,10 @@ func (Question) Rules() map[string]string {
|
|||||||
return map[string]string{
|
return map[string]string{
|
||||||
"quiz_id": "required|integer|min:1",
|
"quiz_id": "required|integer|min:1",
|
||||||
"text": "required",
|
"text": "required",
|
||||||
"type": "required|in:single,multiple,self_check",
|
"type": "required|in:single,multiple,self_check,open",
|
||||||
"category": "nullable|max:255",
|
"category": "nullable|max:255",
|
||||||
"sort_order": "nullable|integer",
|
"sort_order": "nullable|integer",
|
||||||
"points": "required|integer|min:0",
|
"points": "required|integer|min:0",
|
||||||
|
"max_length": "nullable|integer|between:1,20000",
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
45
models/question_hooks.go
Normal file
45
models/question_hooks.go
Normal file
@@ -0,0 +1,45 @@
|
|||||||
|
package models
|
||||||
|
|
||||||
|
import (
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"gorm.io/gorm"
|
||||||
|
)
|
||||||
|
|
||||||
|
// wasOpenKey is the statement setting by which BeforeSave tells AfterSave
|
||||||
|
// that the saved question was open before.
|
||||||
|
const wasOpenKey = "golem15.quizzes:question_was_open"
|
||||||
|
|
||||||
|
// BeforeSave notes whether a stored question that is saved as another
|
||||||
|
// type was open, for AfterSave. Every write path (the admin form and
|
||||||
|
// relation manager, the manage API and MCP, the importer) saves through
|
||||||
|
// GORM, so the hooks cover them all.
|
||||||
|
func (q *Question) BeforeSave(tx *gorm.DB) error {
|
||||||
|
if q.ID == 0 || q.Type == TypeOpen {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
var stored string
|
||||||
|
err := tx.Session(&gorm.Session{NewDB: true}).Model(&Question{}).
|
||||||
|
Where("id = ?", q.ID).Limit(1).Pluck("type", &stored).Error
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if stored == TypeOpen {
|
||||||
|
tx.InstanceSet(wasOpenKey, true)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// AfterSave ends the grading of the answers to a question that stopped
|
||||||
|
// being open, in the same transaction as the save: their grading_status
|
||||||
|
// becomes NULL, so they leave the review queue and needs_review, and a
|
||||||
|
// grading job still queued for them does nothing. Their text, grades and
|
||||||
|
// points stay for the record (stored scores are never touched).
|
||||||
|
func (q *Question) AfterSave(tx *gorm.DB) error {
|
||||||
|
if was, ok := tx.InstanceGet(wasOpenKey); !ok || was != true {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return tx.Session(&gorm.Session{NewDB: true}).Model(&AttemptAnswer{}).
|
||||||
|
Where("question_id = ? AND grading_status IS NOT NULL", q.ID).
|
||||||
|
Updates(map[string]any{"grading_status": nil, "updated_at": time.Now().UTC()}).Error
|
||||||
|
}
|
||||||
@@ -15,6 +15,7 @@ fields:
|
|||||||
single: golem15.quizzes::lang.questions.type_single
|
single: golem15.quizzes::lang.questions.type_single
|
||||||
multiple: golem15.quizzes::lang.questions.type_multiple
|
multiple: golem15.quizzes::lang.questions.type_multiple
|
||||||
self_check: golem15.quizzes::lang.questions.type_self_check
|
self_check: golem15.quizzes::lang.questions.type_self_check
|
||||||
|
open: golem15.quizzes::lang.questions.type_open
|
||||||
text:
|
text:
|
||||||
label: golem15.quizzes::lang.questions.text
|
label: golem15.quizzes::lang.questions.text
|
||||||
type: textarea
|
type: textarea
|
||||||
@@ -35,6 +36,16 @@ fields:
|
|||||||
type: textarea
|
type: textarea
|
||||||
size: small
|
size: small
|
||||||
comment: golem15.quizzes::lang.questions.answer_text_comment
|
comment: golem15.quizzes::lang.questions.answer_text_comment
|
||||||
|
rubric:
|
||||||
|
label: golem15.quizzes::lang.questions.rubric
|
||||||
|
type: textarea
|
||||||
|
size: small
|
||||||
|
comment: golem15.quizzes::lang.questions.rubric_comment
|
||||||
|
max_length:
|
||||||
|
label: golem15.quizzes::lang.questions.max_length
|
||||||
|
type: number
|
||||||
|
span: left
|
||||||
|
comment: golem15.quizzes::lang.questions.max_length_comment
|
||||||
explanation:
|
explanation:
|
||||||
label: golem15.quizzes::lang.questions.explanation
|
label: golem15.quizzes::lang.questions.explanation
|
||||||
type: textarea
|
type: textarea
|
||||||
|
|||||||
@@ -7,11 +7,34 @@ import (
|
|||||||
"time"
|
"time"
|
||||||
"unicode"
|
"unicode"
|
||||||
|
|
||||||
|
"git.golem15.com/golem15/sm-quizzes-plugin/graders"
|
||||||
"gorm.io/gorm"
|
"gorm.io/gorm"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// Quiz modes.
|
||||||
|
const (
|
||||||
|
ModeLearning = "learning"
|
||||||
|
ModeTest = "test"
|
||||||
|
)
|
||||||
|
|
||||||
|
// QuizModes lists the valid values of Quiz.Mode.
|
||||||
|
var QuizModes = []string{ModeLearning, ModeTest}
|
||||||
|
|
||||||
|
// Test navigation.
|
||||||
|
const (
|
||||||
|
NavigationFree = "free"
|
||||||
|
NavigationOneWay = "one_way"
|
||||||
|
)
|
||||||
|
|
||||||
|
// QuizNavigations lists the valid values of Quiz.Navigation.
|
||||||
|
var QuizNavigations = []string{NavigationFree, NavigationOneWay}
|
||||||
|
|
||||||
// Quiz is a set of questions a signed-in user can attempt. Context is a
|
// Quiz is a set of questions a signed-in user can attempt. Context is a
|
||||||
// free-form link to a record of another plugin, such as "acme.shop:course:12".
|
// free-form link to a record of another plugin, such as "acme.shop:course:12".
|
||||||
|
// Mode test withholds solutions until the attempt is finished; Navigation
|
||||||
|
// (free or one_way) and MaxAttempts (nil is unlimited) only apply to tests.
|
||||||
|
// Grader is the code of the grader of its open answers (graders.Manual: the
|
||||||
|
// owner grades them); an unknown code behaves as manual.
|
||||||
type Quiz struct {
|
type Quiz struct {
|
||||||
ID uint `gorm:"column:id;primaryKey"`
|
ID uint `gorm:"column:id;primaryKey"`
|
||||||
Title string `gorm:"column:title"`
|
Title string `gorm:"column:title"`
|
||||||
@@ -23,6 +46,10 @@ type Quiz struct {
|
|||||||
PassingScore int `gorm:"column:passing_score"`
|
PassingScore int `gorm:"column:passing_score"`
|
||||||
ShuffleQuestions bool `gorm:"column:shuffle_questions"`
|
ShuffleQuestions bool `gorm:"column:shuffle_questions"`
|
||||||
RoundSize *int `gorm:"column:round_size"`
|
RoundSize *int `gorm:"column:round_size"`
|
||||||
|
Mode string `gorm:"column:mode"`
|
||||||
|
Navigation string `gorm:"column:navigation"`
|
||||||
|
MaxAttempts *int `gorm:"column:max_attempts"`
|
||||||
|
Grader string `gorm:"column:grader"`
|
||||||
CreatedAt time.Time `gorm:"column:created_at"`
|
CreatedAt time.Time `gorm:"column:created_at"`
|
||||||
UpdatedAt time.Time `gorm:"column:updated_at"`
|
UpdatedAt time.Time `gorm:"column:updated_at"`
|
||||||
Questions []Question `gorm:"foreignKey:QuizID"`
|
Questions []Question `gorm:"foreignKey:QuizID"`
|
||||||
@@ -36,6 +63,7 @@ func (Quiz) Fillable() []string {
|
|||||||
return []string{
|
return []string{
|
||||||
"title", "slug", "description", "context", "is_published",
|
"title", "slug", "description", "context", "is_published",
|
||||||
"time_limit_seconds", "passing_score", "shuffle_questions", "round_size",
|
"time_limit_seconds", "passing_score", "shuffle_questions", "round_size",
|
||||||
|
"mode", "navigation", "max_attempts", "grader",
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -49,22 +77,46 @@ func (Quiz) Rules() map[string]string {
|
|||||||
"passing_score": "required|integer|between:0,100",
|
"passing_score": "required|integer|between:0,100",
|
||||||
"time_limit_seconds": "nullable|integer|min:1",
|
"time_limit_seconds": "nullable|integer|min:1",
|
||||||
"round_size": "nullable|integer|min:1",
|
"round_size": "nullable|integer|min:1",
|
||||||
|
"mode": "nullable|in:learning,test",
|
||||||
|
"navigation": "nullable|in:free,one_way",
|
||||||
|
"max_attempts": "nullable|integer|min:1",
|
||||||
|
"grader": "nullable|max:64",
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// BeforeValidate fills the slug from the title before the admin form
|
// BeforeValidate fills the slug from the title and the mode defaults before
|
||||||
// validates, so the unique rule sees the final slug.
|
// the admin form validates, so the rules see the final values.
|
||||||
func (q *Quiz) BeforeValidate(*gorm.DB) error {
|
func (q *Quiz) BeforeValidate(*gorm.DB) error {
|
||||||
q.fillSlug()
|
q.fillSlug()
|
||||||
|
q.fillDefaults()
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// BeforeSave fills the slug from the title on every other write path.
|
// BeforeSave fills the slug and the mode defaults on every other write path.
|
||||||
func (q *Quiz) BeforeSave(*gorm.DB) error {
|
func (q *Quiz) BeforeSave(*gorm.DB) error {
|
||||||
q.fillSlug()
|
q.fillSlug()
|
||||||
|
q.fillDefaults()
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// fillDefaults stores an empty mode or navigation as learning / free, an
|
||||||
|
// empty grader as manual and a non-positive attempt limit as unlimited. GORM writes Go zero values, so
|
||||||
|
// without it a models.Quiz{} would hit the columns' CHECK constraints.
|
||||||
|
func (q *Quiz) fillDefaults() {
|
||||||
|
if q.Mode == "" {
|
||||||
|
q.Mode = ModeLearning
|
||||||
|
}
|
||||||
|
if q.Navigation == "" {
|
||||||
|
q.Navigation = NavigationFree
|
||||||
|
}
|
||||||
|
if q.Grader == "" {
|
||||||
|
q.Grader = graders.Manual
|
||||||
|
}
|
||||||
|
if q.MaxAttempts != nil && *q.MaxAttempts <= 0 {
|
||||||
|
q.MaxAttempts = nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func (q *Quiz) fillSlug() {
|
func (q *Quiz) fillSlug() {
|
||||||
if strings.TrimSpace(q.Slug) == "" {
|
if strings.TrimSpace(q.Slug) == "" {
|
||||||
q.Slug = Slugify(q.Title)
|
q.Slug = Slugify(q.Title)
|
||||||
|
|||||||
73
models/quiz_test.go
Normal file
73
models/quiz_test.go
Normal file
@@ -0,0 +1,73 @@
|
|||||||
|
package models
|
||||||
|
|
||||||
|
import (
|
||||||
|
"slices"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"git.golem15.com/golem15/sm-quizzes-plugin/graders"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestQuizDefaults(t *testing.T) {
|
||||||
|
zero, negative := 0, -1
|
||||||
|
for name, hook := range map[string]func(*Quiz) error{
|
||||||
|
"BeforeSave": func(q *Quiz) error { return q.BeforeSave(nil) },
|
||||||
|
"BeforeValidate": func(q *Quiz) error { return q.BeforeValidate(nil) },
|
||||||
|
} {
|
||||||
|
for _, limit := range []*int{&zero, &negative} {
|
||||||
|
q := &Quiz{Title: "Q", MaxAttempts: limit}
|
||||||
|
if err := hook(q); err != nil {
|
||||||
|
t.Fatalf("%s: %v", name, err)
|
||||||
|
}
|
||||||
|
if q.Mode != ModeLearning || q.Navigation != NavigationFree || q.MaxAttempts != nil {
|
||||||
|
t.Errorf("%s with max_attempts %d = %q %q %v, want learning free nil", name, *limit, q.Mode, q.Navigation, q.MaxAttempts)
|
||||||
|
}
|
||||||
|
if q.Grader != graders.Manual {
|
||||||
|
t.Errorf("%s left grader %q, want %q", name, q.Grader, graders.Manual)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
two := 2
|
||||||
|
q := &Quiz{Title: "Q", Mode: ModeTest, Navigation: NavigationOneWay, MaxAttempts: &two, Grader: "ai"}
|
||||||
|
if err := hook(q); err != nil {
|
||||||
|
t.Fatalf("%s: %v", name, err)
|
||||||
|
}
|
||||||
|
if q.Mode != ModeTest || q.Navigation != NavigationOneWay || q.MaxAttempts == nil || *q.MaxAttempts != 2 {
|
||||||
|
t.Errorf("%s changed a test quiz: %q %q %v", name, q.Mode, q.Navigation, q.MaxAttempts)
|
||||||
|
}
|
||||||
|
if q.Grader != "ai" {
|
||||||
|
t.Errorf("%s changed an explicit grader to %q", name, q.Grader)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestOpenQuestionModel(t *testing.T) {
|
||||||
|
if !slices.Contains(QuestionTypes, TypeOpen) || len(QuestionTypes) != 4 {
|
||||||
|
t.Errorf("QuestionTypes = %v, want the open type appended", QuestionTypes)
|
||||||
|
}
|
||||||
|
if QuestionTypes[0] != TypeSingle || QuestionTypes[1] != TypeMultiple || QuestionTypes[2] != TypeSelfCheck {
|
||||||
|
t.Errorf("QuestionTypes reordered the existing types: %v", QuestionTypes)
|
||||||
|
}
|
||||||
|
rules := Question{}.Rules()
|
||||||
|
if !strings.Contains(rules["type"], "open") || !strings.Contains(rules["type"], "self_check") {
|
||||||
|
t.Errorf("type rule = %q, want every type including open", rules["type"])
|
||||||
|
}
|
||||||
|
if rules["max_length"] != "nullable|integer|between:1,20000" {
|
||||||
|
t.Errorf("max_length rule = %q", rules["max_length"])
|
||||||
|
}
|
||||||
|
fill := Question{}.Fillable()
|
||||||
|
if !slices.Contains(fill, "rubric") || !slices.Contains(fill, "max_length") {
|
||||||
|
t.Errorf("Fillable = %v, want rubric and max_length", fill)
|
||||||
|
}
|
||||||
|
if DefaultMaxLength != 2000 || MaxMaxLength != 20000 {
|
||||||
|
t.Errorf("max length limits = %d / %d", DefaultMaxLength, MaxMaxLength)
|
||||||
|
}
|
||||||
|
if len(GradingStatuses) != 4 || GradingStatuses[0] != GradingPending {
|
||||||
|
t.Errorf("GradingStatuses = %v", GradingStatuses)
|
||||||
|
}
|
||||||
|
if !slices.Contains(Quiz{}.Fillable(), "grader") {
|
||||||
|
t.Error("Quiz.Fillable lacks grader")
|
||||||
|
}
|
||||||
|
if len(AttemptAnswer{}.Fillable()) != 0 {
|
||||||
|
t.Error("AttemptAnswer.Fillable must stay empty")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -8,6 +8,10 @@ columns:
|
|||||||
context:
|
context:
|
||||||
label: golem15.quizzes::lang.quizzes.context
|
label: golem15.quizzes::lang.quizzes.context
|
||||||
searchable: true
|
searchable: true
|
||||||
|
mode:
|
||||||
|
label: golem15.quizzes::lang.quizzes.mode
|
||||||
|
grader:
|
||||||
|
label: golem15.quizzes::lang.quizzes.grader
|
||||||
is_published:
|
is_published:
|
||||||
label: golem15.quizzes::lang.quizzes.is_published
|
label: golem15.quizzes::lang.quizzes.is_published
|
||||||
type: switch
|
type: switch
|
||||||
|
|||||||
@@ -42,3 +42,33 @@ fields:
|
|||||||
label: golem15.quizzes::lang.quizzes.shuffle_questions
|
label: golem15.quizzes::lang.quizzes.shuffle_questions
|
||||||
type: switch
|
type: switch
|
||||||
span: right
|
span: right
|
||||||
|
mode:
|
||||||
|
label: golem15.quizzes::lang.quizzes.mode
|
||||||
|
type: dropdown
|
||||||
|
span: left
|
||||||
|
default: learning
|
||||||
|
options:
|
||||||
|
learning: golem15.quizzes::lang.quizzes.mode_learning
|
||||||
|
test: golem15.quizzes::lang.quizzes.mode_test
|
||||||
|
comment: golem15.quizzes::lang.quizzes.mode_comment
|
||||||
|
navigation:
|
||||||
|
label: golem15.quizzes::lang.quizzes.navigation
|
||||||
|
type: dropdown
|
||||||
|
span: right
|
||||||
|
default: free
|
||||||
|
options:
|
||||||
|
free: golem15.quizzes::lang.quizzes.navigation_free
|
||||||
|
one_way: golem15.quizzes::lang.quizzes.navigation_one_way
|
||||||
|
comment: golem15.quizzes::lang.quizzes.navigation_comment
|
||||||
|
max_attempts:
|
||||||
|
label: golem15.quizzes::lang.quizzes.max_attempts
|
||||||
|
type: number
|
||||||
|
span: left
|
||||||
|
comment: golem15.quizzes::lang.quizzes.max_attempts_comment
|
||||||
|
grader:
|
||||||
|
label: golem15.quizzes::lang.quizzes.grader
|
||||||
|
type: dropdown
|
||||||
|
span: right
|
||||||
|
default: manual
|
||||||
|
options: getGraderOptions
|
||||||
|
comment: golem15.quizzes::lang.quizzes.grader_comment
|
||||||
|
|||||||
60
models/review.go
Normal file
60
models/review.go
Normal file
@@ -0,0 +1,60 @@
|
|||||||
|
package models
|
||||||
|
|
||||||
|
import "time"
|
||||||
|
|
||||||
|
// ReviewMorphName is Review's morph type. Review shares its table with
|
||||||
|
// AttemptAnswer, so it names itself: two models listed in Models() with the
|
||||||
|
// same morph type would stop deferred:purge.
|
||||||
|
const ReviewMorphName = "golem15.quizzes.review"
|
||||||
|
|
||||||
|
// Review is an open answer as the admin "Do oceny" screen shows it. It reads
|
||||||
|
// the same golem15_quizzes_attempt_answers table as AttemptAnswer, which
|
||||||
|
// keeps its empty Fillable for the API; the admin never writes a column
|
||||||
|
// through it either. The owner's score and comment are form virtual fields
|
||||||
|
// that the controller saves through the review service.
|
||||||
|
type Review struct {
|
||||||
|
ID uint `gorm:"column:id;primaryKey"`
|
||||||
|
AttemptID uint `gorm:"column:attempt_id"`
|
||||||
|
QuestionID uint `gorm:"column:question_id"`
|
||||||
|
TextAnswer *string `gorm:"column:text_answer"`
|
||||||
|
GradingStatus *string `gorm:"column:grading_status"`
|
||||||
|
GradingSeq int `gorm:"column:grading_seq"`
|
||||||
|
GradingAttempts int `gorm:"column:grading_attempts"`
|
||||||
|
Grader *string `gorm:"column:grader"`
|
||||||
|
GraderPoints *float64 `gorm:"column:grader_points"`
|
||||||
|
GraderFeedback *string `gorm:"column:grader_feedback"`
|
||||||
|
GradingError *string `gorm:"column:grading_error"`
|
||||||
|
GradedAt *time.Time `gorm:"column:graded_at"`
|
||||||
|
Points float64 `gorm:"column:points"`
|
||||||
|
IsCorrect bool `gorm:"column:is_correct"`
|
||||||
|
ReviewComment *string `gorm:"column:review_comment"`
|
||||||
|
ReviewedAt *time.Time `gorm:"column:reviewed_at"`
|
||||||
|
ReviewedByUserID *uint `gorm:"column:reviewed_by_user_id"`
|
||||||
|
ReviewedByAdminID *uint `gorm:"column:reviewed_by_admin_id"`
|
||||||
|
CreatedAt time.Time `gorm:"column:created_at"`
|
||||||
|
UpdatedAt time.Time `gorm:"column:updated_at"`
|
||||||
|
|
||||||
|
Question *Question `gorm:"foreignKey:QuestionID"`
|
||||||
|
Attempt *Attempt `gorm:"foreignKey:AttemptID"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// TableName is the attempt answers table.
|
||||||
|
func (Review) TableName() string { return "golem15_quizzes_attempt_answers" }
|
||||||
|
|
||||||
|
// MorphName keeps Review apart from AttemptAnswer, which owns the table.
|
||||||
|
func (Review) MorphName() string { return ReviewMorphName }
|
||||||
|
|
||||||
|
// Fillable is empty: the admin form saves no column of an answer.
|
||||||
|
func (Review) Fillable() []string { return []string{} }
|
||||||
|
|
||||||
|
// Rules are empty: the controller's FormRules check the virtual fields.
|
||||||
|
func (Review) Rules() map[string]string { return map[string]string{} }
|
||||||
|
|
||||||
|
// ReviewStatus reports the grading status, "" when the row is not an open
|
||||||
|
// answer.
|
||||||
|
func (r Review) ReviewStatus() string {
|
||||||
|
if r.GradingStatus == nil {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
return *r.GradingStatus
|
||||||
|
}
|
||||||
21
models/reviews/columns.yaml
Normal file
21
models/reviews/columns.yaml
Normal file
@@ -0,0 +1,21 @@
|
|||||||
|
columns:
|
||||||
|
question:
|
||||||
|
label: golem15.quizzes::lang.reviews.question
|
||||||
|
relation: question
|
||||||
|
select: text
|
||||||
|
searchable: true
|
||||||
|
grading_status:
|
||||||
|
label: golem15.quizzes::lang.reviews.status
|
||||||
|
grader_points:
|
||||||
|
label: golem15.quizzes::lang.reviews.grader_points
|
||||||
|
points:
|
||||||
|
label: golem15.quizzes::lang.reviews.points
|
||||||
|
graded_at:
|
||||||
|
label: golem15.quizzes::lang.reviews.graded_at
|
||||||
|
type: datetime
|
||||||
|
reviewed_at:
|
||||||
|
label: golem15.quizzes::lang.reviews.reviewed_at
|
||||||
|
type: datetime
|
||||||
|
updated_at:
|
||||||
|
label: golem15.quizzes::lang.common.updated_at
|
||||||
|
type: datetime
|
||||||
19
models/reviews/fields.yaml
Normal file
19
models/reviews/fields.yaml
Normal file
@@ -0,0 +1,19 @@
|
|||||||
|
# The answer itself is read-only: the review_context partial shows it from a
|
||||||
|
# curated view model. review_points and review_comment are virtual fields the
|
||||||
|
# controller saves through the review service (SetScore).
|
||||||
|
fields:
|
||||||
|
review_context:
|
||||||
|
label: golem15.quizzes::lang.reviews.context
|
||||||
|
type: partial
|
||||||
|
path: review_context
|
||||||
|
span: full
|
||||||
|
review_points:
|
||||||
|
label: golem15.quizzes::lang.reviews.review_points
|
||||||
|
type: number
|
||||||
|
span: left
|
||||||
|
comment: golem15.quizzes::lang.reviews.review_points_comment
|
||||||
|
review_comment:
|
||||||
|
label: golem15.quizzes::lang.reviews.review_comment
|
||||||
|
type: textarea
|
||||||
|
size: small
|
||||||
|
comment: golem15.quizzes::lang.reviews.review_comment_comment
|
||||||
156
open_authoring_postgres_test.go
Normal file
156
open_authoring_postgres_test.go
Normal file
@@ -0,0 +1,156 @@
|
|||||||
|
package quizzes_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"net/http"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"git.golem15.com/golem15/sm-quizzes-plugin/models"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/surf"
|
||||||
|
)
|
||||||
|
|
||||||
|
// TestOpenAuthoringAgainstDatabase covers authoring open questions over the
|
||||||
|
// owner routes the MCP quiz tools bind (D-01, D-04, D-05, D-10): an import
|
||||||
|
// with an open question and a grader code no plugin registers, the owner
|
||||||
|
// and the student views of it (the rubric only in the owner view), the
|
||||||
|
// open-question rules of the question routes, the grader check of the quiz
|
||||||
|
// routes and the open-answer stats. Skipped under -short; it runs in the
|
||||||
|
// verification phase.
|
||||||
|
func TestOpenAuthoringAgainstDatabase(t *testing.T) {
|
||||||
|
if testing.Short() {
|
||||||
|
t.Skip("Postgres test; runs in the verification phase")
|
||||||
|
}
|
||||||
|
app, plugins, gdb := migrated(t)
|
||||||
|
h, err := surf.Assemble(app, plugins)
|
||||||
|
must(t, err)
|
||||||
|
c := &client{t: t, h: h}
|
||||||
|
const prefix = "/api/v1/quizzes"
|
||||||
|
|
||||||
|
owner, _ := newUser(t, gdb, "owner@example.com")
|
||||||
|
var groupID uint
|
||||||
|
must(t, gdb.Raw(`INSERT INTO user_groups (name, code, permissions, created_at, updated_at)
|
||||||
|
VALUES ('Editors', 'editors', '{"golem15.quizzes.access_quizzes":1}', NOW(), NOW()) RETURNING id`).Scan(&groupID).Error)
|
||||||
|
must(t, gdb.Exec(`INSERT INTO users_groups (user_id, user_group_id) VALUES (?, ?)`, owner.ID, groupID).Error)
|
||||||
|
token := apiToken(t, gdb, owner.ID, "read", "write")
|
||||||
|
_, student := newUser(t, gdb, "student@example.com")
|
||||||
|
|
||||||
|
doc := `{"title":"Eseje","slug":"eseje","is_published":true,"grader":"ai","questions":[
|
||||||
|
{"text":"Wyjaśnij odstraszanie.","type":"open","points":2,"answer_text":"MODEL","rubric":"R-RUBRIC","max_length":300},
|
||||||
|
{"text":"Stolica?","type":"single","answers":[{"text":"Warszawa","is_correct":true},{"text":"Kraków"}]}]}`
|
||||||
|
|
||||||
|
var openID uint
|
||||||
|
t.Run("import and read back", func(t *testing.T) {
|
||||||
|
out := data(c.ok(http.StatusOK, "POST", prefix+"/import", token, doc))
|
||||||
|
if out["slug"] != "eseje" || out["questions"] != float64(2) {
|
||||||
|
t.Fatalf("import = %v", out)
|
||||||
|
}
|
||||||
|
show := data(c.ok(http.StatusOK, "GET", prefix+"/eseje", token, ""))
|
||||||
|
if show["grader"] != "ai" {
|
||||||
|
t.Errorf("owner grader = %v, want ai (kept although no plugin registers it)", show["grader"])
|
||||||
|
}
|
||||||
|
qs := show["questions"].([]any)
|
||||||
|
open := qs[0].(map[string]any)
|
||||||
|
openID = uint(open["id"].(float64))
|
||||||
|
if open["type"] != "open" || open["rubric"] != "R-RUBRIC" || open["max_length"] != float64(300) || open["answer_text"] != "MODEL" {
|
||||||
|
t.Errorf("owner open question = %v", open)
|
||||||
|
}
|
||||||
|
if single := qs[1].(map[string]any); single["rubric"] != nil || single["max_length"] != nil {
|
||||||
|
t.Errorf("owner single question = %v, want null rubric and max_length", single)
|
||||||
|
}
|
||||||
|
|
||||||
|
code, body := c.do("GET", apiPrefix+"/quizzes/eseje", student, "")
|
||||||
|
if code != http.StatusOK {
|
||||||
|
t.Fatalf("student quiz = %d %v", code, body)
|
||||||
|
}
|
||||||
|
if raw := fmt.Sprint(body); strings.Contains(raw, "R-RUBRIC") || strings.Contains(raw, "rubric") {
|
||||||
|
t.Errorf("student quiz carries the rubric: %v", body)
|
||||||
|
}
|
||||||
|
sq := data(body)["questions"].([]any)[0].(map[string]any)
|
||||||
|
if sq["max_length"] != float64(300) {
|
||||||
|
t.Errorf("student open question = %v, want max_length 300", sq)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("question rules", func(t *testing.T) {
|
||||||
|
code, body := c.do("POST", prefix+"/eseje/questions", token, `{"text":"Q","type":"open","answers":[{"text":"a","is_correct":true}]}`)
|
||||||
|
if msg, _ := body["message"].(string); code != http.StatusUnprocessableEntity || !strings.Contains(msg, "an open question has no answers") {
|
||||||
|
t.Errorf("open with answers = %d %v, want 422", code, body)
|
||||||
|
}
|
||||||
|
code, body = c.do("POST", prefix+"/eseje/questions", token, `{"text":"Q","type":"single","rubric":"R","answers":[{"text":"a","is_correct":true},{"text":"b"}]}`)
|
||||||
|
if msg, _ := body["message"].(string); code != http.StatusUnprocessableEntity || !strings.Contains(msg, "rubric applies to open questions only") {
|
||||||
|
t.Errorf("single with rubric = %d %v, want 422", code, body)
|
||||||
|
}
|
||||||
|
out := data(c.ok(http.StatusOK, "PATCH", fmt.Sprintf("%s/eseje/questions/%d", prefix, openID), token, `{"max_length":0}`))
|
||||||
|
if out["max_length"] != nil || out["rubric"] != "R-RUBRIC" {
|
||||||
|
t.Errorf("max_length 0 = %v, want it cleared and the rubric kept", out)
|
||||||
|
}
|
||||||
|
out = data(c.ok(http.StatusOK, "PATCH", fmt.Sprintf("%s/eseje/questions/%d", prefix, openID), token, `{"rubric":"","max_length":500}`))
|
||||||
|
if out["rubric"] != nil || out["max_length"] != float64(500) {
|
||||||
|
t.Errorf("rubric cleared, max_length 500 = %v", out)
|
||||||
|
}
|
||||||
|
var q models.Question
|
||||||
|
must(t, gdb.Where("id = ?", openID).Take(&q).Error)
|
||||||
|
if q.Rubric != nil || q.MaxLength == nil || *q.MaxLength != 500 {
|
||||||
|
t.Errorf("stored question = %+v", q)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("quiz grader", func(t *testing.T) {
|
||||||
|
code, body := c.do("POST", prefix, token, `{"title":"Z","grader":"zzz"}`)
|
||||||
|
if msg, _ := body["message"].(string); code != http.StatusUnprocessableEntity || !strings.Contains(msg, "manual") {
|
||||||
|
t.Errorf("unknown grader = %d %v, want 422 naming manual", code, body)
|
||||||
|
}
|
||||||
|
code, body = c.do("PATCH", prefix+"/eseje", token, `{"grader":"zzz"}`)
|
||||||
|
if code != http.StatusUnprocessableEntity {
|
||||||
|
t.Errorf("update to an unknown grader = %d %v, want 422", code, body)
|
||||||
|
}
|
||||||
|
out := data(c.ok(http.StatusOK, "PATCH", prefix+"/eseje", token, `{"grader":"manual"}`))
|
||||||
|
if out["grader"] != "manual" {
|
||||||
|
t.Errorf("grader manual = %v", out)
|
||||||
|
}
|
||||||
|
out = data(c.ok(http.StatusCreated, "POST", prefix, token, `{"title":"Domyślny"}`))
|
||||||
|
if out["grader"] != "manual" {
|
||||||
|
t.Errorf("default grader = %v, want manual", out["grader"])
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("stats count open answers", func(t *testing.T) {
|
||||||
|
finished := func(email, text string) uint {
|
||||||
|
t.Helper()
|
||||||
|
_, jwt := newUser(t, gdb, email)
|
||||||
|
att := data(c.ok(http.StatusCreated, "POST", apiPrefix+"/quizzes/eseje/attempts", jwt, ""))
|
||||||
|
id := uint(att["id"].(float64))
|
||||||
|
c.ok(http.StatusOK, "POST", fmt.Sprintf("%s/attempts/%d/answers", apiPrefix, id), jwt,
|
||||||
|
fmt.Sprintf(`{"question_id":%d,"text":%q}`, openID, text))
|
||||||
|
c.ok(http.StatusOK, "POST", fmt.Sprintf("%s/attempts/%d/finish", apiPrefix, id), jwt, "")
|
||||||
|
return id
|
||||||
|
}
|
||||||
|
graded := finished("s1@example.com", "Odstraszanie to groźba odwetu.")
|
||||||
|
finished("s2@example.com", "Nie wiem.")
|
||||||
|
now := time.Now().UTC()
|
||||||
|
must(t, gdb.Model(&models.AttemptAnswer{}).Where("attempt_id = ? AND question_id = ?", graded, openID).Updates(map[string]any{
|
||||||
|
"grading_status": models.GradingGraded, "grader": "ai", "grader_points": 1.5, "points": 1.5,
|
||||||
|
"graded_at": now, "updated_at": now,
|
||||||
|
}).Error)
|
||||||
|
|
||||||
|
out := data(c.ok(http.StatusOK, "GET", prefix+"/eseje/stats", token, ""))
|
||||||
|
if out["unreviewed"] != float64(2) {
|
||||||
|
t.Errorf("total unreviewed = %v, want 2", out["unreviewed"])
|
||||||
|
}
|
||||||
|
for _, row := range out["questions"].([]any) {
|
||||||
|
q := row.(map[string]any)
|
||||||
|
switch uint(q["id"].(float64)) {
|
||||||
|
case openID:
|
||||||
|
if q["unreviewed"] != float64(2) || q["average_points"] != 1.5 || q["most_chosen_wrong"] != nil || q["answered"] != float64(2) {
|
||||||
|
t.Errorf("open stats = %v, want unreviewed 2 and average_points 1.5 (the pending answer is not averaged)", q)
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
if q["unreviewed"] != float64(0) || q["average_points"] != nil {
|
||||||
|
t.Errorf("single stats = %v, want no open counts", q)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
526
open_questions_postgres_test.go
Normal file
526
open_questions_postgres_test.go
Normal file
@@ -0,0 +1,526 @@
|
|||||||
|
package quizzes_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"math"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"git.golem15.com/golem15/sm-quizzes-plugin/classes"
|
||||||
|
"git.golem15.com/golem15/sm-quizzes-plugin/events"
|
||||||
|
"git.golem15.com/golem15/sm-quizzes-plugin/graders"
|
||||||
|
"git.golem15.com/golem15/sm-quizzes-plugin/jobs"
|
||||||
|
"git.golem15.com/golem15/sm-quizzes-plugin/models"
|
||||||
|
"git.golem15.com/golem15/sm-quizzes-plugin/updates"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/conga"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/festival"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/pact"
|
||||||
|
"gorm.io/gorm"
|
||||||
|
)
|
||||||
|
|
||||||
|
// fakeGrader answers with a configurable score or error and counts calls.
|
||||||
|
type fakeGrader struct {
|
||||||
|
mu sync.Mutex
|
||||||
|
points float64
|
||||||
|
text string
|
||||||
|
err error
|
||||||
|
calls int
|
||||||
|
last graders.Input
|
||||||
|
}
|
||||||
|
|
||||||
|
func (g *fakeGrader) Code() string { return "fake" }
|
||||||
|
func (g *fakeGrader) Label() string { return "Fake grader" }
|
||||||
|
func (g *fakeGrader) Grade(_ context.Context, in graders.Input) (graders.Result, error) {
|
||||||
|
g.mu.Lock()
|
||||||
|
defer g.mu.Unlock()
|
||||||
|
g.calls++
|
||||||
|
g.last = in
|
||||||
|
if g.err != nil {
|
||||||
|
return graders.Result{}, g.err
|
||||||
|
}
|
||||||
|
return graders.Result{Points: g.points, Feedback: g.text}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (g *fakeGrader) set(points float64, text string, err error) {
|
||||||
|
g.mu.Lock()
|
||||||
|
defer g.mu.Unlock()
|
||||||
|
g.points, g.text, g.err = points, text, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (g *fakeGrader) callCount() int {
|
||||||
|
g.mu.Lock()
|
||||||
|
defer g.mu.Unlock()
|
||||||
|
return g.calls
|
||||||
|
}
|
||||||
|
|
||||||
|
// recordingEnqueuer records the grading jobs instead of inserting them.
|
||||||
|
type recordingEnqueuer struct {
|
||||||
|
mu sync.Mutex
|
||||||
|
jobs []jobs.GradeAnswerArgs
|
||||||
|
opts []conga.EnqueueOpts
|
||||||
|
inTx []bool
|
||||||
|
}
|
||||||
|
|
||||||
|
func (e *recordingEnqueuer) Enqueue(_ context.Context, db *gorm.DB, args pact.JobArgs, o conga.EnqueueOpts) error {
|
||||||
|
e.mu.Lock()
|
||||||
|
defer e.mu.Unlock()
|
||||||
|
a, ok := args.(jobs.GradeAnswerArgs)
|
||||||
|
if !ok {
|
||||||
|
return errors.New("unexpected job args")
|
||||||
|
}
|
||||||
|
_, tx := db.Statement.ConnPool.(gorm.TxCommitter)
|
||||||
|
e.jobs, e.opts, e.inTx = append(e.jobs, a), append(e.opts, o), append(e.inTx, tx)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (e *recordingEnqueuer) take() []jobs.GradeAnswerArgs {
|
||||||
|
e.mu.Lock()
|
||||||
|
defer e.mu.Unlock()
|
||||||
|
out := e.jobs
|
||||||
|
for i, o := range e.opts {
|
||||||
|
if o.Queue != jobs.Queue || o.MaxAttempts != classes.GradeMaxAttempts || !e.inTx[i] {
|
||||||
|
out = append(out, jobs.GradeAnswerArgs{}) // makes the caller's count check fail
|
||||||
|
}
|
||||||
|
}
|
||||||
|
e.jobs, e.opts, e.inTx = nil, nil, nil
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestOpenQuestionsAgainstDatabase covers open questions and their grading
|
||||||
|
// end to end on a migrated database: the migration, learning answers and
|
||||||
|
// their re-answers, the background grade with clamping, recalculation and
|
||||||
|
// the AnswerGraded event, stale jobs, failures, manual quizzes, test mode
|
||||||
|
// (grading at close), the text limits and the migration's rollback.
|
||||||
|
func TestOpenQuestionsAgainstDatabase(t *testing.T) {
|
||||||
|
if testing.Short() {
|
||||||
|
t.Skip("Postgres test; runs in the verification phase")
|
||||||
|
}
|
||||||
|
_, _, gdb := migrated(t)
|
||||||
|
ctx := t.Context()
|
||||||
|
|
||||||
|
grader := &fakeGrader{}
|
||||||
|
reg := graders.NewRegistry()
|
||||||
|
must(t, reg.Add("acme.fake", grader))
|
||||||
|
enq := &recordingEnqueuer{}
|
||||||
|
bus := festival.New()
|
||||||
|
var (
|
||||||
|
evMu sync.Mutex
|
||||||
|
graded []*events.AnswerGradedEvent
|
||||||
|
seenStatus []string
|
||||||
|
)
|
||||||
|
bus.Listen[*events.AnswerGradedEvent]("acme.test", func(ctx context.Context, e *events.AnswerGradedEvent) error {
|
||||||
|
var row models.AttemptAnswer
|
||||||
|
status := "missing"
|
||||||
|
if err := gdb.WithContext(ctx).Where("id = ?", e.AnswerID).Take(&row).Error; err == nil && row.GradingStatus != nil {
|
||||||
|
status = *row.GradingStatus
|
||||||
|
}
|
||||||
|
evMu.Lock()
|
||||||
|
defer evMu.Unlock()
|
||||||
|
graded, seenStatus = append(graded, e), append(seenStatus, status)
|
||||||
|
return errors.New("a listener error is logged, never returned")
|
||||||
|
})
|
||||||
|
takeEvents := func() ([]*events.AnswerGradedEvent, []string) {
|
||||||
|
evMu.Lock()
|
||||||
|
defer evMu.Unlock()
|
||||||
|
out, st := graded, seenStatus
|
||||||
|
graded, seenStatus = nil, nil
|
||||||
|
return out, st
|
||||||
|
}
|
||||||
|
svc := &classes.Service{DB: gdb, Graders: reg, Jobs: enq, Events: bus}
|
||||||
|
|
||||||
|
seedOpen := func(t *testing.T, slug string, mutate func(*models.Quiz)) (models.Quiz, models.Question) {
|
||||||
|
t.Helper()
|
||||||
|
quiz := models.Quiz{Title: slug, Slug: slug, IsPublished: true, PassingScore: 50, Grader: "fake"}
|
||||||
|
if mutate != nil {
|
||||||
|
mutate(&quiz)
|
||||||
|
}
|
||||||
|
must(t, gdb.Create(&quiz).Error)
|
||||||
|
q := models.Question{QuizID: quiz.ID, Text: "Wyjaśnij odstraszanie.", Type: models.TypeOpen,
|
||||||
|
AnswerText: strPtr("MODEL"), Rubric: strPtr("R-SECRET"), Points: 2, SortOrder: 1}
|
||||||
|
must(t, gdb.Create(&q).Error)
|
||||||
|
return quiz, q
|
||||||
|
}
|
||||||
|
users := 0
|
||||||
|
startFor := func(t *testing.T, slug string) (uint, uint) {
|
||||||
|
t.Helper()
|
||||||
|
users++
|
||||||
|
u, _ := newUser(t, gdb, strings.ReplaceAll(t.Name(), "/", "-")+"-"+string(rune('a'+users))+"@example.com")
|
||||||
|
st, err := svc.Start(ctx, u.ID, slug, "")
|
||||||
|
must(t, err)
|
||||||
|
return u.ID, st.Attempt.ID
|
||||||
|
}
|
||||||
|
answer := func(userID, attemptID, questionID uint, text string) (*classes.Feedback, error) {
|
||||||
|
return svc.Answer(ctx, userID, attemptID, classes.AnswerInput{QuestionID: questionID, Text: &text})
|
||||||
|
}
|
||||||
|
rowOf := func(t *testing.T, attemptID, questionID uint) models.AttemptAnswer {
|
||||||
|
t.Helper()
|
||||||
|
var row models.AttemptAnswer
|
||||||
|
must(t, gdb.Where("attempt_id = ? AND question_id = ?", attemptID, questionID).Take(&row).Error)
|
||||||
|
return row
|
||||||
|
}
|
||||||
|
status := func(r models.AttemptAnswer) string {
|
||||||
|
if r.GradingStatus == nil {
|
||||||
|
return "<nil>"
|
||||||
|
}
|
||||||
|
return *r.GradingStatus
|
||||||
|
}
|
||||||
|
fieldKey := func(err error) string {
|
||||||
|
var fe *classes.FieldError
|
||||||
|
if errors.As(err, &fe) {
|
||||||
|
return fe.Field + ":" + fe.Key
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
t.Run("migration", func(t *testing.T) {
|
||||||
|
var n int64
|
||||||
|
must(t, gdb.Raw(`SELECT COUNT(*) FROM pg_constraint WHERE conrelid = 'golem15_quizzes_questions'::regclass
|
||||||
|
AND conname = 'golem15_quizzes_questions_type_check'`).Scan(&n).Error)
|
||||||
|
if n != 1 {
|
||||||
|
t.Errorf("golem15_quizzes_questions_type_check count = %d, want 1", n)
|
||||||
|
}
|
||||||
|
must(t, gdb.Raw(`SELECT COUNT(*) FROM pg_constraint con
|
||||||
|
JOIN pg_attribute att ON att.attrelid = con.conrelid AND att.attname = 'type'
|
||||||
|
WHERE con.conrelid = 'golem15_quizzes_questions'::regclass AND con.contype = 'c' AND con.conkey = ARRAY[att.attnum]`).Scan(&n).Error)
|
||||||
|
if n != 1 {
|
||||||
|
t.Errorf("CHECK constraints on questions.type = %d, want exactly the new one", n)
|
||||||
|
}
|
||||||
|
|
||||||
|
quiz, q := seedOpen(t, "migracja", nil)
|
||||||
|
if q.ID == 0 {
|
||||||
|
t.Fatal("open question not created")
|
||||||
|
}
|
||||||
|
if err := gdb.Exec(`INSERT INTO golem15_quizzes_questions (quiz_id, text, type) VALUES (?, 'Q', 'essay')`, quiz.ID).Error; err == nil {
|
||||||
|
t.Error("a fifth question type was accepted")
|
||||||
|
}
|
||||||
|
if err := gdb.Exec(`INSERT INTO golem15_quizzes_questions (quiz_id, text, type, max_length) VALUES (?, 'Q', 'open', 0)`, quiz.ID).Error; err == nil {
|
||||||
|
t.Error("max_length 0 was accepted")
|
||||||
|
}
|
||||||
|
|
||||||
|
must(t, gdb.Exec(`INSERT INTO golem15_quizzes_quizzes (title, slug, is_published, passing_score, shuffle_questions, created_at, updated_at)
|
||||||
|
VALUES ('Stary otwarty', 'stary-otwarty', true, 50, false, NOW(), NOW())`).Error)
|
||||||
|
var old models.Quiz
|
||||||
|
must(t, gdb.Where("slug = ?", "stary-otwarty").Take(&old).Error)
|
||||||
|
if old.Grader != graders.Manual {
|
||||||
|
t.Errorf("pre-existing quiz grader = %q, want manual", old.Grader)
|
||||||
|
}
|
||||||
|
zero := models.Quiz{Title: "Zero", Slug: "zero-grader", PassingScore: 50}
|
||||||
|
must(t, gdb.Create(&zero).Error)
|
||||||
|
if zero.Grader != graders.Manual {
|
||||||
|
t.Errorf("zero-value quiz grader = %q, want manual", zero.Grader)
|
||||||
|
}
|
||||||
|
|
||||||
|
f := seedQuiz(t, gdb, "zwykly-otwarty", nil)
|
||||||
|
uid, aid := startFor(t, "zwykly-otwarty")
|
||||||
|
_, err := svc.Answer(ctx, uid, aid, classes.AnswerInput{QuestionID: f.single.ID, AnswerIDs: []uint{f.singleRight.ID}})
|
||||||
|
must(t, err)
|
||||||
|
if r := rowOf(t, aid, f.single.ID); r.GradingStatus != nil || r.GradingSeq != 0 || r.TextAnswer != nil || !r.IsCorrect {
|
||||||
|
t.Errorf("single answer row = %+v, want no grading state and the usual score", r)
|
||||||
|
}
|
||||||
|
if jobs := enq.take(); len(jobs) != 0 {
|
||||||
|
t.Errorf("a single answer enqueued %v", jobs)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("learning answer", func(t *testing.T) {
|
||||||
|
_, q := seedOpen(t, "nauka-otwarte", nil)
|
||||||
|
uid, aid := startFor(t, "nauka-otwarte")
|
||||||
|
enq.take()
|
||||||
|
|
||||||
|
fb, err := answer(uid, aid, q.ID, " moja odpowiedź \x00")
|
||||||
|
must(t, err)
|
||||||
|
if fb.Withheld || fb.Answer == nil || status(*fb.Answer) != models.GradingPending || fb.Answer.GradingSeq != 1 {
|
||||||
|
t.Fatalf("feedback = %+v answer %+v", fb, fb.Answer)
|
||||||
|
}
|
||||||
|
if fb.Answer.TextAnswer == nil || *fb.Answer.TextAnswer != "moja odpowiedź" {
|
||||||
|
t.Errorf("stored text = %v, want trimmed without NUL", fb.Answer.TextAnswer)
|
||||||
|
}
|
||||||
|
row := rowOf(t, aid, q.ID)
|
||||||
|
if got := enq.take(); len(got) != 1 || got[0] != (jobs.GradeAnswerArgs{AnswerID: row.ID, Seq: 1}) {
|
||||||
|
t.Errorf("enqueued %v, want one job for answer %d seq 1 in the answer transaction", got, row.ID)
|
||||||
|
}
|
||||||
|
|
||||||
|
if _, err := answer(uid, aid, q.ID, "moja odpowiedź"); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if got := enq.take(); len(got) != 0 {
|
||||||
|
t.Errorf("unchanged text enqueued %v", got)
|
||||||
|
}
|
||||||
|
if r := rowOf(t, aid, q.ID); r.GradingSeq != 1 || !r.UpdatedAt.Equal(row.UpdatedAt) {
|
||||||
|
t.Errorf("unchanged text rewrote the row: seq %d updated %v -> %v", r.GradingSeq, row.UpdatedAt, r.UpdatedAt)
|
||||||
|
}
|
||||||
|
|
||||||
|
must(t, gdb.Model(&models.AttemptAnswer{}).Where("id = ?", row.ID).Updates(map[string]any{
|
||||||
|
"grading_status": models.GradingReviewed, "grader": "fake", "grader_points": 2.0, "points": 2.0, "is_correct": true,
|
||||||
|
"grader_feedback": "stara uwaga", "review_comment": "stary komentarz", "grading_attempts": 1,
|
||||||
|
"graded_at": time.Now(), "reviewed_at": time.Now(), "reviewed_by_user_id": uid,
|
||||||
|
}).Error)
|
||||||
|
fb, err = answer(uid, aid, q.ID, "inna odpowiedź")
|
||||||
|
must(t, err)
|
||||||
|
r := rowOf(t, aid, q.ID)
|
||||||
|
if status(r) != models.GradingPending || r.GradingSeq != 2 || r.GradingAttempts != 0 || r.Points != 0 || r.IsCorrect ||
|
||||||
|
r.Grader != nil || r.GraderPoints != nil || r.GraderFeedback != nil || r.GradedAt != nil ||
|
||||||
|
r.ReviewComment != nil || r.ReviewedAt != nil || r.ReviewedByUserID != nil || *r.TextAnswer != "inna odpowiedź" {
|
||||||
|
t.Errorf("changed text did not reset the grading state: %+v", r)
|
||||||
|
}
|
||||||
|
if fb.Answer == nil || fb.Answer.GradingSeq != 2 {
|
||||||
|
t.Errorf("feedback answer = %+v, want seq 2", fb.Answer)
|
||||||
|
}
|
||||||
|
if got := enq.take(); len(got) != 1 || got[0].Seq != 2 {
|
||||||
|
t.Errorf("changed text enqueued %v, want one job with seq 2", got)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("grading", func(t *testing.T) {
|
||||||
|
_, q := seedOpen(t, "ocena-otwarte", nil)
|
||||||
|
uid, aid := startFor(t, "ocena-otwarte")
|
||||||
|
_, err := answer(uid, aid, q.ID, "odstraszanie to groźba odwetu")
|
||||||
|
must(t, err)
|
||||||
|
row := rowOf(t, aid, q.ID)
|
||||||
|
enq.take()
|
||||||
|
takeEvents()
|
||||||
|
|
||||||
|
grader.set(1.26, " Dobrze, ale bez przykładu. ", nil)
|
||||||
|
calls := grader.callCount()
|
||||||
|
must(t, svc.GradeAnswer(ctx, row.ID, 1))
|
||||||
|
r := rowOf(t, aid, q.ID)
|
||||||
|
if status(r) != models.GradingGraded || r.Points != 1.5 || r.GraderPoints == nil || *r.GraderPoints != 1.5 || r.IsCorrect ||
|
||||||
|
r.Grader == nil || *r.Grader != "fake" || r.GraderFeedback == nil || *r.GraderFeedback != "Dobrze, ale bez przykładu." ||
|
||||||
|
r.GradingAttempts != 1 || r.GradedAt == nil || r.GradingError != nil {
|
||||||
|
t.Errorf("graded row = %+v", r)
|
||||||
|
}
|
||||||
|
if grader.callCount() != calls+1 || grader.last.Rubric != "R-SECRET" || grader.last.ModelAnswer != "MODEL" ||
|
||||||
|
grader.last.Answer != "odstraszanie to groźba odwetu" || grader.last.Points != 2 || grader.last.UserID != uid {
|
||||||
|
t.Errorf("grader input = %+v", grader.last)
|
||||||
|
}
|
||||||
|
evs, st := takeEvents()
|
||||||
|
if len(evs) != 1 || evs[0].AnswerID != row.ID || evs[0].Points != 1.5 || evs[0].MaxPoints != 2 || evs[0].Grader != "fake" ||
|
||||||
|
evs[0].UserID != uid || evs[0].AttemptID != aid || evs[0].QuestionID != q.ID {
|
||||||
|
t.Errorf("AnswerGraded events = %+v", evs)
|
||||||
|
} else if st[0] != models.GradingGraded {
|
||||||
|
t.Errorf("the event fired before the commit: the listener saw %q", st[0])
|
||||||
|
}
|
||||||
|
|
||||||
|
must(t, svc.GradeAnswer(ctx, row.ID, 1))
|
||||||
|
if evs, _ := takeEvents(); len(evs) != 0 || grader.callCount() != calls+1 {
|
||||||
|
t.Errorf("a second job for a graded answer ran the grader or fired again: %d events", len(evs))
|
||||||
|
}
|
||||||
|
|
||||||
|
// Full points on a completed attempt: the stored score follows.
|
||||||
|
_, q2 := seedOpen(t, "ocena-pelna", nil)
|
||||||
|
uid2, aid2 := startFor(t, "ocena-pelna")
|
||||||
|
_, err = answer(uid2, aid2, q2.ID, "pełna odpowiedź")
|
||||||
|
must(t, err)
|
||||||
|
_, err = svc.Finish(ctx, uid2, aid2)
|
||||||
|
must(t, err)
|
||||||
|
var before models.Attempt
|
||||||
|
must(t, gdb.Where("id = ?", aid2).Take(&before).Error)
|
||||||
|
if before.ScorePoints != 0 || before.MaxPoints != 2 {
|
||||||
|
t.Fatalf("finished attempt = %v / %d, want 0 / 2", before.ScorePoints, before.MaxPoints)
|
||||||
|
}
|
||||||
|
grader.set(7, "", nil)
|
||||||
|
must(t, svc.GradeAnswer(ctx, rowOf(t, aid2, q2.ID).ID, 1))
|
||||||
|
r2 := rowOf(t, aid2, q2.ID)
|
||||||
|
if r2.Points != 2 || !r2.IsCorrect || r2.GraderFeedback != nil {
|
||||||
|
t.Errorf("full-points row = %+v", r2)
|
||||||
|
}
|
||||||
|
var after models.Attempt
|
||||||
|
must(t, gdb.Where("id = ?", aid2).Take(&after).Error)
|
||||||
|
if after.ScorePoints != 2 || after.ScorePercent == nil || *after.ScorePercent != 100 || after.MaxPoints != 2 {
|
||||||
|
t.Errorf("recalculated attempt = %v / %v / %d, want 2 / 100 / 2", after.ScorePoints, after.ScorePercent, after.MaxPoints)
|
||||||
|
}
|
||||||
|
res, err := svc.Result(ctx, uid2, aid2)
|
||||||
|
must(t, err)
|
||||||
|
if res.OpenAnswers != 1 || res.Unreviewed != 1 {
|
||||||
|
t.Errorf("result open / unreviewed = %d / %d, want 1 / 1", res.OpenAnswers, res.Unreviewed)
|
||||||
|
}
|
||||||
|
hist, _, err := svc.History(ctx, uid2, "", 1, 10)
|
||||||
|
must(t, err)
|
||||||
|
if len(hist) != 1 || hist[0].OpenAnswers != 1 || hist[0].Unreviewed != 1 || hist[0].AnsweredCount != 1 {
|
||||||
|
t.Errorf("history = %+v", hist)
|
||||||
|
}
|
||||||
|
takeEvents()
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("stale job", func(t *testing.T) {
|
||||||
|
_, q := seedOpen(t, "stary-job", nil)
|
||||||
|
uid, aid := startFor(t, "stary-job")
|
||||||
|
_, err := answer(uid, aid, q.ID, "pierwsza")
|
||||||
|
must(t, err)
|
||||||
|
_, err = answer(uid, aid, q.ID, "druga")
|
||||||
|
must(t, err)
|
||||||
|
row := rowOf(t, aid, q.ID)
|
||||||
|
enq.take()
|
||||||
|
grader.set(2, "", nil)
|
||||||
|
calls := grader.callCount()
|
||||||
|
must(t, svc.GradeAnswer(ctx, row.ID, 1))
|
||||||
|
r := rowOf(t, aid, q.ID)
|
||||||
|
if status(r) != models.GradingPending || r.GradingSeq != 2 || r.GradingAttempts != 0 || grader.callCount() != calls {
|
||||||
|
t.Errorf("a stale job changed the answer or called the grader: %+v", r)
|
||||||
|
}
|
||||||
|
must(t, svc.GradeAnswer(ctx, row.ID+100000, 1))
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("failure", func(t *testing.T) {
|
||||||
|
_, q := seedOpen(t, "porazka", nil)
|
||||||
|
uid, aid := startFor(t, "porazka")
|
||||||
|
_, err := answer(uid, aid, q.ID, "odpowiedź")
|
||||||
|
must(t, err)
|
||||||
|
row := rowOf(t, aid, q.ID)
|
||||||
|
enq.take()
|
||||||
|
takeEvents()
|
||||||
|
|
||||||
|
grader.set(0, "", errors.New("provider down"))
|
||||||
|
for i := 1; i <= 2; i++ {
|
||||||
|
if err := svc.GradeAnswer(ctx, row.ID, 1); err == nil || !strings.Contains(err.Error(), "provider down") {
|
||||||
|
t.Fatalf("attempt %d: err = %v, want the grader error for a retry", i, err)
|
||||||
|
}
|
||||||
|
if r := rowOf(t, aid, q.ID); status(r) != models.GradingPending || r.GradingAttempts != i {
|
||||||
|
t.Errorf("after attempt %d: %s, attempts %d", i, status(r), r.GradingAttempts)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err := svc.GradeAnswer(ctx, row.ID, 1); err != nil {
|
||||||
|
t.Fatalf("last attempt returned %v, want nil", err)
|
||||||
|
}
|
||||||
|
r := rowOf(t, aid, q.ID)
|
||||||
|
if status(r) != models.GradingFailed || r.GradingError == nil || *r.GradingError != "provider down" || r.GradingAttempts != 3 {
|
||||||
|
t.Errorf("failed row = %+v", r)
|
||||||
|
}
|
||||||
|
if evs, _ := takeEvents(); len(evs) != 0 {
|
||||||
|
t.Errorf("a failure fired %d AnswerGraded events", len(evs))
|
||||||
|
}
|
||||||
|
|
||||||
|
// A score that is not a number counts as a failure.
|
||||||
|
_, q2 := seedOpen(t, "porazka-nan", nil)
|
||||||
|
uid2, aid2 := startFor(t, "porazka-nan")
|
||||||
|
_, err = answer(uid2, aid2, q2.ID, "odpowiedź")
|
||||||
|
must(t, err)
|
||||||
|
grader.set(math.NaN(), "", nil)
|
||||||
|
if err := svc.GradeAnswer(ctx, rowOf(t, aid2, q2.ID).ID, 1); err == nil || !strings.Contains(err.Error(), "invalid score") {
|
||||||
|
t.Errorf("NaN score: err = %v, want the invalid score error", err)
|
||||||
|
}
|
||||||
|
grader.set(0, "", nil)
|
||||||
|
enq.take()
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("manual grader", func(t *testing.T) {
|
||||||
|
_, q := seedOpen(t, "recznie", func(qz *models.Quiz) { qz.Grader = "" })
|
||||||
|
uid, aid := startFor(t, "recznie")
|
||||||
|
_, err := answer(uid, aid, q.ID, "odpowiedź")
|
||||||
|
must(t, err)
|
||||||
|
if got := enq.take(); len(got) != 0 {
|
||||||
|
t.Errorf("a manual quiz enqueued %v", got)
|
||||||
|
}
|
||||||
|
calls := grader.callCount()
|
||||||
|
row := rowOf(t, aid, q.ID)
|
||||||
|
must(t, svc.GradeAnswer(ctx, row.ID, 1))
|
||||||
|
if r := rowOf(t, aid, q.ID); status(r) != models.GradingPending || r.GradingAttempts != 0 || grader.callCount() != calls {
|
||||||
|
t.Errorf("a manual answer was graded: %+v", r)
|
||||||
|
}
|
||||||
|
|
||||||
|
_, q2 := seedOpen(t, "nieznany", func(qz *models.Quiz) { qz.Grader = "nobody" })
|
||||||
|
uid2, aid2 := startFor(t, "nieznany")
|
||||||
|
_, err = answer(uid2, aid2, q2.ID, "odpowiedź")
|
||||||
|
must(t, err)
|
||||||
|
if got := enq.take(); len(got) != 0 {
|
||||||
|
t.Errorf("an unknown grader enqueued %v", got)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("test mode", func(t *testing.T) {
|
||||||
|
quiz, q := seedOpen(t, "test-otwarty", func(qz *models.Quiz) { qz.Mode = models.ModeTest })
|
||||||
|
q2 := models.Question{QuizID: quiz.ID, Text: "Drugie pytanie", Type: models.TypeOpen, Points: 1, SortOrder: 2}
|
||||||
|
must(t, gdb.Create(&q2).Error)
|
||||||
|
uid, aid := startFor(t, "test-otwarty")
|
||||||
|
enq.take()
|
||||||
|
for _, id := range []uint{q.ID, q2.ID} {
|
||||||
|
fb, err := answer(uid, aid, id, "odpowiedź w teście")
|
||||||
|
must(t, err)
|
||||||
|
if !fb.Withheld {
|
||||||
|
t.Errorf("open test feedback is not withheld")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_, err := answer(uid, aid, q.ID, "poprawiona odpowiedź")
|
||||||
|
must(t, err)
|
||||||
|
if got := enq.take(); len(got) != 0 {
|
||||||
|
t.Errorf("answers in a running test enqueued %v", got)
|
||||||
|
}
|
||||||
|
res, err := svc.Finish(ctx, uid, aid)
|
||||||
|
must(t, err)
|
||||||
|
got := enq.take()
|
||||||
|
want := map[jobs.GradeAnswerArgs]bool{
|
||||||
|
{AnswerID: rowOf(t, aid, q.ID).ID, Seq: 2}: true,
|
||||||
|
{AnswerID: rowOf(t, aid, q2.ID).ID, Seq: 1}: true,
|
||||||
|
}
|
||||||
|
if len(got) != 2 || !want[got[0]] || !want[got[1]] || got[0] == got[1] {
|
||||||
|
t.Errorf("Finish enqueued %v, want one job per pending open answer %v", got, want)
|
||||||
|
}
|
||||||
|
if classes.Withheld(&res.Attempt) || res.OpenAnswers != 2 || res.Unreviewed != 2 {
|
||||||
|
t.Errorf("finished result withheld %v open %d unreviewed %d", classes.Withheld(&res.Attempt), res.OpenAnswers, res.Unreviewed)
|
||||||
|
}
|
||||||
|
|
||||||
|
// An expired test closed lazily by Result enqueues too.
|
||||||
|
limit := 60
|
||||||
|
_, q3 := seedOpen(t, "test-czasowy", func(qz *models.Quiz) { qz.Mode = models.ModeTest; qz.TimeLimitSeconds = &limit })
|
||||||
|
uid3, aid3 := startFor(t, "test-czasowy")
|
||||||
|
_, err = answer(uid3, aid3, q3.ID, "zdążyłem")
|
||||||
|
must(t, err)
|
||||||
|
enq.take()
|
||||||
|
late := *svc
|
||||||
|
late.Now = func() time.Time { return time.Now().Add(2 * time.Hour) }
|
||||||
|
_, err = late.Result(ctx, uid3, aid3)
|
||||||
|
must(t, err)
|
||||||
|
if got := enq.take(); len(got) != 1 || got[0].AnswerID != rowOf(t, aid3, q3.ID).ID {
|
||||||
|
t.Errorf("the lazy close enqueued %v, want the one open answer", got)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("text limits", func(t *testing.T) {
|
||||||
|
quiz, _ := seedOpen(t, "limity", nil)
|
||||||
|
five := 5
|
||||||
|
short := models.Question{QuizID: quiz.ID, Text: "Krótko", Type: models.TypeOpen, Points: 1, MaxLength: &five, SortOrder: 2}
|
||||||
|
must(t, gdb.Create(&short).Error)
|
||||||
|
uid, aid := startFor(t, "limity")
|
||||||
|
if _, err := svc.Answer(ctx, uid, aid, classes.AnswerInput{QuestionID: short.ID}); fieldKey(err) != "text:text_required" {
|
||||||
|
t.Errorf("no text: err = %v", err)
|
||||||
|
}
|
||||||
|
if _, err := answer(uid, aid, short.ID, " "); fieldKey(err) != "text:text_required" {
|
||||||
|
t.Errorf("blank text: err = %v", err)
|
||||||
|
}
|
||||||
|
if _, err := answer(uid, aid, short.ID, "abcdef"); fieldKey(err) != "text:text_too_long" {
|
||||||
|
t.Errorf("6 characters with max 5: err = %v", err)
|
||||||
|
}
|
||||||
|
if _, err := answer(uid, aid, short.ID, "żółtą"); err != nil {
|
||||||
|
t.Errorf("5 characters (8 bytes) with max 5: err = %v", err)
|
||||||
|
}
|
||||||
|
enq.take()
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("rollback", func(t *testing.T) {
|
||||||
|
m := updates.AddOpenQuestionsAndGrading()
|
||||||
|
err := m.Rollback(gdb)
|
||||||
|
if err == nil || !strings.Contains(err.Error(), "rollback refused") {
|
||||||
|
t.Fatalf("rollback with open questions = %v, want a refusal", err)
|
||||||
|
}
|
||||||
|
must(t, gdb.Exec(`DELETE FROM golem15_quizzes_questions WHERE type = 'open'`).Error)
|
||||||
|
must(t, m.Rollback(gdb))
|
||||||
|
var quizID uint
|
||||||
|
must(t, gdb.Raw(`SELECT id FROM golem15_quizzes_quizzes ORDER BY id LIMIT 1`).Scan(&quizID).Error)
|
||||||
|
if err := gdb.Exec(`INSERT INTO golem15_quizzes_questions (quiz_id, text, type) VALUES (?, 'Q', 'open')`, quizID).Error; err == nil {
|
||||||
|
t.Error("the rolled-back CHECK still accepts open")
|
||||||
|
}
|
||||||
|
var cols int64
|
||||||
|
must(t, gdb.Raw(`SELECT COUNT(*) FROM information_schema.columns
|
||||||
|
WHERE (table_name = 'golem15_quizzes_attempt_answers' AND column_name IN ('text_answer', 'grading_status', 'reviewed_by_admin_id'))
|
||||||
|
OR (table_name = 'golem15_quizzes_quizzes' AND column_name = 'grader')
|
||||||
|
OR (table_name = 'golem15_quizzes_questions' AND column_name IN ('rubric', 'max_length'))`).Scan(&cols).Error)
|
||||||
|
if cols != 0 {
|
||||||
|
t.Errorf("%d added columns survived the rollback", cols)
|
||||||
|
}
|
||||||
|
must(t, m.Migrate(gdb))
|
||||||
|
must(t, gdb.Exec(`INSERT INTO golem15_quizzes_questions (quiz_id, text, type) VALUES (?, 'Q', 'open')`, quizID).Error)
|
||||||
|
})
|
||||||
|
}
|
||||||
146
plugin.go
146
plugin.go
@@ -3,15 +3,27 @@ package quizzes
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"embed"
|
"embed"
|
||||||
|
"errors"
|
||||||
"io/fs"
|
"io/fs"
|
||||||
|
"net/http"
|
||||||
|
"strconv"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"git.golem15.com/golem15/sm-quizzes-plugin/classes"
|
||||||
"git.golem15.com/golem15/sm-quizzes-plugin/console"
|
"git.golem15.com/golem15/sm-quizzes-plugin/console"
|
||||||
|
"git.golem15.com/golem15/sm-quizzes-plugin/controllers"
|
||||||
|
"git.golem15.com/golem15/sm-quizzes-plugin/graders"
|
||||||
|
"git.golem15.com/golem15/sm-quizzes-plugin/jobs"
|
||||||
"git.golem15.com/golem15/sm-quizzes-plugin/models"
|
"git.golem15.com/golem15/sm-quizzes-plugin/models"
|
||||||
"git.golem15.com/golem15/summercms/modules/backpack"
|
"git.golem15.com/golem15/summercms/modules/backpack"
|
||||||
"git.golem15.com/golem15/summercms/modules/bonfire"
|
"git.golem15.com/golem15/summercms/modules/bonfire"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/bouncer"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/cabana"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/conga"
|
||||||
"git.golem15.com/golem15/summercms/modules/lagoon"
|
"git.golem15.com/golem15/summercms/modules/lagoon"
|
||||||
"git.golem15.com/golem15/summercms/modules/pact"
|
"git.golem15.com/golem15/summercms/modules/pact"
|
||||||
"git.golem15.com/golem15/summercms/modules/party"
|
"git.golem15.com/golem15/summercms/modules/party"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/surf"
|
||||||
"github.com/go-gormigrate/gormigrate/v2"
|
"github.com/go-gormigrate/gormigrate/v2"
|
||||||
"gorm.io/gorm"
|
"gorm.io/gorm"
|
||||||
)
|
)
|
||||||
@@ -28,6 +40,9 @@ var (
|
|||||||
_ pact.AdminAssets = (*Plugin)(nil)
|
_ pact.AdminAssets = (*Plugin)(nil)
|
||||||
_ pact.HasPermissions = (*Plugin)(nil)
|
_ pact.HasPermissions = (*Plugin)(nil)
|
||||||
_ pact.HasNavigation = (*Plugin)(nil)
|
_ pact.HasNavigation = (*Plugin)(nil)
|
||||||
|
|
||||||
|
_ pact.HasFrontendPermissions = (*Plugin)(nil)
|
||||||
|
_ surf.BucketProvider = (*Plugin)(nil)
|
||||||
)
|
)
|
||||||
|
|
||||||
//go:embed config
|
//go:embed config
|
||||||
@@ -39,12 +54,14 @@ var langFS embed.FS
|
|||||||
//go:embed views/mail
|
//go:embed views/mail
|
||||||
var mailFS embed.FS
|
var mailFS embed.FS
|
||||||
|
|
||||||
//go:embed controllers/*/*.yaml models/*/*.yaml
|
//go:embed controllers/*/*.yaml controllers/*/*.htm models/*/*.yaml
|
||||||
var adminFS embed.FS
|
var adminFS embed.FS
|
||||||
|
|
||||||
// Plugin is the golem15.quizzes plugin.
|
// Plugin is the golem15.quizzes plugin.
|
||||||
type Plugin struct {
|
type Plugin struct {
|
||||||
app *backpack.App
|
app *backpack.App
|
||||||
|
// graders is the grader registry built at Boot.
|
||||||
|
graders *graders.Registry
|
||||||
}
|
}
|
||||||
|
|
||||||
func (p *Plugin) ID() string { return "golem15.quizzes" }
|
func (p *Plugin) ID() string { return "golem15.quizzes" }
|
||||||
@@ -60,10 +77,18 @@ func (p *Plugin) Register(app *backpack.App) error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// Boot keeps the application and points the admin filter choices at its
|
// Boot keeps the application, collects the grader registry and points the
|
||||||
// database.
|
// admin hooks at it: the filter choices and the review screen at its
|
||||||
|
// database, the quiz grader dropdown at the registry.
|
||||||
|
//
|
||||||
|
// Grading plugins never register themselves: golem15.quizzes pulls their
|
||||||
|
// graders through graders.HasGraders, as golem15.paymentgateway pulls
|
||||||
|
// payment operators.
|
||||||
func (p *Plugin) Boot(app *backpack.App) error {
|
func (p *Plugin) Boot(app *backpack.App) error {
|
||||||
p.app = app
|
p.app = app
|
||||||
|
if err := bootGraders(p, app); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
models.FilterDB = func() *gorm.DB {
|
models.FilterDB = func() *gorm.DB {
|
||||||
if app == nil {
|
if app == nil {
|
||||||
return nil
|
return nil
|
||||||
@@ -71,9 +96,59 @@ func (p *Plugin) Boot(app *backpack.App) error {
|
|||||||
gdb, _ := app.Lookup[*gorm.DB]()
|
gdb, _ := app.Lookup[*gorm.DB]()
|
||||||
return gdb
|
return gdb
|
||||||
}
|
}
|
||||||
|
controllers.GraderOptions = p.graders.Options
|
||||||
|
controllers.Reviews = func(ctx context.Context) *classes.Service {
|
||||||
|
return reviewService(ctx, app)
|
||||||
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// reviewService is the admin review screen's service: over the admin
|
||||||
|
// request's write transaction when there is one, so a review nests in the
|
||||||
|
// save, else over the application's database.
|
||||||
|
func reviewService(ctx context.Context, app *backpack.App) *classes.Service {
|
||||||
|
if tx, ok := cabana.TxFromContext(ctx); ok && tx != nil {
|
||||||
|
return classes.ForApp(app, tx)
|
||||||
|
}
|
||||||
|
if app == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
gdb, ok := app.Lookup[*gorm.DB]()
|
||||||
|
if !ok || gdb == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return classes.ForApp(app, gdb)
|
||||||
|
}
|
||||||
|
|
||||||
|
// bootGraders builds the grader registry: manual first, then the graders of
|
||||||
|
// every other activated plugin that implements graders.HasGraders, in
|
||||||
|
// activation order. A duplicate or reserved code fails boot. The registry
|
||||||
|
// is kept on p and published on the app as *graders.Registry.
|
||||||
|
func bootGraders(p *Plugin, app *backpack.App) error {
|
||||||
|
reg := graders.NewRegistry()
|
||||||
|
if app == nil {
|
||||||
|
p.graders = reg
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
activated, _ := app.Lookup[party.Activated]()
|
||||||
|
for _, plugin := range activated {
|
||||||
|
if plugin == nil || plugin.ID() == p.ID() {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
hg, ok := plugin.(graders.HasGraders)
|
||||||
|
if !ok {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
for _, g := range hg.QuizGraders() {
|
||||||
|
if err := reg.Add(plugin.ID(), g); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
p.graders = reg
|
||||||
|
return app.Publish(reg)
|
||||||
|
}
|
||||||
|
|
||||||
func (p *Plugin) ConfigFS() fs.FS { return configFS }
|
func (p *Plugin) ConfigFS() fs.FS { return configFS }
|
||||||
func (p *Plugin) LangFS() fs.FS { return langFS }
|
func (p *Plugin) LangFS() fs.FS { return langFS }
|
||||||
|
|
||||||
@@ -83,7 +158,27 @@ func (p *Plugin) MailLayouts() map[string]string { return nil }
|
|||||||
|
|
||||||
func (p *Plugin) Models() []any { return generatedModels() }
|
func (p *Plugin) Models() []any { return generatedModels() }
|
||||||
func (p *Plugin) Migrations() []*gormigrate.Migration { return generatedMigrations() }
|
func (p *Plugin) Migrations() []*gormigrate.Migration { return generatedMigrations() }
|
||||||
func (p *Plugin) Jobs() []pact.Job { return generatedJobs() }
|
|
||||||
|
// Jobs returns the generated jobs plus the grading job: one open answer per
|
||||||
|
// job on its own queue, GradeMaxAttempts attempts, each with GradeTimeout.
|
||||||
|
func (p *Plugin) Jobs() []pact.Job {
|
||||||
|
return append(generatedJobs(), conga.Job(p.gradeAnswer,
|
||||||
|
conga.OnQueue(jobs.Queue),
|
||||||
|
conga.MaxAttempts(classes.GradeMaxAttempts),
|
||||||
|
conga.Timeout(classes.GradeTimeout)))
|
||||||
|
}
|
||||||
|
|
||||||
|
// gradeAnswer runs one grading job on the application's database.
|
||||||
|
func (p *Plugin) gradeAnswer(ctx context.Context, args jobs.GradeAnswerArgs) error {
|
||||||
|
var gdb *gorm.DB
|
||||||
|
if p.app != nil {
|
||||||
|
gdb, _ = p.app.Lookup[*gorm.DB]()
|
||||||
|
}
|
||||||
|
if gdb == nil {
|
||||||
|
return errors.New("quizzes: database unavailable")
|
||||||
|
}
|
||||||
|
return classes.ForApp(p.app, gdb).GradeAnswer(ctx, args.AnswerID, args.Seq)
|
||||||
|
}
|
||||||
func (p *Plugin) AdminControllers() []pact.AdminController {
|
func (p *Plugin) AdminControllers() []pact.AdminController {
|
||||||
return generatedAdminControllers()
|
return generatedAdminControllers()
|
||||||
}
|
}
|
||||||
@@ -115,11 +210,51 @@ func (p *Plugin) AdminFS() fs.FS { return adminFS }
|
|||||||
// Permissions declares the admin permissions.
|
// Permissions declares the admin permissions.
|
||||||
func (p *Plugin) Permissions() []pact.Permission {
|
func (p *Plugin) Permissions() []pact.Permission {
|
||||||
return []pact.Permission{
|
return []pact.Permission{
|
||||||
{Code: "golem15.quizzes.access_quizzes", Tab: "golem15.quizzes::lang.plugin.name", Label: "golem15.quizzes::lang.permissions.access_quizzes"},
|
{Code: permQuizzes, Tab: "golem15.quizzes::lang.plugin.name", Label: "golem15.quizzes::lang.permissions.access_quizzes"},
|
||||||
{Code: "golem15.quizzes.access_attempts", Tab: "golem15.quizzes::lang.plugin.name", Label: "golem15.quizzes::lang.permissions.access_attempts"},
|
{Code: "golem15.quizzes.access_attempts", Tab: "golem15.quizzes::lang.plugin.name", Label: "golem15.quizzes::lang.permissions.access_attempts"},
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// FrontendPermissions declares the code the owner manage routes check (the
|
||||||
|
// MCP quiz tools), so golem15.user's User Groups editor can grant it.
|
||||||
|
// Declaring it grants nothing by itself.
|
||||||
|
func (p *Plugin) FrontendPermissions() []pact.FrontendPermission {
|
||||||
|
return []pact.FrontendPermission{{
|
||||||
|
Code: permQuizzes,
|
||||||
|
Label: "golem15.quizzes::lang.permissions.access_quizzes",
|
||||||
|
Tab: "golem15.quizzes::lang.plugin.name",
|
||||||
|
}}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Buckets declares the per-user rate limits: the owner manage routes
|
||||||
|
// (building a quiz question by question is chatty, so 120 calls a minute),
|
||||||
|
// and the student's answers and attempt starts, configurable as
|
||||||
|
// golem15.quizzes.throttle.answers_per_minute and attempts_per_minute. A
|
||||||
|
// request without a user (never after user.api_token or jwt.auth) keys by
|
||||||
|
// client IP.
|
||||||
|
func (p *Plugin) Buckets() map[string]surf.Bucket {
|
||||||
|
trusted := surf.TrustedProxies(nil)
|
||||||
|
answers, starts := classes.DefaultAnswersPerMinute, classes.DefaultAttemptsPerMinute
|
||||||
|
if p != nil && p.app != nil {
|
||||||
|
trusted = surf.TrustedProxies(p.app.Config)
|
||||||
|
answers = classes.PerMinuteFrom(p.app.Config, "golem15.quizzes.throttle.answers_per_minute", answers)
|
||||||
|
starts = classes.PerMinuteFrom(p.app.Config, "golem15.quizzes.throttle.attempts_per_minute", starts)
|
||||||
|
}
|
||||||
|
byUser := func(prefix string) func(*http.Request) string {
|
||||||
|
return func(r *http.Request) string {
|
||||||
|
if u, ok := bouncer.User(r.Context()); ok && u.ID != 0 {
|
||||||
|
return prefix + "|u:" + strconv.FormatUint(uint64(u.ID), 10)
|
||||||
|
}
|
||||||
|
return prefix + "|ip:" + surf.ClientIP(r, trusted)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return map[string]surf.Bucket{
|
||||||
|
bucketManage: {Max: 120, Decay: time.Minute, Key: byUser(bucketManage)},
|
||||||
|
bucketAnswer: {Max: answers, Decay: time.Minute, Key: byUser(bucketAnswer)},
|
||||||
|
bucketStart: {Max: starts, Decay: time.Minute, Key: byUser(bucketStart)},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Navigation declares the "Quizzes" admin menu with its side menu.
|
// Navigation declares the "Quizzes" admin menu with its side menu.
|
||||||
func (p *Plugin) Navigation() []pact.NavigationItem {
|
func (p *Plugin) Navigation() []pact.NavigationItem {
|
||||||
return []pact.NavigationItem{{
|
return []pact.NavigationItem{{
|
||||||
@@ -132,6 +267,7 @@ func (p *Plugin) Navigation() []pact.NavigationItem {
|
|||||||
{Code: "quizzes", Label: "golem15.quizzes::lang.quizzes.title", Icon: "icon-list", Controller: "golem15.quizzes.quizzes", Permissions: []string{"golem15.quizzes.access_quizzes"}},
|
{Code: "quizzes", Label: "golem15.quizzes::lang.quizzes.title", Icon: "icon-list", Controller: "golem15.quizzes.quizzes", Permissions: []string{"golem15.quizzes.access_quizzes"}},
|
||||||
{Code: "questions", Label: "golem15.quizzes::lang.questions.title", Icon: "icon-question", Controller: "golem15.quizzes.questions", Permissions: []string{"golem15.quizzes.access_quizzes"}},
|
{Code: "questions", Label: "golem15.quizzes::lang.questions.title", Icon: "icon-question", Controller: "golem15.quizzes.questions", Permissions: []string{"golem15.quizzes.access_quizzes"}},
|
||||||
{Code: "answers", Label: "golem15.quizzes::lang.answers.title", Icon: "icon-check-square", Controller: "golem15.quizzes.answers", Permissions: []string{"golem15.quizzes.access_quizzes"}},
|
{Code: "answers", Label: "golem15.quizzes::lang.answers.title", Icon: "icon-check-square", Controller: "golem15.quizzes.answers", Permissions: []string{"golem15.quizzes.access_quizzes"}},
|
||||||
|
{Code: "reviews", Label: "golem15.quizzes::lang.reviews.title", Icon: "icon-check", Controller: "golem15.quizzes.reviews", Permissions: []string{"golem15.quizzes.access_quizzes"}},
|
||||||
{Code: "attempts", Label: "golem15.quizzes::lang.attempts.title", Icon: "icon-bar-chart", Controller: "golem15.quizzes.attempts", Permissions: []string{"golem15.quizzes.access_attempts"}},
|
{Code: "attempts", Label: "golem15.quizzes::lang.attempts.title", Icon: "icon-bar-chart", Controller: "golem15.quizzes.attempts", Permissions: []string{"golem15.quizzes.access_attempts"}},
|
||||||
},
|
},
|
||||||
}}
|
}}
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ id: golem15.quizzes
|
|||||||
module: git.golem15.com/golem15/sm-quizzes-plugin
|
module: git.golem15.com/golem15/sm-quizzes-plugin
|
||||||
package: git.golem15.com/golem15/sm-quizzes-plugin
|
package: git.golem15.com/golem15/sm-quizzes-plugin
|
||||||
name: Quizzes
|
name: Quizzes
|
||||||
description: "A reusable quiz plugin for SummerCMS applications: quizzes with single-choice, multiple-choice and self-check (flashcard) questions, scored attempts for signed-in users, an admin backend and a JSON importer."
|
description: "A reusable quiz plugin for SummerCMS applications: quizzes with single-choice, multiple-choice, self-check (flashcard) and open questions answered in free text, a learning and a test mode that withholds solutions until an attempt is finished, scored attempts for signed-in users, open answers graded by the owner or by a grader another plugin provides, with an owner review queue, an admin backend, a JSON importer and owner management over a token API and MCP tools."
|
||||||
framework: v0.6.0
|
framework: v0.6.0
|
||||||
requires:
|
requires:
|
||||||
golem15.user: v0.1.0
|
golem15.user: v0.1.0
|
||||||
|
|||||||
@@ -36,11 +36,15 @@ func TestPluginActivates(t *testing.T) {
|
|||||||
if got := p.Requires(); !slices.Equal(got, []string{"golem15.user"}) {
|
if got := p.Requires(); !slices.Equal(got, []string{"golem15.user"}) {
|
||||||
t.Errorf("Requires = %v, want golem15.user", got)
|
t.Errorf("Requires = %v, want golem15.user", got)
|
||||||
}
|
}
|
||||||
if got := len(p.(pact.HasModels).Models()); got != 5 {
|
if got := len(p.(pact.HasModels).Models()); got != 6 {
|
||||||
t.Errorf("Models = %d, want 5", got)
|
t.Errorf("Models = %d, want 6", got)
|
||||||
}
|
}
|
||||||
if len(p.(pact.HasMigrations).Migrations()) == 0 {
|
migrations := p.(pact.HasMigrations).Migrations()
|
||||||
t.Error("no migrations")
|
if len(migrations) == 0 {
|
||||||
|
t.Fatal("no migrations")
|
||||||
|
}
|
||||||
|
if got := migrations[len(migrations)-1].ID; got != "20261109180000_add_open_questions_and_grading" {
|
||||||
|
t.Errorf("last migration = %s, want 20261109180000_add_open_questions_and_grading", got)
|
||||||
}
|
}
|
||||||
if app.Config.Bool("golem15.quizzes.scoring.multiple_partial") {
|
if app.Config.Bool("golem15.quizzes.scoring.multiple_partial") {
|
||||||
t.Error("scoring.multiple_partial defaults to true, want false")
|
t.Error("scoring.multiple_partial defaults to true, want false")
|
||||||
@@ -65,6 +69,24 @@ func TestRoutesRegistered(t *testing.T) {
|
|||||||
"POST /_quizzes/api/v1/attempts/{id}/answers",
|
"POST /_quizzes/api/v1/attempts/{id}/answers",
|
||||||
"POST /_quizzes/api/v1/attempts/{id}/finish",
|
"POST /_quizzes/api/v1/attempts/{id}/finish",
|
||||||
"POST /api/v1/quizzes/import",
|
"POST /api/v1/quizzes/import",
|
||||||
|
"GET /api/v1/quizzes",
|
||||||
|
"GET /api/v1/quizzes/{slug}",
|
||||||
|
"POST /api/v1/quizzes",
|
||||||
|
"PATCH /api/v1/quizzes/{slug}",
|
||||||
|
"DELETE /api/v1/quizzes/{slug}",
|
||||||
|
"POST /api/v1/quizzes/{slug}/publish",
|
||||||
|
"POST /api/v1/quizzes/{slug}/unpublish",
|
||||||
|
"GET /api/v1/quizzes/{slug}/stats",
|
||||||
|
"POST /api/v1/quizzes/{slug}/questions",
|
||||||
|
"PATCH /api/v1/quizzes/{slug}/questions/{id}",
|
||||||
|
"DELETE /api/v1/quizzes/{slug}/questions/{id}",
|
||||||
|
"PUT /api/v1/quizzes/{slug}/questions/order",
|
||||||
|
"GET /api/v1/quiz-reviews",
|
||||||
|
"GET /api/v1/quiz-reviews/{id}",
|
||||||
|
"POST /api/v1/quiz-reviews/{id}/confirm",
|
||||||
|
"POST /api/v1/quiz-reviews/{id}/score",
|
||||||
|
"POST /api/v1/quiz-reviews/confirm",
|
||||||
|
"POST /api/v1/quiz-reviews/regrade",
|
||||||
}
|
}
|
||||||
var got []string
|
var got []string
|
||||||
for _, r := range router.Routes() {
|
for _, r := range router.Routes() {
|
||||||
@@ -80,6 +102,18 @@ func TestRoutesRegistered(t *testing.T) {
|
|||||||
}
|
}
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
if r.Pattern == "/api/v1/quizzes" || strings.HasPrefix(r.Pattern, "/api/v1/quizzes/") ||
|
||||||
|
r.Pattern == "/api/v1/quiz-reviews" || strings.HasPrefix(r.Pattern, "/api/v1/quiz-reviews/") {
|
||||||
|
for _, mw := range []string{"user.api_token", "throttle:golem15.quizzes.manage", "user.permission:golem15.quizzes.access_quizzes"} {
|
||||||
|
if !slices.Contains(r.Middleware, mw) {
|
||||||
|
t.Errorf("%s %s is not behind %s: %v", r.Method, r.Pattern, mw, r.Middleware)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !slices.Contains(r.Middleware, "user.scope:read") && !slices.Contains(r.Middleware, "user.scope:write") {
|
||||||
|
t.Errorf("%s %s has no token scope: %v", r.Method, r.Pattern, r.Middleware)
|
||||||
|
}
|
||||||
|
continue
|
||||||
|
}
|
||||||
if !slices.Contains(r.Middleware, "jwt.auth") {
|
if !slices.Contains(r.Middleware, "jwt.auth") {
|
||||||
t.Errorf("%s %s is not behind jwt.auth: %v", r.Method, r.Pattern, r.Middleware)
|
t.Errorf("%s %s is not behind jwt.auth: %v", r.Method, r.Pattern, r.Middleware)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -18,6 +18,7 @@ func generatedModels() []any {
|
|||||||
&models.AttemptAnswer{},
|
&models.AttemptAnswer{},
|
||||||
&models.Question{},
|
&models.Question{},
|
||||||
&models.Quiz{},
|
&models.Quiz{},
|
||||||
|
&models.Review{},
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -26,6 +27,8 @@ func generatedMigrations() []*gormigrate.Migration {
|
|||||||
updates.CreateQuizzesTables(),
|
updates.CreateQuizzesTables(),
|
||||||
updates.AddCategoryToAttempts(),
|
updates.AddCategoryToAttempts(),
|
||||||
updates.AddCompletedAttemptsIndex(),
|
updates.AddCompletedAttemptsIndex(),
|
||||||
|
updates.AddTestModeToQuizzes(),
|
||||||
|
updates.AddOpenQuestionsAndGrading(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -43,5 +46,6 @@ func generatedAdminControllers() []pact.AdminController {
|
|||||||
controllers.AttemptsController(),
|
controllers.AttemptsController(),
|
||||||
controllers.QuestionsController(),
|
controllers.QuestionsController(),
|
||||||
controllers.QuizzesController(),
|
controllers.QuizzesController(),
|
||||||
|
controllers.ReviewsController(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
488
reviews_postgres_test.go
Normal file
488
reviews_postgres_test.go
Normal file
@@ -0,0 +1,488 @@
|
|||||||
|
package quizzes_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"git.golem15.com/golem15/sm-quizzes-plugin/classes"
|
||||||
|
"git.golem15.com/golem15/sm-quizzes-plugin/controllers/api"
|
||||||
|
"git.golem15.com/golem15/sm-quizzes-plugin/events"
|
||||||
|
"git.golem15.com/golem15/sm-quizzes-plugin/graders"
|
||||||
|
"git.golem15.com/golem15/sm-quizzes-plugin/models"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/bouncer"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/surf"
|
||||||
|
"gorm.io/gorm"
|
||||||
|
)
|
||||||
|
|
||||||
|
// TestReviewsAgainstDatabase covers the owner review routes the
|
||||||
|
// quizzes_review_* MCP tools bind (D-10..D-14): the permission matrix, the
|
||||||
|
// queue and its filters, the detail, confirm, set_score with a comment the
|
||||||
|
// student sees, bulk confirm with the AttemptReviewed event, regrade
|
||||||
|
// through the quiz's grader, and the recalculation of finished attempts.
|
||||||
|
// Skipped under -short; it runs in the verification phase.
|
||||||
|
func TestReviewsAgainstDatabase(t *testing.T) {
|
||||||
|
if testing.Short() {
|
||||||
|
t.Skip("Postgres test; runs in the verification phase")
|
||||||
|
}
|
||||||
|
app, plugins, gdb := migrated(t)
|
||||||
|
reg, ok := app.Lookup[*graders.Registry]()
|
||||||
|
if !ok || reg == nil {
|
||||||
|
t.Fatal("golem15.quizzes published no grader registry")
|
||||||
|
}
|
||||||
|
grader := &fakeGrader{}
|
||||||
|
must(t, reg.Add("acme.test", grader))
|
||||||
|
if app.Events == nil {
|
||||||
|
t.Fatal("the app has no event bus")
|
||||||
|
}
|
||||||
|
var (
|
||||||
|
evMu sync.Mutex
|
||||||
|
reviewed []*events.AnswerReviewedEvent
|
||||||
|
done []*events.AttemptReviewedEvent
|
||||||
|
)
|
||||||
|
app.Events.Listen[*events.AnswerReviewedEvent]("acme.test", func(_ context.Context, e *events.AnswerReviewedEvent) error {
|
||||||
|
evMu.Lock()
|
||||||
|
defer evMu.Unlock()
|
||||||
|
reviewed = append(reviewed, e)
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
app.Events.Listen[*events.AttemptReviewedEvent]("acme.test", func(_ context.Context, e *events.AttemptReviewedEvent) error {
|
||||||
|
evMu.Lock()
|
||||||
|
defer evMu.Unlock()
|
||||||
|
done = append(done, e)
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
takeEvents := func() ([]*events.AnswerReviewedEvent, []*events.AttemptReviewedEvent) {
|
||||||
|
evMu.Lock()
|
||||||
|
defer evMu.Unlock()
|
||||||
|
a, b := reviewed, done
|
||||||
|
reviewed, done = nil, nil
|
||||||
|
return a, b
|
||||||
|
}
|
||||||
|
|
||||||
|
h, err := surf.Assemble(app, plugins)
|
||||||
|
must(t, err)
|
||||||
|
c := &client{t: t, h: h}
|
||||||
|
const prefix = "/api/v1/quiz-reviews"
|
||||||
|
|
||||||
|
owner, _ := newUser(t, gdb, "owner@example.com")
|
||||||
|
stranger, _ := newUser(t, gdb, "stranger@example.com")
|
||||||
|
var groupID uint
|
||||||
|
must(t, gdb.Raw(`INSERT INTO user_groups (name, code, permissions, created_at, updated_at)
|
||||||
|
VALUES ('Editors', 'editors', '{"golem15.quizzes.access_quizzes":1}', NOW(), NOW()) RETURNING id`).Scan(&groupID).Error)
|
||||||
|
must(t, gdb.Exec(`INSERT INTO users_groups (user_id, user_group_id) VALUES (?, ?)`, owner.ID, groupID).Error)
|
||||||
|
token := apiToken(t, gdb, owner.ID, "read", "write")
|
||||||
|
readOnly := apiToken(t, gdb, owner.ID, "read")
|
||||||
|
|
||||||
|
// seed writes a published quiz with two open questions worth 2 points.
|
||||||
|
seed := func(t *testing.T, slug, code, mode string) (models.Quiz, models.Question, models.Question) {
|
||||||
|
t.Helper()
|
||||||
|
quiz := models.Quiz{Title: "Eseje " + slug, Slug: slug, IsPublished: true, PassingScore: 50, Grader: code, Mode: mode}
|
||||||
|
must(t, gdb.Create(&quiz).Error)
|
||||||
|
q1 := models.Question{QuizID: quiz.ID, Text: "Wyjaśnij odstraszanie.", Type: models.TypeOpen,
|
||||||
|
AnswerText: strPtr("MODEL"), Rubric: strPtr("R-RUBRIC"), Points: 2, SortOrder: 1}
|
||||||
|
q2 := models.Question{QuizID: quiz.ID, Text: "Opisz dylemat bezpieczeństwa.", Type: models.TypeOpen,
|
||||||
|
AnswerText: strPtr("MODEL 2"), Rubric: strPtr("R-RUBRIC 2"), Points: 2, SortOrder: 2}
|
||||||
|
must(t, gdb.Create(&q1).Error)
|
||||||
|
must(t, gdb.Create(&q2).Error)
|
||||||
|
return quiz, q1, q2
|
||||||
|
}
|
||||||
|
// attempt is one student's attempt with an answer to each question,
|
||||||
|
// finished when finish is set. It returns the user, the student JWT and
|
||||||
|
// the attempt id.
|
||||||
|
attempt := func(t *testing.T, email, slug string, finish bool, questions ...models.Question) (uint, string, uint) {
|
||||||
|
t.Helper()
|
||||||
|
u, jwt := newUser(t, gdb, email)
|
||||||
|
att := data(c.ok(http.StatusCreated, "POST", apiPrefix+"/quizzes/"+slug+"/attempts", jwt, ""))
|
||||||
|
id := uint(att["id"].(float64))
|
||||||
|
for i, q := range questions {
|
||||||
|
c.ok(http.StatusOK, "POST", fmt.Sprintf("%s/attempts/%d/answers", apiPrefix, id), jwt,
|
||||||
|
fmt.Sprintf(`{"question_id":%d,"text":"Odpowiedź %d studenta %s."}`, q.ID, i+1, email))
|
||||||
|
}
|
||||||
|
if finish {
|
||||||
|
c.ok(http.StatusOK, "POST", fmt.Sprintf("%s/attempts/%d/finish", apiPrefix, id), jwt, "")
|
||||||
|
}
|
||||||
|
return u.ID, jwt, id
|
||||||
|
}
|
||||||
|
answerID := func(t *testing.T, attemptID, questionID uint) uint {
|
||||||
|
t.Helper()
|
||||||
|
var row models.AttemptAnswer
|
||||||
|
must(t, gdb.Where("attempt_id = ? AND question_id = ?", attemptID, questionID).Take(&row).Error)
|
||||||
|
return row.ID
|
||||||
|
}
|
||||||
|
// grade stores a grader result directly, as the grading job would.
|
||||||
|
grade := func(t *testing.T, id uint, points float64) {
|
||||||
|
t.Helper()
|
||||||
|
must(t, gdb.Exec(`UPDATE golem15_quizzes_attempt_answers SET grading_status = 'graded', grader = 'fake',
|
||||||
|
grader_points = ?, points = ?, grader_feedback = 'Dobrze.', graded_at = NOW(), updated_at = NOW() WHERE id = ?`, points, points, id).Error)
|
||||||
|
}
|
||||||
|
fail := func(t *testing.T, id uint) {
|
||||||
|
t.Helper()
|
||||||
|
must(t, gdb.Exec(`UPDATE golem15_quizzes_attempt_answers SET grading_status = 'failed', grader = 'fake',
|
||||||
|
grading_attempts = 3, grading_error = 'grader timed out', updated_at = NOW() WHERE id = ?`, id).Error)
|
||||||
|
}
|
||||||
|
attemptRow := func(t *testing.T, id uint) models.Attempt {
|
||||||
|
t.Helper()
|
||||||
|
var a models.Attempt
|
||||||
|
must(t, gdb.Where("id = ?", id).Take(&a).Error)
|
||||||
|
return a
|
||||||
|
}
|
||||||
|
statusOf := func(t *testing.T, id uint) string {
|
||||||
|
t.Helper()
|
||||||
|
var row models.AttemptAnswer
|
||||||
|
must(t, gdb.Where("id = ?", id).Take(&row).Error)
|
||||||
|
if row.GradingStatus == nil {
|
||||||
|
return "<nil>"
|
||||||
|
}
|
||||||
|
return *row.GradingStatus
|
||||||
|
}
|
||||||
|
meta := func(m map[string]any) map[string]any { d, _ := m["meta"].(map[string]any); return d }
|
||||||
|
|
||||||
|
quiz, q1, q2 := seed(t, "eseje", "fake", models.ModeLearning)
|
||||||
|
u1, jwt1, a1 := attempt(t, "s1@example.com", quiz.Slug, true, q1, q2)
|
||||||
|
u2, _, a2 := attempt(t, "s2@example.com", quiz.Slug, true, q1, q2)
|
||||||
|
a1q1, a1q2 := answerID(t, a1, q1.ID), answerID(t, a1, q2.ID)
|
||||||
|
a2q1, a2q2 := answerID(t, a2, q1.ID), answerID(t, a2, q2.ID)
|
||||||
|
grade(t, a1q1, 1.5)
|
||||||
|
fail(t, a2q2)
|
||||||
|
|
||||||
|
t.Run("permissions", func(t *testing.T) {
|
||||||
|
for name, tc := range map[string]struct {
|
||||||
|
method, path, token string
|
||||||
|
want int
|
||||||
|
}{
|
||||||
|
"no token on the list": {"GET", prefix, "", http.StatusUnauthorized},
|
||||||
|
"no token on confirm": {"POST", fmt.Sprintf("%s/%d/confirm", prefix, a1q1), "", http.StatusUnauthorized},
|
||||||
|
"user without permission": {"GET", prefix, apiToken(t, gdb, stranger.ID, "read", "write"), http.StatusForbidden},
|
||||||
|
"no permission on regrade": {"POST", prefix + "/regrade", apiToken(t, gdb, stranger.ID, "read", "write"), http.StatusForbidden},
|
||||||
|
"read token on confirm": {"POST", fmt.Sprintf("%s/%d/confirm", prefix, a1q1), readOnly, http.StatusForbidden},
|
||||||
|
"read token on set_score": {"POST", fmt.Sprintf("%s/%d/score", prefix, a1q1), readOnly, http.StatusForbidden},
|
||||||
|
"read token on bulk confirm": {"POST", prefix + "/confirm", readOnly, http.StatusForbidden},
|
||||||
|
"read token on regrade": {"POST", prefix + "/regrade", readOnly, http.StatusForbidden},
|
||||||
|
"student session JWT": {"GET", prefix, jwt1, http.StatusUnauthorized},
|
||||||
|
} {
|
||||||
|
body := ""
|
||||||
|
if tc.method == "POST" {
|
||||||
|
body = `{"points":1,"quiz":"eseje"}`
|
||||||
|
}
|
||||||
|
if code, _ := c.do(tc.method, tc.path, tc.token, body); code != tc.want {
|
||||||
|
t.Errorf("%s: %s %s = %d, want %d", name, tc.method, tc.path, code, tc.want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if code, _ := c.do("GET", prefix, readOnly, ""); code != http.StatusOK {
|
||||||
|
t.Errorf("read token on the list = %d, want 200", code)
|
||||||
|
}
|
||||||
|
if statusOf(t, a1q1) != models.GradingGraded {
|
||||||
|
t.Error("a refused confirm changed the answer")
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("queue", func(t *testing.T) {
|
||||||
|
out := c.ok(http.StatusOK, "GET", prefix, token, "")
|
||||||
|
rows := list(out)
|
||||||
|
if len(rows) != 4 || meta(out)["total"] != float64(4) {
|
||||||
|
t.Fatalf("open queue = %d rows, meta %v; want 4", len(rows), meta(out))
|
||||||
|
}
|
||||||
|
first := rows[0].(map[string]any)
|
||||||
|
for _, key := range []string{"answer_id", "status", "quiz", "question", "attempt", "student", "text", "text_truncated", "grader_points", "points", "graded_at", "reviewed_at", "updated_at"} {
|
||||||
|
if _, ok := first[key]; !ok {
|
||||||
|
t.Errorf("row lacks %q: %v", key, first)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if strings.Contains(fmt.Sprint(rows), "R-RUBRIC") || strings.Contains(fmt.Sprint(rows), "MODEL") {
|
||||||
|
t.Error("a queue row carries the rubric or the model answer")
|
||||||
|
}
|
||||||
|
count := func(query string) int {
|
||||||
|
t.Helper()
|
||||||
|
return len(list(c.ok(http.StatusOK, "GET", prefix+query, token, "")))
|
||||||
|
}
|
||||||
|
for query, want := range map[string]int{
|
||||||
|
"?status=pending": 2,
|
||||||
|
"?status=graded": 1,
|
||||||
|
"?status=failed": 1,
|
||||||
|
"?status=reviewed": 0,
|
||||||
|
"?status=all": 4,
|
||||||
|
"?quiz=eseje": 4,
|
||||||
|
"?quiz=nie-ma": 0,
|
||||||
|
"?user_id=" + fmt.Sprint(u1): 2,
|
||||||
|
"?attempt_id=" + fmt.Sprint(a2): 2,
|
||||||
|
"?user_id=" + fmt.Sprint(u2) + "&status=failed": 1,
|
||||||
|
} {
|
||||||
|
if got := count(query); got != want {
|
||||||
|
t.Errorf("%s = %d rows, want %d", query, got, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
failed := list(c.ok(http.StatusOK, "GET", prefix+"?status=failed", token, ""))
|
||||||
|
if row := failed[0].(map[string]any); row["status"] != "failed" || row["answer_id"] != float64(a2q2) {
|
||||||
|
t.Errorf("failed row = %v", row)
|
||||||
|
}
|
||||||
|
student := first["student"].(map[string]any)
|
||||||
|
if !strings.HasSuffix(student["email"].(string), "@example.com") {
|
||||||
|
t.Errorf("student = %v", student)
|
||||||
|
}
|
||||||
|
page := c.ok(http.StatusOK, "GET", prefix+"?per_page=1&page=2", token, "")
|
||||||
|
if len(list(page)) != 1 || meta(page)["last_page"] != float64(4) || meta(page)["current_page"] != float64(2) {
|
||||||
|
t.Errorf("page 2 of 4 = %v", meta(page))
|
||||||
|
}
|
||||||
|
if code, _ := c.do("GET", prefix+"?status=done", token, ""); code != http.StatusUnprocessableEntity {
|
||||||
|
t.Errorf("status=done = %d, want 422", code)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("show", func(t *testing.T) {
|
||||||
|
out := data(c.ok(http.StatusOK, "GET", fmt.Sprintf("%s/%d", prefix, a2q2), token, ""))
|
||||||
|
q := out["question"].(map[string]any)
|
||||||
|
if q["rubric"] != "R-RUBRIC 2" || q["answer_text"] != "MODEL 2" || q["max_length"] != float64(models.DefaultMaxLength) {
|
||||||
|
t.Errorf("question = %v", q)
|
||||||
|
}
|
||||||
|
if out["grading_error"] != "grader timed out" || out["grading_attempts"] != float64(3) || out["status"] != "failed" {
|
||||||
|
t.Errorf("failed detail = %v", out)
|
||||||
|
}
|
||||||
|
if !strings.HasPrefix(out["text"].(string), "Odpowiedź 2") {
|
||||||
|
t.Errorf("text = %v", out["text"])
|
||||||
|
}
|
||||||
|
must(t, gdb.Exec(`UPDATE golem15_quizzes_attempt_answers SET grading_status = NULL WHERE id = ?`, a2q1).Error)
|
||||||
|
if code, _ := c.do("GET", fmt.Sprintf("%s/%d", prefix, a2q1), token, ""); code != http.StatusNotFound {
|
||||||
|
t.Errorf("an answer that is not open = %d, want 404", code)
|
||||||
|
}
|
||||||
|
must(t, gdb.Exec(`UPDATE golem15_quizzes_attempt_answers SET grading_status = 'pending' WHERE id = ?`, a2q1).Error)
|
||||||
|
if code, _ := c.do("GET", prefix+"/999999", token, ""); code != http.StatusNotFound {
|
||||||
|
t.Errorf("missing answer = %d, want 404", code)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("confirm", func(t *testing.T) {
|
||||||
|
takeEvents()
|
||||||
|
out := data(c.ok(http.StatusOK, "POST", fmt.Sprintf("%s/%d/confirm", prefix, a1q1), token, ""))
|
||||||
|
by := out["reviewed_by"].(map[string]any)
|
||||||
|
if out["status"] != "reviewed" || out["points"] != float64(1.5) || out["reviewed_at"] == nil || by["user_id"] != float64(owner.ID) || by["admin_id"] != nil {
|
||||||
|
t.Errorf("confirmed = %v", out)
|
||||||
|
}
|
||||||
|
again := data(c.ok(http.StatusOK, "POST", fmt.Sprintf("%s/%d/confirm", prefix, a1q1), token, ""))
|
||||||
|
if again["reviewed_at"] != out["reviewed_at"] || again["points"] != float64(1.5) {
|
||||||
|
t.Errorf("repeated confirm changed the answer: %v", again)
|
||||||
|
}
|
||||||
|
answers, attempts := takeEvents()
|
||||||
|
if len(answers) != 1 || answers[0].AnswerID != a1q1 || answers[0].Points != 1.5 || answers[0].ReviewerUserID == nil || *answers[0].ReviewerUserID != owner.ID {
|
||||||
|
t.Errorf("AnswerReviewed events = %v, want one for the first confirm", answers)
|
||||||
|
}
|
||||||
|
if len(attempts) != 0 {
|
||||||
|
t.Errorf("AttemptReviewed fired with an open answer left: %v", attempts)
|
||||||
|
}
|
||||||
|
code, body := c.do("POST", fmt.Sprintf("%s/%d/confirm", prefix, a1q2), token, "")
|
||||||
|
if code != http.StatusConflict || body["code"] != "no_grader_score" {
|
||||||
|
t.Errorf("confirm of a pending answer = %d %v, want 409 no_grader_score", code, body)
|
||||||
|
}
|
||||||
|
code, body = c.do("POST", fmt.Sprintf("%s/%d/confirm", prefix, a2q2), token, "")
|
||||||
|
if code != http.StatusConflict || body["code"] != "no_grader_score" {
|
||||||
|
t.Errorf("confirm of a failed answer = %d %v, want 409 no_grader_score", code, body)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("set_score and recalculation", func(t *testing.T) {
|
||||||
|
path := fmt.Sprintf("%s/%d/score", prefix, a1q2)
|
||||||
|
for _, body := range []string{`{"points":1.25}`, `{"points":2.5}`, `{"points":-0.5}`, `{}`, `{"points":1,"comment":"` + strings.Repeat("x", 2001) + `"}`} {
|
||||||
|
if code, _ := c.do("POST", path, token, body); code != http.StatusUnprocessableEntity {
|
||||||
|
t.Errorf("set_score %s = %d, want 422", body, code)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if statusOf(t, a1q2) != models.GradingPending {
|
||||||
|
t.Fatal("a refused set_score changed the answer")
|
||||||
|
}
|
||||||
|
takeEvents()
|
||||||
|
out := data(c.ok(http.StatusOK, "POST", path, token, `{"points":2,"comment":" Bardzo dobrze, pełna odpowiedź. "}`))
|
||||||
|
if out["status"] != "reviewed" || out["points"] != float64(2) || out["is_correct"] != true || out["review_comment"] != "Bardzo dobrze, pełna odpowiedź." {
|
||||||
|
t.Errorf("set_score = %v", out)
|
||||||
|
}
|
||||||
|
// Attempt 1: 1.5 (confirmed) + 2 (set) of 4 points.
|
||||||
|
if a := attemptRow(t, a1); a.ScorePoints != 3.5 || a.ScorePercent == nil || *a.ScorePercent != 87.5 {
|
||||||
|
t.Errorf("attempt 1 score = %v / %v, want 3.5 / 87.5", a.ScorePoints, a.ScorePercent)
|
||||||
|
}
|
||||||
|
answers, attempts := takeEvents()
|
||||||
|
if len(answers) != 1 || answers[0].Comment == nil || answers[0].GraderPoints != nil {
|
||||||
|
t.Errorf("AnswerReviewed = %v", answers)
|
||||||
|
}
|
||||||
|
if len(attempts) != 1 || attempts[0].AttemptID != a1 || attempts[0].ScorePoints != 3.5 || !attempts[0].Passed || attempts[0].MaxPoints != 4 {
|
||||||
|
t.Errorf("AttemptReviewed = %v, want attempt 1 passed with 3.5 of 4", attempts)
|
||||||
|
}
|
||||||
|
|
||||||
|
res := data(c.ok(http.StatusOK, "GET", fmt.Sprintf("%s/attempts/%d", apiPrefix, a1), jwt1, ""))
|
||||||
|
var comment any
|
||||||
|
for _, q := range res["questions"].([]any) {
|
||||||
|
if q := q.(map[string]any); q["id"] == float64(q2.ID) {
|
||||||
|
comment = q["review_comment"]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if comment != "Bardzo dobrze, pełna odpowiedź." {
|
||||||
|
t.Errorf("the student sees review_comment %v", comment)
|
||||||
|
}
|
||||||
|
if strings.Contains(fmt.Sprint(res), "R-RUBRIC") {
|
||||||
|
t.Error("the student's result carries the rubric")
|
||||||
|
}
|
||||||
|
|
||||||
|
// A lower score moves the attempt and the student's best score.
|
||||||
|
c.ok(http.StatusOK, "POST", path, token, `{"points":0.5}`)
|
||||||
|
if a := attemptRow(t, a1); a.ScorePercent == nil || *a.ScorePercent != 50 {
|
||||||
|
t.Errorf("attempt 1 after a lower score = %v, want 50", a.ScorePercent)
|
||||||
|
}
|
||||||
|
var best any
|
||||||
|
for _, row := range list(c.ok(http.StatusOK, "GET", apiPrefix+"/quizzes", jwt1, "")) {
|
||||||
|
if row := row.(map[string]any); row["slug"] == quiz.Slug {
|
||||||
|
best = row["best_score_percent"]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if best != float64(50) {
|
||||||
|
t.Errorf("best_score_percent = %v, want 50", best)
|
||||||
|
}
|
||||||
|
if out := data(c.ok(http.StatusOK, "POST", path, token, `{"points":0.5}`)); out["review_comment"] != nil {
|
||||||
|
t.Errorf("a set_score without a comment kept %v", out["review_comment"])
|
||||||
|
}
|
||||||
|
code, body := c.do("POST", fmt.Sprintf("%s/%d/score", prefix, a2q2), token, `{"points":1}`)
|
||||||
|
if code != http.StatusOK || data(body)["status"] != "reviewed" {
|
||||||
|
t.Errorf("set_score on a failed answer = %d %v", code, body)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("bulk confirm", func(t *testing.T) {
|
||||||
|
bq, b1, b2 := seed(t, "hurt", "fake", models.ModeLearning)
|
||||||
|
_, _, x := attempt(t, "b1@example.com", bq.Slug, true, b1, b2)
|
||||||
|
_, _, y := attempt(t, "b2@example.com", bq.Slug, true, b1, b2)
|
||||||
|
_, _, z := attempt(t, "b3@example.com", bq.Slug, false, b1)
|
||||||
|
grade(t, answerID(t, x, b1.ID), 2)
|
||||||
|
grade(t, answerID(t, x, b2.ID), 1)
|
||||||
|
grade(t, answerID(t, y, b1.ID), 0.5)
|
||||||
|
grade(t, answerID(t, z, b1.ID), 2)
|
||||||
|
yPending := answerID(t, y, b2.ID)
|
||||||
|
takeEvents()
|
||||||
|
|
||||||
|
for _, body := range []string{`{}`, `{"quiz":"hurt","attempt_id":1}`} {
|
||||||
|
if code, _ := c.do("POST", prefix+"/confirm", token, body); code != http.StatusUnprocessableEntity {
|
||||||
|
t.Errorf("bulk %s = %d, want 422", body, code)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if code, _ := c.do("POST", prefix+"/confirm", token, `{"quiz":"nie-ma"}`); code != http.StatusNotFound {
|
||||||
|
t.Errorf("bulk on a missing quiz = %d, want 404", code)
|
||||||
|
}
|
||||||
|
out := data(c.ok(http.StatusOK, "POST", prefix+"/confirm", token, fmt.Sprintf(`{"attempt_id":%d}`, x)))
|
||||||
|
if out["confirmed"] != float64(2) {
|
||||||
|
t.Errorf("bulk by attempt = %v, want 2", out)
|
||||||
|
}
|
||||||
|
answers, attempts := takeEvents()
|
||||||
|
if len(answers) != 2 || len(attempts) != 1 || attempts[0].AttemptID != x || attempts[0].ScorePoints != 3 {
|
||||||
|
t.Errorf("events after bulk by attempt = %d answers, %v", len(answers), attempts)
|
||||||
|
}
|
||||||
|
out = data(c.ok(http.StatusOK, "POST", prefix+"/confirm", token, `{"quiz":"hurt"}`))
|
||||||
|
if out["confirmed"] != float64(2) {
|
||||||
|
t.Errorf("bulk by quiz = %v, want 2 (y's graded and z's)", out)
|
||||||
|
}
|
||||||
|
answers, attempts = takeEvents()
|
||||||
|
if len(answers) != 2 || len(attempts) != 0 {
|
||||||
|
t.Errorf("events after bulk by quiz = %d answers, %v attempts; y still has a pending answer and z is open", len(answers), attempts)
|
||||||
|
}
|
||||||
|
if statusOf(t, yPending) != models.GradingPending {
|
||||||
|
t.Error("bulk confirm touched a pending answer")
|
||||||
|
}
|
||||||
|
if again := data(c.ok(http.StatusOK, "POST", prefix+"/confirm", token, `{"quiz":"hurt"}`)); again["confirmed"] != float64(0) {
|
||||||
|
t.Errorf("second bulk = %v, want 0", again)
|
||||||
|
}
|
||||||
|
|
||||||
|
// z closes with every open answer reviewed: AttemptReviewed fires
|
||||||
|
// at close.
|
||||||
|
var zUser models.Attempt
|
||||||
|
must(t, gdb.Where("id = ?", z).Take(&zUser).Error)
|
||||||
|
svc := classes.ForApp(app, gdb)
|
||||||
|
if _, err := svc.Finish(t.Context(), zUser.UserID, z); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, attempts := takeEvents(); len(attempts) != 1 || attempts[0].AttemptID != z {
|
||||||
|
t.Errorf("AttemptReviewed at close = %v, want one for z", attempts)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("regrade", func(t *testing.T) {
|
||||||
|
mq, m1, _ := seed(t, "reczne", "manual", models.ModeLearning)
|
||||||
|
_, _, ma := attempt(t, "m1@example.com", mq.Slug, true, m1)
|
||||||
|
code, body := c.do("POST", prefix+"/regrade", token, `{"quiz":"reczne"}`)
|
||||||
|
if code != http.StatusConflict || body["code"] != "grader_manual" {
|
||||||
|
t.Errorf("regrade of a manual quiz = %d %v, want 409 grader_manual", code, body)
|
||||||
|
}
|
||||||
|
code, body = c.do("POST", prefix+"/regrade", token, fmt.Sprintf(`{"answer_id":%d}`, answerID(t, ma, m1.ID)))
|
||||||
|
if code != http.StatusConflict || body["code"] != "grader_manual" {
|
||||||
|
t.Errorf("regrade of a manual answer = %d %v, want 409 grader_manual", code, body)
|
||||||
|
}
|
||||||
|
if code, _ := c.do("POST", prefix+"/regrade", token, `{"answer_id":1,"quiz":"eseje"}`); code != http.StatusUnprocessableEntity {
|
||||||
|
t.Errorf("regrade with two keys = %d, want 422", code)
|
||||||
|
}
|
||||||
|
|
||||||
|
rq, r1, r2 := seed(t, "ponownie", "fake", models.ModeLearning)
|
||||||
|
_, _, ra := attempt(t, "r1@example.com", rq.Slug, true, r1, r2)
|
||||||
|
tq, t1, _ := seed(t, "test-otwarty", "fake", models.ModeTest)
|
||||||
|
_, _, ta := attempt(t, "r2@example.com", tq.Slug, false, t1)
|
||||||
|
graded, kept := answerID(t, ra, r1.ID), answerID(t, ra, r2.ID)
|
||||||
|
grade(t, graded, 2)
|
||||||
|
grade(t, kept, 2)
|
||||||
|
c.ok(http.StatusOK, "POST", fmt.Sprintf("%s/%d/confirm", prefix, kept), token, "")
|
||||||
|
if a := attemptRow(t, ra); a.ScorePoints != 4 {
|
||||||
|
t.Fatalf("attempt before regrade = %v, want 4", a.ScorePoints)
|
||||||
|
}
|
||||||
|
code, body = c.do("POST", prefix+"/regrade", token, fmt.Sprintf(`{"answer_id":%d}`, kept))
|
||||||
|
if code != http.StatusConflict || body["code"] != "already_reviewed" {
|
||||||
|
t.Errorf("regrade of a reviewed answer = %d %v, want 409 already_reviewed", code, body)
|
||||||
|
}
|
||||||
|
|
||||||
|
// The handler's Service hook swaps in a recording job queue.
|
||||||
|
enq := &recordingEnqueuer{}
|
||||||
|
hook := api.New(app)
|
||||||
|
hook.Service = func(db *gorm.DB) *classes.Service {
|
||||||
|
s := classes.ForApp(app, db)
|
||||||
|
s.Jobs = enq
|
||||||
|
return s
|
||||||
|
}
|
||||||
|
regrade := func(body string) (int, map[string]any) {
|
||||||
|
req := httptest.NewRequest("POST", prefix+"/regrade", strings.NewReader(body))
|
||||||
|
req = req.WithContext(bouncer.WithUser(req.Context(), &bouncer.Principal{ID: owner.ID}))
|
||||||
|
rec := httptest.NewRecorder()
|
||||||
|
hook.ReviewRegrade(rec, req)
|
||||||
|
var out map[string]any
|
||||||
|
if err := json.Unmarshal(rec.Body.Bytes(), &out); err != nil {
|
||||||
|
t.Fatalf("regrade %s: %d %v\n%s", body, rec.Code, err, rec.Body.String())
|
||||||
|
}
|
||||||
|
return rec.Code, out
|
||||||
|
}
|
||||||
|
var before models.AttemptAnswer
|
||||||
|
must(t, gdb.Where("id = ?", graded).Take(&before).Error)
|
||||||
|
code, out := regrade(fmt.Sprintf(`{"attempt_id":%d}`, ra))
|
||||||
|
if code != http.StatusOK || data(out)["regraded"] != float64(1) {
|
||||||
|
t.Errorf("regrade by attempt = %d %v, want 1 (the reviewed answer is skipped)", code, out)
|
||||||
|
}
|
||||||
|
var after models.AttemptAnswer
|
||||||
|
must(t, gdb.Where("id = ?", graded).Take(&after).Error)
|
||||||
|
if after.GradingStatus == nil || *after.GradingStatus != models.GradingPending || after.GradingSeq != before.GradingSeq+1 ||
|
||||||
|
after.GraderPoints != nil || after.Points != 0 || after.GradingAttempts != 0 {
|
||||||
|
t.Errorf("regraded row = %+v", after)
|
||||||
|
}
|
||||||
|
if statusOf(t, kept) != models.GradingReviewed {
|
||||||
|
t.Error("regrade touched a reviewed answer")
|
||||||
|
}
|
||||||
|
if a := attemptRow(t, ra); a.ScorePoints != 2 {
|
||||||
|
t.Errorf("attempt after regrade = %v, want 2 (only the reviewed answer counts)", a.ScorePoints)
|
||||||
|
}
|
||||||
|
if jobs := enq.take(); len(jobs) != 1 || jobs[0].AnswerID != graded || jobs[0].Seq != after.GradingSeq {
|
||||||
|
t.Errorf("jobs = %v, want one for the regraded answer with its new seq", jobs)
|
||||||
|
}
|
||||||
|
|
||||||
|
code, out = regrade(`{"quiz":"test-otwarty"}`)
|
||||||
|
if code != http.StatusOK || data(out)["regraded"] != float64(1) {
|
||||||
|
t.Errorf("regrade of an open test = %d %v, want 1", code, out)
|
||||||
|
}
|
||||||
|
if jobs := enq.take(); len(jobs) != 0 {
|
||||||
|
t.Errorf("jobs for an open test attempt = %v, want none (close enqueues them)", jobs)
|
||||||
|
}
|
||||||
|
_ = ta
|
||||||
|
})
|
||||||
|
}
|
||||||
72
routes.go
72
routes.go
@@ -11,25 +11,48 @@ var _ pact.HasRoutes = (*Plugin)(nil)
|
|||||||
// ManagePrefix is the path prefix of the management API.
|
// ManagePrefix is the path prefix of the management API.
|
||||||
const ManagePrefix = "/api/v1/quizzes"
|
const ManagePrefix = "/api/v1/quizzes"
|
||||||
|
|
||||||
|
// ReviewPrefix is the path prefix of the owner review routes (the MCP
|
||||||
|
// review tools). It is a separate prefix on purpose: under ManagePrefix a
|
||||||
|
// literal segment such as /reviews would shadow the quiz whose slug it is.
|
||||||
|
const ReviewPrefix = "/api/v1/quiz-reviews"
|
||||||
|
|
||||||
// permQuizzes is the permission that lets a user manage quizzes, in the
|
// permQuizzes is the permission that lets a user manage quizzes, in the
|
||||||
// admin and through the management API.
|
// admin and through the management API.
|
||||||
const permQuizzes = "golem15.quizzes.access_quizzes"
|
const permQuizzes = "golem15.quizzes.access_quizzes"
|
||||||
|
|
||||||
|
// bucketManage limits the owner manage routes (the MCP quiz tools). It runs
|
||||||
|
// after user.api_token, so it keys by user.
|
||||||
|
const bucketManage = "golem15.quizzes.manage"
|
||||||
|
|
||||||
|
// bucketAnswer and bucketStart limit the student's answers and attempt
|
||||||
|
// starts. They run after jwt.auth, so they key by user. In a learning quiz
|
||||||
|
// with a grader every new or changed open answer is a paid grading call,
|
||||||
|
// and every new attempt starts a fresh answer row (WR-03).
|
||||||
|
const (
|
||||||
|
bucketAnswer = "golem15.quizzes.answer"
|
||||||
|
bucketStart = "golem15.quizzes.start"
|
||||||
|
)
|
||||||
|
|
||||||
// Routes mounts the quiz API under /_quizzes/api/v1 behind golem15.user's
|
// Routes mounts the quiz API under /_quizzes/api/v1 behind golem15.user's
|
||||||
// jwt.auth middleware, and the management API under /api/v1/quizzes behind
|
// jwt.auth middleware, and the management API under /api/v1/quizzes behind
|
||||||
// its application-wide API token.
|
// its application-wide API token: the import route, and the owner manage
|
||||||
|
// routes the MCP quiz tools bind, which also need the access_quizzes
|
||||||
|
// permission and run under the per-user golem15.quizzes.manage throttle.
|
||||||
|
// Answering and starting an attempt run under per-user throttles too.
|
||||||
|
// The owner review routes under /api/v1/quiz-reviews (the MCP review
|
||||||
|
// tools) run behind the same middleware and permission (D-13).
|
||||||
func (p *Plugin) Routes(r pact.Router) error {
|
func (p *Plugin) Routes(r pact.Router) error {
|
||||||
h := api.New(p.app)
|
h := api.New(p.app)
|
||||||
r.Group("/_quizzes/api/v1", surf.Use("jwt.auth"), func(g pact.Router) {
|
r.Group("/_quizzes/api/v1", surf.Use("jwt.auth"), func(g pact.Router) {
|
||||||
g.Get("/quizzes", h.ListQuizzes)
|
g.Get("/quizzes", h.ListQuizzes)
|
||||||
g.Get("/quizzes/{slug}", h.ShowQuiz)
|
g.Get("/quizzes/{slug}", h.ShowQuiz)
|
||||||
g.Where("slug", `[a-z0-9-]+`)
|
g.Where("slug", `[a-z0-9-]+`)
|
||||||
g.Post("/quizzes/{slug}/attempts", h.StartAttempt)
|
g.Post("/quizzes/{slug}/attempts", h.StartAttempt, "throttle:"+bucketStart)
|
||||||
g.Where("slug", `[a-z0-9-]+`)
|
g.Where("slug", `[a-z0-9-]+`)
|
||||||
g.Get("/attempts", h.ListAttempts)
|
g.Get("/attempts", h.ListAttempts)
|
||||||
g.Get("/attempts/{id}", h.ShowAttempt)
|
g.Get("/attempts/{id}", h.ShowAttempt)
|
||||||
g.Where("id", `[0-9]+`)
|
g.Where("id", `[0-9]+`)
|
||||||
g.Post("/attempts/{id}/answers", h.Answer)
|
g.Post("/attempts/{id}/answers", h.Answer, "throttle:"+bucketAnswer)
|
||||||
g.Where("id", `[0-9]+`)
|
g.Where("id", `[0-9]+`)
|
||||||
g.Post("/attempts/{id}/finish", h.Finish)
|
g.Post("/attempts/{id}/finish", h.Finish)
|
||||||
g.Where("id", `[0-9]+`)
|
g.Where("id", `[0-9]+`)
|
||||||
@@ -39,5 +62,48 @@ func (p *Plugin) Routes(r pact.Router) error {
|
|||||||
r.Group(ManagePrefix, surf.Use("throttle:60,1", "user.api_token"), func(g pact.Router) {
|
r.Group(ManagePrefix, surf.Use("throttle:60,1", "user.api_token"), func(g pact.Router) {
|
||||||
g.Post("/import", h.ImportQuiz, "user.scope:write", "user.permission:"+permQuizzes)
|
g.Post("/import", h.ImportQuiz, "user.scope:write", "user.permission:"+permQuizzes)
|
||||||
})
|
})
|
||||||
|
// The owner manage routes (MCP). user.api_token runs first so the
|
||||||
|
// bucket keys by user; every route needs the permission, so a student
|
||||||
|
// whose groups lack it never lists or reaches these tools.
|
||||||
|
perm := "user.permission:" + permQuizzes
|
||||||
|
r.Group(ManagePrefix, surf.Use("user.api_token", "throttle:"+bucketManage), func(g pact.Router) {
|
||||||
|
g.Get("", h.ManageListQuizzes, "user.scope:read", perm)
|
||||||
|
g.Get("/{slug}", h.ManageShowQuiz, "user.scope:read", perm)
|
||||||
|
g.Where("slug", `[a-z0-9-]+`)
|
||||||
|
g.Post("", h.ManageCreateQuiz, "user.scope:write", perm)
|
||||||
|
g.Patch("/{slug}", h.ManageUpdateQuiz, "user.scope:write", perm)
|
||||||
|
g.Where("slug", `[a-z0-9-]+`)
|
||||||
|
g.Delete("/{slug}", h.ManageDeleteQuiz, "user.scope:write", perm)
|
||||||
|
g.Where("slug", `[a-z0-9-]+`)
|
||||||
|
g.Post("/{slug}/publish", h.ManagePublish, "user.scope:write", perm)
|
||||||
|
g.Where("slug", `[a-z0-9-]+`)
|
||||||
|
g.Post("/{slug}/unpublish", h.ManageUnpublish, "user.scope:write", perm)
|
||||||
|
g.Where("slug", `[a-z0-9-]+`)
|
||||||
|
g.Get("/{slug}/stats", h.ManageQuizStats, "user.scope:read", perm)
|
||||||
|
g.Where("slug", `[a-z0-9-]+`)
|
||||||
|
g.Post("/{slug}/questions", h.ManageCreateQuestion, "user.scope:write", perm)
|
||||||
|
g.Where("slug", `[a-z0-9-]+`)
|
||||||
|
g.Patch("/{slug}/questions/{id}", h.ManageUpdateQuestion, "user.scope:write", perm)
|
||||||
|
g.Where("slug", `[a-z0-9-]+`)
|
||||||
|
g.Where("id", "[0-9]+")
|
||||||
|
g.Delete("/{slug}/questions/{id}", h.ManageDeleteQuestion, "user.scope:write", perm)
|
||||||
|
g.Where("slug", `[a-z0-9-]+`)
|
||||||
|
g.Where("id", "[0-9]+")
|
||||||
|
g.Put("/{slug}/questions/order", h.ManageReorderQuestions, "user.scope:write", perm)
|
||||||
|
g.Where("slug", `[a-z0-9-]+`)
|
||||||
|
})
|
||||||
|
// The owner review routes (MCP review tools): the queue of open
|
||||||
|
// answers and the owner's decisions on them.
|
||||||
|
r.Group(ReviewPrefix, surf.Use("user.api_token", "throttle:"+bucketManage), func(g pact.Router) {
|
||||||
|
g.Get("", h.ReviewList, "user.scope:read", perm)
|
||||||
|
g.Get("/{id}", h.ReviewShow, "user.scope:read", perm)
|
||||||
|
g.Where("id", "[0-9]+")
|
||||||
|
g.Post("/{id}/confirm", h.ReviewConfirm, "user.scope:write", perm)
|
||||||
|
g.Where("id", "[0-9]+")
|
||||||
|
g.Post("/{id}/score", h.ReviewSetScore, "user.scope:write", perm)
|
||||||
|
g.Where("id", "[0-9]+")
|
||||||
|
g.Post("/confirm", h.ReviewConfirmBulk, "user.scope:write", perm)
|
||||||
|
g.Post("/regrade", h.ReviewRegrade, "user.scope:write", perm)
|
||||||
|
})
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|||||||
340
test_mode_postgres_test.go
Normal file
340
test_mode_postgres_test.go
Normal file
@@ -0,0 +1,340 @@
|
|||||||
|
package quizzes_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"slices"
|
||||||
|
"sync"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"git.golem15.com/golem15/sm-quizzes-plugin/classes"
|
||||||
|
"git.golem15.com/golem15/sm-quizzes-plugin/models"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/surf"
|
||||||
|
)
|
||||||
|
|
||||||
|
// TestTestModeAgainstDatabase covers test mode end to end: the migration's
|
||||||
|
// defaults, withheld solutions over HTTP, the attempt limit and resume
|
||||||
|
// under the advisory lock, the one-way lock, the grace and the lazy close
|
||||||
|
// (through a classes.Service with an injected clock) and the stable order.
|
||||||
|
func TestTestModeAgainstDatabase(t *testing.T) {
|
||||||
|
app, plugins, gdb := migrated(t)
|
||||||
|
h, err := surf.Assemble(app, plugins)
|
||||||
|
must(t, err)
|
||||||
|
test := func(mutate func(*models.Quiz)) func(*models.Quiz) {
|
||||||
|
return func(q *models.Quiz) {
|
||||||
|
q.Mode = models.ModeTest
|
||||||
|
if mutate != nil {
|
||||||
|
mutate(q)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
start := func(c *client, slug, token string, want int) map[string]any {
|
||||||
|
c.t.Helper()
|
||||||
|
return data(c.ok(want, "POST", apiPrefix+"/quizzes/"+slug+"/attempts", token, ""))
|
||||||
|
}
|
||||||
|
attemptPath := func(att map[string]any) string {
|
||||||
|
return fmt.Sprintf("%s/attempts/%d", apiPrefix, int(att["id"].(float64)))
|
||||||
|
}
|
||||||
|
countAttempts := func(t *testing.T, quizID, userID uint) int64 {
|
||||||
|
t.Helper()
|
||||||
|
var n int64
|
||||||
|
must(t, gdb.Model(&models.Attempt{}).Where("quiz_id = ? AND user_id = ?", quizID, userID).Count(&n).Error)
|
||||||
|
return n
|
||||||
|
}
|
||||||
|
|
||||||
|
t.Run("existing quizzes stay learning", func(t *testing.T) {
|
||||||
|
must(t, gdb.Exec(`INSERT INTO golem15_quizzes_quizzes (title, slug, is_published, passing_score, shuffle_questions, created_at, updated_at)
|
||||||
|
VALUES ('Stary', 'stary', true, 50, false, NOW(), NOW())`).Error)
|
||||||
|
var q models.Quiz
|
||||||
|
must(t, gdb.Where("slug = ?", "stary").Take(&q).Error)
|
||||||
|
if q.Mode != models.ModeLearning || q.Navigation != models.NavigationFree || q.MaxAttempts != nil {
|
||||||
|
t.Errorf("pre-existing quiz = %q %q %v, want learning free NULL", q.Mode, q.Navigation, q.MaxAttempts)
|
||||||
|
}
|
||||||
|
f := seedQuiz(t, gdb, "zero-value", nil)
|
||||||
|
if f.quiz.Mode != models.ModeLearning || f.quiz.Navigation != models.NavigationFree {
|
||||||
|
t.Errorf("zero-value quiz = %q %q", f.quiz.Mode, f.quiz.Navigation)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("an imported sample is learning", func(t *testing.T) {
|
||||||
|
raw, err := os.ReadFile("testdata/quiz.json")
|
||||||
|
must(t, err)
|
||||||
|
doc, err := classes.ParseImport(raw)
|
||||||
|
must(t, err)
|
||||||
|
res, err := classes.Import(t.Context(), gdb, doc, false)
|
||||||
|
must(t, err)
|
||||||
|
if res.Quiz.Mode != models.ModeLearning || res.Quiz.Navigation != models.NavigationFree || res.Quiz.MaxAttempts != nil {
|
||||||
|
t.Errorf("imported quiz = %q %q %v", res.Quiz.Mode, res.Quiz.Navigation, res.Quiz.MaxAttempts)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("solutions are withheld until finish", func(t *testing.T) {
|
||||||
|
c := &client{t: t, h: h}
|
||||||
|
f := seedQuiz(t, gdb, "test-ukryty", test(nil))
|
||||||
|
_, token := newUser(t, gdb, "withheld@example.com")
|
||||||
|
|
||||||
|
detail := data(c.ok(200, "GET", apiPrefix+"/quizzes/test-ukryty", token, ""))
|
||||||
|
if qs, _ := detail["questions"].([]any); len(qs) != 0 || detail["question_count"] != float64(3) || detail["mode"] != models.ModeTest {
|
||||||
|
t.Errorf("test detail = %v, want questions [] and question_count 3", detail)
|
||||||
|
}
|
||||||
|
for _, row := range list(c.ok(200, "GET", apiPrefix+"/quizzes", token, "")) {
|
||||||
|
r := row.(map[string]any)
|
||||||
|
if r["slug"] == "test-ukryty" {
|
||||||
|
if types, _ := r["question_types"].(map[string]any); types["single"] != float64(1) || types["multiple"] != float64(1) || types["self_check"] != float64(1) {
|
||||||
|
t.Errorf("question_types = %v", r["question_types"])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
att := start(c, "test-ukryty", token, 201)
|
||||||
|
if att["resumed"] != false || att["quiz_mode"] != models.ModeTest {
|
||||||
|
t.Errorf("start = %v", att)
|
||||||
|
}
|
||||||
|
path := attemptPath(att)
|
||||||
|
for _, body := range []string{
|
||||||
|
fmt.Sprintf(`{"question_id":%d,"answer_ids":[%d]}`, f.single.ID, f.singleRight.ID),
|
||||||
|
fmt.Sprintf(`{"question_id":%d,"answer_ids":[%d,%d]}`, f.multi.ID, f.multiA.ID, f.multiB.ID),
|
||||||
|
fmt.Sprintf(`{"question_id":%d,"known":true}`, f.selfQ.ID),
|
||||||
|
} {
|
||||||
|
fb := data(c.ok(200, "POST", path+"/answers", token, body))
|
||||||
|
if fb["withheld"] != true {
|
||||||
|
t.Errorf("feedback withheld = %v", fb["withheld"])
|
||||||
|
}
|
||||||
|
for _, k := range []string{"is_correct", "points", "correct_answer_ids", "explanation", "answer_text"} {
|
||||||
|
if fb[k] != nil {
|
||||||
|
t.Errorf("feedback %s = %v, want null", k, fb[k])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, a := range fb["answers"].([]any) {
|
||||||
|
if am := a.(map[string]any); am["is_correct"] != nil || am["explanation"] != nil {
|
||||||
|
t.Errorf("feedback answer = %v", am)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
res := data(c.ok(200, "GET", path, token, ""))
|
||||||
|
if res["solutions_withheld"] != true {
|
||||||
|
t.Errorf("open result solutions_withheld = %v", res["solutions_withheld"])
|
||||||
|
}
|
||||||
|
for _, q := range res["questions"].([]any) {
|
||||||
|
qm := q.(map[string]any)
|
||||||
|
for _, k := range []string{"is_correct", "points_earned", "correct_answer_ids", "explanation", "answer_text"} {
|
||||||
|
if qm[k] != nil {
|
||||||
|
t.Errorf("open result question %v: %s = %v, want null", qm["id"], k, qm[k])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if qm["answered"] != true {
|
||||||
|
t.Errorf("open result question %v lost answered", qm["id"])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
done := data(c.ok(200, "POST", path+"/finish", token, ""))
|
||||||
|
if done["solutions_withheld"] != false || done["passed"] != true {
|
||||||
|
t.Errorf("finish = %v", done)
|
||||||
|
}
|
||||||
|
for _, q := range done["questions"].([]any) {
|
||||||
|
qm := q.(map[string]any)
|
||||||
|
if qm["is_correct"] == nil || qm["points_earned"] == nil {
|
||||||
|
t.Errorf("finished question %v hides its result", qm["id"])
|
||||||
|
}
|
||||||
|
if qm["id"] == float64(f.single.ID) && (qm["correct_answer_ids"] == nil || qm["explanation"] == nil) {
|
||||||
|
t.Errorf("finished single question hides its solution: %v", qm)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("a test refuses a category", func(t *testing.T) {
|
||||||
|
c := &client{t: t, h: h}
|
||||||
|
seedQuiz(t, gdb, "test-kategoria", test(nil))
|
||||||
|
_, token := newUser(t, gdb, "category@example.com")
|
||||||
|
out := c.ok(422, "POST", apiPrefix+"/quizzes/test-kategoria/attempts", token, `{"category":"Geografia"}`)
|
||||||
|
if errs, _ := out["errors"].(map[string]any); errs["category"] == nil {
|
||||||
|
t.Errorf("category start = %v, want errors.category", out)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("attempt limit and resume", func(t *testing.T) {
|
||||||
|
c := &client{t: t, h: h}
|
||||||
|
f := seedQuiz(t, gdb, "test-limit", test(func(q *models.Quiz) { q.MaxAttempts = intPtr(1) }))
|
||||||
|
u, token := newUser(t, gdb, "limit@example.com")
|
||||||
|
att := start(c, "test-limit", token, 201)
|
||||||
|
if att["attempts_left"] != float64(0) {
|
||||||
|
t.Errorf("attempts_left after the only start = %v", att["attempts_left"])
|
||||||
|
}
|
||||||
|
again := start(c, "test-limit", token, 200)
|
||||||
|
if again["resumed"] != true || again["id"] != att["id"] || countAttempts(t, f.quiz.ID, u.ID) != 1 {
|
||||||
|
t.Errorf("second start = %v, want the open attempt resumed", again)
|
||||||
|
}
|
||||||
|
c.ok(200, "POST", attemptPath(att)+"/finish", token, "")
|
||||||
|
out := c.ok(409, "POST", apiPrefix+"/quizzes/test-limit/attempts", token, "")
|
||||||
|
if out["code"] != "attempt_limit_reached" {
|
||||||
|
t.Errorf("start past the limit = %v", out)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("concurrent starts share one attempt", func(t *testing.T) {
|
||||||
|
f := seedQuiz(t, gdb, "test-wyscig", test(func(q *models.Quiz) { q.MaxAttempts = intPtr(1) }))
|
||||||
|
u, _ := newUser(t, gdb, "race@example.com")
|
||||||
|
svc := &classes.Service{DB: gdb, Grace: 5 * time.Second}
|
||||||
|
var wg sync.WaitGroup
|
||||||
|
ids := make([]uint, 2)
|
||||||
|
errs := make([]error, 2)
|
||||||
|
for i := range 2 {
|
||||||
|
wg.Go(func() {
|
||||||
|
st, err := svc.Start(t.Context(), u.ID, "test-wyscig", "")
|
||||||
|
errs[i] = err
|
||||||
|
if err == nil {
|
||||||
|
ids[i] = st.Attempt.ID
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
wg.Wait()
|
||||||
|
for _, err := range errs {
|
||||||
|
must(t, err)
|
||||||
|
}
|
||||||
|
if ids[0] != ids[1] || countAttempts(t, f.quiz.ID, u.ID) != 1 {
|
||||||
|
t.Errorf("concurrent starts = %v with %d rows, want one attempt", ids, countAttempts(t, f.quiz.ID, u.ID))
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("one_way answers are final", func(t *testing.T) {
|
||||||
|
c := &client{t: t, h: h}
|
||||||
|
f := seedQuiz(t, gdb, "test-jednokierunkowy", test(func(q *models.Quiz) { q.Navigation = models.NavigationOneWay }))
|
||||||
|
_, token := newUser(t, gdb, "oneway@example.com")
|
||||||
|
path := attemptPath(start(c, "test-jednokierunkowy", token, 201))
|
||||||
|
c.ok(200, "POST", path+"/answers", token, fmt.Sprintf(`{"question_id":%d,"answer_ids":[%d]}`, f.single.ID, f.singleRight.ID))
|
||||||
|
out := c.ok(409, "POST", path+"/answers", token, fmt.Sprintf(`{"question_id":%d,"answer_ids":[%d]}`, f.single.ID, f.singleNo.ID))
|
||||||
|
if out["code"] != "answer_locked" {
|
||||||
|
t.Errorf("changed one_way answer = %v", out)
|
||||||
|
}
|
||||||
|
var row models.AttemptAnswer
|
||||||
|
must(t, gdb.Where("question_id = ?", f.single.ID).Take(&row).Error)
|
||||||
|
if !slices.Equal(row.AnswerIDs.Data, []uint{f.singleRight.ID}) {
|
||||||
|
t.Errorf("stored answer = %v, want the first one", row.AnswerIDs.Data)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("free answers are overwritten", func(t *testing.T) {
|
||||||
|
c := &client{t: t, h: h}
|
||||||
|
f := seedQuiz(t, gdb, "test-swobodny", test(nil))
|
||||||
|
_, token := newUser(t, gdb, "free@example.com")
|
||||||
|
path := attemptPath(start(c, "test-swobodny", token, 201))
|
||||||
|
c.ok(200, "POST", path+"/answers", token, fmt.Sprintf(`{"question_id":%d,"answer_ids":[%d]}`, f.single.ID, f.singleRight.ID))
|
||||||
|
c.ok(200, "POST", path+"/answers", token, fmt.Sprintf(`{"question_id":%d,"answer_ids":[%d]}`, f.single.ID, f.singleNo.ID))
|
||||||
|
var row models.AttemptAnswer
|
||||||
|
must(t, gdb.Where("question_id = ?", f.single.ID).Take(&row).Error)
|
||||||
|
if !slices.Equal(row.AnswerIDs.Data, []uint{f.singleNo.ID}) {
|
||||||
|
t.Errorf("stored answer = %v, want the second one", row.AnswerIDs.Data)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("grace applies to tests only", func(t *testing.T) {
|
||||||
|
ft := seedQuiz(t, gdb, "test-laska", test(func(q *models.Quiz) { q.TimeLimitSeconds = intPtr(60) }))
|
||||||
|
fl := seedQuiz(t, gdb, "nauka-czas", func(q *models.Quiz) { q.TimeLimitSeconds = intPtr(60) })
|
||||||
|
u, _ := newUser(t, gdb, "grace@example.com")
|
||||||
|
t0 := time.Now().UTC().Truncate(time.Second)
|
||||||
|
clock := t0
|
||||||
|
svc := &classes.Service{DB: gdb, Now: func() time.Time { return clock }, Grace: 5 * time.Second}
|
||||||
|
|
||||||
|
st, err := svc.Start(t.Context(), u.ID, "test-laska", "")
|
||||||
|
must(t, err)
|
||||||
|
clock = t0.Add(62 * time.Second)
|
||||||
|
if _, err := svc.Answer(t.Context(), u.ID, st.Attempt.ID, classes.AnswerInput{QuestionID: ft.single.ID, AnswerIDs: []uint{ft.singleRight.ID}}); err != nil {
|
||||||
|
t.Errorf("test answer at +62s = %v, want accepted inside the grace", err)
|
||||||
|
}
|
||||||
|
clock = t0.Add(66 * time.Second)
|
||||||
|
if _, err := svc.Answer(t.Context(), u.ID, st.Attempt.ID, classes.AnswerInput{QuestionID: ft.selfQ.ID, Known: new(true)}); !errors.Is(err, classes.ErrTimeLimit) {
|
||||||
|
t.Errorf("test answer at +66s = %v, want ErrTimeLimit", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
clock = t0
|
||||||
|
lst, err := svc.Start(t.Context(), u.ID, "nauka-czas", "")
|
||||||
|
must(t, err)
|
||||||
|
clock = t0.Add(61 * time.Second)
|
||||||
|
if _, err := svc.Answer(t.Context(), u.ID, lst.Attempt.ID, classes.AnswerInput{QuestionID: fl.selfQ.ID, Known: new(true)}); !errors.Is(err, classes.ErrTimeLimit) {
|
||||||
|
t.Errorf("learning answer at +61s = %v, want ErrTimeLimit", err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("an expired test is closed at its deadline", func(t *testing.T) {
|
||||||
|
f := seedQuiz(t, gdb, "test-wygasly", test(func(q *models.Quiz) { q.TimeLimitSeconds = intPtr(60) }))
|
||||||
|
u, _ := newUser(t, gdb, "lazy@example.com")
|
||||||
|
t0 := time.Now().UTC().Truncate(time.Second)
|
||||||
|
clock := t0
|
||||||
|
svc := &classes.Service{DB: gdb, Now: func() time.Time { return clock }, Grace: 5 * time.Second}
|
||||||
|
st, err := svc.Start(t.Context(), u.ID, "test-wygasly", "")
|
||||||
|
must(t, err)
|
||||||
|
clock = t0.Add(10 * time.Second)
|
||||||
|
_, err = svc.Answer(t.Context(), u.ID, st.Attempt.ID, classes.AnswerInput{QuestionID: f.single.ID, AnswerIDs: []uint{f.singleRight.ID}})
|
||||||
|
must(t, err)
|
||||||
|
|
||||||
|
clock = t0.Add(70 * time.Second)
|
||||||
|
next, err := svc.Start(t.Context(), u.ID, "test-wygasly", "")
|
||||||
|
must(t, err)
|
||||||
|
if next.Resumed || next.Attempt.ID == st.Attempt.ID {
|
||||||
|
t.Errorf("start after expiry = %+v, want a new attempt", next)
|
||||||
|
}
|
||||||
|
var old models.Attempt
|
||||||
|
must(t, gdb.Take(&old, st.Attempt.ID).Error)
|
||||||
|
if old.CompletedAt == nil || !old.CompletedAt.Equal(t0.Add(60*time.Second)) {
|
||||||
|
t.Errorf("expired attempt completed_at = %v, want %v", old.CompletedAt, t0.Add(60*time.Second))
|
||||||
|
}
|
||||||
|
if old.ScorePoints != 1 || old.MaxPoints != 4 {
|
||||||
|
t.Errorf("expired attempt score = %v / %d, want 1 / 4", old.ScorePoints, old.MaxPoints)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("the last expired attempt is closed at the limit", func(t *testing.T) {
|
||||||
|
f := seedQuiz(t, gdb, "test-wygasly-limit", test(func(q *models.Quiz) {
|
||||||
|
q.TimeLimitSeconds = intPtr(60)
|
||||||
|
q.MaxAttempts = intPtr(1)
|
||||||
|
}))
|
||||||
|
u, _ := newUser(t, gdb, "lazy-limit@example.com")
|
||||||
|
t0 := time.Now().UTC().Truncate(time.Second)
|
||||||
|
clock := t0
|
||||||
|
svc := &classes.Service{DB: gdb, Now: func() time.Time { return clock }, Grace: 5 * time.Second}
|
||||||
|
st, err := svc.Start(t.Context(), u.ID, "test-wygasly-limit", "")
|
||||||
|
must(t, err)
|
||||||
|
clock = t0.Add(10 * time.Second)
|
||||||
|
_, err = svc.Answer(t.Context(), u.ID, st.Attempt.ID, classes.AnswerInput{QuestionID: f.single.ID, AnswerIDs: []uint{f.singleRight.ID}})
|
||||||
|
must(t, err)
|
||||||
|
|
||||||
|
clock = t0.Add(70 * time.Second)
|
||||||
|
if _, err := svc.Start(t.Context(), u.ID, "test-wygasly-limit", ""); !errors.Is(err, classes.ErrAttemptLimit) {
|
||||||
|
t.Errorf("start after the last attempt expired = %v, want ErrAttemptLimit", err)
|
||||||
|
}
|
||||||
|
var old models.Attempt
|
||||||
|
must(t, gdb.Take(&old, st.Attempt.ID).Error)
|
||||||
|
if old.CompletedAt == nil || !old.CompletedAt.Equal(t0.Add(60*time.Second)) {
|
||||||
|
t.Errorf("expired attempt completed_at = %v, want %v (closed despite the limit)", old.CompletedAt, t0.Add(60*time.Second))
|
||||||
|
}
|
||||||
|
if old.ScorePoints != 1 || old.MaxPoints != 4 {
|
||||||
|
t.Errorf("expired attempt score = %v / %d, want 1 / 4", old.ScorePoints, old.MaxPoints)
|
||||||
|
}
|
||||||
|
if n := countAttempts(t, f.quiz.ID, u.ID); n != 1 {
|
||||||
|
t.Errorf("attempts after the refused start = %d, want 1", n)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("a shuffled test keeps its order", func(t *testing.T) {
|
||||||
|
c := &client{t: t, h: h}
|
||||||
|
seedQuiz(t, gdb, "test-losowy", test(func(q *models.Quiz) { q.ShuffleQuestions = true }))
|
||||||
|
_, token := newUser(t, gdb, "shuffle@example.com")
|
||||||
|
path := attemptPath(start(c, "test-losowy", token, 201))
|
||||||
|
order := func(res map[string]any) []float64 {
|
||||||
|
var ids []float64
|
||||||
|
for _, q := range res["questions"].([]any) {
|
||||||
|
ids = append(ids, q.(map[string]any)["id"].(float64))
|
||||||
|
}
|
||||||
|
return ids
|
||||||
|
}
|
||||||
|
first := order(data(c.ok(200, "GET", path, token, "")))
|
||||||
|
second := order(data(c.ok(200, "GET", path, token, "")))
|
||||||
|
finished := order(data(c.ok(200, "POST", path+"/finish", token, "")))
|
||||||
|
if len(first) != 3 || !slices.Equal(first, second) || !slices.Equal(first, finished) {
|
||||||
|
t.Errorf("orders = %v %v %v, want one stable order", first, second, finished)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
28
updates/20261109120000_add_test_mode_to_quizzes.go
Normal file
28
updates/20261109120000_add_test_mode_to_quizzes.go
Normal file
@@ -0,0 +1,28 @@
|
|||||||
|
// Code generated by summer make. DO NOT EDIT.
|
||||||
|
|
||||||
|
package updates
|
||||||
|
|
||||||
|
import (
|
||||||
|
"github.com/go-gormigrate/gormigrate/v2"
|
||||||
|
"gorm.io/gorm"
|
||||||
|
)
|
||||||
|
|
||||||
|
// AddTestModeToQuizzes returns the 20261109120000_add_test_mode_to_quizzes gormigrate entry.
|
||||||
|
// A test quiz withholds solutions until the attempt is finished; navigation
|
||||||
|
// and max_attempts apply only to tests. Every existing quiz stays a learning
|
||||||
|
// quiz with free navigation and no attempt limit.
|
||||||
|
func AddTestModeToQuizzes() *gormigrate.Migration {
|
||||||
|
return &gormigrate.Migration{
|
||||||
|
ID: "20261109120000_add_test_mode_to_quizzes",
|
||||||
|
Migrate: func(tx *gorm.DB) error {
|
||||||
|
return tx.Exec(`ALTER TABLE golem15_quizzes_quizzes
|
||||||
|
ADD COLUMN mode VARCHAR(20) NOT NULL DEFAULT 'learning' CHECK (mode IN ('learning', 'test')),
|
||||||
|
ADD COLUMN navigation VARCHAR(20) NOT NULL DEFAULT 'free' CHECK (navigation IN ('free', 'one_way')),
|
||||||
|
ADD COLUMN max_attempts INTEGER NULL CHECK (max_attempts IS NULL OR max_attempts >= 1)`).Error
|
||||||
|
},
|
||||||
|
Rollback: func(tx *gorm.DB) error {
|
||||||
|
return tx.Exec(`ALTER TABLE golem15_quizzes_quizzes
|
||||||
|
DROP COLUMN IF EXISTS max_attempts, DROP COLUMN IF EXISTS navigation, DROP COLUMN IF EXISTS mode`).Error
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
108
updates/20261109180000_add_open_questions_and_grading.go
Normal file
108
updates/20261109180000_add_open_questions_and_grading.go
Normal file
@@ -0,0 +1,108 @@
|
|||||||
|
// Code generated by summer make. DO NOT EDIT.
|
||||||
|
|
||||||
|
package updates
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
|
||||||
|
"github.com/go-gormigrate/gormigrate/v2"
|
||||||
|
"gorm.io/gorm"
|
||||||
|
)
|
||||||
|
|
||||||
|
// AddOpenQuestionsAndGrading returns the 20261109180000_add_open_questions_and_grading gormigrate entry.
|
||||||
|
// It adds the open question type (answered in free text, graded against the
|
||||||
|
// model answer and an owner-only rubric), the quiz grader and the grading
|
||||||
|
// and review state of each attempt answer. Every existing question, quiz and
|
||||||
|
// answer keeps today's behaviour: the grader is manual, no question is open
|
||||||
|
// and every existing answer row has no grading state.
|
||||||
|
func AddOpenQuestionsAndGrading() *gormigrate.Migration {
|
||||||
|
return &gormigrate.Migration{
|
||||||
|
ID: "20261109180000_add_open_questions_and_grading",
|
||||||
|
Migrate: func(tx *gorm.DB) error {
|
||||||
|
// The original type CHECK is an unnamed inline constraint, so
|
||||||
|
// it is found by the column it checks rather than by an assumed
|
||||||
|
// name. Its definition cannot be matched on "IN": Postgres
|
||||||
|
// stores it as type = ANY (ARRAY[...]).
|
||||||
|
for _, stmt := range []string{
|
||||||
|
`DO $$
|
||||||
|
DECLARE c RECORD;
|
||||||
|
BEGIN
|
||||||
|
FOR c IN
|
||||||
|
SELECT con.conname FROM pg_constraint con
|
||||||
|
JOIN pg_attribute att ON att.attrelid = con.conrelid AND att.attname = 'type'
|
||||||
|
WHERE con.conrelid = 'golem15_quizzes_questions'::regclass
|
||||||
|
AND con.contype = 'c'
|
||||||
|
AND con.conkey = ARRAY[att.attnum]
|
||||||
|
LOOP
|
||||||
|
EXECUTE format('ALTER TABLE golem15_quizzes_questions DROP CONSTRAINT %I', c.conname);
|
||||||
|
END LOOP;
|
||||||
|
END $$`,
|
||||||
|
`ALTER TABLE golem15_quizzes_questions
|
||||||
|
ADD CONSTRAINT golem15_quizzes_questions_type_check CHECK (type IN ('single', 'multiple', 'self_check', 'open')),
|
||||||
|
ADD COLUMN rubric TEXT NULL,
|
||||||
|
ADD COLUMN max_length INTEGER NULL CHECK (max_length IS NULL OR max_length BETWEEN 1 AND 20000)`,
|
||||||
|
`ALTER TABLE golem15_quizzes_quizzes
|
||||||
|
ADD COLUMN grader VARCHAR(64) NOT NULL DEFAULT 'manual'`,
|
||||||
|
`ALTER TABLE golem15_quizzes_attempt_answers
|
||||||
|
ADD COLUMN text_answer TEXT NULL,
|
||||||
|
ADD COLUMN grading_status VARCHAR(20) NULL CHECK (grading_status IS NULL OR grading_status IN ('pending', 'graded', 'failed', 'reviewed')),
|
||||||
|
ADD COLUMN grading_seq INTEGER NOT NULL DEFAULT 0,
|
||||||
|
ADD COLUMN grading_attempts INTEGER NOT NULL DEFAULT 0,
|
||||||
|
ADD COLUMN grader VARCHAR(64) NULL,
|
||||||
|
ADD COLUMN grader_points DOUBLE PRECISION NULL,
|
||||||
|
ADD COLUMN grader_feedback TEXT NULL,
|
||||||
|
ADD COLUMN grading_error TEXT NULL,
|
||||||
|
ADD COLUMN graded_at TIMESTAMPTZ NULL,
|
||||||
|
ADD COLUMN review_comment TEXT NULL,
|
||||||
|
ADD COLUMN reviewed_at TIMESTAMPTZ NULL,
|
||||||
|
ADD COLUMN reviewed_by_user_id INTEGER NULL,
|
||||||
|
ADD COLUMN reviewed_by_admin_id INTEGER NULL`,
|
||||||
|
`CREATE INDEX golem15_quizzes_attempt_answers_grading_index ON golem15_quizzes_attempt_answers (grading_status)
|
||||||
|
WHERE grading_status IN ('pending', 'graded', 'failed')`,
|
||||||
|
} {
|
||||||
|
if err := tx.Exec(stmt).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
},
|
||||||
|
Rollback: func(tx *gorm.DB) error {
|
||||||
|
var n int64
|
||||||
|
if err := tx.Raw(`SELECT COUNT(*) FROM golem15_quizzes_questions WHERE type = 'open'`).Scan(&n).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if n > 0 {
|
||||||
|
return fmt.Errorf("quizzes: rollback refused: %d open questions exist; delete them first", n)
|
||||||
|
}
|
||||||
|
for _, stmt := range []string{
|
||||||
|
`DROP INDEX IF EXISTS golem15_quizzes_attempt_answers_grading_index`,
|
||||||
|
`ALTER TABLE golem15_quizzes_attempt_answers
|
||||||
|
DROP COLUMN IF EXISTS reviewed_by_admin_id,
|
||||||
|
DROP COLUMN IF EXISTS reviewed_by_user_id,
|
||||||
|
DROP COLUMN IF EXISTS reviewed_at,
|
||||||
|
DROP COLUMN IF EXISTS review_comment,
|
||||||
|
DROP COLUMN IF EXISTS graded_at,
|
||||||
|
DROP COLUMN IF EXISTS grading_error,
|
||||||
|
DROP COLUMN IF EXISTS grader_feedback,
|
||||||
|
DROP COLUMN IF EXISTS grader_points,
|
||||||
|
DROP COLUMN IF EXISTS grader,
|
||||||
|
DROP COLUMN IF EXISTS grading_attempts,
|
||||||
|
DROP COLUMN IF EXISTS grading_seq,
|
||||||
|
DROP COLUMN IF EXISTS grading_status,
|
||||||
|
DROP COLUMN IF EXISTS text_answer`,
|
||||||
|
`ALTER TABLE golem15_quizzes_quizzes DROP COLUMN IF EXISTS grader`,
|
||||||
|
`ALTER TABLE golem15_quizzes_questions
|
||||||
|
DROP COLUMN IF EXISTS max_length,
|
||||||
|
DROP COLUMN IF EXISTS rubric,
|
||||||
|
DROP CONSTRAINT IF EXISTS golem15_quizzes_questions_type_check`,
|
||||||
|
`ALTER TABLE golem15_quizzes_questions
|
||||||
|
ADD CONSTRAINT golem15_quizzes_questions_type_check CHECK (type IN ('single', 'multiple', 'self_check'))`,
|
||||||
|
} {
|
||||||
|
if err := tx.Exec(stmt).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user