blob: 809fa9e573575fc74fead4d643f10f16a0ec877e [file] [log] [blame]
Neil Trini Lasrado3f0a5812016-07-19 14:17:33 +05301# -*- coding: utf-8 -*-
2# Copyright (c) 2015, Frappe Technologies and contributors
3# For lice
4
scmmishra4ae11f42018-10-12 15:18:26 +05305from __future__ import unicode_literals, division
Neil Trini Lasrado3f0a5812016-07-19 14:17:33 +05306import frappe
7from frappe import _
8
9class OverlapError(frappe.ValidationError): pass
10
11def validate_overlap_for(doc, doctype, fieldname, value=None):
Manas Solanki54c42402017-04-12 19:24:12 +053012 """Checks overlap for specified field.
Neil Trini Lasrado3f0a5812016-07-19 14:17:33 +053013
Manas Solanki54c42402017-04-12 19:24:12 +053014 :param fieldname: Checks Overlap for this field
Neil Trini Lasrado3f0a5812016-07-19 14:17:33 +053015 """
16
17 existing = get_overlap_for(doc, doctype, fieldname, value)
18 if existing:
19 frappe.throw(_("This {0} conflicts with {1} for {2} {3}").format(doc.doctype, existing.name,
20 doc.meta.get_label(fieldname) if not value else fieldname , value or doc.get(fieldname)), OverlapError)
21
22def get_overlap_for(doc, doctype, fieldname, value=None):
Manas Solanki54c42402017-04-12 19:24:12 +053023 """Returns overlaping document for specified field.
Neil Trini Lasrado3f0a5812016-07-19 14:17:33 +053024
Manas Solanki54c42402017-04-12 19:24:12 +053025 :param fieldname: Checks Overlap for this field
Neil Trini Lasrado3f0a5812016-07-19 14:17:33 +053026 """
27
28 existing = frappe.db.sql("""select name, from_time, to_time from `tab{0}`
29 where `{1}`=%(val)s and schedule_date = %(schedule_date)s and
30 (
31 (from_time > %(from_time)s and from_time < %(to_time)s) or
32 (to_time > %(from_time)s and to_time < %(to_time)s) or
33 (%(from_time)s > from_time and %(from_time)s < to_time) or
34 (%(from_time)s = from_time and %(to_time)s = to_time))
Manas Solanki84e9d452017-11-28 18:04:08 +053035 and name!=%(name)s and docstatus!=2""".format(doctype, fieldname),
Neil Trini Lasrado3f0a5812016-07-19 14:17:33 +053036 {
37 "schedule_date": doc.schedule_date,
38 "val": value or doc.get(fieldname),
39 "from_time": doc.from_time,
40 "to_time": doc.to_time,
41 "name": doc.name or "No Name"
42 }, as_dict=True)
43
44 return existing[0] if existing else None
Neil Trini Lasradof521a9c2016-07-22 01:28:41 +053045
46def 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
55def get_student_name(email=None):
56 """Returns student user name, example EDU-STU-2018-00001 (Based on the naming series).
57
58 :param user: a user email address
59 """
60 try:
61 return frappe.get_all('Student', filters={'student_email_id': email}, fields=['name'])[0].name
62 except IndexError:
63 return None
64
65@frappe.whitelist()
66def evaluate_quiz(quiz_response, **kwargs):
67 """LMS Function: Evaluates a simple multiple choice quiz. It recieves arguments from `www/lms/course.js` as dictionary using FormData[1].
68
69
70 :param quiz_response: contains user selected choices for a quiz in the form of a string formatted as a dictionary. The function uses `json.loads()` to convert it to a python dictionary.
71 [1]: https://developer.mozilla.org/en-US/docs/Web/API/FormData
72 """
73 import json
74 quiz_response = json.loads(quiz_response)
75 correct_answers = [frappe.get_value('Question', name, 'correct_options') for name in quiz_response.keys()]
76 selected_options = quiz_response.values()
77 result = [selected == correct for selected, correct in zip(selected_options, correct_answers)]
78 try:
79 score = int((result.count(True)/len(selected_options))*100)
80 except ZeroDivisionError:
81 score = 0
82
83 kwargs['selected_options'] = selected_options
84 kwargs['result'] = result
85 kwargs['score'] = score
86 add_activity('Quiz', **kwargs)
87 return score
88
89@frappe.whitelist()
90def add_activity(content_type, **kwargs):
91 activity_does_not_exists, activity = check_entry_exists(kwargs.get('program'))
92 if activity_does_not_exists:
93 current_activity = frappe.get_doc({
scmmishra31cbe3c2018-10-15 16:04:14 +053094 "doctype": "Course Activity",
scmmishra17294e72018-10-15 11:45:17 +053095 "student_id": get_student_id(frappe.session.user),
scmmishra4ae11f42018-10-12 15:18:26 +053096 "program_name": kwargs.get('program'),
97 "lms_activity": [{
98 "course_name": kwargs.get('course'),
99 "content_name": kwargs.get('content'),
100 "status": "Completed"
101 }]
102 })
103 if content_type == "Quiz":
104 activity = current_activity.lms_activity[-1]
105 activity.quiz_score = kwargs.get('score')
106 activity.selected_options = ", ".join(kwargs.get('selected_options'))
107 activity.result = ", ".join([str(item) for item in kwargs.get('result')]),
108 activity.status = "Passed"
109 current_activity.save()
110 frappe.db.commit()
111 else:
112 if content_type in ("Article", "Video"):
113 lms_activity_list = [[data.course_name, data.content_name] for data in activity.lms_activity]
114 if not [kwargs.get('course'), kwargs.get('content')] in lms_activity_list:
115 activity.append("lms_activity", {
116 "course_name": kwargs.get('course'),
117 "content_name": kwargs.get('content'),
118 "status": "Completed"
119 })
120 else:
121 activity.append("lms_activity", {
122 "course_name": kwargs.get('course'),
123 "content_name": kwargs.get('content'),
124 "status": "Passed",
125 "quiz_score": kwargs.get('score'),
126 "selected_options": ", ".join(kwargs.get('selected_options')),
127 "result": ", ".join([str(item) for item in kwargs.get('result')])
128 })
129 activity.save()
130 frappe.db.commit()
131
132def check_entry_exists(program):
133 try:
scmmishra31cbe3c2018-10-15 16:04:14 +0530134 activity_name = frappe.get_all("Course Activity", filters={"student_id": get_student_id(frappe.session.user), "program_name": program})[0]
scmmishra4ae11f42018-10-12 15:18:26 +0530135 except IndexError:
scmmishra17294e72018-10-15 11:45:17 +0530136 print("------ Got No Doc ------")
scmmishra4ae11f42018-10-12 15:18:26 +0530137 return True, None
138 else:
scmmishra17294e72018-10-15 11:45:17 +0530139 print("------ Got A Doc ------")
scmmishra31cbe3c2018-10-15 16:04:14 +0530140 return None, frappe.get_doc("Course Activity", activity_name)
scmmishra17294e72018-10-15 11:45:17 +0530141
142def get_student_id(email):
143 """Returns Student ID, example EDU-STU-2018-00001 from email address
144
145 :params email: email address of the student"""
146 try:
147 student = frappe.get_list('Student', filters={'student_email_id': email})[0].name
148 return student
149 except IndexError:
scmmishra31cbe3c2018-10-15 16:04:14 +0530150 frappe.throw("Student Account with email:{0} does not exist".format(email))
151
152def get_quiz(content):
153 """Helper Function to get questions for a quiz
154
155 :params content: name of a Content doctype with content_type quiz"""
156 try:
157 quiz_doc = frappe.get_doc("Content", content)
158 if quiz_doc.content_type == "Quiz":
159 import json
160 quiz = [frappe.get_doc("Question", item.question_link) for item in quiz_doc.questions]
161 data = []
162 for question in quiz:
163 d = {}
164 d['Options'] = [{'option':item.option,'is_correct':item.is_correct} for item in quiz[0].options]
165 d['Question'] = question.question
166 data.append(d)
167 return json.dumps(data)
168 else:
169 frappe.throw("<b>{0}</b> is not a Quiz".format(content))
170 except frappe.DoesNotExistError:
171 return None