blob: a7a15d18ce8c7a90529e770a96141549ab3343ca [file] [log] [blame]
Neil Trini Lasrado3f0a5812016-07-19 14:17:33 +05301# Copyright (c) 2015, Frappe Technologies and contributors
Neil Trini Lasrado3f0a5812016-07-19 14:17:33 +05302
Neil Trini Lasrado3f0a5812016-07-19 14:17:33 +05303import frappe
4from frappe import _
5
Chillar Anand915b3432021-09-02 16:44:59 +05306
Neil Trini Lasrado3f0a5812016-07-19 14:17:33 +05307class OverlapError(frappe.ValidationError): pass
8
9def validate_overlap_for(doc, doctype, fieldname, value=None):
Manas Solanki54c42402017-04-12 19:24:12 +053010 """Checks overlap for specified field.
scmmishra685584b2018-10-17 12:41:50 +053011
12 :param fieldname: Checks Overlap for this field
Neil Trini Lasrado3f0a5812016-07-19 14:17:33 +053013 """
scmmishra685584b2018-10-17 12:41:50 +053014
Neil Trini Lasrado3f0a5812016-07-19 14:17:33 +053015 existing = get_overlap_for(doc, doctype, fieldname, value)
16 if existing:
17 frappe.throw(_("This {0} conflicts with {1} for {2} {3}").format(doc.doctype, existing.name,
18 doc.meta.get_label(fieldname) if not value else fieldname , value or doc.get(fieldname)), OverlapError)
scmmishra685584b2018-10-17 12:41:50 +053019
Neil Trini Lasrado3f0a5812016-07-19 14:17:33 +053020def get_overlap_for(doc, doctype, fieldname, value=None):
Manas Solanki54c42402017-04-12 19:24:12 +053021 """Returns overlaping document for specified field.
scmmishra685584b2018-10-17 12:41:50 +053022
23 :param fieldname: Checks Overlap for this field
Neil Trini Lasrado3f0a5812016-07-19 14:17:33 +053024 """
25
26 existing = frappe.db.sql("""select name, from_time, to_time from `tab{0}`
27 where `{1}`=%(val)s and schedule_date = %(schedule_date)s and
28 (
29 (from_time > %(from_time)s and from_time < %(to_time)s) or
30 (to_time > %(from_time)s and to_time < %(to_time)s) or
31 (%(from_time)s > from_time and %(from_time)s < to_time) or
32 (%(from_time)s = from_time and %(to_time)s = to_time))
Manas Solanki84e9d452017-11-28 18:04:08 +053033 and name!=%(name)s and docstatus!=2""".format(doctype, fieldname),
Neil Trini Lasrado3f0a5812016-07-19 14:17:33 +053034 {
35 "schedule_date": doc.schedule_date,
36 "val": value or doc.get(fieldname),
37 "from_time": doc.from_time,
38 "to_time": doc.to_time,
39 "name": doc.name or "No Name"
40 }, as_dict=True)
41
42 return existing[0] if existing else None
scmmishra685584b2018-10-17 12:41:50 +053043
scmmishra7409fe62018-10-22 18:37:03 +053044
Neil Trini Lasradof521a9c2016-07-22 01:28:41 +053045def validate_duplicate_student(students):
46 unique_students= []
47 for stud in students:
48 if stud.student in unique_students:
49 frappe.throw(_("Student {0} - {1} appears Multiple times in row {2} & {3}")
50 .format(stud.student, stud.student_name, unique_students.index(stud.student)+1, stud.idx))
51 else:
52 unique_students.append(stud.student)
scmmishra4ae11f42018-10-12 15:18:26 +053053
scmmishrababb68d2018-11-19 16:13:21 +053054 return None
55
scmmishra11925292018-11-20 17:38:01 +053056# LMS Utils
scmmishrababb68d2018-11-19 16:13:21 +053057def get_current_student():
Shivam Mishraf9275022019-05-29 18:39:52 +053058 """Returns current student from frappe.session.user
59
60 Returns:
Shivam Mishradfdb92f2019-05-30 16:35:15 +053061 object: Student Document
scmmishrababb68d2018-11-19 16:13:21 +053062 """
63 email = frappe.session.user
64 if email in ('Administrator', 'Guest'):
65 return None
66 try:
scmmishrada39da62018-12-13 11:51:31 +053067 student_id = frappe.get_all("Student", {"student_email_id": email}, ["name"])[0].name
scmmishra327334a2019-04-22 12:03:17 +053068 return frappe.get_doc("Student", student_id)
69 except (IndexError, frappe.DoesNotExistError):
scmmishra66d23922019-04-22 12:54:43 +053070 return None
scmmishrababb68d2018-11-19 16:13:21 +053071
Shivam Mishraf9275022019-05-29 18:39:52 +053072def get_portal_programs():
73 """Returns a list of all program to be displayed on the portal
74 Programs are returned based on the following logic
75 is_published and (student_is_enrolled or student_can_self_enroll)
scmmishra000e7062019-03-19 12:30:43 +053076
Shivam Mishraf9275022019-05-29 18:39:52 +053077 Returns:
Shivam Mishrae94e9d22019-05-30 18:05:00 +053078 list of dictionary: List of all programs and to be displayed on the portal along with access rights
scmmishrababb68d2018-11-19 16:13:21 +053079 """
Shivam Mishraf9275022019-05-29 18:39:52 +053080 published_programs = frappe.get_all("Program", filters={"is_published": True})
81 if not published_programs:
scmmishrababb68d2018-11-19 16:13:21 +053082 return None
Shivam Mishraf9275022019-05-29 18:39:52 +053083
84 program_list = [frappe.get_doc("Program", program) for program in published_programs]
Shivam Mishra12579612019-05-30 17:19:11 +053085 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]
Shivam Mishraf9275022019-05-29 18:39:52 +053086
87 return portal_programs
88
Shivam Mishradfdb92f2019-05-30 16:35:15 +053089def allowed_program_access(program, student=None):
Shivam Mishraf9275022019-05-29 18:39:52 +053090 """Returns enrollment status for current student
91
92 Args:
Shivam Mishradfdb92f2019-05-30 16:35:15 +053093 program (string): Name of the program
94 student (object): instance of Student document
Shivam Mishraf9275022019-05-29 18:39:52 +053095
96 Returns:
Shivam Mishradfdb92f2019-05-30 16:35:15 +053097 bool: Is current user enrolled or not
Shivam Mishraf9275022019-05-29 18:39:52 +053098 """
Shivam Mishradfdb92f2019-05-30 16:35:15 +053099 if has_super_access():
100 return True
Shivam Mishraf9275022019-05-29 18:39:52 +0530101 if not student:
102 student = get_current_student()
103 if student and get_enrollment('program', program, student.name):
104 return True
scmmishrababb68d2018-11-19 16:13:21 +0530105 else:
Shivam Mishraf9275022019-05-29 18:39:52 +0530106 return False
scmmishrababb68d2018-11-19 16:13:21 +0530107
Shivam Mishraf9275022019-05-29 18:39:52 +0530108def get_enrollment(master, document, student):
109 """Gets enrollment for course or program
scmmishrababb68d2018-11-19 16:13:21 +0530110
Shivam Mishraf9275022019-05-29 18:39:52 +0530111 Args:
Shivam Mishradfdb92f2019-05-30 16:35:15 +0530112 master (string): can either be program or course
113 document (string): program or course name
114 student (string): Student ID
Shivam Mishraf9275022019-05-29 18:39:52 +0530115
116 Returns:
Shivam Mishradfdb92f2019-05-30 16:35:15 +0530117 string: Enrollment Name if exists else returns empty string
Shivam Mishraf9275022019-05-29 18:39:52 +0530118 """
119 if master == 'program':
Shivam Mishradfdb92f2019-05-30 16:35:15 +0530120 enrollments = frappe.get_all("Program Enrollment", filters={'student':student, 'program': document, 'docstatus': 1})
Shivam Mishraf9275022019-05-29 18:39:52 +0530121 if master == 'course':
122 enrollments = frappe.get_all("Course Enrollment", filters={'student':student, 'course': document})
123
124 if enrollments:
Shivam Mishradfdb92f2019-05-30 16:35:15 +0530125 return enrollments[0].name
Shivam Mishraf9275022019-05-29 18:39:52 +0530126 else:
Shivam Mishradfdb92f2019-05-30 16:35:15 +0530127 return None
Shivam Mishraf9275022019-05-29 18:39:52 +0530128
Shivam Mishradfdb92f2019-05-30 16:35:15 +0530129@frappe.whitelist()
130def enroll_in_program(program_name, student=None):
131 """Enroll student in program
132
133 Args:
134 program_name (string): Name of the program to be enrolled into
135 student (string, optional): name of student who has to be enrolled, if not
136 provided, a student will be created from the current user
137
138 Returns:
139 string: name of the program enrollment document
140 """
141 if has_super_access():
142 return
143
144 if not student == None:
145 student = frappe.get_doc("Student", student)
146 else:
147 # Check if self enrollment in allowed
148 program = frappe.get_doc('Program', program_name)
149 if not program.allow_self_enroll:
Anurag Mishra841d8522019-07-03 15:15:08 +0530150 return frappe.throw(_("You are not allowed to enroll for this course"))
Shivam Mishradfdb92f2019-05-30 16:35:15 +0530151
152 student = get_current_student()
153 if not student:
154 student = create_student_from_current_user()
155
156 # Check if student is already enrolled in program
157 enrollment = get_enrollment('program', program_name, student.name)
158 if enrollment:
159 return enrollment
160
161 # Check if self enrollment in allowed
162 program = frappe.get_doc('Program', program_name)
163 if not program.allow_self_enroll:
Anurag Mishra841d8522019-07-03 15:15:08 +0530164 return frappe.throw(_("You are not allowed to enroll for this course"))
Shivam Mishradfdb92f2019-05-30 16:35:15 +0530165
166 # Enroll in program
167 program_enrollment = student.enroll_in_program(program_name)
168 return program_enrollment.name
169
170def has_super_access():
Shivam Mishrae94e9d22019-05-30 18:05:00 +0530171 """Check if user has a role that allows full access to LMS
172
173 Returns:
Shivam Mishrad1a25212019-06-03 12:57:38 +0530174 bool: true if user has access to all lms content
Shivam Mishrae94e9d22019-05-30 18:05:00 +0530175 """
Shivam Mishradfdb92f2019-05-30 16:35:15 +0530176 current_user = frappe.get_doc('User', frappe.session.user)
177 roles = set([role.role for role in current_user.roles])
178 return bool(roles & {'Administrator', 'Instructor', 'Education Manager', 'System Manager', 'Academic User'})
Shivam Mishraf9275022019-05-29 18:39:52 +0530179
Shivam Mishrae94e9d22019-05-30 18:05:00 +0530180@frappe.whitelist()
Shivam Mishra8ddb63a2019-06-03 14:40:52 +0530181def add_activity(course, content_type, content, program):
Shivam Mishrae94e9d22019-05-30 18:05:00 +0530182 if has_super_access():
183 return None
Shivam Mishraf9275022019-05-29 18:39:52 +0530184
Shivam Mishrae94e9d22019-05-30 18:05:00 +0530185 student = get_current_student()
186 if not student:
Suraj Shetty48e9bc32020-01-29 15:06:18 +0530187 return frappe.throw(_("Student with email {0} does not exist").format(frappe.session.user), frappe.DoesNotExistError)
Shivam Mishraf9275022019-05-29 18:39:52 +0530188
Shivam Mishra8ddb63a2019-06-03 14:40:52 +0530189 enrollment = get_or_create_course_enrollment(course, program)
Shivam Mishrae94e9d22019-05-30 18:05:00 +0530190 if content_type == 'Quiz':
191 return
192 else:
193 return enrollment.add_activity(content_type, content)
scmmishrababb68d2018-11-19 16:13:21 +0530194
Shivam Mishrad1a25212019-06-03 12:57:38 +0530195@frappe.whitelist()
Jannat Pateldcdd3be2021-04-19 10:36:40 +0530196def evaluate_quiz(quiz_response, quiz_name, course, program, time_taken):
Shivam Mishrad1a25212019-06-03 12:57:38 +0530197 import json
198
199 student = get_current_student()
200
201 quiz_response = json.loads(quiz_response)
202 quiz = frappe.get_doc("Quiz", quiz_name)
203 result, score, status = quiz.evaluate(quiz_response, quiz_name)
204
205 if has_super_access():
206 return {'result': result, 'score': score, 'status': status}
207
208 if student:
Shivam Mishra8ddb63a2019-06-03 14:40:52 +0530209 enrollment = get_or_create_course_enrollment(course, program)
210 if quiz.allowed_attempt(enrollment, quiz_name):
Jannat Pateldcdd3be2021-04-19 10:36:40 +0530211 enrollment.add_quiz_activity(quiz_name, quiz_response, result, score, status, time_taken)
Shivam Mishra8ddb63a2019-06-03 14:40:52 +0530212 return {'result': result, 'score': score, 'status': status}
Shivam Mishrad1a25212019-06-03 12:57:38 +0530213 else:
Shivam Mishra8ddb63a2019-06-03 14:40:52 +0530214 return None
Shivam Mishrad1a25212019-06-03 12:57:38 +0530215
216@frappe.whitelist()
217def get_quiz(quiz_name, course):
218 try:
219 quiz = frappe.get_doc("Quiz", quiz_name)
220 questions = quiz.get_questions()
Ankush Menat694ae812021-09-01 14:40:56 +0530221 except Exception:
Jannat Pateldcdd3be2021-04-19 10:36:40 +0530222 frappe.throw(_("Quiz {0} does not exist").format(quiz_name), frappe.DoesNotExistError)
Shivam Mishrad1a25212019-06-03 12:57:38 +0530223 return None
224
225 questions = [{
226 'name': question.name,
227 'question': question.question,
228 'type': question.question_type,
229 'options': [{'name': option.name, 'option': option.option}
230 for option in question.options],
231 } for question in questions]
232
233 if has_super_access():
Jannat Pateldcdd3be2021-04-19 10:36:40 +0530234 return {
235 'questions': questions,
236 'activity': None,
pateljannatbbf07d92021-06-08 17:05:44 +0530237 'is_time_bound': quiz.is_time_bound,
238 'duration': quiz.duration
Jannat Pateldcdd3be2021-04-19 10:36:40 +0530239 }
Shivam Mishrad1a25212019-06-03 12:57:38 +0530240
241 student = get_current_student()
242 course_enrollment = get_enrollment("course", course, student.name)
Jannat Pateldcdd3be2021-04-19 10:36:40 +0530243 status, score, result, time_taken = check_quiz_completion(quiz, course_enrollment)
244 return {
pateljannatbbf07d92021-06-08 17:05:44 +0530245 'questions': questions,
Jannat Pateldcdd3be2021-04-19 10:36:40 +0530246 'activity': {'is_complete': status, 'score': score, 'result': result, 'time_taken': time_taken},
pateljannat7ace06a2021-06-08 18:26:23 +0530247 'is_time_bound': quiz.is_time_bound,
Jannat Pateldcdd3be2021-04-19 10:36:40 +0530248 'duration': quiz.duration
249 }
Shivam Mishrad1a25212019-06-03 12:57:38 +0530250
Shivam Mishra16b41292019-06-05 17:29:48 +0530251def get_topic_progress(topic, course_name, program):
Shivam Mishra6d4c6662019-06-03 14:41:05 +0530252 """
253 Return the porgress of a course in a program as well as the content to continue from.
254 :param topic_name:
255 :param course_name:
256 """
257 student = get_current_student()
Shivam Mishra65932632019-06-05 13:29:51 +0530258 if not student:
259 return None
Shivam Mishra6d4c6662019-06-03 14:41:05 +0530260 course_enrollment = get_or_create_course_enrollment(course_name, program)
261 progress = student.get_topic_progress(course_enrollment.name, topic)
262 if not progress:
Shivam Mishra570161b2019-06-05 13:08:53 +0530263 return None
Shivam Mishra6d4c6662019-06-03 14:41:05 +0530264 count = sum([activity['is_complete'] for activity in progress])
265 if count == 0:
Shivam Mishra570161b2019-06-05 13:08:53 +0530266 return {'completed': False, 'started': False}
Shivam Mishra6d4c6662019-06-03 14:41:05 +0530267 elif count == len(progress):
Shivam Mishra570161b2019-06-05 13:08:53 +0530268 return {'completed': True, 'started': True}
Shivam Mishra6d4c6662019-06-03 14:41:05 +0530269 elif count < len(progress):
Shivam Mishra570161b2019-06-05 13:08:53 +0530270 return {'completed': False, 'started': True}
271
Shivam Mishra16b41292019-06-05 17:29:48 +0530272def get_course_progress(course, program):
Shivam Mishra570161b2019-06-05 13:08:53 +0530273 """
274 Return the porgress of a course in a program as well as the content to continue from.
275 :param topic_name:
276 :param course_name:
277 """
278 course_progress = []
279 for course_topic in course.topics:
280 topic = frappe.get_doc("Topic", course_topic.topic)
Shivam Mishra16b41292019-06-05 17:29:48 +0530281 progress = get_topic_progress(topic, course.name, program)
Shivam Mishra570161b2019-06-05 13:08:53 +0530282 if progress:
283 course_progress.append(progress)
Shivam Mishra570161b2019-06-05 13:08:53 +0530284 if course_progress:
285 number_of_completed_topics = sum([activity['completed'] for activity in course_progress])
286 total_topics = len(course_progress)
Shivam Mishra16b41292019-06-05 17:29:48 +0530287 if total_topics == 1:
288 return course_progress[0]
Shivam Mishra570161b2019-06-05 13:08:53 +0530289 if number_of_completed_topics == 0:
290 return {'completed': False, 'started': False}
291 if number_of_completed_topics == total_topics:
292 return {'completed': True, 'started': True}
293 if number_of_completed_topics < total_topics:
294 return {'completed': False, 'started': True}
295
296 return None
Shivam Mishra6d4c6662019-06-03 14:41:05 +0530297
Shivam Mishra16b41292019-06-05 17:29:48 +0530298def get_program_progress(program):
299 program_progress = []
300 if not program.courses:
301 return None
302 for program_course in program.courses:
303 course = frappe.get_doc("Course", program_course.course)
304 progress = get_course_progress(course, program.name)
305 if progress:
306 progress['name'] = course.name
307 progress['course'] = course.course_name
308 program_progress.append(progress)
309
310 if program_progress:
311 return program_progress
312
313 return None
314
315def get_program_completion(program):
Shivam Mishrad49b5e42019-06-06 17:19:53 +0530316 topics = frappe.db.sql("""select `tabCourse Topic`.topic, `tabCourse Topic`.parent
317 from `tabCourse Topic`,
318 `tabProgram Course`
319 where `tabCourse Topic`.parent = `tabProgram Course`.course
320 and `tabProgram Course`.parent = %s""", program.name)
Shivam Mishra16b41292019-06-05 17:29:48 +0530321
322 progress = []
323 for topic in topics:
324 topic_doc = frappe.get_doc('Topic', topic[0])
325 topic_progress = get_topic_progress(topic_doc, topic[1], program.name)
326 if topic_progress:
327 progress.append(topic_progress)
328
329 if progress:
330 number_of_completed_topics = sum([activity['completed'] for activity in progress if activity])
331 total_topics = len(progress)
332 try:
333 return int((float(number_of_completed_topics)/total_topics)*100)
334 except ZeroDivisionError:
335 return 0
336
337 return 0
338
scmmishrabf9a10f2019-03-06 15:45:35 +0530339def create_student_from_current_user():
scmmishra082e3c92018-11-23 17:16:22 +0530340 user = frappe.get_doc("User", frappe.session.user)
Shivam Mishradfdb92f2019-05-30 16:35:15 +0530341
scmmishrababb68d2018-11-19 16:13:21 +0530342 student = frappe.get_doc({
343 "doctype": "Student",
scmmishra082e3c92018-11-23 17:16:22 +0530344 "first_name": user.first_name,
345 "last_name": user.last_name,
346 "student_email_id": user.email,
scmmishrac84a3182018-12-06 20:17:39 +0530347 "user": frappe.session.user
scmmishrababb68d2018-11-19 16:13:21 +0530348 })
Shivam Mishradfdb92f2019-05-30 16:35:15 +0530349
scmmishrababb68d2018-11-19 16:13:21 +0530350 student.save(ignore_permissions=True)
scmmishra97c994f2018-11-26 14:41:15 +0530351 return student
352
Shivam Mishra8ddb63a2019-06-03 14:40:52 +0530353def get_or_create_course_enrollment(course, program):
scmmishra66d23922019-04-22 12:54:43 +0530354 student = get_current_student()
Shivam Mishra8ddb63a2019-06-03 14:40:52 +0530355 course_enrollment = get_enrollment("course", course, student.name)
356 if not course_enrollment:
Jannat Patel0a15a032021-07-02 13:06:56 +0530357 program_enrollment = get_enrollment('program', program.name, student.name)
Shivam Mishra8ddb63a2019-06-03 14:40:52 +0530358 if not program_enrollment:
Suraj Shetty48e9bc32020-01-29 15:06:18 +0530359 frappe.throw(_("You are not enrolled in program {0}").format(program))
Shivam Mishra8ddb63a2019-06-03 14:40:52 +0530360 return
Jannat Patel0a15a032021-07-02 13:06:56 +0530361 return student.enroll_in_course(course_name=course, program_enrollment=get_enrollment('program', program.name, student.name))
Shivam Mishra8ddb63a2019-06-03 14:40:52 +0530362 else:
363 return frappe.get_doc('Course Enrollment', course_enrollment)
scmmishrababb68d2018-11-19 16:13:21 +0530364
scmmishra766f68a2018-12-12 16:14:36 +0530365def check_content_completion(content_name, content_type, enrollment_name):
scmmishrada39da62018-12-13 11:51:31 +0530366 activity = frappe.get_all("Course Activity", filters={'enrollment': enrollment_name, 'content_type': content_type, 'content': content_name})
scmmishra766f68a2018-12-12 16:14:36 +0530367 if activity:
368 return True
369 else:
370 return False
371
372def check_quiz_completion(quiz, enrollment_name):
Jannat Pateldcdd3be2021-04-19 10:36:40 +0530373 attempts = frappe.get_all("Quiz Activity",
374 filters={
pateljannatbbf07d92021-06-08 17:05:44 +0530375 'enrollment': enrollment_name,
Jannat Pateldcdd3be2021-04-19 10:36:40 +0530376 'quiz': quiz.name
pateljannatbbf07d92021-06-08 17:05:44 +0530377 },
Jannat Pateldcdd3be2021-04-19 10:36:40 +0530378 fields=["name", "activity_date", "score", "status", "time_taken"]
379 )
Shivam Mishrad1a25212019-06-03 12:57:38 +0530380 status = False if quiz.max_attempts == 0 else bool(len(attempts) >= quiz.max_attempts)
scmmishra766f68a2018-12-12 16:14:36 +0530381 score = None
382 result = None
Jannat Pateldcdd3be2021-04-19 10:36:40 +0530383 time_taken = None
scmmishra766f68a2018-12-12 16:14:36 +0530384 if attempts:
385 if quiz.grading_basis == 'Last Highest Score':
386 attempts = sorted(attempts, key = lambda i: int(i.score), reverse=True)
387 score = attempts[0]['score']
388 result = attempts[0]['status']
Jannat Pateldcdd3be2021-04-19 10:36:40 +0530389 time_taken = attempts[0]['time_taken']
scmmishra766f68a2018-12-12 16:14:36 +0530390 if result == 'Pass':
391 status = True
pateljannatbbf07d92021-06-08 17:05:44 +0530392 return status, score, result, time_taken