feat: add assessment, privacy and support flows
This commit is contained in:
1 parent
ee3738ee73
commit
e4f24fa202
339 files changed
+56454
-1126
No files matched your search
@@ -0,0 +1,657 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"math"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// AssessmentBasicScore is the reproducible raw result of a demo_basic run.
|
||||
type AssessmentBasicScore struct {
|
||||
Points int32 `json:"points"`
|
||||
MaxPoints int32 `json:"max_points"`
|
||||
PassPoints int32 `json:"pass_points"`
|
||||
}
|
||||
|
||||
// AssessmentAttemptDecision is the immutable completion data derived from
|
||||
// answers and the policy pinned to the attempt.
|
||||
type AssessmentAttemptDecision struct {
|
||||
Outcome AssessmentAttemptOutcome
|
||||
Score *AssessmentBasicScore
|
||||
Rationale AssessmentAttemptDecisionRationale
|
||||
}
|
||||
|
||||
type numberAssessmentAnswer struct {
|
||||
Format string `json:"format"`
|
||||
Number json.RawMessage `json:"number"`
|
||||
}
|
||||
|
||||
type orderAssessmentAnswer struct {
|
||||
Format string `json:"format"`
|
||||
ElementIDs []string `json:"element_ids"`
|
||||
}
|
||||
|
||||
// CanonicalAssessmentAnswer validates and canonicalizes a request answer
|
||||
// before its idempotency fingerprint is created.
|
||||
func CanonicalAssessmentAnswer(answer json.RawMessage) (json.RawMessage, error) {
|
||||
const location = "domain.CanonicalAssessmentAnswer"
|
||||
format, err := assessmentAnswerFormat(answer)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s - answer format is invalid: %w", location, ErrInvalidAssessmentAttempt)
|
||||
}
|
||||
switch format {
|
||||
case "number":
|
||||
canonical, err := canonicalNumberAssessmentAnswer(answer)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s - number answer is invalid or exceeds its bound: %w", location, err)
|
||||
}
|
||||
return canonical, nil
|
||||
case "order":
|
||||
canonical, err := canonicalOrderAssessmentAnswer(answer)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s - order answer is invalid or exceeds its bound: %w", location, err)
|
||||
}
|
||||
return canonical, nil
|
||||
default:
|
||||
return nil, fmt.Errorf("%s - answer format is not supported by the current bank: %w", location, ErrInvalidAssessmentAttempt)
|
||||
}
|
||||
}
|
||||
|
||||
func assessmentAnswerFormat(answer json.RawMessage) (string, error) {
|
||||
if len(answer) == 0 || len(answer) > maxAssessmentAttemptAnswerBytes {
|
||||
return "", ErrInvalidAssessmentAttempt
|
||||
}
|
||||
var header struct {
|
||||
Format string `json:"format"`
|
||||
}
|
||||
if err := json.Unmarshal(answer, &header); err != nil || header.Format == "" {
|
||||
return "", ErrInvalidAssessmentAttempt
|
||||
}
|
||||
return header.Format, nil
|
||||
}
|
||||
|
||||
func canonicalNumberAssessmentAnswer(answer []byte) ([]byte, error) {
|
||||
var submitted numberAssessmentAnswer
|
||||
if err := decodeStrictAssessmentAnswer(answer, &submitted); err != nil || len(submitted.Number) == 0 {
|
||||
return nil, ErrInvalidAssessmentAttempt
|
||||
}
|
||||
number, err := canonicalAssessmentNumber(submitted.Number)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
canonical, err := json.Marshal(struct {
|
||||
Format string `json:"format"`
|
||||
Number json.RawMessage `json:"number"`
|
||||
}{Format: "number", Number: json.RawMessage(number)})
|
||||
if err != nil || len(canonical) > maxAssessmentAttemptAnswerBytes {
|
||||
return nil, ErrInvalidAssessmentAttempt
|
||||
}
|
||||
return canonical, nil
|
||||
}
|
||||
|
||||
func canonicalOrderAssessmentAnswer(answer []byte) ([]byte, error) {
|
||||
var submitted orderAssessmentAnswer
|
||||
if err := decodeStrictAssessmentAnswer(answer, &submitted); err != nil || len(submitted.ElementIDs) < 2 || len(submitted.ElementIDs) > 20 {
|
||||
return nil, ErrInvalidAssessmentAttempt
|
||||
}
|
||||
if err := validateAssessmentOrderElements(submitted.ElementIDs); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
canonical, err := json.Marshal(map[string]any{"format": "order", "element_ids": submitted.ElementIDs})
|
||||
if err != nil || len(canonical) > maxAssessmentAttemptAnswerBytes {
|
||||
return nil, ErrInvalidAssessmentAttempt
|
||||
}
|
||||
return canonical, nil
|
||||
}
|
||||
|
||||
func validateAssessmentOrderElements(elementIDs []string) error {
|
||||
seen := make(map[string]struct{}, len(elementIDs))
|
||||
for _, elementID := range elementIDs {
|
||||
if !assessmentPublicTaskElementIDPattern.MatchString(elementID) {
|
||||
return ErrInvalidAssessmentAttempt
|
||||
}
|
||||
if _, exists := seen[elementID]; exists {
|
||||
return ErrInvalidAssessmentAttempt
|
||||
}
|
||||
seen[elementID] = struct{}{}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// CanonicalAssessmentAnswerForVariant accepts only the answer formats
|
||||
// currently produced by the reviewed assessment bank. The returned JSON is
|
||||
// stable for idempotency and preserves exact sequence semantics for orders.
|
||||
func CanonicalAssessmentAnswerForVariant(answer json.RawMessage, variant AssessmentVariant) (json.RawMessage, bool, error) {
|
||||
const location = "domain.CanonicalAssessmentAnswerForVariant"
|
||||
canonical, err := CanonicalAssessmentAnswer(answer)
|
||||
if err != nil {
|
||||
return nil, false, fmt.Errorf("%s - canonicalize answer: %w", location, err)
|
||||
}
|
||||
switch variant.AnswerFormat {
|
||||
case AnswerFormatInteger:
|
||||
correct, err := assessmentIntegerAnswerIsCorrect(canonical, variant.ReferenceAnswer)
|
||||
if err != nil {
|
||||
return nil, false, fmt.Errorf("%s - compare frozen integer key: %w", location, err)
|
||||
}
|
||||
return canonical, correct, nil
|
||||
case AnswerFormatIntegerSequence:
|
||||
correct, err := assessmentOrderAnswerIsCorrect(canonical, variant)
|
||||
if err != nil {
|
||||
return nil, false, fmt.Errorf("%s - compare frozen order key: %w", location, err)
|
||||
}
|
||||
return canonical, correct, nil
|
||||
default:
|
||||
return nil, false, fmt.Errorf("%s - frozen answer format is unsupported: %w", location, ErrInvalidAssessmentAttempt)
|
||||
}
|
||||
}
|
||||
|
||||
func assessmentIntegerAnswerIsCorrect(canonical []byte, referenceAnswer string) (bool, error) {
|
||||
var submitted numberAssessmentAnswer
|
||||
if err := decodeStrictAssessmentAnswer(canonical, &submitted); err != nil || submitted.Format != "number" || len(submitted.Number) == 0 {
|
||||
return false, ErrInvalidAssessmentAttempt
|
||||
}
|
||||
reference, err := strconv.ParseInt(referenceAnswer, 10, 64)
|
||||
if err != nil {
|
||||
return false, ErrInvalidAssessmentAttempt
|
||||
}
|
||||
return string(submitted.Number) == strconv.FormatInt(reference, 10), nil
|
||||
}
|
||||
|
||||
func assessmentOrderAnswerIsCorrect(canonical []byte, variant AssessmentVariant) (bool, error) {
|
||||
var submitted orderAssessmentAnswer
|
||||
if err := decodeStrictAssessmentAnswer(canonical, &submitted); err != nil || submitted.Format != "order" {
|
||||
return false, ErrInvalidAssessmentAttempt
|
||||
}
|
||||
taskCount, ok := variant.Parameters["tasks"]
|
||||
if !ok || taskCount < 2 || taskCount > 20 || len(submitted.ElementIDs) != int(taskCount) {
|
||||
return false, ErrInvalidAssessmentAttempt
|
||||
}
|
||||
if err := validateAssessmentOrderElements(submitted.ElementIDs); err != nil || !assessmentOrderHasEveryTask(submitted.ElementIDs, taskCount) {
|
||||
return false, ErrInvalidAssessmentAttempt
|
||||
}
|
||||
return assessmentOrderMatchesReference(submitted.ElementIDs, variant.ReferenceAnswer, taskCount)
|
||||
}
|
||||
|
||||
func assessmentOrderHasEveryTask(elementIDs []string, taskCount int32) bool {
|
||||
seen := make(map[string]struct{}, len(elementIDs))
|
||||
for _, elementID := range elementIDs {
|
||||
seen[elementID] = struct{}{}
|
||||
}
|
||||
for ordinal := int32(1); ordinal <= taskCount; ordinal++ {
|
||||
if _, exists := seen["job_"+strconv.FormatInt(int64(ordinal), 10)]; !exists {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func assessmentOrderMatchesReference(elementIDs []string, referenceAnswer string, taskCount int32) (bool, error) {
|
||||
reference := strings.Fields(referenceAnswer)
|
||||
if len(reference) != int(taskCount) {
|
||||
return false, ErrInvalidAssessmentAttempt
|
||||
}
|
||||
for index, token := range reference {
|
||||
ordinal, err := strconv.ParseInt(token, 10, 32)
|
||||
if err != nil || ordinal < 1 || ordinal > int64(taskCount) {
|
||||
return false, ErrInvalidAssessmentAttempt
|
||||
}
|
||||
if elementIDs[index] != "job_"+strconv.FormatInt(ordinal, 10) {
|
||||
return false, nil
|
||||
}
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
|
||||
func decodeStrictAssessmentAnswer(encoded []byte, target any) error {
|
||||
if len(encoded) == 0 || len(encoded) > maxAssessmentAttemptAnswerBytes || !json.Valid(encoded) {
|
||||
return ErrInvalidAssessmentAttempt
|
||||
}
|
||||
decoder := json.NewDecoder(bytes.NewReader(encoded))
|
||||
decoder.UseNumber()
|
||||
decoder.DisallowUnknownFields()
|
||||
if err := decoder.Decode(target); err != nil {
|
||||
return errors.Join(ErrInvalidAssessmentAttempt, err)
|
||||
}
|
||||
var extra any
|
||||
if err := decoder.Decode(&extra); !errors.Is(err, io.EOF) {
|
||||
return ErrInvalidAssessmentAttempt
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func canonicalAssessmentNumber(encoded json.RawMessage) (string, error) {
|
||||
if len(encoded) == 0 || len(encoded) > maxAssessmentAttemptAnswerBytes || !json.Valid(encoded) {
|
||||
return "", ErrInvalidAssessmentAttempt
|
||||
}
|
||||
decoder := json.NewDecoder(bytes.NewReader(encoded))
|
||||
decoder.UseNumber()
|
||||
var value any
|
||||
if err := decoder.Decode(&value); err != nil {
|
||||
return "", ErrInvalidAssessmentAttempt
|
||||
}
|
||||
number, ok := value.(json.Number)
|
||||
if !ok {
|
||||
return "", ErrInvalidAssessmentAttempt
|
||||
}
|
||||
digits, scale, negative, err := assessmentDecimalParts(number.String())
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return formatAssessmentDecimal(digits, scale, negative)
|
||||
}
|
||||
|
||||
func assessmentDecimalParts(text string) (string, int64, bool, error) {
|
||||
negative := strings.HasPrefix(text, "-")
|
||||
if negative {
|
||||
text = text[1:]
|
||||
}
|
||||
mantissa, exponent, err := assessmentDecimalMantissaAndExponent(text)
|
||||
if err != nil {
|
||||
return "", 0, false, err
|
||||
}
|
||||
integerDigits := mantissa
|
||||
fractionDigits := ""
|
||||
if point := strings.IndexByte(mantissa, '.'); point >= 0 {
|
||||
integerDigits = mantissa[:point]
|
||||
fractionDigits = mantissa[point+1:]
|
||||
}
|
||||
digits := integerDigits + fractionDigits
|
||||
scale := int64(len(fractionDigits)) - exponent
|
||||
if scale > maxAssessmentAttemptAnswerBytes || scale < -maxAssessmentAttemptAnswerBytes {
|
||||
return "", 0, false, ErrInvalidAssessmentAttempt
|
||||
}
|
||||
digits = strings.TrimLeft(digits, "0")
|
||||
for len(digits) > 0 && scale > 0 && digits[len(digits)-1] == '0' {
|
||||
digits = digits[:len(digits)-1]
|
||||
scale--
|
||||
}
|
||||
return digits, scale, negative, nil
|
||||
}
|
||||
|
||||
func assessmentDecimalMantissaAndExponent(text string) (string, int64, error) {
|
||||
decimalAt := strings.IndexAny(text, ".eE")
|
||||
mantissa := text
|
||||
exponent := int64(0)
|
||||
if decimalAt >= 0 {
|
||||
if text[decimalAt] == '.' {
|
||||
exponentAt := strings.IndexAny(text[decimalAt+1:], "eE")
|
||||
if exponentAt >= 0 {
|
||||
exponentAt += decimalAt + 1
|
||||
parsed, err := parseAssessmentExponent(text[exponentAt+1:])
|
||||
if err != nil {
|
||||
return "", 0, err
|
||||
}
|
||||
exponent = parsed
|
||||
mantissa = text[:exponentAt]
|
||||
}
|
||||
} else {
|
||||
mantissa = text[:decimalAt]
|
||||
parsed, err := parseAssessmentExponent(text[decimalAt+1:])
|
||||
if err != nil {
|
||||
return "", 0, err
|
||||
}
|
||||
exponent = parsed
|
||||
}
|
||||
}
|
||||
return mantissa, exponent, nil
|
||||
}
|
||||
|
||||
func parseAssessmentExponent(value string) (int64, error) {
|
||||
exponent, err := strconv.ParseInt(value, 10, 64)
|
||||
if err != nil || exponent > maxAssessmentAttemptAnswerBytes || exponent < -maxAssessmentAttemptAnswerBytes {
|
||||
return 0, ErrInvalidAssessmentAttempt
|
||||
}
|
||||
return exponent, nil
|
||||
}
|
||||
|
||||
func formatAssessmentDecimal(digits string, scale int64, negative bool) (string, error) {
|
||||
if digits == "" {
|
||||
return "0", nil
|
||||
}
|
||||
outputLength := len(digits)
|
||||
switch {
|
||||
case scale <= 0:
|
||||
outputLength += int(-scale)
|
||||
case int64(len(digits)) <= scale:
|
||||
outputLength += int(scale-int64(len(digits))) + 2
|
||||
default:
|
||||
outputLength++
|
||||
}
|
||||
if negative {
|
||||
outputLength++
|
||||
}
|
||||
if outputLength > maxAssessmentAttemptAnswerBytes {
|
||||
return "", ErrInvalidAssessmentAttempt
|
||||
}
|
||||
var canonical string
|
||||
switch {
|
||||
case scale <= 0:
|
||||
canonical = digits + strings.Repeat("0", int(-scale))
|
||||
case int64(len(digits)) <= scale:
|
||||
canonical = "0." + strings.Repeat("0", int(scale-int64(len(digits)))) + digits
|
||||
default:
|
||||
point := len(digits) - int(scale)
|
||||
canonical = digits[:point] + "." + digits[point:]
|
||||
}
|
||||
if negative {
|
||||
canonical = "-" + canonical
|
||||
}
|
||||
return canonical, nil
|
||||
}
|
||||
|
||||
// SubmitAnswer stores one final answer to the current frozen item. Identical
|
||||
// repeats are no-ops even when their expected version is stale.
|
||||
func (attempt AssessmentAttempt) SubmitAnswer(
|
||||
expectedVersion int64,
|
||||
itemID uuid.UUID,
|
||||
answer json.RawMessage,
|
||||
at time.Time,
|
||||
) (AssessmentAttempt, bool, error) {
|
||||
const location = "AssessmentAttempt.SubmitAnswer"
|
||||
if attempt.IsZero() || itemID == uuid.Nil || at.IsZero() {
|
||||
return AssessmentAttempt{}, false, fmt.Errorf("%s - attempt, item, and time are required: %w", location, ErrInvalidAssessmentAttempt)
|
||||
}
|
||||
index := attempt.itemIndex(itemID)
|
||||
if index < 0 {
|
||||
return AssessmentAttempt{}, false, fmt.Errorf("%s - item is not part of this attempt: %w", location, ErrInvalidAssessmentAttempt)
|
||||
}
|
||||
return attempt.submitAnswerToItem(expectedVersion, index, answer, canonicalAssessmentTime(at))
|
||||
}
|
||||
|
||||
func (attempt AssessmentAttempt) submitAnswerToItem(
|
||||
expectedVersion int64,
|
||||
index int,
|
||||
answer json.RawMessage,
|
||||
answeredAt time.Time,
|
||||
) (AssessmentAttempt, bool, error) {
|
||||
const location = "AssessmentAttempt.submitAnswerToItem"
|
||||
item := attempt.snapshot.Items[index]
|
||||
canonical, _, err := CanonicalAssessmentAnswerForVariant(answer, item.Variant)
|
||||
if err != nil {
|
||||
return AssessmentAttempt{}, false, fmt.Errorf("%s - validate answer: %w", location, err)
|
||||
}
|
||||
replayed, err := assessmentAnswerReplay(item, canonical, expectedVersion, attempt.snapshot.Version)
|
||||
if err != nil {
|
||||
return AssessmentAttempt{}, false, fmt.Errorf("%s - check existing answer: %w", location, err)
|
||||
}
|
||||
if replayed {
|
||||
return attempt, false, nil
|
||||
}
|
||||
if err := validateNewAssessmentAnswer(attempt.snapshot, index, expectedVersion, answeredAt); err != nil {
|
||||
return AssessmentAttempt{}, false, fmt.Errorf("%s - validate lifecycle: %w", location, err)
|
||||
}
|
||||
return storeAssessmentAttemptAnswer(attempt, index, canonical, answeredAt)
|
||||
}
|
||||
|
||||
func assessmentAnswerReplay(
|
||||
item AssessmentAttemptItemSnapshot,
|
||||
canonical []byte,
|
||||
expectedVersion, currentVersion int64,
|
||||
) (bool, error) {
|
||||
if len(item.Answer) == 0 {
|
||||
return false, nil
|
||||
}
|
||||
if bytes.Equal(item.Answer, canonical) {
|
||||
return true, nil
|
||||
}
|
||||
if expectedVersion != currentVersion {
|
||||
return false, ErrAssessmentAttemptVersionConflict
|
||||
}
|
||||
return false, ErrAssessmentAttemptNotActive
|
||||
}
|
||||
|
||||
func validateNewAssessmentAnswer(
|
||||
snapshot AssessmentAttemptSnapshot,
|
||||
index int,
|
||||
expectedVersion int64,
|
||||
answeredAt time.Time,
|
||||
) error {
|
||||
if expectedVersion != snapshot.Version {
|
||||
return ErrAssessmentAttemptVersionConflict
|
||||
}
|
||||
if snapshot.State != AssessmentAttemptStateInProgress ||
|
||||
!answeredAt.Before(snapshot.ExpiresAt) || !snapshot.ChainDeadline.IsZero() && !answeredAt.Before(snapshot.ChainDeadline) {
|
||||
return ErrAssessmentAttemptNotActive
|
||||
}
|
||||
idleAt := snapshot.LastActivityAt.Add(time.Duration(snapshot.IdleTimeoutSeconds) * time.Second)
|
||||
if !answeredAt.Before(idleAt) {
|
||||
return ErrAssessmentAttemptNotActive
|
||||
}
|
||||
if answeredAt.Before(snapshot.LastActivityAt) {
|
||||
return ErrInvalidAssessmentAttempt
|
||||
}
|
||||
if index != firstUnansweredAssessmentItemIndex(snapshot.Items) {
|
||||
return ErrAssessmentAttemptNotActive
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func storeAssessmentAttemptAnswer(
|
||||
attempt AssessmentAttempt,
|
||||
index int,
|
||||
canonical []byte,
|
||||
answeredAt time.Time,
|
||||
) (AssessmentAttempt, bool, error) {
|
||||
next := attempt.Snapshot()
|
||||
next.Items[index].Answer = canonical
|
||||
next.Items[index].AnsweredAt = answeredAt
|
||||
next.LastActivityAt = answeredAt
|
||||
next.UpdatedAt = answeredAt
|
||||
next.Version++
|
||||
if allAssessmentAttemptItemsAnswered(next.Items) {
|
||||
next.State = AssessmentAttemptStateReadyToFinalize
|
||||
}
|
||||
updated, err := RestoreAssessmentAttempt(next)
|
||||
return updated, true, err
|
||||
}
|
||||
|
||||
func (attempt AssessmentAttempt) itemIndex(itemID uuid.UUID) int {
|
||||
for index, item := range attempt.snapshot.Items {
|
||||
if item.ID == itemID {
|
||||
return index
|
||||
}
|
||||
}
|
||||
return -1
|
||||
}
|
||||
|
||||
func firstUnansweredAssessmentItemIndex(items []AssessmentAttemptItemSnapshot) int {
|
||||
for index, item := range items {
|
||||
if len(item.Answer) == 0 {
|
||||
return index
|
||||
}
|
||||
}
|
||||
return -1
|
||||
}
|
||||
|
||||
func allAssessmentAttemptItemsAnswered(items []AssessmentAttemptItemSnapshot) bool {
|
||||
if len(items) == 0 {
|
||||
return false
|
||||
}
|
||||
for _, item := range items {
|
||||
if len(item.Answer) == 0 {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// ExpireIfDue records the terminal deadline transition for an incomplete
|
||||
// in-progress attempt. It does not advance time for read operations.
|
||||
func (attempt AssessmentAttempt) ExpireIfDue(at time.Time) (AssessmentAttempt, bool, error) {
|
||||
const location = "AssessmentAttempt.ExpireIfDue"
|
||||
if attempt.IsZero() || at.IsZero() {
|
||||
return AssessmentAttempt{}, false, fmt.Errorf("%s - attempt and time are required: %w", location, ErrInvalidAssessmentAttempt)
|
||||
}
|
||||
if attempt.snapshot.State != AssessmentAttemptStateInProgress {
|
||||
return attempt, false, nil
|
||||
}
|
||||
expiredAt := canonicalAssessmentTime(at)
|
||||
if expiredAt.Before(attempt.snapshot.LastActivityAt) {
|
||||
return AssessmentAttempt{}, false, fmt.Errorf("%s - expiry time predates activity: %w", location, ErrInvalidAssessmentAttempt)
|
||||
}
|
||||
if expiredAt.Before(attempt.snapshot.ExpiresAt) &&
|
||||
(attempt.snapshot.ChainDeadline.IsZero() || expiredAt.Before(attempt.snapshot.ChainDeadline)) {
|
||||
return attempt, false, nil
|
||||
}
|
||||
next := attempt.Snapshot()
|
||||
next.State = AssessmentAttemptStateExpired
|
||||
next.UpdatedAt = expiredAt
|
||||
next.EndedAt = expiredAt
|
||||
next.Version++
|
||||
updated, err := RestoreAssessmentAttempt(next)
|
||||
return updated, true, err
|
||||
}
|
||||
|
||||
// FinalizeDemo applies only the explicit demo_basic pass mark or returns a
|
||||
// separate demonstration outcome for demo_express. Adaptive scoring is not
|
||||
// inferred from a basic score.
|
||||
func (attempt AssessmentAttempt) FinalizeDemo(
|
||||
expectedVersion int64,
|
||||
policy AssessmentPolicy,
|
||||
at time.Time,
|
||||
) (AssessmentAttempt, bool, AssessmentAttemptDecision, error) {
|
||||
const location = "AssessmentAttempt.FinalizeDemo"
|
||||
if attempt.IsZero() || at.IsZero() {
|
||||
return AssessmentAttempt{}, false, AssessmentAttemptDecision{}, fmt.Errorf("%s - attempt and time are required: %w", location, ErrInvalidAssessmentAttempt)
|
||||
}
|
||||
if attempt.snapshot.State == AssessmentAttemptStateCompleted {
|
||||
decision, err := decisionForCompletedAttempt(attempt, policy)
|
||||
return attempt, false, decision, err
|
||||
}
|
||||
if expectedVersion != attempt.snapshot.Version {
|
||||
return AssessmentAttempt{}, false, AssessmentAttemptDecision{}, fmt.Errorf("%s - expected version is stale: %w", location, ErrAssessmentAttemptVersionConflict)
|
||||
}
|
||||
if attempt.snapshot.State != AssessmentAttemptStateReadyToFinalize || !allAssessmentAttemptItemsAnswered(attempt.snapshot.Items) {
|
||||
return AssessmentAttempt{}, false, AssessmentAttemptDecision{}, fmt.Errorf("%s - required assessment answers are incomplete: %w", location, ErrAssessmentAttemptNotActive)
|
||||
}
|
||||
finalizedAt := canonicalAssessmentTime(at)
|
||||
if finalizedAt.Before(attempt.snapshot.LastActivityAt) {
|
||||
return AssessmentAttempt{}, false, AssessmentAttemptDecision{}, fmt.Errorf("%s - decision time predates answer activity: %w", location, ErrInvalidAssessmentAttempt)
|
||||
}
|
||||
idleAt := attempt.snapshot.LastActivityAt.Add(time.Duration(attempt.snapshot.IdleTimeoutSeconds) * time.Second)
|
||||
deadlineDue := !finalizedAt.Before(attempt.snapshot.ExpiresAt) ||
|
||||
!attempt.snapshot.ChainDeadline.IsZero() && !finalizedAt.Before(attempt.snapshot.ChainDeadline)
|
||||
if !finalizedAt.Before(idleAt) && !deadlineDue {
|
||||
return AssessmentAttempt{}, false, AssessmentAttemptDecision{}, fmt.Errorf("%s - work session is idle: %w", location, ErrAssessmentAttemptNotActive)
|
||||
}
|
||||
decision, err := assessmentAttemptDecision(attempt.snapshot, policy)
|
||||
if err != nil {
|
||||
return AssessmentAttempt{}, false, AssessmentAttemptDecision{}, fmt.Errorf("%s - calculate pinned demo decision: %w", location, err)
|
||||
}
|
||||
next := attempt.Snapshot()
|
||||
next.State = AssessmentAttemptStateCompleted
|
||||
next.Outcome = decision.Outcome
|
||||
next.EndedAt = finalizedAt
|
||||
next.UpdatedAt = finalizedAt
|
||||
next.Version++
|
||||
updated, err := RestoreAssessmentAttempt(next)
|
||||
return updated, true, decision, err
|
||||
}
|
||||
|
||||
func decisionForCompletedAttempt(attempt AssessmentAttempt, policy AssessmentPolicy) (AssessmentAttemptDecision, error) {
|
||||
return assessmentAttemptDecision(attempt.snapshot, policy)
|
||||
}
|
||||
|
||||
func assessmentAttemptDecision(snapshot AssessmentAttemptSnapshot, policy AssessmentPolicy) (AssessmentAttemptDecision, error) {
|
||||
if snapshot.Kind == AssessmentAttemptKindDemoExpress {
|
||||
return assessmentTrainingDecision(snapshot, policy)
|
||||
}
|
||||
if snapshot.Kind != AssessmentAttemptKindRoot && snapshot.Kind != AssessmentAttemptKindCorrective {
|
||||
return AssessmentAttemptDecision{}, ErrAssessmentAttemptNotActive
|
||||
}
|
||||
return assessmentBasicDecision(snapshot, policy)
|
||||
}
|
||||
|
||||
func assessmentTrainingDecision(snapshot AssessmentAttemptSnapshot, policy AssessmentPolicy) (AssessmentAttemptDecision, error) {
|
||||
if policy.Training == nil || !allAssessmentAttemptItemsAnswered(snapshot.Items) ||
|
||||
snapshot.State == AssessmentAttemptStateCompleted && snapshot.Outcome != AssessmentAttemptOutcomeDemonstration ||
|
||||
snapshot.State != AssessmentAttemptStateCompleted && snapshot.State != AssessmentAttemptStateReadyToFinalize {
|
||||
return AssessmentAttemptDecision{}, ErrInvalidAssessmentAttempt
|
||||
}
|
||||
return AssessmentAttemptDecision{
|
||||
Outcome: AssessmentAttemptOutcomeDemonstration,
|
||||
Rationale: AssessmentAttemptDecisionRationale{Rule: assessmentResultRuleTrainingOnly},
|
||||
}, nil
|
||||
}
|
||||
|
||||
func assessmentBasicDecision(snapshot AssessmentAttemptSnapshot, policy AssessmentPolicy) (AssessmentAttemptDecision, error) {
|
||||
maxScored, passMark, err := assessmentBasicDecisionInputs(snapshot, policy)
|
||||
if err != nil {
|
||||
return AssessmentAttemptDecision{}, err
|
||||
}
|
||||
points, err := scoreAssessmentAttemptItems(snapshot.Items, maxScored)
|
||||
if err != nil {
|
||||
return AssessmentAttemptDecision{}, err
|
||||
}
|
||||
passPoints64 := (int64(maxScored)*int64(passMark) + int64(basisPointsPerUnit) - 1) / int64(basisPointsPerUnit)
|
||||
if passPoints64 < 1 || passPoints64 > int64(maxScored) || passPoints64 > math.MaxInt32 {
|
||||
return AssessmentAttemptDecision{}, ErrInvalidAssessmentAttempt
|
||||
}
|
||||
passPoints := int32(passPoints64)
|
||||
outcome, err := assessmentBasicOutcome(snapshot, points, passPoints)
|
||||
if err != nil {
|
||||
return AssessmentAttemptDecision{}, err
|
||||
}
|
||||
return AssessmentAttemptDecision{
|
||||
Outcome: outcome,
|
||||
Score: &AssessmentBasicScore{Points: points, MaxPoints: maxScored, PassPoints: passPoints},
|
||||
Rationale: AssessmentAttemptDecisionRationale{
|
||||
Rule: assessmentResultRuleBasicPassMark, PassMarkBasisPoints: int32(passMark),
|
||||
PassPoints: passPoints, ScoredItems: maxScored,
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
|
||||
func assessmentBasicDecisionInputs(snapshot AssessmentAttemptSnapshot, policy AssessmentPolicy) (int32, BasisPoints, error) {
|
||||
if snapshot.Mode != AssessmentAttemptModeDemoBasic || policy.Attempt == nil || !allAssessmentAttemptItemsAnswered(snapshot.Items) {
|
||||
return 0, 0, ErrAssessmentAttemptNotActive
|
||||
}
|
||||
maxScored := policy.StopRule.MaxScoredItems
|
||||
seedCount := policy.StopRule.SeedItems
|
||||
if maxScored < 1 || seedCount < 0 || int64(maxScored)+int64(seedCount) != int64(len(snapshot.Items)) {
|
||||
return 0, 0, ErrInvalidAssessmentAttempt
|
||||
}
|
||||
passMark := policy.Attempt.BasicPassMark
|
||||
if passMark < 1 || passMark > basisPointsPerUnit {
|
||||
return 0, 0, ErrInvalidAssessmentAttempt
|
||||
}
|
||||
return maxScored, passMark, nil
|
||||
}
|
||||
|
||||
func assessmentBasicOutcome(
|
||||
snapshot AssessmentAttemptSnapshot,
|
||||
points int32,
|
||||
passPoints int32,
|
||||
) (AssessmentAttemptOutcome, error) {
|
||||
outcome := AssessmentAttemptOutcomeNotConfirmed
|
||||
if points >= passPoints {
|
||||
outcome = AssessmentAttemptOutcomeConfirmed
|
||||
}
|
||||
if snapshot.State == AssessmentAttemptStateCompleted && snapshot.Outcome != outcome {
|
||||
return "", ErrInvalidAssessmentAttempt
|
||||
}
|
||||
return outcome, nil
|
||||
}
|
||||
|
||||
func scoreAssessmentAttemptItems(items []AssessmentAttemptItemSnapshot, scoredItems int32) (int32, error) {
|
||||
var points int32
|
||||
for index := int32(0); index < scoredItems; index++ {
|
||||
item := items[index]
|
||||
_, correct, err := CanonicalAssessmentAnswerForVariant(item.Answer, item.Variant)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if correct {
|
||||
points++
|
||||
}
|
||||
}
|
||||
return points, nil
|
||||
}
|
||||
Reference in new issue
Block a user