blob: 9db8a4a90df6e45635b413c0c35c1d6b0f2b3f62 [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()
Jannat Pateldcdd3be2021-04-19 10:36:40 +0530197def evaluate_quiz(quiz_response, quiz_name, course, program, time_taken):
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):
Jannat Pateldcdd3be2021-04-19 10:36:40 +0530212 enrollment.add_quiz_activity(quiz_name, quiz_response, result, score, status, time_taken)
Shivam Mishra8ddb63a2019-06-03 14:40:52 +0530213 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:
Jannat Pateldcdd3be2021-04-19 10:36:40 +0530223 frappe.throw(_("Quiz {0} does not exist").format(quiz_name), frappe.DoesNotExistError)
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():
Jannat Pateldcdd3be2021-04-19 10:36:40 +0530235 return {
236 'questions': questions,
237 'activity': None,
pateljannatbbf07d92021-06-08 17:05:44 +0530238 'is_time_bound': quiz.is_time_bound,
239 'duration': quiz.duration
Jannat Pateldcdd3be2021-04-19 10:36:40 +0530240 }
Shivam Mishrad1a25212019-06-03 12:57:38 +0530241
242 student = get_current_student()
243 course_enrollment = get_enrollment("course", course, student.name)
Jannat Pateldcdd3be2021-04-19 10:36:40 +0530244 status, score, result, time_taken = check_quiz_completion(quiz, course_enrollment)
245 return {
pateljannatbbf07d92021-06-08 17:05:44 +0530246 'questions': questions,
Jannat Pateldcdd3be2021-04-19 10:36:40 +0530247 'activity': {'is_complete': status, 'score': score, 'result': result, 'time_taken': time_taken},
pateljannat7ace06a2021-06-08 18:26:23 +0530248 'is_time_bound': quiz.is_time_bound,
Jannat Pateldcdd3be2021-04-19 10:36:40 +0530249 'duration': quiz.duration
250 }
Shivam Mishrad1a25212019-06-03 12:57:38 +0530251
Shivam Mishra16b41292019-06-05 17:29:48 +0530252def get_topic_progress(topic, course_name, program):
Shivam Mishra6d4c6662019-06-03 14:41:05 +0530253 """
254 Return the porgress of a course in a program as well as the content to continue from.
255 :param topic_name:
256 :param course_name:
257 """
258 student = get_current_student()
Shivam Mishra65932632019-06-05 13:29:51 +0530259 if not student:
260 return None
Shivam Mishra6d4c6662019-06-03 14:41:05 +0530261 course_enrollment = get_or_create_course_enrollment(course_name, program)
262 progress = student.get_topic_progress(course_enrollment.name, topic)
263 if not progress:
Shivam Mishra570161b2019-06-05 13:08:53 +0530264 return None
Shivam Mishra6d4c6662019-06-03 14:41:05 +0530265 count = sum([activity['is_complete'] for activity in progress])
266 if count == 0:
Shivam Mishra570161b2019-06-05 13:08:53 +0530267 return {'completed': False, 'started': False}
Shivam Mishra6d4c6662019-06-03 14:41:05 +0530268 elif count == len(progress):
Shivam Mishra570161b2019-06-05 13:08:53 +0530269 return {'completed': True, 'started': True}
Shivam Mishra6d4c6662019-06-03 14:41:05 +0530270 elif count < len(progress):
Shivam Mishra570161b2019-06-05 13:08:53 +0530271 return {'completed': False, 'started': True}
272
Shivam Mishra16b41292019-06-05 17:29:48 +0530273def get_course_progress(course, program):
Shivam Mishra570161b2019-06-05 13:08:53 +0530274 """
275 Return the porgress of a course in a program as well as the content to continue from.
276 :param topic_name:
277 :param course_name:
278 """
279 course_progress = []
280 for course_topic in course.topics:
281 topic = frappe.get_doc("Topic", course_topic.topic)
Shivam Mishra16b41292019-06-05 17:29:48 +0530282 progress = get_topic_progress(topic, course.name, program)
Shivam Mishra570161b2019-06-05 13:08:53 +0530283 if progress:
284 course_progress.append(progress)
Shivam Mishra570161b2019-06-05 13:08:53 +0530285 if course_progress:
286 number_of_completed_topics = sum([activity['completed'] for activity in course_progress])
287 total_topics = len(course_progress)
Shivam Mishra16b41292019-06-05 17:29:48 +0530288 if total_topics == 1:
289 return course_progress[0]
Shivam Mishra570161b2019-06-05 13:08:53 +0530290 if number_of_completed_topics == 0:
291 return {'completed': False, 'started': False}
292 if number_of_completed_topics == total_topics:
293 return {'completed': True, 'started': True}
294 if number_of_completed_topics < total_topics:
295 return {'completed': False, 'started': True}
296
297 return None
Shivam Mishra6d4c6662019-06-03 14:41:05 +0530298
Shivam Mishra16b41292019-06-05 17:29:48 +0530299def get_program_progress(program):
300 program_progress = []
301 if not program.courses:
302 return None
303 for program_course in program.courses:
304 course = frappe.get_doc("Course", program_course.course)
305 progress = get_course_progress(course, program.name)
306 if progress:
307 progress['name'] = course.name
308 progress['course'] = course.course_name
309 program_progress.append(progress)
310
311 if program_progress:
312 return program_progress
313
314 return None
315
316def get_program_completion(program):
Shivam Mishrad49b5e42019-06-06 17:19:53 +0530317 topics = frappe.db.sql("""select `tabCourse Topic`.topic, `tabCourse Topic`.parent
318 from `tabCourse Topic`,
319 `tabProgram Course`
320 where `tabCourse Topic`.parent = `tabProgram Course`.course
321 and `tabProgram Course`.parent = %s""", program.name)
Shivam Mishra16b41292019-06-05 17:29:48 +0530322
323 progress = []
324 for topic in topics:
325 topic_doc = frappe.get_doc('Topic', topic[0])
326 topic_progress = get_topic_progress(topic_doc, topic[1], program.name)
327 if topic_progress:
328 progress.append(topic_progress)
329
330 if progress:
331 number_of_completed_topics = sum([activity['completed'] for activity in progress if activity])
332 total_topics = len(progress)
333 try:
334 return int((float(number_of_completed_topics)/total_topics)*100)
335 except ZeroDivisionError:
336 return 0
337
338 return 0
339
scmmishrabf9a10f2019-03-06 15:45:35 +0530340def create_student_from_current_user():
scmmishra082e3c92018-11-23 17:16:22 +0530341 user = frappe.get_doc("User", frappe.session.user)
Shivam Mishradfdb92f2019-05-30 16:35:15 +0530342
scmmishrababb68d2018-11-19 16:13:21 +0530343 student = frappe.get_doc({
344 "doctype": "Student",
scmmishra082e3c92018-11-23 17:16:22 +0530345 "first_name": user.first_name,
346 "last_name": user.last_name,
347 "student_email_id": user.email,
scmmishrac84a3182018-12-06 20:17:39 +0530348 "user": frappe.session.user
scmmishrababb68d2018-11-19 16:13:21 +0530349 })
Shivam Mishradfdb92f2019-05-30 16:35:15 +0530350
scmmishrababb68d2018-11-19 16:13:21 +0530351 student.save(ignore_permissions=True)
scmmishra97c994f2018-11-26 14:41:15 +0530352 return student
353
Shivam Mishra8ddb63a2019-06-03 14:40:52 +0530354def get_or_create_course_enrollment(course, program):
scmmishra66d23922019-04-22 12:54:43 +0530355 student = get_current_student()
Shivam Mishra8ddb63a2019-06-03 14:40:52 +0530356 course_enrollment = get_enrollment("course", course, student.name)
357 if not course_enrollment:
358 program_enrollment = get_enrollment('program', program, student.name)
359 if not program_enrollment:
Suraj Shetty48e9bc32020-01-29 15:06:18 +0530360 frappe.throw(_("You are not enrolled in program {0}").format(program))
Shivam Mishra8ddb63a2019-06-03 14:40:52 +0530361 return
362 return student.enroll_in_course(course_name=course, program_enrollment=get_enrollment('program', program, student.name))
363 else:
364 return frappe.get_doc('Course Enrollment', course_enrollment)
scmmishrababb68d2018-11-19 16:13:21 +0530365
scmmishra766f68a2018-12-12 16:14:36 +0530366def check_content_completion(content_name, content_type, enrollment_name):
scmmishrada39da62018-12-13 11:51:31 +0530367 activity = frappe.get_all("Course Activity", filters={'enrollment': enrollment_name, 'content_type': content_type, 'content': content_name})
scmmishra766f68a2018-12-12 16:14:36 +0530368 if activity:
369 return True
370 else:
371 return False
372
373def check_quiz_completion(quiz, enrollment_name):
Jannat Pateldcdd3be2021-04-19 10:36:40 +0530374 attempts = frappe.get_all("Quiz Activity",
375 filters={
pateljannatbbf07d92021-06-08 17:05:44 +0530376 'enrollment': enrollment_name,
Jannat Pateldcdd3be2021-04-19 10:36:40 +0530377 'quiz': quiz.name
pateljannatbbf07d92021-06-08 17:05:44 +0530378 },
Jannat Pateldcdd3be2021-04-19 10:36:40 +0530379 fields=["name", "activity_date", "score", "status", "time_taken"]
380 )
Shivam Mishrad1a25212019-06-03 12:57:38 +0530381 status = False if quiz.max_attempts == 0 else bool(len(attempts) >= quiz.max_attempts)
scmmishra766f68a2018-12-12 16:14:36 +0530382 score = None
383 result = None
Jannat Pateldcdd3be2021-04-19 10:36:40 +0530384 time_taken = None
scmmishra766f68a2018-12-12 16:14:36 +0530385 if attempts:
386 if quiz.grading_basis == 'Last Highest Score':
387 attempts = sorted(attempts, key = lambda i: int(i.score), reverse=True)
388 score = attempts[0]['score']
389 result = attempts[0]['status']
Jannat Pateldcdd3be2021-04-19 10:36:40 +0530390 time_taken = attempts[0]['time_taken']
scmmishra766f68a2018-12-12 16:14:36 +0530391 if result == 'Pass':
392 status = True
pateljannatbbf07d92021-06-08 17:05:44 +0530393 return status, score, result, time_taken