feat: add questions to quiz

This commit is contained in:
Jannat Patel
2024-08-02 20:20:43 +05:30
parent 471e7d9229
commit 27ca13ece6
6 changed files with 509 additions and 184 deletions

View File

@@ -75,7 +75,7 @@
> >
<li <li
:class="[ :class="[
'flex items-center rounded px-2.5 py-1.5 text-base', 'flex items-center rounded px-2.5 py-2 text-base',
{ 'bg-gray-100': active }, { 'bg-gray-100': active },
]" ]"
> >
@@ -87,7 +87,14 @@
name="item-label" name="item-label"
v-bind="{ active, selected, option }" v-bind="{ active, selected, option }"
> >
{{ option.label }} <div class="flex flex-col space-y-1">
<div>
{{ option.label }}
</div>
<div class="text-xs text-gray-700">
{{ option.description }}
</div>
</div>
</slot> </slot>
</li> </li>
</ComboboxOption> </ComboboxOption>

View File

@@ -118,6 +118,7 @@ const options = createResource({
return { return {
label: option.value, label: option.value,
value: option.value, value: option.value,
description: option.description,
} }
}) })
}, },

View File

@@ -2,46 +2,92 @@
<Dialog v-model="show" :options="dialogOptions"> <Dialog v-model="show" :options="dialogOptions">
<template #body-content> <template #body-content>
<div class="space-y-4"> <div class="space-y-4">
<div> <div class="flex items-center text-xs text-gray-700 space-x-5">
<label class="block text-xs text-gray-600 mb-1"> <div class="flex items-center space-x-2">
{{ __('Question') }} <input
</label> type="radio"
<TextEditor id="existing"
:content="question.question" value="existing"
@change="(val) => (question.question = val)" v-model="questionType"
:editable="true" class="w-3 h-3 accent-gray-900"
:fixedMenu="true" />
editorClass="prose-sm max-w-none border-b border-x bg-gray-100 rounded-b-md py-1 px-2 min-h-[7rem]" <label for="existing">
/> {{ __('Add an existing question') }}
</label>
</div>
<div class="flex items-center space-x-2">
<input
type="radio"
id="new"
value="new"
v-model="questionType"
class="w-3 h-3"
/>
<label for="new">
{{ __('Create a new question') }}
</label>
</div>
</div> </div>
<FormControl <div v-if="questionType == 'new'" class="space-y-2">
:label="__('Type')" <div>
v-model="question.type" <label class="block text-xs text-gray-600 mb-1">
type="select" {{ __('Question') }}
:options="['Choices', 'User Input']" </label>
class="pb-2" <TextEditor
/> :content="question.question"
<div v-if="question.type == 'Choices'" class="divide-y"> @change="(val) => (question.question = val)"
<div v-for="n in 4" class="space-y-4 py-2"> :editable="true"
<FormControl :fixedMenu="true"
:label="__('Option') + ' ' + n" editorClass="prose-sm max-w-none border-b border-x bg-gray-100 rounded-b-md py-1 px-2 min-h-[7rem]"
v-model="question[`option_${n}`]"
/> />
</div>
<FormControl
v-model="question.marks"
:label="__('Marks')"
type="number"
/>
<FormControl
:label="__('Type')"
v-model="question.type"
type="select"
:options="['Choices', 'User Input']"
class="pb-2"
/>
<div v-if="question.type == 'Choices'" class="divide-y border-t">
<div v-for="n in 4" class="space-y-4 py-2">
<FormControl
:label="__('Option') + ' ' + n"
v-model="question[`option_${n}`]"
/>
<FormControl
:label="__('Explanation')"
v-model="question[`explanation_${n}`]"
/>
<FormControl
:label="__('Correct Answer')"
v-model="question[`is_correct_${n}`]"
type="checkbox"
/>
</div>
</div>
<div v-else v-for="n in 4" class="space-y-2">
<FormControl <FormControl
:label="__('Explanation')" :label="__('Possibility') + ' ' + n"
v-model="question[`explanation_${n}`]" v-model="question[`possibility_${n}`]"
/>
<FormControl
:label="__('Correct Answer')"
v-model="question[`correct_answer_${n}`]"
type="checkbox"
/> />
</div> </div>
</div> </div>
<div v-else v-for="n in 4" class="space-y-2"> <div v-else-if="questionType == 'existing'" class="space-y-2">
<Link
v-model="existingQuestion.question"
:label="__('Select a question')"
doctype="LMS Question"
/>
<FormControl <FormControl
:label="__('Possibility') + ' ' + n" v-model="existingQuestion.marks"
v-model="question[`possibility_${n}`]" :label="__('Marks')"
type="number"
/> />
</div> </div>
</div> </div>
@@ -49,51 +95,62 @@
</Dialog> </Dialog>
</template> </template>
<script setup> <script setup>
import { Dialog, FormControl, TextEditor, createResource } from 'frappe-ui' import {
import { computed, onMounted, reactive, inject } from 'vue' Dialog,
FormControl,
TextEditor,
createResource,
createDocumentResource,
} from 'frappe-ui'
import { computed, watch, reactive, ref } from 'vue'
import Link from '@/components/Controls/Link.vue'
import { showToast } from '@/utils'
const show = defineModel() const show = defineModel()
const user = inject('$user') const quiz = defineModel('quiz')
const questionType = ref(null)
const existingQuestion = reactive({
question: '',
marks: 0,
})
const question = reactive({ const question = reactive({
question: '', question: '',
type: 'Choices', type: 'Choices',
}) marks: 0,
onMounted(() => {
populateFields()
console.log(props.questionName)
if (
props.questionName == 'new' &&
!user.data?.is_moderator &&
!user.data?.is_instructor
) {
router.push({ name: 'Courses' })
}
if (props.courseName !== 'new') {
questionDoc.reload()
}
window.addEventListener('keydown', keyboardShortcut)
}) })
const props = defineProps({ const props = defineProps({
title: { title: {
type: String, type: String,
default: __('Add a Question'), default: __('Add a new question'),
}, },
questionName: { questionName: {
type: String, type: String,
}, },
}) })
const questionDoc = createResource({ const populateFields = () => {
let fields = ['option', 'is_correct', 'explanation', 'possibility']
let counter = 1
fields.forEach((field) => {
while (counter <= 4) {
question[`${field}_${counter}`] = field === 'is_correct' ? false : ''
counter++
}
})
}
const questionData = createResource({
url: 'frappe.client.get', url: 'frappe.client.get',
makeParams: (values) => { makeParams(values) {
return { return {
doctype: 'LMS Question', doctype: 'LMS Question',
name: props.questionName, name: props.questionName,
} }
}, },
auto: false,
cache: ['question', props.questionName],
onSuccess(data) { onSuccess(data) {
let counter = 1 let counter = 1
Object.keys(data).forEach((key) => { Object.keys(data).forEach((key) => {
@@ -107,28 +164,100 @@ const questionDoc = createResource({
}, },
}) })
const populateFields = () => { const questionRow = createResource({
let fields = ['option', 'correct_answer', 'explanation', 'possibility'] url: 'frappe.client.insert',
let counter = 1 makeParams(values) {
fields.forEach((field) => { console.log(values)
while (counter <= 4) { return {
question[`${field}_${counter}`] = field === 'correct_answer' ? false : '' doc: {
counter++ doctype: 'LMS Quiz Question',
parent: quiz.value.data.name,
parentfield: 'questions',
parenttype: 'LMS Quiz',
...values,
},
} }
}) },
})
const questionCreation = createResource({
url: 'frappe.client.insert',
makeParams(values) {
return {
doc: {
doctype: 'LMS Question',
...question,
},
}
},
})
const submitQuestion = (close) => {
if (questionData.data?.name) updateQuestion()
else addQuestion(close)
} }
const keyboardShortcut = (e) => { const addQuestion = (close) => {
if ( if (questionType.value == 'existing') {
e.key === 's' && addQuestionRow(
(e.ctrlKey || e.metaKey) && {
!e.target.classList.contains('ProseMirror') question: existingQuestion.question,
) { marks: existingQuestion.marks,
submitQuestion() },
e.preventDefault() close
)
} else {
questionCreation.submit(
{},
{
onSuccess(data) {
addQuestionRow(
{
question: data.name,
marks: question.marks,
},
close
)
},
onError(err) {
showToast(__('Error'), __(err.message?.[0] || err), 'x')
},
}
)
} }
} }
const addQuestionRow = (question, close) => {
questionRow.submit(
{
...question,
},
{
onSuccess() {
show.value = false
showToast(__('Success'), __('Question added successfully'), 'check')
quiz.value.reload()
close()
},
onError(err) {
showToast(__('Error'), __(err.message?.[0] || err), 'x')
close()
},
}
)
}
watch(
() => props.questionName,
async (name) => {
console.log('name', name)
populateFields()
if (name != 'new') {
questionData.reload()
}
}
)
const dialogOptions = computed(() => { const dialogOptions = computed(() => {
return { return {
title: __(props.title), title: __(props.title),
@@ -145,3 +274,10 @@ const dialogOptions = computed(() => {
} }
}) })
</script> </script>
<style>
input[type='radio']:checked {
background-color: theme('colors.gray.900') !important;
border-color: theme('colors.gray.900') !important;
--tw-ring-color: theme('colors.gray.900') !important;
}
</style>

View File

@@ -3,6 +3,9 @@
class="sticky top-0 z-10 flex items-center justify-between border-b bg-white px-3 py-2.5 sm:px-5" class="sticky top-0 z-10 flex items-center justify-between border-b bg-white px-3 py-2.5 sm:px-5"
> >
<Breadcrumbs :items="breadcrumbs" /> <Breadcrumbs :items="breadcrumbs" />
<Button variant="solid" @click="submitQuiz()">
{{ __('Save') }}
</Button>
</header> </header>
<div class="w-3/4 mx-auto py-5"> <div class="w-3/4 mx-auto py-5">
<!-- Details --> <!-- Details -->
@@ -10,107 +13,128 @@
<div class="text-sm font-semibold mb-4"> <div class="text-sm font-semibold mb-4">
{{ __('Details') }} {{ __('Details') }}
</div> </div>
<div class="grid grid-cols-2 gap-5"> <FormControl
<div class="space-y-2"> v-model="quiz.title"
<FormControl v-model="quiz.title" :label="__('Title')" /> :label="
<FormControl quizDetails.data?.name
v-model="quiz.max_attempts" ? __('Title')
:label="__('Maximun Attempts')" : __('Enter a title and save the quiz to proceed')
/> "
<FormControl />
v-model="quiz.limit_questions_to" <div v-if="quizDetails.data?.name">
:label="__('Limit Questions To')" <div class="grid grid-cols-2 gap-5 mt-2 mb-8">
/> <div class="space-y-2">
<FormControl
v-model="quiz.max_attempts"
:label="__('Maximun Attempts')"
/>
<FormControl
v-model="quiz.limit_questions_to"
:label="__('Limit Questions To')"
/>
</div>
<div class="space-y-2">
<FormControl
v-model="quiz.total_marks"
:label="__('Total Marks')"
disabled
/>
<FormControl
v-model="quiz.passing_percentage"
:label="__('Passing Percentage')"
/>
</div>
</div> </div>
<div class="space-y-2">
<FormControl v-model="quiz.total_marks" :label="__('Total Marks')" />
<FormControl
v-model="quiz.passing_percentage"
:label="__('Passing Percentage')"
/>
</div>
</div>
</div>
<!-- Settings --> <!-- Settings -->
<div class="mb-8"> <div class="mb-8">
<div class="text-sm font-semibold mb-4"> <div class="text-sm font-semibold mb-4">
{{ __('Settings') }} {{ __('Settings') }}
</div> </div>
<div class="grid grid-cols-3 gap-5 my-4"> <div class="grid grid-cols-3 gap-5 my-4">
<FormControl <FormControl
v-model="quiz.show_answers" v-model="quiz.show_answers"
type="checkbox" type="checkbox"
:label="__('Show Answers')" :label="__('Show Answers')"
/> />
<FormControl <FormControl
v-model="quiz.show_submission_history" v-model="quiz.show_submission_history"
type="checkbox" type="checkbox"
:label="__('Show Submission History')" :label="__('Show Submission History')"
/> />
<FormControl <FormControl
v-model="quiz.shuffle_questions" v-model="quiz.shuffle_questions"
type="checkbox" type="checkbox"
:label="__('Shuffle Questions')" :label="__('Shuffle Questions')"
/> />
</div> </div>
</div>
<!-- Questions -->
<div>
<div class="flex items-center justify-between mb-4">
<div class="text-sm font-semibold">
{{ __('Questions') }}
</div> </div>
<Button @click="openQuestionModal()">
<template #prefix> <!-- Questions -->
<Plus class="w-4 h-4" /> <div>
</template> <div class="flex items-center justify-between mb-4">
{{ __('New Question') }} <div class="text-sm font-semibold">
</Button> {{ __('Questions') }}
</div> </div>
<ListView <Button @click="openQuestionModal()">
:columns="questionColumns" <template #prefix>
:rows="quiz.questions" <Plus class="w-4 h-4" />
row-key="name" </template>
:options="{ {{ __('New Question') }}
showTooltip: false, </Button>
}" </div>
> <ListView
<ListHeader :columns="questionColumns"
class="mb-2 grid items-center space-x-4 rounded bg-gray-100 p-2" :rows="quiz.questions"
> row-key="name"
<ListHeaderItem :item="item" v-for="item in questionColumns" /> :options="{
</ListHeader> showTooltip: false,
<ListRows> }"
<ListRow
:row="row"
v-slot="{ idx, column, item }"
v-for="row in quiz.questions"
@click="openQuestionModal(row.question)"
> >
<ListRowItem :item="item"> <ListHeader
<div class="mb-2 grid items-center space-x-4 rounded bg-gray-100 p-2"
v-if="column.key == 'question_detail'" >
class="text-xs truncate" <ListHeaderItem :item="item" v-for="item in questionColumns" />
</ListHeader>
<ListRows>
<ListRow
:row="row"
v-slot="{ idx, column, item }"
v-for="row in quiz.questions"
@click="openQuestionModal(row.question)"
> >
{{ item }} <ListRowItem :item="item">
</div> <div
<div v-else class="text-xs"> v-if="column.key == 'question_detail'"
{{ item }} class="text-xs truncate"
</div> >
</ListRowItem> {{ item }}
</ListRow> </div>
</ListRows> <div v-else class="text-xs">
</ListView> {{ item }}
</div>
</ListRowItem>
</ListRow>
</ListRows>
</ListView>
</div>
</div>
</div> </div>
</div> </div>
<Question v-model="showQuestionModal" :questionName="currentQuestion" /> <Question
v-model="showQuestionModal"
:questionName="currentQuestion"
v-model:quiz="quizDetails"
:title="
currentQuestion ? __('Edit the question') : __('Add a new question')
"
/>
</template> </template>
<script setup> <script setup>
import { import {
Breadcrumbs, Breadcrumbs,
createDocumentResource, createDocumentResource,
createResource,
FormControl, FormControl,
ListView, ListView,
ListHeader, ListHeader,
@@ -120,12 +144,54 @@ import {
ListRowItem, ListRowItem,
Button, Button,
} from 'frappe-ui' } from 'frappe-ui'
import { computed, reactive, ref } from 'vue' import {
computed,
reactive,
ref,
onMounted,
inject,
onBeforeUnmount,
watch,
} from 'vue'
import { Plus } from 'lucide-vue-next' import { Plus } from 'lucide-vue-next'
import Question from '@/components/Modals/Question.vue' import Question from '@/components/Modals/Question.vue'
import { showToast } from '../utils'
import { useRouter } from 'vue-router'
const showQuestionModal = ref(false) const showQuestionModal = ref(false)
const currentQuestion = ref(null) const currentQuestion = ref(null)
const user = inject('$user')
const router = useRouter()
onMounted(() => {
if (
props.quizID == 'new' &&
!user.data?.is_moderator &&
!user.data?.is_instructor
) {
router.push({ name: 'Courses' })
}
if (props.quizID !== 'new') {
console.log('here')
quizDetails.reload()
}
window.addEventListener('keydown', keyboardShortcut)
})
const keyboardShortcut = (e) => {
if (
e.key === 's' &&
(e.ctrlKey || e.metaKey) &&
!e.target.classList.contains('ProseMirror')
) {
submitQuiz()
e.preventDefault()
}
}
onBeforeUnmount(() => {
window.removeEventListener('keydown', keyboardShortcut)
})
const props = defineProps({ const props = defineProps({
quizID: { quizID: {
@@ -136,8 +202,8 @@ const props = defineProps({
const quiz = reactive({ const quiz = reactive({
title: '', title: '',
total_marks: '', total_marks: 0,
passing_percentage: '', passing_percentage: 0,
max_attempts: 0, max_attempts: 0,
limit_questions_to: 0, limit_questions_to: 0,
show_answers: true, show_answers: true,
@@ -146,11 +212,14 @@ const quiz = reactive({
questions: [], questions: [],
}) })
const quizDetails = createDocumentResource({ const quizDetails = createResource({
doctype: 'LMS Quiz', url: 'frappe.client.get',
name: props.quizID, makeParams(values) {
auto: true, return { doctype: 'LMS Quiz', name: props.quizID }
},
cache: ['quiz', props.quizID], cache: ['quiz', props.quizID],
auto: false,
onSuccess(data) { onSuccess(data) {
Object.keys(data).forEach((key) => { Object.keys(data).forEach((key) => {
if (Object.hasOwn(quiz, key)) quiz[key] = data[key] if (Object.hasOwn(quiz, key)) quiz[key] = data[key]
@@ -168,6 +237,82 @@ const quizDetails = createDocumentResource({
}, },
}) })
const quizCreate = createResource({
url: 'frappe.client.insert',
auto: false,
makeParams(values) {
return {
doc: {
doctype: 'LMS Quiz',
...quiz,
},
}
},
})
const quizUpdate = createResource({
url: 'frappe.client.set_value',
auto: false,
makeParams(values) {
return {
doctype: 'LMS Quiz',
name: values.quizID,
fieldname: {
total_marks: calculateTotalMarks(),
...quiz,
},
}
},
})
const submitQuiz = () => {
if (quizDetails.data?.name) updateQuiz()
else createQuiz()
}
const createQuiz = () => {
quizCreate.submit(
{},
{
onSuccess(data) {
showToast(__('Success'), __('Quiz created successfully', 'check'))
router.push({
name: 'QuizCreation',
params: { quizID: data.name },
})
},
onError(err) {
showToast(__('Error'), __(err.messages?.[0] || err), 'x')
},
}
)
}
const updateQuiz = () => {
quizUpdate.submit(
{ quizID: quizDetails.data?.name },
{
onSuccess(data) {
quiz.total_marks = data.total_marks
showToast(__('Success'), __('Quiz updated successfully'), 'check')
},
onError(err) {
showToast(__('Error'), __(err.messages?.[0] || err), 'x')
},
}
)
}
const calculateTotalMarks = () => {
let totalMarks = 0
if (quiz.limit_questions_to && quiz.questions.length > 0)
return quiz.questions[0].marks * quiz.limit_questions_to
quiz.questions.forEach((question) => {
totalMarks += question.marks
})
return totalMarks
}
const questionColumns = computed(() => { const questionColumns = computed(() => {
return [ return [
{ {
@@ -188,11 +333,20 @@ const questionColumns = computed(() => {
] ]
}) })
watch(
() => props.quizID !== 'new',
(newVal) => {
console.log(props.quizID)
if (newVal) {
quizDetails.reload()
}
}
)
const openQuestionModal = (question = null) => { const openQuestionModal = (question = null) => {
console.log('called')
console.log(question)
currentQuestion.value = question currentQuestion.value = question
showQuestionModal.value = true showQuestionModal.value = true
console.log(currentQuestion.value)
} }
const breadcrumbs = computed(() => { const breadcrumbs = computed(() => {
@@ -204,6 +358,15 @@ const breadcrumbs = computed(() => {
}, },
}, },
] ]
/* if (quizDetails.data) {
crumbs.push({
label: quiz.title,
})
} */
crumbs.push({
label: props.quizID == 'new' ? 'New Quiz' : quizDetails.data?.title,
route: { name: 'QuizCreation', params: { quizID: props.quizID } },
})
return crumbs return crumbs
}) })
</script> </script>

View File

@@ -3,12 +3,21 @@
class="sticky top-0 z-10 flex items-center justify-between border-b bg-white px-3 py-2.5 sm:px-5" class="sticky top-0 z-10 flex items-center justify-between border-b bg-white px-3 py-2.5 sm:px-5"
> >
<Breadcrumbs :items="breadcrumbs" /> <Breadcrumbs :items="breadcrumbs" />
<Button variant="solid"> <router-link
<template #prefix> :to="{
<Plus class="w-4 h-4"/> name: 'QuizCreation',
</template> params: {
{{ __('New Quiz') }} quizID: 'new',
</Button> },
}"
>
<Button variant="solid">
<template #prefix>
<Plus class="w-4 h-4" />
</template>
{{ __('New Quiz') }}
</Button>
</router-link>
</header> </header>
<div v-if="quizzes.data?.length" class="w-3/4 mx-auto py-5"> <div v-if="quizzes.data?.length" class="w-3/4 mx-auto py-5">
<ListView <ListView
@@ -50,10 +59,18 @@ import {
ListHeaderItem, ListHeaderItem,
Button, Button,
} from 'frappe-ui' } from 'frappe-ui'
import { computed, inject } from 'vue' import { useRouter } from 'vue-router'
import { computed, inject, onMounted } from 'vue'
import { Plus } from 'lucide-vue-next' import { Plus } from 'lucide-vue-next'
const user = inject('$user') const user = inject('$user')
const router = useRouter()
onMounted(() => {
if (!user.data?.is_moderator && !user.data?.is_instructor) {
router.push({ name: 'Courses' })
}
})
const quizFilter = computed(() => { const quizFilter = computed(() => {
if (user.data?.is_moderator) return {} if (user.data?.is_moderator) return {}
@@ -68,6 +85,7 @@ const quizzes = createListResource({
fields: ['name', 'title', 'passing_percentage', 'total_marks'], fields: ['name', 'title', 'passing_percentage', 'total_marks'],
auto: true, auto: true,
cache: ['quizzes', user.data?.name], cache: ['quizzes', user.data?.name],
orderBy: 'modified desc',
onSuccess(data) { onSuccess(data) {
data.forEach((row) => {}) data.forEach((row) => {})
}, },

View File

@@ -5,7 +5,7 @@ import json
import frappe import frappe
from frappe import _ from frappe import _
from frappe.model.document import Document from frappe.model.document import Document
from frappe.utils import cstr, comma_and from frappe.utils import cstr, comma_and, cint
from fuzzywuzzy import fuzz from fuzzywuzzy import fuzz
from lms.lms.doctype.course_lesson.course_lesson import save_progress from lms.lms.doctype.course_lesson.course_lesson import save_progress
from lms.lms.utils import ( from lms.lms.utils import (
@@ -30,12 +30,12 @@ class LMSQuiz(Document):
) )
def validate_limit(self): def validate_limit(self):
if self.limit_questions_to and self.limit_questions_to >= len(self.questions): if self.limit_questions_to and cint(self.limit_questions_to) >= len(self.questions):
frappe.throw( frappe.throw(
_("Limit cannot be greater than or equal to the number of questions in the quiz.") _("Limit cannot be greater than or equal to the number of questions in the quiz.")
) )
if self.limit_questions_to and self.limit_questions_to < len(self.questions): if self.limit_questions_to and cint(self.limit_questions_to) < len(self.questions):
marks = [question.marks for question in self.questions] marks = [question.marks for question in self.questions]
if len(set(marks)) > 1: if len(set(marks)) > 1:
frappe.throw(_("All questions should have the same marks if the limit is set.")) frappe.throw(_("All questions should have the same marks if the limit is set."))
@@ -43,10 +43,10 @@ class LMSQuiz(Document):
def calculate_total_marks(self): def calculate_total_marks(self):
if self.limit_questions_to: if self.limit_questions_to:
self.total_marks = sum( self.total_marks = sum(
question.marks for question in self.questions[: self.limit_questions_to] question.marks for question in self.questions[: cint(self.limit_questions_to)]
) )
else: else:
self.total_marks = sum(question.marks for question in self.questions) self.total_marks = sum(cint(question.marks) for question in self.questions)
def autoname(self): def autoname(self):
if not self.name: if not self.name: