blob: 33394e179639ca518e38df8eb2e7d3eb26cd488e [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
Chillar Anand915b3432021-09-02 16:44:59 +05304from __future__ import division, unicode_literals
5
Neil Trini Lasrado3f0a5812016-07-19 14:17:33 +05306import frappe
7from frappe import _
8
Chillar Anand915b3432021-09-02 16:44:59 +05309
Neil Trini Lasrado3f0a5812016-07-19 14:17:33 +053010class OverlapError(frappe.ValidationError): pass
11
12def validate_overlap_for(doc, doctype, fieldname, value=None):
Manas Solanki54c42402017-04-12 19:24:12 +053013 """Checks overlap for specified field.
scmmishra685584b2018-10-17 12:41:50 +053014
15 :param fieldname: Checks Overlap for this field
Neil Trini Lasrado3f0a5812016-07-19 14:17:33 +053016 """
scmmishra685584b2018-10-17 12:41:50 +053017
Neil Trini Lasrado3f0a5812016-07-19 14:17:33 +053018 existing = get_overlap_for(doc, doctype, fieldname, value)
19 if existing:
20 frappe.throw(_("This {0} conflicts with {1} for {2} {3}").format(doc.doctype, existing.name,
21 doc.meta.get_label(fieldname) if not value else fieldname , value or doc.get(fieldname)), OverlapError)
scmmishra685584b2018-10-17 12:41:50 +053022
Neil Trini Lasrado3f0a5812016-07-19 14:17:33 +053023def get_overlap_for(doc, doctype, fieldname, value=None):
Manas Solanki54c42402017-04-12 19:24:12 +053024 """Returns overlaping document for specified field.
scmmishra685584b2018-10-17 12:41:50 +053025
26 :param fieldname: Checks Overlap for this field
Neil Trini Lasrado3f0a5812016-07-19 14:17:33 +053027 """
28
29 existing = frappe.db.sql("""select name, from_time, to_time from `tab{0}`
30 where `{1}`=%(val)s and schedule_date = %(schedule_date)s and
31 (
32 (from_time > %(from_time)s and from_time < %(to_time)s) or
33 (to_time > %(from_time)s and to_time < %(to_time)s) or
34 (%(from_time)s > from_time and %(from_time)s < to_time) or
35 (%(from_time)s = from_time and %(to_time)s = to_time))
Manas Solanki84e9d452017-11-28 18:04:08 +053036 and name!=%(name)s and docstatus!=2""".format(doctype, fieldname),
Neil Trini Lasrado3f0a5812016-07-19 14:17:33 +053037 {
38 "schedule_date": doc.schedule_date,
39 "val": value or doc.get(fieldname),
40 "from_time": doc.from_time,
41 "to_time": doc.to_time,
42 "name": doc.name or "No Name"
43 }, as_dict=True)
44
45 return existing[0] if existing else None
scmmishra685584b2018-10-17 12:41:50 +053046
scmmishra7409fe62018-10-22 18:37:03 +053047
Neil Trini Lasradof521a9c2016-07-22 01:28:41 +053048def validate_duplicate_student(students):
49 unique_students= []
50 for stud in students:
51 if stud.student in unique_students:
52 frappe.throw(_("Student {0} - {1} appears Multiple times in row {2} & {3}")
53 .format(stud.student, stud.student_name, unique_students.index(stud.student)+1, stud.idx))
54 else:
55 unique_students.append(stud.student)
scmmishra4ae11f42018-10-12 15:18:26 +053056
scmmishrababb68d2018-11-19 16:13:21 +053057 return None
58
scmmishra11925292018-11-20 17:38:01 +053059# LMS Utils
scmmishrababb68d2018-11-19 16:13:21 +053060def get_current_student():
Shivam Mishraf9275022019-05-29 18:39:52 +053061 """Returns current student from frappe.session.user
62
63 Returns:
Shivam Mishradfdb92f2019-05-30 16:35:15 +053064 object: Student Document
scmmishrababb68d2018-11-19 16:13:21 +053065 """
66 email = frappe.session.user
67 if email in ('Administrator', 'Guest'):
68 return None
69 try:
scmmishrada39da62018-12-13 11:51:31 +053070 student_id = frappe.get_all("Student", {"student_email_id": email}, ["name"])[0].name
scmmishra327334a2019-04-22 12:03:17 +053071 return frappe.get_doc("Student", student_id)
72 except (IndexError, frappe.DoesNotExistError):
scmmishra66d23922019-04-22 12:54:43 +053073 return None
scmmishrababb68d2018-11-19 16:13:21 +053074
Shivam Mishraf9275022019-05-29 18:39:52 +053075def get_portal_programs():
76 """Returns a list of all program to be displayed on the portal
77 Programs are returned based on the following logic
78 is_published and (student_is_enrolled or student_can_self_enroll)
scmmishra000e7062019-03-19 12:30:43 +053079
Shivam Mishraf9275022019-05-29 18:39:52 +053080 Returns:
Shivam Mishrae94e9d22019-05-30 18:05:00 +053081 list of dictionary: List of all programs and to be displayed on the portal along with access rights
scmmishrababb68d2018-11-19 16:13:21 +053082 """
Shivam Mishraf9275022019-05-29 18:39:52 +053083 published_programs = frappe.get_all("Program", filters={"is_published": True})
84 if not published_programs:
scmmishrababb68d2018-11-19 16:13:21 +053085 return None
Shivam Mishraf9275022019-05-29 18:39:52 +053086
87 program_list = [frappe.get_doc("Program", program) for program in published_programs]
Shivam Mishra12579612019-05-30 17:19:11 +053088 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 +053089
90 return portal_programs
91
Shivam Mishradfdb92f2019-05-30 16:35:15 +053092def allowed_program_access(program, student=None):
Shivam Mishraf9275022019-05-29 18:39:52 +053093 """Returns enrollment status for current student
94
95 Args:
Shivam Mishradfdb92f2019-05-30 16:35:15 +053096 program (string): Name of the program
97 student (object): instance of Student document
Shivam Mishraf9275022019-05-29 18:39:52 +053098
99 Returns:
Shivam Mishradfdb92f2019-05-30 16:35:15 +0530100 bool: Is current user enrolled or not
Shivam Mishraf9275022019-05-29 18:39:52 +0530101 """
Shivam Mishradfdb92f2019-05-30 16:35:15 +0530102 if has_super_access():
103 return True
Shivam Mishraf9275022019-05-29 18:39:52 +0530104 if not student:
105 student = get_current_student()
106 if student and get_enrollment('program', program, student.name):
107 return True
scmmishrababb68d2018-11-19 16:13:21 +0530108 else:
Shivam Mishraf9275022019-05-29 18:39:52 +0530109 return False
scmmishrababb68d2018-11-19 16:13:21 +0530110
Shivam Mishraf9275022019-05-29 18:39:52 +0530111def get_enrollment(master, document, student):
112 """Gets enrollment for course or program
scmmishrababb68d2018-11-19 16:13:21 +0530113
Shivam Mishraf9275022019-05-29 18:39:52 +0530114 Args:
Shivam Mishradfdb92f2019-05-30 16:35:15 +0530115 master (string): can either be program or course
116 document (string): program or course name
117 student (string): Student ID
Shivam Mishraf9275022019-05-29 18:39:52 +0530118
119 Returns:
Shivam Mishradfdb92f2019-05-30 16:35:15 +0530120 string: Enrollment Name if exists else returns empty string
Shivam Mishraf9275022019-05-29 18:39:52 +0530121 """
122 if master == 'program':
Shivam Mishradfdb92f2019-05-30 16:35:15 +0530123 enrollments = frappe.get_all("Program Enrollment", filters={'student':student, 'program': document, 'docstatus': 1})
Shivam Mishraf9275022019-05-29 18:39:52 +0530124 if master == 'course':
125 enrollments = frappe.get_all("Course Enrollment", filters={'student':student, 'course': document})
126
127 if enrollments:
Shivam Mishradfdb92f2019-05-30 16:35:15 +0530128 return enrollments[0].name
Shivam Mishraf9275022019-05-29 18:39:52 +0530129 else:
Shivam Mishradfdb92f2019-05-30 16:35:15 +0530130 return None
Shivam Mishraf9275022019-05-29 18:39:52 +0530131
Shivam Mishradfdb92f2019-05-30 16:35:15 +0530132@frappe.whitelist()
133def enroll_in_program(program_name, student=None):
134 """Enroll student in program
135
136 Args:
137 program_name (string): Name of the program to be enrolled into
138 student (string, optional): name of student who has to be enrolled, if not
139 provided, a student will be created from the current user
140
141 Returns:
142 string: name of the program enrollment document
143 """
144 if has_super_access():
145 return
146
147 if not student == None:
148 student = frappe.get_doc("Student", student)
149 else:
150 # Check if self enrollment in allowed
151 program = frappe.get_doc('Program', program_name)
152 if not program.allow_self_enroll:
Anurag Mishra841d8522019-07-03 15:15:08 +0530153 return frappe.throw(_("You are not allowed to enroll for this course"))
Shivam Mishradfdb92f2019-05-30 16:35:15 +0530154
155 student = get_current_student()
156 if not student:
157 student = create_student_from_current_user()
158
159 # Check if student is already enrolled in program
160 enrollment = get_enrollment('program', program_name, student.name)
161 if enrollment:
162 return enrollment
163
164 # Check if self enrollment in allowed
165 program = frappe.get_doc('Program', program_name)
166 if not program.allow_self_enroll:
Anurag Mishra841d8522019-07-03 15:15:08 +0530167 return frappe.throw(_("You are not allowed to enroll for this course"))
Shivam Mishradfdb92f2019-05-30 16:35:15 +0530168
169 # Enroll in program
170 program_enrollment = student.enroll_in_program(program_name)
171 return program_enrollment.name
172
173def has_super_access():
Shivam Mishrae94e9d22019-05-30 18:05:00 +0530174 """Check if user has a role that allows full access to LMS
175
176 Returns:
Shivam Mishrad1a25212019-06-03 12:57:38 +0530177 bool: true if user has access to all lms content
Shivam Mishrae94e9d22019-05-30 18:05:00 +0530178 """
Shivam Mishradfdb92f2019-05-30 16:35:15 +0530179 current_user = frappe.get_doc('User', frappe.session.user)
180 roles = set([role.role for role in current_user.roles])
181 return bool(roles & {'Administrator', 'Instructor', 'Education Manager', 'System Manager', 'Academic User'})
Shivam Mishraf9275022019-05-29 18:39:52 +0530182
Shivam Mishrae94e9d22019-05-30 18:05:00 +0530183@frappe.whitelist()
Shivam Mishra8ddb63a2019-06-03 14:40:52 +0530184def add_activity(course, content_type, content, program):
Shivam Mishrae94e9d22019-05-30 18:05:00 +0530185 if has_super_access():
186 return None
Shivam Mishraf9275022019-05-29 18:39:52 +0530187
Shivam Mishrae94e9d22019-05-30 18:05:00 +0530188 student = get_current_student()
189 if not student:
Suraj Shetty48e9bc32020-01-29 15:06:18 +0530190 return frappe.throw(_("Student with email {0} does not exist").format(frappe.session.user), frappe.DoesNotExistError)
Shivam Mishraf9275022019-05-29 18:39:52 +0530191
Shivam Mishra8ddb63a2019-06-03 14:40:52 +0530192 enrollment = get_or_create_course_enrollment(course, program)
Shivam Mishrae94e9d22019-05-30 18:05:00 +0530193 if content_type == 'Quiz':
194 return
195 else:
196 return enrollment.add_activity(content_type, content)
scmmishrababb68d2018-11-19 16:13:21 +0530197
Shivam Mishrad1a25212019-06-03 12:57:38 +0530198@frappe.whitelist()
Jannat Pateldcdd3be2021-04-19 10:36:40 +0530199def evaluate_quiz(quiz_response, quiz_name, course, program, time_taken):
Shivam Mishrad1a25212019-06-03 12:57:38 +0530200 import json
201
202 student = get_current_student()
203
204 quiz_response = json.loads(quiz_response)
205 quiz = frappe.get_doc("Quiz", quiz_name)
206 result, score, status = quiz.evaluate(quiz_response, quiz_name)
207
208 if has_super_access():
209 return {'result': result, 'score': score, 'status': status}
210
211 if student:
Shivam Mishra8ddb63a2019-06-03 14:40:52 +0530212 enrollment = get_or_create_course_enrollment(course, program)
213 if quiz.allowed_attempt(enrollment, quiz_name):
Jannat Pateldcdd3be2021-04-19 10:36:40 +0530214 enrollment.add_quiz_activity(quiz_name, quiz_response, result, score, status, time_taken)
Shivam Mishra8ddb63a2019-06-03 14:40:52 +0530215 return {'result': result, 'score': score, 'status': status}
Shivam Mishrad1a25212019-06-03 12:57:38 +0530216 else:
Shivam Mishra8ddb63a2019-06-03 14:40:52 +0530217 return None
Shivam Mishrad1a25212019-06-03 12:57:38 +0530218
219@frappe.whitelist()
220def get_quiz(quiz_name, course):
221 try:
222 quiz = frappe.get_doc("Quiz", quiz_name)
223 questions = quiz.get_questions()
Ankush Menat694ae812021-09-01 14:40:56 +0530224 except Exception:
Jannat Pateldcdd3be2021-04-19 10:36:40 +0530225 frappe.throw(_("Quiz {0} does not exist").format(quiz_name), frappe.DoesNotExistError)
Shivam Mishrad1a25212019-06-03 12:57:38 +0530226 return None
227
228 questions = [{
229 'name': question.name,
230 'question': question.question,
231 'type': question.question_type,
232 'options': [{'name': option.name, 'option': option.option}
233 for option in question.options],
234 } for question in questions]
235
236 if has_super_access():
Jannat Pateldcdd3be2021-04-19 10:36:40 +0530237 return {
238 'questions': questions,
239 'activity': None,
pateljannatbbf07d92021-06-08 17:05:44 +0530240 'is_time_bound': quiz.is_time_bound,
241 'duration': quiz.duration
Jannat Pateldcdd3be2021-04-19 10:36:40 +0530242 }
Shivam Mishrad1a25212019-06-03 12:57:38 +0530243
244 student = get_current_student()
245 course_enrollment = get_enrollment("course", course, student.name)
Jannat Pateldcdd3be2021-04-19 10:36:40 +0530246 status, score, result, time_taken = check_quiz_completion(quiz, course_enrollment)
247 return {
pateljannatbbf07d92021-06-08 17:05:44 +0530248 'questions': questions,
Jannat Pateldcdd3be2021-04-19 10:36:40 +0530249 'activity': {'is_complete': status, 'score': score, 'result': result, 'time_taken': time_taken},
pateljannat7ace06a2021-06-08 18:26:23 +0530250 'is_time_bound': quiz.is_time_bound,
Jannat Pateldcdd3be2021-04-19 10:36:40 +0530251 'duration': quiz.duration
252 }
Shivam Mishrad1a25212019-06-03 12:57:38 +0530253
Shivam Mishra16b41292019-06-05 17:29:48 +0530254def get_topic_progress(topic, course_name, program):
Shivam Mishra6d4c6662019-06-03 14:41:05 +0530255 """
256 Return the porgress of a course in a program as well as the content to continue from.
257 :param topic_name:
258 :param course_name:
259 """
260 student = get_current_student()
Shivam Mishra65932632019-06-05 13:29:51 +0530261 if not student:
262 return None
Shivam Mishra6d4c6662019-06-03 14:41:05 +0530263 course_enrollment = get_or_create_course_enrollment(course_name, program)
264 progress = student.get_topic_progress(course_enrollment.name, topic)
265 if not progress:
Shivam Mishra570161b2019-06-05 13:08:53 +0530266 return None
Shivam Mishra6d4c6662019-06-03 14:41:05 +0530267 count = sum([activity['is_complete'] for activity in progress])
268 if count == 0:
Shivam Mishra570161b2019-06-05 13:08:53 +0530269 return {'completed': False, 'started': False}
Shivam Mishra6d4c6662019-06-03 14:41:05 +0530270 elif count == len(progress):
Shivam Mishra570161b2019-06-05 13:08:53 +0530271 return {'completed': True, 'started': True}
Shivam Mishra6d4c6662019-06-03 14:41:05 +0530272 elif count < len(progress):
Shivam Mishra570161b2019-06-05 13:08:53 +0530273 return {'completed': False, 'started': True}
274
Shivam Mishra16b41292019-06-05 17:29:48 +0530275def get_course_progress(course, program):
Shivam Mishra570161b2019-06-05 13:08:53 +0530276 """
277 Return the porgress of a course in a program as well as the content to continue from.
278 :param topic_name:
279 :param course_name:
280 """
281 course_progress = []
282 for course_topic in course.topics:
283 topic = frappe.get_doc("Topic", course_topic.topic)
Shivam Mishra16b41292019-06-05 17:29:48 +0530284 progress = get_topic_progress(topic, course.name, program)
Shivam Mishra570161b2019-06-05 13:08:53 +0530285 if progress:
286 course_progress.append(progress)
Shivam Mishra570161b2019-06-05 13:08:53 +0530287 if course_progress:
288 number_of_completed_topics = sum([activity['completed'] for activity in course_progress])
289 total_topics = len(course_progress)
Shivam Mishra16b41292019-06-05 17:29:48 +0530290 if total_topics == 1:
291 return course_progress[0]
Shivam Mishra570161b2019-06-05 13:08:53 +0530292 if number_of_completed_topics == 0:
293 return {'completed': False, 'started': False}
294 if number_of_completed_topics == total_topics:
295 return {'completed': True, 'started': True}
296 if number_of_completed_topics < total_topics:
297 return {'completed': False, 'started': True}
298
299 return None
Shivam Mishra6d4c6662019-06-03 14:41:05 +0530300
Shivam Mishra16b41292019-06-05 17:29:48 +0530301def get_program_progress(program):
302 program_progress = []
303 if not program.courses:
304 return None
305 for program_course in program.courses:
306 course = frappe.get_doc("Course", program_course.course)
307 progress = get_course_progress(course, program.name)
308 if progress:
309 progress['name'] = course.name
310 progress['course'] = course.course_name
311 program_progress.append(progress)
312
313 if program_progress:
314 return program_progress
315
316 return None
317
318def get_program_completion(program):
Shivam Mishrad49b5e42019-06-06 17:19:53 +0530319 topics = frappe.db.sql("""select `tabCourse Topic`.topic, `tabCourse Topic`.parent
320 from `tabCourse Topic`,
321 `tabProgram Course`
322 where `tabCourse Topic`.parent = `tabProgram Course`.course
323 and `tabProgram Course`.parent = %s""", program.name)
Shivam Mishra16b41292019-06-05 17:29:48 +0530324
325 progress = []
326 for topic in topics:
327 topic_doc = frappe.get_doc('Topic', topic[0])
328 topic_progress = get_topic_progress(topic_doc, topic[1], program.name)
329 if topic_progress:
330 progress.append(topic_progress)
331
332 if progress:
333 number_of_completed_topics = sum([activity['completed'] for activity in progress if activity])
334 total_topics = len(progress)
335 try:
336 return int((float(number_of_completed_topics)/total_topics)*100)
337 except ZeroDivisionError:
338 return 0
339
340 return 0
341
scmmishrabf9a10f2019-03-06 15:45:35 +0530342def create_student_from_current_user():
scmmishra082e3c92018-11-23 17:16:22 +0530343 user = frappe.get_doc("User", frappe.session.user)
Shivam Mishradfdb92f2019-05-30 16:35:15 +0530344
scmmishrababb68d2018-11-19 16:13:21 +0530345 student = frappe.get_doc({
346 "doctype": "Student",
scmmishra082e3c92018-11-23 17:16:22 +0530347 "first_name": user.first_name,
348 "last_name": user.last_name,
349 "student_email_id": user.email,
scmmishrac84a3182018-12-06 20:17:39 +0530350 "user": frappe.session.user
scmmishrababb68d2018-11-19 16:13:21 +0530351 })
Shivam Mishradfdb92f2019-05-30 16:35:15 +0530352
scmmishrababb68d2018-11-19 16:13:21 +0530353 student.save(ignore_permissions=True)
scmmishra97c994f2018-11-26 14:41:15 +0530354 return student
355
Shivam Mishra8ddb63a2019-06-03 14:40:52 +0530356def get_or_create_course_enrollment(course, program):
scmmishra66d23922019-04-22 12:54:43 +0530357 student = get_current_student()
Shivam Mishra8ddb63a2019-06-03 14:40:52 +0530358 course_enrollment = get_enrollment("course", course, student.name)
359 if not course_enrollment:
Jannat Patel0a15a032021-07-02 13:06:56 +0530360 program_enrollment = get_enrollment('program', program.name, student.name)
Shivam Mishra8ddb63a2019-06-03 14:40:52 +0530361 if not program_enrollment:
Suraj Shetty48e9bc32020-01-29 15:06:18 +0530362 frappe.throw(_("You are not enrolled in program {0}").format(program))
Shivam Mishra8ddb63a2019-06-03 14:40:52 +0530363 return
Jannat Patel0a15a032021-07-02 13:06:56 +0530364 return student.enroll_in_course(course_name=course, program_enrollment=get_enrollment('program', program.name, student.name))
Shivam Mishra8ddb63a2019-06-03 14:40:52 +0530365 else:
366 return frappe.get_doc('Course Enrollment', course_enrollment)
scmmishrababb68d2018-11-19 16:13:21 +0530367
scmmishra766f68a2018-12-12 16:14:36 +0530368def check_content_completion(content_name, content_type, enrollment_name):
scmmishrada39da62018-12-13 11:51:31 +0530369 activity = frappe.get_all("Course Activity", filters={'enrollment': enrollment_name, 'content_type': content_type, 'content': content_name})
scmmishra766f68a2018-12-12 16:14:36 +0530370 if activity:
371 return True
372 else:
373 return False
374
375def check_quiz_completion(quiz, enrollment_name):
Jannat Pateldcdd3be2021-04-19 10:36:40 +0530376 attempts = frappe.get_all("Quiz Activity",
377 filters={
pateljannatbbf07d92021-06-08 17:05:44 +0530378 'enrollment': enrollment_name,
Jannat Pateldcdd3be2021-04-19 10:36:40 +0530379 'quiz': quiz.name
pateljannatbbf07d92021-06-08 17:05:44 +0530380 },
Jannat Pateldcdd3be2021-04-19 10:36:40 +0530381 fields=["name", "activity_date", "score", "status", "time_taken"]
382 )
Shivam Mishrad1a25212019-06-03 12:57:38 +0530383 status = False if quiz.max_attempts == 0 else bool(len(attempts) >= quiz.max_attempts)
scmmishra766f68a2018-12-12 16:14:36 +0530384 score = None
385 result = None
Jannat Pateldcdd3be2021-04-19 10:36:40 +0530386 time_taken = None
scmmishra766f68a2018-12-12 16:14:36 +0530387 if attempts:
388 if quiz.grading_basis == 'Last Highest Score':
389 attempts = sorted(attempts, key = lambda i: int(i.score), reverse=True)
390 score = attempts[0]['score']
391 result = attempts[0]['status']
Jannat Pateldcdd3be2021-04-19 10:36:40 +0530392 time_taken = attempts[0]['time_taken']
scmmishra766f68a2018-12-12 16:14:36 +0530393 if result == 'Pass':
394 status = True
pateljannatbbf07d92021-06-08 17:05:44 +0530395 return status, score, result, time_taken