question type multuple components issue fix
This commit is contained in:
parent
69788a1e43
commit
d02f21b276
105
.cursor/plans/multi_slot_correct_answers_plan.md
Normal file
105
.cursor/plans/multi_slot_correct_answers_plan.md
Normal file
|
|
@ -0,0 +1,105 @@
|
|||
# Plan: Per-instance correct answers for multi-slot dynamic components
|
||||
|
||||
## Goal
|
||||
|
||||
When a dynamic question type has multiple instances of the same component (e.g. two `OPTION` slots), each instance must keep its own correct answer / pairing. Fix the admin authoring bug and add a backend safety net; extend the same per-instance pattern to matching and cloze.
|
||||
|
||||
## Root cause
|
||||
|
||||
Storage is already per schema element `id` (`dynamic_payload.response[]` / `stimulus[]` each carry their own `value`). The failure is in the admin UI:
|
||||
|
||||
- Correct radios use `name={mcq-correct-${label}}` in `DynamicSchemaSlotField.tsx`
|
||||
- Every new `OPTION` slot gets the same default label (`"Answer choices"`)
|
||||
- The browser treats all those radios as **one** group → only one Correct selection globally
|
||||
|
||||
Matching / cloze have the analogous bug: pairing helpers return the **first** `MATCHING_INPUTS` / cloze stimulus of that kind, so every answer slot binds to the same inputs.
|
||||
|
||||
## Approach
|
||||
|
||||
1. **Admin MCQ radios** — unique `name` per slot: `mcq-correct-${side}-${row.id}`
|
||||
2. **Admin matching/cloze** — positional pairing (Nth answer ↔ Nth inputs/stimulus), with fallback to current first-of-kind for single-instance regressions
|
||||
3. **Backend** — validate each `OPTION` / `MULTIPLE_CHOICE` payload element has ≥1 `is_correct` (and basic options shape); leave matching/cloze/sequence value internals opaque (client already validates)
|
||||
4. **Out of scope** — legacy `mcqOptionsConsumed` seed, legacy `schemaElementID` first-of-kind outbound, learner grading engine, new `config.pairs_with` schema field
|
||||
|
||||
---
|
||||
|
||||
## Files to change
|
||||
|
||||
### Admin
|
||||
|
||||
| File | Change |
|
||||
|------|--------|
|
||||
| `Yimaru-Admin/src/components/content-management/DynamicSchemaSlotField.tsx` | Pass `groupName={`mcq-correct-${side}-${row.id}`}` into `DynamicMultipleChoiceSlot`; use positional pairing helpers for matching/cloze render |
|
||||
| `Yimaru-Admin/src/lib/matchingSlotValue.ts` | Add `findMatchingInputsForAnswerRow(...)` (positional + fallback) |
|
||||
| `Yimaru-Admin/src/lib/selectMissingWordsSlotValue.ts` | Add `findSelectMissingWordsStimulusForResponseRow(...)` (positional + fallback) |
|
||||
| `Yimaru-Admin/src/lib/practiceDynamicQuestionPayload.ts` | Use positional helpers when building payload for matching/cloze answer slots |
|
||||
| `Yimaru-Admin/src/lib/learnEnglishDefinitionQuestion.ts` | Resolve matching/cloze reference **inside** each answer-slot validation loop (not once globally) |
|
||||
|
||||
Optional polish (same PR if cheap): when adding a second slot of the same kind in `QuestionTypeConfigStep.tsx`, suffix labels (`Answer choices 2`) so authors can tell slots apart — not required for correctness once radio `name` uses `row.id`.
|
||||
|
||||
### Backend
|
||||
|
||||
| File | Change |
|
||||
|------|--------|
|
||||
| `Yimaru-BackEnd/internal/domain/question_type_builder.go` | In `ValidateDynamicPayloadAgainstDefinition`, for each stimulus/response element with kind `OPTION` or `MULTIPLE_CHOICE`, validate `value.options` (≥2), unique option ids, ≥1 `is_correct` |
|
||||
| `Yimaru-BackEnd/internal/domain/question_type_builder_test.go` | Tests: two OPTION elements each with own correct → OK; zero correct / <2 options / dup option ids → error |
|
||||
|
||||
---
|
||||
|
||||
## Implementation detail
|
||||
|
||||
### 1. Radio group (primary fix)
|
||||
|
||||
```tsx
|
||||
// DynamicMultipleChoiceSlot — add prop
|
||||
groupName: string
|
||||
|
||||
<input type="radio" name={groupName} ... />
|
||||
|
||||
// Caller
|
||||
<DynamicMultipleChoiceSlot
|
||||
...
|
||||
groupName={`mcq-correct-${side}-${row.id}`}
|
||||
/>
|
||||
```
|
||||
|
||||
No change to field state keys or payload shape — they already use `response:${row.id}`.
|
||||
|
||||
### 2. Positional pairing (matching / cloze)
|
||||
|
||||
- Build ordered lists of input-family and answer-family slots (schema order: stimulus then response for matching; cloze answer index within response vs stimulus cloze list).
|
||||
- Pair *k*-th answer with *k*-th inputs/stimulus.
|
||||
- If target empty or index OOB → fall back to existing `find*InFieldValues` (preserves single-slot behavior).
|
||||
|
||||
Wire the new helpers in:
|
||||
- `DynamicSchemaSlotField` (editor dropdowns)
|
||||
- `practiceDynamicQuestionPayload` (persist)
|
||||
- `learnEnglishDefinitionQuestion` (save validation)
|
||||
|
||||
### 3. Backend MCQ value check
|
||||
|
||||
Per element (stimulus and response loops), when kind is `OPTION` or `MULTIPLE_CHOICE`:
|
||||
|
||||
- `value` must be an object with `options` array length ≥ 2
|
||||
- option `id`s unique when present
|
||||
- at least one `is_correct: true`
|
||||
|
||||
Do **not** add cross-slot matching/cloze validation in Go in this pass.
|
||||
|
||||
---
|
||||
|
||||
## Verification
|
||||
|
||||
1. Definition with **two OPTION** response slots: mark different corrects in each; both stay selected; save + reload → each element in `dynamic_payload` has its own `is_correct`
|
||||
2. OPTION on stimulus + response: no cross-side radio interference
|
||||
3. Two matching pairs and two cloze pairs: each answer slot shows / saves against its own inputs/stimulus
|
||||
4. Single-slot OPTION / matching / cloze: unchanged behavior
|
||||
5. `go test ./internal/domain/...` — new MCQ multi-element cases pass; existing tests green
|
||||
6. Save with a second OPTION slot that has no correct marked → client and API reject with slot-scoped error
|
||||
|
||||
## Out of scope
|
||||
|
||||
- Legacy flat `mcqOptions` → first dynamic slot seed
|
||||
- Legacy outbound `schemaElementID(kind)` first-of-kind
|
||||
- DB/schema migrations or `config.pairs_with`
|
||||
- Mobile/learner grading changes
|
||||
|
|
@ -519,6 +519,10 @@ func ValidateDynamicPayloadAgainstDefinition(payload DynamicQuestionPayload, def
|
|||
if _, ok := allowedStimulus[kind]; !ok {
|
||||
errs = append(errs, fmt.Sprintf("dynamic_payload.stimulus[%d]: kind %q is not allowed by selected definition", i, kind))
|
||||
}
|
||||
if isMultipleChoiceComponentKind(kind) {
|
||||
errs = append(errs, validateMultipleChoiceElementValue(
|
||||
fmt.Sprintf("dynamic_payload.stimulus[%d]", i), el.Value)...)
|
||||
}
|
||||
}
|
||||
|
||||
for i, el := range payload.Response {
|
||||
|
|
@ -538,6 +542,10 @@ func ValidateDynamicPayloadAgainstDefinition(payload DynamicQuestionPayload, def
|
|||
if _, ok := allowedResponse[kind]; !ok {
|
||||
errs = append(errs, fmt.Sprintf("dynamic_payload.response[%d]: kind %q is not allowed by selected definition", i, kind))
|
||||
}
|
||||
if isMultipleChoiceComponentKind(kind) {
|
||||
errs = append(errs, validateMultipleChoiceElementValue(
|
||||
fmt.Sprintf("dynamic_payload.response[%d]", i), el.Value)...)
|
||||
}
|
||||
}
|
||||
|
||||
for id := range requiredStimulusIDs {
|
||||
|
|
@ -558,6 +566,68 @@ func ValidateDynamicPayloadAgainstDefinition(payload DynamicQuestionPayload, def
|
|||
return fmt.Errorf("%s", strings.Join(errs, "; "))
|
||||
}
|
||||
|
||||
func isMultipleChoiceComponentKind(kind string) bool {
|
||||
switch strings.TrimSpace(kind) {
|
||||
case string(ResponseMultipleChoice), string(ResponseOption):
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// validateMultipleChoiceElementValue checks OPTION / MULTIPLE_CHOICE value shape when options are present.
|
||||
// Empty options are skipped so optional unfilled slots can still appear in the payload.
|
||||
// Each filled element must have its own correct choice (not a question-global one).
|
||||
func validateMultipleChoiceElementValue(prefix string, value interface{}) []string {
|
||||
if value == nil {
|
||||
return nil
|
||||
}
|
||||
m, ok := value.(map[string]interface{})
|
||||
if !ok {
|
||||
return []string{fmt.Sprintf("%s: multiple-choice value must be an object", prefix)}
|
||||
}
|
||||
rawOpts, ok := m["options"]
|
||||
if !ok || rawOpts == nil {
|
||||
return nil
|
||||
}
|
||||
opts, ok := rawOpts.([]interface{})
|
||||
if !ok {
|
||||
return []string{fmt.Sprintf("%s: options must be an array", prefix)}
|
||||
}
|
||||
if len(opts) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
var errs []string
|
||||
if len(opts) < 2 {
|
||||
errs = append(errs, fmt.Sprintf("%s: at least 2 options required", prefix))
|
||||
}
|
||||
|
||||
correct := 0
|
||||
ids := make(map[string]struct{})
|
||||
for _, o := range opts {
|
||||
om, ok := o.(map[string]interface{})
|
||||
if !ok {
|
||||
errs = append(errs, fmt.Sprintf("%s: each option must be an object", prefix))
|
||||
continue
|
||||
}
|
||||
if id, _ := om["id"].(string); strings.TrimSpace(id) != "" {
|
||||
id = strings.TrimSpace(id)
|
||||
if _, dup := ids[id]; dup {
|
||||
errs = append(errs, fmt.Sprintf("%s: duplicate option id %q", prefix, id))
|
||||
}
|
||||
ids[id] = struct{}{}
|
||||
}
|
||||
if c, _ := om["is_correct"].(bool); c {
|
||||
correct++
|
||||
}
|
||||
}
|
||||
if correct < 1 {
|
||||
errs = append(errs, fmt.Sprintf("%s: mark at least one option correct", prefix))
|
||||
}
|
||||
return errs
|
||||
}
|
||||
|
||||
func normalizeKindList(in []string) []string {
|
||||
var out []string
|
||||
for _, s := range in {
|
||||
|
|
|
|||
|
|
@ -200,6 +200,123 @@ func TestValidateDynamicPayloadAgainstDefinition_requiredMissing(t *testing.T) {
|
|||
}
|
||||
}
|
||||
|
||||
func TestValidateDynamicPayloadAgainstDefinition_multiOptionCorrectPerElement(t *testing.T) {
|
||||
def := QuestionTypeDefinition{
|
||||
ResponseComponentKinds: []string{"OPTION"},
|
||||
ResponseSchema: []DynamicElementDefinition{
|
||||
{ID: "choices_1", Kind: "OPTION", Required: true},
|
||||
{ID: "choices_2", Kind: "OPTION", Required: true},
|
||||
},
|
||||
}
|
||||
payload := DynamicQuestionPayload{
|
||||
Response: []DynamicElementInstance{
|
||||
{
|
||||
ID: "choices_1",
|
||||
Kind: "OPTION",
|
||||
Value: map[string]interface{}{
|
||||
"options": []interface{}{
|
||||
map[string]interface{}{"id": "a", "text": "One", "is_correct": true},
|
||||
map[string]interface{}{"id": "b", "text": "Two", "is_correct": false},
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
ID: "choices_2",
|
||||
Kind: "OPTION",
|
||||
Value: map[string]interface{}{
|
||||
"options": []interface{}{
|
||||
map[string]interface{}{"id": "a", "text": "Red", "is_correct": false},
|
||||
map[string]interface{}{"id": "b", "text": "Blue", "is_correct": true},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
if err := ValidateDynamicPayloadAgainstDefinition(payload, def); err != nil {
|
||||
t.Fatalf("expected multi-OPTION payload with per-element correct answers to pass, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateDynamicPayloadAgainstDefinition_optionMissingCorrect(t *testing.T) {
|
||||
def := QuestionTypeDefinition{
|
||||
ResponseComponentKinds: []string{"OPTION"},
|
||||
ResponseSchema: []DynamicElementDefinition{
|
||||
{ID: "choices_1", Kind: "OPTION", Required: true},
|
||||
},
|
||||
}
|
||||
payload := DynamicQuestionPayload{
|
||||
Response: []DynamicElementInstance{
|
||||
{
|
||||
ID: "choices_1",
|
||||
Kind: "OPTION",
|
||||
Value: map[string]interface{}{
|
||||
"options": []interface{}{
|
||||
map[string]interface{}{"id": "a", "text": "One", "is_correct": false},
|
||||
map[string]interface{}{"id": "b", "text": "Two", "is_correct": false},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
err := ValidateDynamicPayloadAgainstDefinition(payload, def)
|
||||
if err == nil || !strings.Contains(err.Error(), "mark at least one option correct") {
|
||||
t.Fatalf("expected missing-correct error, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateDynamicPayloadAgainstDefinition_optionTooFewOptions(t *testing.T) {
|
||||
def := QuestionTypeDefinition{
|
||||
ResponseComponentKinds: []string{"MULTIPLE_CHOICE"},
|
||||
ResponseSchema: []DynamicElementDefinition{
|
||||
{ID: "mcq_1", Kind: "MULTIPLE_CHOICE", Required: true},
|
||||
},
|
||||
}
|
||||
payload := DynamicQuestionPayload{
|
||||
Response: []DynamicElementInstance{
|
||||
{
|
||||
ID: "mcq_1",
|
||||
Kind: "MULTIPLE_CHOICE",
|
||||
Value: map[string]interface{}{
|
||||
"options": []interface{}{
|
||||
map[string]interface{}{"id": "a", "text": "Only", "is_correct": true},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
err := ValidateDynamicPayloadAgainstDefinition(payload, def)
|
||||
if err == nil || !strings.Contains(err.Error(), "at least 2 options") {
|
||||
t.Fatalf("expected too-few-options error, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateDynamicPayloadAgainstDefinition_optionDuplicateOptionID(t *testing.T) {
|
||||
def := QuestionTypeDefinition{
|
||||
ResponseComponentKinds: []string{"OPTION"},
|
||||
ResponseSchema: []DynamicElementDefinition{
|
||||
{ID: "choices_1", Kind: "OPTION", Required: true},
|
||||
},
|
||||
}
|
||||
payload := DynamicQuestionPayload{
|
||||
Response: []DynamicElementInstance{
|
||||
{
|
||||
ID: "choices_1",
|
||||
Kind: "OPTION",
|
||||
Value: map[string]interface{}{
|
||||
"options": []interface{}{
|
||||
map[string]interface{}{"id": "a", "text": "One", "is_correct": true},
|
||||
map[string]interface{}{"id": "a", "text": "Two", "is_correct": false},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
err := ValidateDynamicPayloadAgainstDefinition(payload, def)
|
||||
if err == nil || !strings.Contains(err.Error(), "duplicate option id") {
|
||||
t.Fatalf("expected duplicate option id error, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func testQuestionTypeCatalog() []QuestionTypeDefinition {
|
||||
return []QuestionTypeDefinition{
|
||||
{ID: 1, Key: "multiple_choice", DisplayName: "Multiple Choice", IsSystem: true},
|
||||
|
|
|
|||
Loading…
Reference in New Issue
Block a user