brotherton-erpnext/erpnext/education/utils.py

450 lines
13 KiB
Python
Raw Normal View History

2016-07-19 08:47:33 +00:00
# Copyright (c) 2015, Frappe Technologies and contributors
import frappe
from frappe import _
2022-03-28 13:22:46 +00:00
class OverlapError(frappe.ValidationError):
pass
2016-07-19 08:47:33 +00:00
def validate_overlap_for(doc, doctype, fieldname, value=None):
2017-04-12 13:54:12 +00:00
"""Checks overlap for specified field.
:param fieldname: Checks Overlap for this field
2016-07-19 08:47:33 +00:00
"""
2016-07-19 08:47:33 +00:00
existing = get_overlap_for(doc, doctype, fieldname, value)
if existing:
2022-03-28 13:22:46 +00:00
frappe.throw(
_("This {0} conflicts with {1} for {2} {3}").format(
doc.doctype,
existing.name,
doc.meta.get_label(fieldname) if not value else fieldname,
value or doc.get(fieldname),
),
OverlapError,
)
2016-07-19 08:47:33 +00:00
def get_overlap_for(doc, doctype, fieldname, value=None):
2017-04-12 13:54:12 +00:00
"""Returns overlaping document for specified field.
:param fieldname: Checks Overlap for this field
2016-07-19 08:47:33 +00:00
"""
2022-03-28 13:22:46 +00:00
existing = frappe.db.sql(
"""select name, from_time, to_time from `tab{0}`
2016-07-19 08:47:33 +00:00
where `{1}`=%(val)s and schedule_date = %(schedule_date)s and
(
(from_time > %(from_time)s and from_time < %(to_time)s) or
(to_time > %(from_time)s and to_time < %(to_time)s) or
(%(from_time)s > from_time and %(from_time)s < to_time) or
(%(from_time)s = from_time and %(to_time)s = to_time))
2022-03-28 13:22:46 +00:00
and name!=%(name)s and docstatus!=2""".format(
doctype, fieldname
),
2016-07-19 08:47:33 +00:00
{
"schedule_date": doc.schedule_date,
"val": value or doc.get(fieldname),
"from_time": doc.from_time,
"to_time": doc.to_time,
2022-03-28 13:22:46 +00:00
"name": doc.name or "No Name",
},
as_dict=True,
)
2016-07-19 08:47:33 +00:00
return existing[0] if existing else None
2016-07-21 19:58:41 +00:00
def validate_duplicate_student(students):
2022-03-28 13:22:46 +00:00
unique_students = []
2016-07-21 19:58:41 +00:00
for stud in students:
if stud.student in unique_students:
2022-03-28 13:22:46 +00:00
frappe.throw(
_("Student {0} - {1} appears Multiple times in row {2} & {3}").format(
stud.student, stud.student_name, unique_students.index(stud.student) + 1, stud.idx
)
)
2016-07-21 19:58:41 +00:00
else:
unique_students.append(stud.student)
2018-11-19 10:43:21 +00:00
return None
2022-03-28 13:22:46 +00:00
2018-11-20 12:08:01 +00:00
# LMS Utils
2018-11-19 10:43:21 +00:00
def get_current_student():
"""Returns current student from frappe.session.user
Returns:
2022-03-28 13:22:46 +00:00
object: Student Document
2018-11-19 10:43:21 +00:00
"""
email = frappe.session.user
2022-03-28 13:22:46 +00:00
if email in ("Administrator", "Guest"):
2018-11-19 10:43:21 +00:00
return None
try:
student_id = frappe.get_all("Student", {"student_email_id": email}, ["name"])[0].name
return frappe.get_doc("Student", student_id)
except (IndexError, frappe.DoesNotExistError):
2019-04-22 07:24:43 +00:00
return None
2018-11-19 10:43:21 +00:00
2022-03-28 13:22:46 +00:00
def get_portal_programs():
"""Returns a list of all program to be displayed on the portal
Programs are returned based on the following logic
2022-03-28 13:22:46 +00:00
is_published and (student_is_enrolled or student_can_self_enroll)
Returns:
2022-03-28 13:22:46 +00:00
list of dictionary: List of all programs and to be displayed on the portal along with access rights
2018-11-19 10:43:21 +00:00
"""
published_programs = frappe.get_all("Program", filters={"is_published": True})
if not published_programs:
return None
program_list = [frappe.get_doc("Program", program) for program in published_programs]
2022-03-28 13:22:46 +00:00
portal_programs = [
{"program": program, "has_access": allowed_program_access(program.name)}
for program in program_list
if allowed_program_access(program.name) or program.allow_self_enroll
]
return portal_programs
2022-03-28 13:22:46 +00:00
2019-05-30 11:05:15 +00:00
def allowed_program_access(program, student=None):
"""Returns enrollment status for current student
Args:
2022-03-28 13:22:46 +00:00
program (string): Name of the program
student (object): instance of Student document
Returns:
2022-03-28 13:22:46 +00:00
bool: Is current user enrolled or not
2018-11-19 10:43:21 +00:00
"""
2019-05-30 11:05:15 +00:00
if has_super_access():
return True
2018-11-19 10:43:21 +00:00
if not student:
student = get_current_student()
2022-03-28 13:22:46 +00:00
if student and get_enrollment("program", program, student.name):
return True
2018-11-19 10:43:21 +00:00
else:
return False
2018-11-19 10:43:21 +00:00
2022-03-28 13:22:46 +00:00
def get_enrollment(master, document, student):
"""Gets enrollment for course or program
2018-11-19 10:43:21 +00:00
Args:
2022-03-28 13:22:46 +00:00
master (string): can either be program or course
document (string): program or course name
student (string): Student ID
Returns:
2022-03-28 13:22:46 +00:00
string: Enrollment Name if exists else returns empty string
"""
2022-03-28 13:22:46 +00:00
if master == "program":
enrollments = frappe.get_all(
"Program Enrollment", filters={"student": student, "program": document, "docstatus": 1}
)
if master == "course":
enrollments = frappe.get_all(
"Course Enrollment", filters={"student": student, "course": document}
)
if enrollments:
2019-05-30 11:05:15 +00:00
return enrollments[0].name
else:
2019-05-30 11:05:15 +00:00
return None
2022-03-28 13:22:46 +00:00
2019-05-30 11:05:15 +00:00
@frappe.whitelist()
def enroll_in_program(program_name, student=None):
"""Enroll student in program
Args:
2022-03-28 13:22:46 +00:00
program_name (string): Name of the program to be enrolled into
student (string, optional): name of student who has to be enrolled, if not
provided, a student will be created from the current user
2019-05-30 11:05:15 +00:00
Returns:
2022-03-28 13:22:46 +00:00
string: name of the program enrollment document
2019-05-30 11:05:15 +00:00
"""
if has_super_access():
return
if not student == None:
student = frappe.get_doc("Student", student)
else:
# Check if self enrollment in allowed
2022-03-28 13:22:46 +00:00
program = frappe.get_doc("Program", program_name)
2019-05-30 11:05:15 +00:00
if not program.allow_self_enroll:
return frappe.throw(_("You are not allowed to enroll for this course"))
2019-05-30 11:05:15 +00:00
student = get_current_student()
if not student:
student = create_student_from_current_user()
# Check if student is already enrolled in program
2022-03-28 13:22:46 +00:00
enrollment = get_enrollment("program", program_name, student.name)
2019-05-30 11:05:15 +00:00
if enrollment:
return enrollment
# Check if self enrollment in allowed
2022-03-28 13:22:46 +00:00
program = frappe.get_doc("Program", program_name)
2019-05-30 11:05:15 +00:00
if not program.allow_self_enroll:
return frappe.throw(_("You are not allowed to enroll for this course"))
2019-05-30 11:05:15 +00:00
# Enroll in program
program_enrollment = student.enroll_in_program(program_name)
return program_enrollment.name
2022-03-28 13:22:46 +00:00
2019-05-30 11:05:15 +00:00
def has_super_access():
"""Check if user has a role that allows full access to LMS
Returns:
2022-03-28 13:22:46 +00:00
bool: true if user has access to all lms content
"""
2022-03-28 13:22:46 +00:00
current_user = frappe.get_doc("User", frappe.session.user)
2019-05-30 11:05:15 +00:00
roles = set([role.role for role in current_user.roles])
2022-03-28 13:22:46 +00:00
return bool(
roles & {"Administrator", "Instructor", "Education Manager", "System Manager", "Academic User"}
)
@frappe.whitelist()
def add_activity(course, content_type, content, program):
if has_super_access():
return None
student = get_current_student()
if not student:
2022-03-28 13:22:46 +00:00
return frappe.throw(
_("Student with email {0} does not exist").format(frappe.session.user), frappe.DoesNotExistError
)
enrollment = get_or_create_course_enrollment(course, program)
2022-03-28 13:22:46 +00:00
if content_type == "Quiz":
return
else:
return enrollment.add_activity(content_type, content)
2018-11-19 10:43:21 +00:00
2022-03-28 13:22:46 +00:00
@frappe.whitelist()
def evaluate_quiz(quiz_response, quiz_name, course, program, time_taken):
import json
student = get_current_student()
quiz_response = json.loads(quiz_response)
quiz = frappe.get_doc("Quiz", quiz_name)
result, score, status = quiz.evaluate(quiz_response, quiz_name)
if has_super_access():
2022-03-28 13:22:46 +00:00
return {"result": result, "score": score, "status": status}
if student:
enrollment = get_or_create_course_enrollment(course, program)
if quiz.allowed_attempt(enrollment, quiz_name):
enrollment.add_quiz_activity(quiz_name, quiz_response, result, score, status, time_taken)
2022-03-28 13:22:46 +00:00
return {"result": result, "score": score, "status": status}
else:
return None
2022-03-28 13:22:46 +00:00
@frappe.whitelist()
def get_quiz(quiz_name, course):
try:
quiz = frappe.get_doc("Quiz", quiz_name)
questions = quiz.get_questions()
2021-09-01 09:10:56 +00:00
except Exception:
frappe.throw(_("Quiz {0} does not exist").format(quiz_name), frappe.DoesNotExistError)
return None
2022-03-28 13:22:46 +00:00
questions = [
{
"name": question.name,
"question": question.question,
"type": question.question_type,
"options": [{"name": option.name, "option": option.option} for option in question.options],
}
for question in questions
]
if has_super_access():
return {
2022-03-28 13:22:46 +00:00
"questions": questions,
"activity": None,
"is_time_bound": quiz.is_time_bound,
"duration": quiz.duration,
}
student = get_current_student()
course_enrollment = get_enrollment("course", course, student.name)
status, score, result, time_taken = check_quiz_completion(quiz, course_enrollment)
return {
2022-03-28 13:22:46 +00:00
"questions": questions,
"activity": {"is_complete": status, "score": score, "result": result, "time_taken": time_taken},
"is_time_bound": quiz.is_time_bound,
"duration": quiz.duration,
}
2022-03-28 13:22:46 +00:00
2019-06-05 11:59:48 +00:00
def get_topic_progress(topic, course_name, program):
2019-06-03 09:11:05 +00:00
"""
Return the porgress of a course in a program as well as the content to continue from.
2022-03-28 13:22:46 +00:00
:param topic_name:
:param course_name:
2019-06-03 09:11:05 +00:00
"""
student = get_current_student()
2019-06-05 07:59:51 +00:00
if not student:
return None
2019-06-03 09:11:05 +00:00
course_enrollment = get_or_create_course_enrollment(course_name, program)
progress = student.get_topic_progress(course_enrollment.name, topic)
if not progress:
2019-06-05 07:38:53 +00:00
return None
2022-03-28 13:22:46 +00:00
count = sum([activity["is_complete"] for activity in progress])
2019-06-03 09:11:05 +00:00
if count == 0:
2022-03-28 13:22:46 +00:00
return {"completed": False, "started": False}
2019-06-03 09:11:05 +00:00
elif count == len(progress):
2022-03-28 13:22:46 +00:00
return {"completed": True, "started": True}
2019-06-03 09:11:05 +00:00
elif count < len(progress):
2022-03-28 13:22:46 +00:00
return {"completed": False, "started": True}
2019-06-05 07:38:53 +00:00
2019-06-05 11:59:48 +00:00
def get_course_progress(course, program):
2019-06-05 07:38:53 +00:00
"""
Return the porgress of a course in a program as well as the content to continue from.
2022-03-28 13:22:46 +00:00
:param topic_name:
:param course_name:
2019-06-05 07:38:53 +00:00
"""
course_progress = []
for course_topic in course.topics:
topic = frappe.get_doc("Topic", course_topic.topic)
2019-06-05 11:59:48 +00:00
progress = get_topic_progress(topic, course.name, program)
2019-06-05 07:38:53 +00:00
if progress:
course_progress.append(progress)
if course_progress:
2022-03-28 13:22:46 +00:00
number_of_completed_topics = sum([activity["completed"] for activity in course_progress])
2019-06-05 07:38:53 +00:00
total_topics = len(course_progress)
2019-06-05 11:59:48 +00:00
if total_topics == 1:
return course_progress[0]
2019-06-05 07:38:53 +00:00
if number_of_completed_topics == 0:
2022-03-28 13:22:46 +00:00
return {"completed": False, "started": False}
2019-06-05 07:38:53 +00:00
if number_of_completed_topics == total_topics:
2022-03-28 13:22:46 +00:00
return {"completed": True, "started": True}
2019-06-05 07:38:53 +00:00
if number_of_completed_topics < total_topics:
2022-03-28 13:22:46 +00:00
return {"completed": False, "started": True}
2019-06-05 07:38:53 +00:00
return None
2019-06-03 09:11:05 +00:00
2022-03-28 13:22:46 +00:00
2019-06-05 11:59:48 +00:00
def get_program_progress(program):
program_progress = []
if not program.courses:
return None
for program_course in program.courses:
course = frappe.get_doc("Course", program_course.course)
progress = get_course_progress(course, program.name)
if progress:
2022-03-28 13:22:46 +00:00
progress["name"] = course.name
progress["course"] = course.course_name
2019-06-05 11:59:48 +00:00
program_progress.append(progress)
if program_progress:
return program_progress
return None
2022-03-28 13:22:46 +00:00
2019-06-05 11:59:48 +00:00
def get_program_completion(program):
2022-03-28 13:22:46 +00:00
topics = frappe.db.sql(
"""select `tabCourse Topic`.topic, `tabCourse Topic`.parent
2019-06-06 11:49:53 +00:00
from `tabCourse Topic`,
`tabProgram Course`
where `tabCourse Topic`.parent = `tabProgram Course`.course
2022-03-28 13:22:46 +00:00
and `tabProgram Course`.parent = %s""",
program.name,
)
2019-06-05 11:59:48 +00:00
progress = []
for topic in topics:
2022-03-28 13:22:46 +00:00
topic_doc = frappe.get_doc("Topic", topic[0])
2019-06-05 11:59:48 +00:00
topic_progress = get_topic_progress(topic_doc, topic[1], program.name)
if topic_progress:
progress.append(topic_progress)
if progress:
2022-03-28 13:22:46 +00:00
number_of_completed_topics = sum([activity["completed"] for activity in progress if activity])
2019-06-05 11:59:48 +00:00
total_topics = len(progress)
try:
2022-03-28 13:22:46 +00:00
return int((float(number_of_completed_topics) / total_topics) * 100)
2019-06-05 11:59:48 +00:00
except ZeroDivisionError:
return 0
return 0
2022-03-28 13:22:46 +00:00
2019-03-06 10:15:35 +00:00
def create_student_from_current_user():
2018-11-23 11:46:22 +00:00
user = frappe.get_doc("User", frappe.session.user)
2019-05-30 11:05:15 +00:00
2022-03-28 13:22:46 +00:00
student = frappe.get_doc(
{
"doctype": "Student",
"first_name": user.first_name,
"last_name": user.last_name,
"student_email_id": user.email,
"user": frappe.session.user,
}
)
2019-05-30 11:05:15 +00:00
2018-11-19 10:43:21 +00:00
student.save(ignore_permissions=True)
return student
2022-03-28 13:22:46 +00:00
def get_or_create_course_enrollment(course, program):
2019-04-22 07:24:43 +00:00
student = get_current_student()
course_enrollment = get_enrollment("course", course, student.name)
if not course_enrollment:
2022-03-28 13:22:46 +00:00
program_enrollment = get_enrollment("program", program.name, student.name)
if not program_enrollment:
2020-01-29 09:36:18 +00:00
frappe.throw(_("You are not enrolled in program {0}").format(program))
return
2022-03-28 13:22:46 +00:00
return student.enroll_in_course(
course_name=course, program_enrollment=get_enrollment("program", program.name, student.name)
)
else:
2022-03-28 13:22:46 +00:00
return frappe.get_doc("Course Enrollment", course_enrollment)
2018-11-19 10:43:21 +00:00
def check_content_completion(content_name, content_type, enrollment_name):
2022-03-28 13:22:46 +00:00
activity = frappe.get_all(
"Course Activity",
filters={"enrollment": enrollment_name, "content_type": content_type, "content": content_name},
)
if activity:
return True
else:
return False
2022-03-28 13:22:46 +00:00
def check_quiz_completion(quiz, enrollment_name):
2022-03-28 13:22:46 +00:00
attempts = frappe.get_all(
"Quiz Activity",
filters={"enrollment": enrollment_name, "quiz": quiz.name},
fields=["name", "activity_date", "score", "status", "time_taken"],
)
status = False if quiz.max_attempts == 0 else bool(len(attempts) >= quiz.max_attempts)
score = None
result = None
time_taken = None
if attempts:
2022-03-28 13:22:46 +00:00
if quiz.grading_basis == "Last Highest Score":
attempts = sorted(attempts, key=lambda i: int(i.score), reverse=True)
score = attempts[0]["score"]
result = attempts[0]["status"]
time_taken = attempts[0]["time_taken"]
if result == "Pass":
status = True
2021-06-08 11:35:44 +00:00
return status, score, result, time_taken