blob: cffc3960a05301068e06527743e13e3e2e59b583 [file] [log] [blame]
Neil Trini Lasrado3f0a5812016-07-19 14:17:33 +05301# -*- coding: utf-8 -*-
2# Copyright (c) 2015, Frappe Technologies and contributors
Neil Trini Lasrado3f0a5812016-07-19 14:17:33 +05303
scmmishra4ae11f42018-10-12 15:18:26 +05304from __future__ import unicode_literals, division
Neil Trini Lasrado3f0a5812016-07-19 14:17:33 +05305import frappe
6from frappe import _
7
8class OverlapError(frappe.ValidationError): pass
9
10def validate_overlap_for(doc, doctype, fieldname, value=None):
Manas Solanki54c42402017-04-12 19:24:12 +053011 """Checks overlap for specified field.
scmmishra685584b2018-10-17 12:41:50 +053012
13 :param fieldname: Checks Overlap for this field
Neil Trini Lasrado3f0a5812016-07-19 14:17:33 +053014 """
scmmishra685584b2018-10-17 12:41:50 +053015
Neil Trini Lasrado3f0a5812016-07-19 14:17:33 +053016 existing = get_overlap_for(doc, doctype, fieldname, value)
17 if existing:
18 frappe.throw(_("This {0} conflicts with {1} for {2} {3}").format(doc.doctype, existing.name,
19 doc.meta.get_label(fieldname) if not value else fieldname , value or doc.get(fieldname)), OverlapError)
scmmishra685584b2018-10-17 12:41:50 +053020
Neil Trini Lasrado3f0a5812016-07-19 14:17:33 +053021def get_overlap_for(doc, doctype, fieldname, value=None):
Manas Solanki54c42402017-04-12 19:24:12 +053022 """Returns overlaping document for specified field.
scmmishra685584b2018-10-17 12:41:50 +053023
24 :param fieldname: Checks Overlap for this field
Neil Trini Lasrado3f0a5812016-07-19 14:17:33 +053025 """
26
27 existing = frappe.db.sql("""select name, from_time, to_time from `tab{0}`
28 where `{1}`=%(val)s and schedule_date = %(schedule_date)s and
29 (
30 (from_time > %(from_time)s and from_time < %(to_time)s) or
31 (to_time > %(from_time)s and to_time < %(to_time)s) or
32 (%(from_time)s > from_time and %(from_time)s < to_time) or
33 (%(from_time)s = from_time and %(to_time)s = to_time))
Manas Solanki84e9d452017-11-28 18:04:08 +053034 and name!=%(name)s and docstatus!=2""".format(doctype, fieldname),
Neil Trini Lasrado3f0a5812016-07-19 14:17:33 +053035 {
36 "schedule_date": doc.schedule_date,
37 "val": value or doc.get(fieldname),
38 "from_time": doc.from_time,
39 "to_time": doc.to_time,
40 "name": doc.name or "No Name"
41 }, as_dict=True)
42
43 return existing[0] if existing else None
scmmishra685584b2018-10-17 12:41:50 +053044
scmmishra7409fe62018-10-22 18:37:03 +053045
Neil Trini Lasradof521a9c2016-07-22 01:28:41 +053046def validate_duplicate_student(students):
47 unique_students= []
48 for stud in students:
49 if stud.student in unique_students:
50 frappe.throw(_("Student {0} - {1} appears Multiple times in row {2} & {3}")
51 .format(stud.student, stud.student_name, unique_students.index(stud.student)+1, stud.idx))
52 else:
53 unique_students.append(stud.student)
scmmishra4ae11f42018-10-12 15:18:26 +053054
scmmishrababb68d2018-11-19 16:13:21 +053055 return None
56
scmmishra11925292018-11-20 17:38:01 +053057# LMS Utils
scmmishrababb68d2018-11-19 16:13:21 +053058def get_current_student():
Shivam Mishraf9275022019-05-29 18:39:52 +053059 """Returns current student from frappe.session.user
60
61 Returns:
Shivam Mishradfdb92f2019-05-30 16:35:15 +053062 object: Student Document
scmmishrababb68d2018-11-19 16:13:21 +053063 """
64 email = frappe.session.user
65 if email in ('Administrator', 'Guest'):
66 return None
67 try:
scmmishrada39da62018-12-13 11:51:31 +053068 student_id = frappe.get_all("Student", {"student_email_id": email}, ["name"])[0].name
scmmishra327334a2019-04-22 12:03:17 +053069 return frappe.get_doc("Student", student_id)
70 except (IndexError, frappe.DoesNotExistError):
scmmishra66d23922019-04-22 12:54:43 +053071 return None
scmmishrababb68d2018-11-19 16:13:21 +053072
Shivam Mishraf9275022019-05-29 18:39:52 +053073def get_portal_programs():
74 """Returns a list of all program to be displayed on the portal
75 Programs are returned based on the following logic
76 is_published and (student_is_enrolled or student_can_self_enroll)
scmmishra000e7062019-03-19 12:30:43 +053077
Shivam Mishraf9275022019-05-29 18:39:52 +053078 Returns:
Shivam Mishrae94e9d22019-05-30 18:05:00 +053079 list of dictionary: List of all programs and to be displayed on the portal along with access rights
scmmishrababb68d2018-11-19 16:13:21 +053080 """
Shivam Mishraf9275022019-05-29 18:39:52 +053081 published_programs = frappe.get_all("Program", filters={"is_published": True})
82 if not published_programs:
scmmishrababb68d2018-11-19 16:13:21 +053083 return None
Shivam Mishraf9275022019-05-29 18:39:52 +053084
85 program_list = [frappe.get_doc("Program", program) for program in published_programs]
Shivam Mishra12579612019-05-30 17:19:11 +053086 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 +053087
88 return portal_programs
89
Shivam Mishradfdb92f2019-05-30 16:35:15 +053090def allowed_program_access(program, student=None):
Shivam Mishraf9275022019-05-29 18:39:52 +053091 """Returns enrollment status for current student
92
93 Args:
Shivam Mishradfdb92f2019-05-30 16:35:15 +053094 program (string): Name of the program
95 student (object): instance of Student document
Shivam Mishraf9275022019-05-29 18:39:52 +053096
97 Returns:
Shivam Mishradfdb92f2019-05-30 16:35:15 +053098 bool: Is current user enrolled or not
Shivam Mishraf9275022019-05-29 18:39:52 +053099 """
Shivam Mishradfdb92f2019-05-30 16:35:15 +0530100 if has_super_access():
101 return True
Shivam Mishraf9275022019-05-29 18:39:52 +0530102 if not student:
103 student = get_current_student()
104 if student and get_enrollment('program', program, student.name):
105 return True
scmmishrababb68d2018-11-19 16:13:21 +0530106 else:
Shivam Mishraf9275022019-05-29 18:39:52 +0530107 return False
scmmishrababb68d2018-11-19 16:13:21 +0530108
Shivam Mishraf9275022019-05-29 18:39:52 +0530109def get_enrollment(master, document, student):
110 """Gets enrollment for course or program
scmmishrababb68d2018-11-19 16:13:21 +0530111
Shivam Mishraf9275022019-05-29 18:39:52 +0530112 Args:
Shivam Mishradfdb92f2019-05-30 16:35:15 +0530113 master (string): can either be program or course
114 document (string): program or course name
115 student (string): Student ID
Shivam Mishraf9275022019-05-29 18:39:52 +0530116
117 Returns:
Shivam Mishradfdb92f2019-05-30 16:35:15 +0530118 string: Enrollment Name if exists else returns empty string
Shivam Mishraf9275022019-05-29 18:39:52 +0530119 """
120 if master == 'program':
Shivam Mishradfdb92f2019-05-30 16:35:15 +0530121 enrollments = frappe.get_all("Program Enrollment", filters={'student':student, 'program': document, 'docstatus': 1})
Shivam Mishraf9275022019-05-29 18:39:52 +0530122 if master == 'course':
123 enrollments = frappe.get_all("Course Enrollment", filters={'student':student, 'course': document})
124
125 if enrollments:
Shivam Mishradfdb92f2019-05-30 16:35:15 +0530126 return enrollments[0].name
Shivam Mishraf9275022019-05-29 18:39:52 +0530127 else:
Shivam Mishradfdb92f2019-05-30 16:35:15 +0530128 return None
Shivam Mishraf9275022019-05-29 18:39:52 +0530129
Shivam Mishradfdb92f2019-05-30 16:35:15 +0530130@frappe.whitelist()
131def enroll_in_program(program_name, student=None):
132 """Enroll student in program
133
134 Args:
135 program_name (string): Name of the program to be enrolled into
136 student (string, optional): name of student who has to be enrolled, if not
137 provided, a student will be created from the current user
138
139 Returns:
140 string: name of the program enrollment document
141 """
142 if has_super_access():
143 return
144
145 if not student == None:
146 student = frappe.get_doc("Student", student)
147 else:
148 # Check if self enrollment in allowed
149 program = frappe.get_doc('Program', program_name)
150 if not program.allow_self_enroll:
Anurag Mishra841d8522019-07-03 15:15:08 +0530151 return frappe.throw(_("You are not allowed to enroll for this course"))
Shivam Mishradfdb92f2019-05-30 16:35:15 +0530152
153 student = get_current_student()
154 if not student:
155 student = create_student_from_current_user()
156
157 # Check if student is already enrolled in program
158 enrollment = get_enrollment('program', program_name, student.name)
159 if enrollment:
160 return enrollment
161
162 # Check if self enrollment in allowed
163 program = frappe.get_doc('Program', program_name)
164 if not program.allow_self_enroll:
Anurag Mishra841d8522019-07-03 15:15:08 +0530165 return frappe.throw(_("You are not allowed to enroll for this course"))
Shivam Mishradfdb92f2019-05-30 16:35:15 +0530166
167 # Enroll in program
168 program_enrollment = student.enroll_in_program(program_name)
169 return program_enrollment.name
170
171def has_super_access():
Shivam Mishrae94e9d22019-05-30 18:05:00 +0530172 """Check if user has a role that allows full access to LMS
173
174 Returns:
Shivam Mishrad1a25212019-06-03 12:57:38 +0530175 bool: true if user has access to all lms content
Shivam Mishrae94e9d22019-05-30 18:05:00 +0530176 """
Shivam Mishradfdb92f2019-05-30 16:35:15 +0530177 current_user = frappe.get_doc('User', frappe.session.user)
178 roles = set([role.role for role in current_user.roles])
179 return bool(roles & {'Administrator', 'Instructor', 'Education Manager', 'System Manager', 'Academic User'})
Shivam Mishraf9275022019-05-29 18:39:52 +0530180
Shivam Mishrae94e9d22019-05-30 18:05:00 +0530181@frappe.whitelist()
Shivam Mishra8ddb63a2019-06-03 14:40:52 +0530182def add_activity(course, content_type, content, program):
Shivam Mishrae94e9d22019-05-30 18:05:00 +0530183 if has_super_access():
184 return None
Shivam Mishraf9275022019-05-29 18:39:52 +0530185
Shivam Mishrae94e9d22019-05-30 18:05:00 +0530186 student = get_current_student()
187 if not student:
Suraj Shetty48e9bc32020-01-29 15:06:18 +0530188 return frappe.throw(_("Student with email {0} does not exist").format(frappe.session.user), frappe.DoesNotExistError)
Shivam Mishraf9275022019-05-29 18:39:52 +0530189
Shivam Mishra8ddb63a2019-06-03 14:40:52 +0530190 enrollment = get_or_create_course_enrollment(course, program)
Shivam Mishrae94e9d22019-05-30 18:05:00 +0530191 if content_type == 'Quiz':
192 return
193 else:
194 return enrollment.add_activity(content_type, content)
scmmishrababb68d2018-11-19 16:13:21 +0530195
Shivam Mishrad1a25212019-06-03 12:57:38 +0530196@frappe.whitelist()
Shivam Mishra8ddb63a2019-06-03 14:40:52 +0530197def evaluate_quiz(quiz_response, quiz_name, course, program):
Shivam Mishrad1a25212019-06-03 12:57:38 +0530198 import json
199
200 student = get_current_student()
201
202 quiz_response = json.loads(quiz_response)
203 quiz = frappe.get_doc("Quiz", quiz_name)
204 result, score, status = quiz.evaluate(quiz_response, quiz_name)
205
206 if has_super_access():
207 return {'result': result, 'score': score, 'status': status}
208
209 if student:
Shivam Mishra8ddb63a2019-06-03 14:40:52 +0530210 enrollment = get_or_create_course_enrollment(course, program)
211 if quiz.allowed_attempt(enrollment, quiz_name):
212 enrollment.add_quiz_activity(quiz_name, quiz_response, result, score, status)
213 return {'result': result, 'score': score, 'status': status}
Shivam Mishrad1a25212019-06-03 12:57:38 +0530214 else:
Shivam Mishra8ddb63a2019-06-03 14:40:52 +0530215 return None
Shivam Mishrad1a25212019-06-03 12:57:38 +0530216
217@frappe.whitelist()
218def get_quiz(quiz_name, course):
219 try:
220 quiz = frappe.get_doc("Quiz", quiz_name)
221 questions = quiz.get_questions()
222 except:
Suraj Shetty48e9bc32020-01-29 15:06:18 +0530223 frappe.throw(_("Quiz {0} does not exist").format(quiz_name))
Shivam Mishrad1a25212019-06-03 12:57:38 +0530224 return None
225
226 questions = [{
227 'name': question.name,
228 'question': question.question,
229 'type': question.question_type,
230 'options': [{'name': option.name, 'option': option.option}
231 for option in question.options],
232 } for question in questions]
233
234 if has_super_access():
235 return {'questions': questions, 'activity': None}
236
237 student = get_current_student()
238 course_enrollment = get_enrollment("course", course, student.name)
239 status, score, result = check_quiz_completion(quiz, course_enrollment)
240 return {'questions': questions, 'activity': {'is_complete': status, 'score': score, 'result': result}}
241
Shivam Mishra16b41292019-06-05 17:29:48 +0530242def get_topic_progress(topic, course_name, program):
Shivam Mishra6d4c6662019-06-03 14:41:05 +0530243 """
244 Return the porgress of a course in a program as well as the content to continue from.
245 :param topic_name:
246 :param course_name:
247 """
248 student = get_current_student()
Shivam Mishra65932632019-06-05 13:29:51 +0530249 if not student:
250 return None
Shivam Mishra6d4c6662019-06-03 14:41:05 +0530251 course_enrollment = get_or_create_course_enrollment(course_name, program)
252 progress = student.get_topic_progress(course_enrollment.name, topic)
253 if not progress:
Shivam Mishra570161b2019-06-05 13:08:53 +0530254 return None
Shivam Mishra6d4c6662019-06-03 14:41:05 +0530255 count = sum([activity['is_complete'] for activity in progress])
256 if count == 0:
Shivam Mishra570161b2019-06-05 13:08:53 +0530257 return {'completed': False, 'started': False}
Shivam Mishra6d4c6662019-06-03 14:41:05 +0530258 elif count == len(progress):
Shivam Mishra570161b2019-06-05 13:08:53 +0530259 return {'completed': True, 'started': True}
Shivam Mishra6d4c6662019-06-03 14:41:05 +0530260 elif count < len(progress):
Shivam Mishra570161b2019-06-05 13:08:53 +0530261 return {'completed': False, 'started': True}
262
Shivam Mishra16b41292019-06-05 17:29:48 +0530263def get_course_progress(course, program):
Shivam Mishra570161b2019-06-05 13:08:53 +0530264 """
265 Return the porgress of a course in a program as well as the content to continue from.
266 :param topic_name:
267 :param course_name:
268 """
269 course_progress = []
270 for course_topic in course.topics:
271 topic = frappe.get_doc("Topic", course_topic.topic)
Shivam Mishra16b41292019-06-05 17:29:48 +0530272 progress = get_topic_progress(topic, course.name, program)
Shivam Mishra570161b2019-06-05 13:08:53 +0530273 if progress:
274 course_progress.append(progress)
Shivam Mishra570161b2019-06-05 13:08:53 +0530275 if course_progress:
276 number_of_completed_topics = sum([activity['completed'] for activity in course_progress])
277 total_topics = len(course_progress)
Shivam Mishra16b41292019-06-05 17:29:48 +0530278 if total_topics == 1:
279 return course_progress[0]
Shivam Mishra570161b2019-06-05 13:08:53 +0530280 if number_of_completed_topics == 0:
281 return {'completed': False, 'started': False}
282 if number_of_completed_topics == total_topics:
283 return {'completed': True, 'started': True}
284 if number_of_completed_topics < total_topics:
285 return {'completed': False, 'started': True}
286
287 return None
Shivam Mishra6d4c6662019-06-03 14:41:05 +0530288
Shivam Mishra16b41292019-06-05 17:29:48 +0530289def get_program_progress(program):
290 program_progress = []
291 if not program.courses:
292 return None
293 for program_course in program.courses:
294 course = frappe.get_doc("Course", program_course.course)
295 progress = get_course_progress(course, program.name)
296 if progress:
297 progress['name'] = course.name
298 progress['course'] = course.course_name
299 program_progress.append(progress)
300
301 if program_progress:
302 return program_progress
303
304 return None
305
306def get_program_completion(program):
Shivam Mishrad49b5e42019-06-06 17:19:53 +0530307 topics = frappe.db.sql("""select `tabCourse Topic`.topic, `tabCourse Topic`.parent
308 from `tabCourse Topic`,
309 `tabProgram Course`
310 where `tabCourse Topic`.parent = `tabProgram Course`.course
311 and `tabProgram Course`.parent = %s""", program.name)
Shivam Mishra16b41292019-06-05 17:29:48 +0530312
313 progress = []
314 for topic in topics:
315 topic_doc = frappe.get_doc('Topic', topic[0])
316 topic_progress = get_topic_progress(topic_doc, topic[1], program.name)
317 if topic_progress:
318 progress.append(topic_progress)
319
320 if progress:
321 number_of_completed_topics = sum([activity['completed'] for activity in progress if activity])
322 total_topics = len(progress)
323 try:
324 return int((float(number_of_completed_topics)/total_topics)*100)
325 except ZeroDivisionError:
326 return 0
327
328 return 0
329
scmmishrabf9a10f2019-03-06 15:45:35 +0530330def create_student_from_current_user():
scmmishra082e3c92018-11-23 17:16:22 +0530331 user = frappe.get_doc("User", frappe.session.user)
Shivam Mishradfdb92f2019-05-30 16:35:15 +0530332
scmmishrababb68d2018-11-19 16:13:21 +0530333 student = frappe.get_doc({
334 "doctype": "Student",
scmmishra082e3c92018-11-23 17:16:22 +0530335 "first_name": user.first_name,
336 "last_name": user.last_name,
337 "student_email_id": user.email,
scmmishrac84a3182018-12-06 20:17:39 +0530338 "user": frappe.session.user
scmmishrababb68d2018-11-19 16:13:21 +0530339 })
Shivam Mishradfdb92f2019-05-30 16:35:15 +0530340
scmmishrababb68d2018-11-19 16:13:21 +0530341 student.save(ignore_permissions=True)
scmmishra97c994f2018-11-26 14:41:15 +0530342 return student
343
Shivam Mishra8ddb63a2019-06-03 14:40:52 +0530344def get_or_create_course_enrollment(course, program):
scmmishra66d23922019-04-22 12:54:43 +0530345 student = get_current_student()
Shivam Mishra8ddb63a2019-06-03 14:40:52 +0530346 course_enrollment = get_enrollment("course", course, student.name)
347 if not course_enrollment:
348 program_enrollment = get_enrollment('program', program, student.name)
349 if not program_enrollment:
Suraj Shetty48e9bc32020-01-29 15:06:18 +0530350 frappe.throw(_("You are not enrolled in program {0}").format(program))
Shivam Mishra8ddb63a2019-06-03 14:40:52 +0530351 return
352 return student.enroll_in_course(course_name=course, program_enrollment=get_enrollment('program', program, student.name))
353 else:
354 return frappe.get_doc('Course Enrollment', course_enrollment)
scmmishrababb68d2018-11-19 16:13:21 +0530355
scmmishra766f68a2018-12-12 16:14:36 +0530356def check_content_completion(content_name, content_type, enrollment_name):
scmmishrada39da62018-12-13 11:51:31 +0530357 activity = frappe.get_all("Course Activity", filters={'enrollment': enrollment_name, 'content_type': content_type, 'content': content_name})
scmmishra766f68a2018-12-12 16:14:36 +0530358 if activity:
359 return True
360 else:
361 return False
362
363def check_quiz_completion(quiz, enrollment_name):
scmmishrada39da62018-12-13 11:51:31 +0530364 attempts = frappe.get_all("Quiz Activity", filters={'enrollment': enrollment_name, 'quiz': quiz.name}, fields=["name", "activity_date", "score", "status"])
Shivam Mishrad1a25212019-06-03 12:57:38 +0530365 status = False if quiz.max_attempts == 0 else bool(len(attempts) >= quiz.max_attempts)
scmmishra766f68a2018-12-12 16:14:36 +0530366 score = None
367 result = None
368 if attempts:
369 if quiz.grading_basis == 'Last Highest Score':
370 attempts = sorted(attempts, key = lambda i: int(i.score), reverse=True)
371 score = attempts[0]['score']
372 result = attempts[0]['status']
373 if result == 'Pass':
374 status = True
scmmishrabf9a10f2019-03-06 15:45:35 +0530375 return status, score, result