Compare commits

...

82 Commits

Author SHA1 Message Date
pateljannat
6c751cdf39 fix: test 2021-06-22 12:17:06 +05:30
pateljannat
2c570ea214 fix: added default value for arguements 2021-06-22 10:48:33 +05:30
pateljannat
ecfcc8a2f7 fix: redirects and urls 2021-06-22 10:45:07 +05:30
pateljannat
3384f974e5 fix: batch switch with query parameters 2021-06-22 10:11:21 +05:30
pateljannat
eb435261fe feat: learning modes 2021-06-18 18:31:10 +05:30
Jannat Patel
dc7eabefb9 Merge pull request #131 from fossunited/minor-fixes
fix: web form, progress ui, title non unique
2021-06-16 13:15:10 +05:30
pateljannat
fed4b5568b fix: web form, progress ui, title non unique 2021-06-16 13:04:45 +05:30
Jannat Patel
aa77c60abd Merge pull request #129 from fossunited/minor-fix
fix: minor issues
2021-06-15 18:46:33 +05:30
pateljannat
9c1506d3c8 fix: minor issues 2021-06-15 18:40:14 +05:30
Jannat Patel
e94c3f27ab Merge pull request #128 from fossunited/ui-fixes
fix: UI fixes
2021-06-15 13:19:03 +05:30
pateljannat
5fa8bdd40c fix: invite request test, removed print statements and unused classes' 2021-06-15 13:09:48 +05:30
pateljannat
17f03aeee7 fix: join batch, removed code revision, redirects for other pages if batch missing 2021-06-15 13:01:57 +05:30
pateljannat
7840512a13 fix: ui, preview, progress, batches 2021-06-14 18:45:46 +05:30
Anand Chitipothu
526ded784b Merge pull request #125 from fossunited/hotfix-exercise-image
fix: fixed error on saving exercises
2021-06-12 21:42:27 +05:30
Anand Chitipothu
6b5ddcd54a fix: fixed error on saving exercises
Removed the image generation when exercise is saved. The library used
for exercises has changed and generating the image doesn't work any
more.
2021-06-12 10:49:27 +05:30
Jannat Patel
c42247db42 Merge pull request #122 from fderyckel/patch-1
frappe wasn't imported
2021-06-10 20:47:05 +05:30
François de Ryckel
8f8d4901ff frappe wasn't imported
error with NameError: name 'frappe' is not defined
2021-06-10 18:04:40 +03:00
pateljannat
f5f3c808d4 Merge branch 'main' of https://github.com/frappe/community into ui-fixes 2021-06-10 13:41:31 +05:30
pateljannat
1e3152e303 fix: ui 2021-06-10 13:41:11 +05:30
Jannat Patel
344661cf83 Merge pull request #121 from fossunited/lesson-markup
Lesson markup
2021-06-10 12:32:16 +05:30
Anand Chitipothu
d9185c0b6b feat: integrated lesson markup
- added PageExtension plugin to inject custom styles scripts in a page
- removed the livecode integration and enabled PageExtension plugins for
  learn page
- also merged the profile_tab.py with plugins.py
- added a utility to find the macros from given text
- updated the before_save of lesson to find exercises using the macros
  and update the exercises as before

Issue #115
2021-06-09 23:58:21 +05:30
Anand Chitipothu
5363fb7eb3 feat: extend markdown to support macros
With this feature, the exercises can be added to the lesson as:

    {{ Exercise("two-circles") }}

This also added fenced_code extension that allows adding id and classes
to code blocks.

This uses Python-Markdown library instead of Markdown2 that is used
everywhere in Frappe. The Python-Markdown is more easily extensible than
Markdown2.

Issue #115
2021-06-09 23:22:00 +05:30
Jannat Patel
d90a1247f1 Merge pull request #120 from fossunited/profile-tabs
feat: pluggable profile tabs
2021-06-08 14:53:38 +05:30
Anand Chitipothu
ef0c3e4a24 feat: pluggable profile tabs
Added ProfileTab class to represent a profile tab and made the profile
page render the tabs specified in the hook `profile_tabs`. This allows
plugging in new tabs in the profile page without makeing any changes to
the community module.
2021-06-08 10:36:12 +05:30
Anand Chitipothu
3619b136f8 Merge pull request #117 from fossunited/lesson-progress
feat: lesson progress
2021-06-07 11:24:52 +05:30
pateljannat
671b4a0650 fix: api and orm 2021-06-02 20:19:36 +05:30
Anand Chitipothu
586b39c0fd fix: issue with numbering the exercises
The exercises being listed in unpredicted order instead of the order
they were listed in the lesson. The was because the `index_` of the
exercise was never updated. Fixed this by updating the `index_` whenever
a lesson edited. However, the user still need to run reindex exercises
on the course correct the ordering, which wasn't possible earlier.
2021-06-02 17:48:02 +05:30
pateljannat
4fd7af053b fix: tests 2021-06-02 16:47:17 +05:30
pateljannat
5fd1143f76 feat: lesson progress 2021-06-02 13:52:50 +05:30
Jannat Patel
0dc4743556 Merge pull request #116 from fossunited/reindex-exercises
feat: actions to reindex lessons and exercises
2021-06-01 11:40:52 +05:30
Anand Chitipothu
c96a14c972 feat: ignore orphan exercises in the progress
Don't show exercises that are not added to any lesson in the progress.
2021-06-01 08:15:52 +05:30
Anand Chitipothu
400e706be1 feat: update the index of orphan exercises
When an exercise is removed from a lesson, the link to the lesson is
removed from that exercise and the index is reset. This will make sure
the removed exercises won't show up in places like progress.
2021-06-01 05:59:01 +05:30
Anand Chitipothu
a12a52747e feat: show exercise index in the title
Show exercise as "Exercise 2.1: Draw a Circle".
2021-06-01 05:49:45 +05:30
Anand Chitipothu
b9a93bb160 feat: added actions to reindex lessons and exercises
Some lessons gets deleted and some new ones get added in the progress of
course creation and it may happen then some of the lesson index may
become inconsistent.  Also, we would like to maintain an index for the
exercises. To support both of these, added actions to reindex lessons
and exercises to the course doctype.
2021-06-01 05:46:32 +05:30
Jannat Patel
9c65ff8ae6 Merge pull request #113 from fossunited/invite-based-membership
feat: Invite based membership
2021-05-31 13:41:12 +05:30
pateljannat
bb0aa09b4e fix: messages and url 2021-05-31 13:39:31 +05:30
pateljannat
a8752afb3b feat: invite based membership become a member page 2021-05-28 13:53:34 +05:30
pateljannat
327bde870b Merge branch 'main' of https://github.com/frappe/community into invite-based-membership 2021-05-27 17:32:48 +05:30
Jannat Patel
640ead4922 Merge pull request #109 from fossunited/style-fixes
fix: Style fixes
2021-05-27 11:54:08 +05:30
pateljannat
687f7f7f7b fix: minor home page issues 2021-05-27 11:25:05 +05:30
Anand Chitipothu
527a563e4a chore: added "programming" to the hero title 2021-05-27 09:39:07 +05:30
pateljannat
5bc9a7fe37 Merge branch 'style-fixes' of https://github.com/frappe/community into invite-based-membership 2021-05-26 19:10:38 +05:30
pateljannat
24835acd9c fix: jinja 2021-05-26 19:10:08 +05:30
pateljannat
3648b3ab47 Merge branch 'style-fixes' of https://github.com/frappe/community into invite-based-membership 2021-05-26 19:08:38 +05:30
pateljannat
914f8504a0 fix: added class in lms_message 2021-05-26 18:56:57 +05:30
pateljannat
ab8546a121 fix: course outline, discussion, lms batch 2021-05-26 17:16:00 +05:30
pateljannat
f327c6fb10 fix: tests for course description 2021-05-26 12:38:50 +05:30
pateljannat
c7ccefa632 fix: discussion, batch home page, new fields for batches 2021-05-26 12:13:04 +05:30
Anand Chitipothu
823cf4e431 style: fixed word-wrap of output 2021-05-25 16:06:12 +05:30
pateljannat
18f074d8ac fix: ignore user permission for membership 2021-05-24 19:35:26 +05:30
pateljannat
c9185ae68c fix: tabs and learn page 2021-05-24 19:24:07 +05:30
Anand Chitipothu
82fa0fa4d7 fix: error in loading the progress page 2021-05-24 13:46:59 +05:30
Jannat Patel
64752433d2 Merge pull request #106 from fossunited/issue-103
Redirect the learn page to the current lesson of the user
2021-05-24 13:40:50 +05:30
Anand Chitipothu
50856fdfa5 fix: fixed failing test 2021-05-24 13:30:47 +05:30
Anand Chitipothu
cac4f2afef feat: redirect the learn page to the current lesson of the user
The current lesson is maintained in the LMS Batch Membership and that is
updated everytime a lesson page is visited.
2021-05-24 13:07:29 +05:30
Anand Chitipothu
df431165e8 feat: redirect non-members visiting any batch page to the course page 2021-05-24 12:57:01 +05:30
Anand Chitipothu
69125e571f feat: added member_username and current_lesson fields to LMS Batch Membership
And removed member_email field which is a duplicate of member.
2021-05-24 12:43:20 +05:30
Anand Chitipothu
68f7215b95 fix: error in updating LMS Batch membership
The validation was always failing when trying to updating an LMS Batch
Membership document. This was due to a bug in the validation logic that
was considering itself as a duplicate record. This has been fixed.

Also added tests to verify that.
2021-05-24 12:15:16 +05:30
pateljannat
ca42c32f54 Merge branch 'main' of https://github.com/frappe/community into style-fixes 2021-05-24 11:57:53 +05:30
Anand Chitipothu
20adc8079e Merge pull request #105 from fossunited/community-member-to-user-refactor
refactor: Community Member to User refactor
2021-05-24 11:44:45 +05:30
Anand Chitipothu
d55941d4bb Merge branch 'main' into community-member-to-user-refactor 2021-05-24 11:39:20 +05:30
Jannat Patel
6074ee3688 Merge pull request #104 from fossunited/resume-course
Added "Resume Course" button to the course teaser
2021-05-24 11:36:06 +05:30
pateljannat
b3f87ba5b6 fix: removed community course member and references to profile macro 2021-05-24 10:39:04 +05:30
pateljannat
631275e9a8 refactor: course and sidebar cleanup 2021-05-24 10:28:02 +05:30
Anand Chitipothu
8d7963fc60 feat: added "Resume Course" button to course teaser
Closes #102
2021-05-24 09:55:35 +05:30
Anand Chitipothu
38938ac14b feat: added ability to find the batch of a student
Added the course field and member_email fields to LMS Batch Membership
to allow the possibility of querying if a user is a student of a course.

Closes #101
2021-05-24 09:55:13 +05:30
Anand Chitipothu
14f9d4875a chore: added issue template for Feature Request 2021-05-24 08:36:09 +05:30
pateljannat
419a7e666f refactor: tests, mentor request, messages 2021-05-22 20:49:47 +05:30
pateljannat
713dcf178a refactor: patches to fix data, profile dashboard, lms mentor mapping page fixes 2021-05-21 21:40:31 +05:30
pateljannat
637c795321 refactor: moved community member class functions to user override 2021-05-21 16:22:59 +05:30
pateljannat
63d00a46c4 Merge branch 'main' of https://github.com/frappe/community into community-member-to-user-refactor 2021-05-21 13:27:22 +05:30
pateljannat
e991dc5c73 refactor: removed community member doctype 2021-05-21 13:27:15 +05:30
Anand Chitipothu
4a2ecff15d Merge pull request #98 from fossunited/remove-primary-color-from-app
fix: removed primary color from app
2021-05-21 13:26:38 +05:30
Jannat Patel
f8d6b5b949 Merge pull request #99 from fossunited/mentor-dashboard
Refactored batch pages and added batch progress page
2021-05-21 13:25:56 +05:30
Anand Chitipothu
c77835b81f feat: added page to see progress of a batch 2021-05-21 13:13:34 +05:30
Anand Chitipothu
e04bbb633d refactor: moved courses/*/index pages to batch/* 2021-05-21 13:12:52 +05:30
Anand Chitipothu
a2b856aaf8 feat: added image to exercise submission 2021-05-21 13:10:54 +05:30
pateljannat
7a650b46ac fix: removed primary color from app 2021-05-21 11:06:37 +05:30
Jannat Patel
b61ca1d7a2 Merge pull request #97 from fossunited/gitignore-build-file
fix: gitignore dist folder
2021-05-21 10:31:40 +05:30
Anand Chitipothu
632693c9f8 fix: show submitted solution in the exercise 2021-05-20 21:03:24 +05:30
Anand Chitipothu
463aec01f8 fix: permission issue when a student submits an exercise 2021-05-20 21:02:54 +05:30
Anand Chitipothu
e7d116f31c chore: removed obsolete doctype LMS Topic
It has been replaced by Chapter and Lesson.
Moved the section_parser from lms_topic directory to the lms.
2021-05-20 16:52:51 +05:30
138 changed files with 2226 additions and 2539 deletions

View File

@@ -0,0 +1,20 @@
---
name: Feature request
about: Suggest an idea for this project
title: ''
labels: ''
assignees: ''
---
**Is your feature request related to a problem? Please describe.**
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
**Describe the solution you'd like**
A clear and concise description of what you want to happen.
**Describe alternatives you've considered**
A clear and concise description of any alternative solutions or features you've considered.
**Additional context**
Add any other context or screenshots about the feature request here.

View File

@@ -1,8 +0,0 @@
// Copyright (c) 2021, Frappe and contributors
// For license information, please see license.txt
frappe.ui.form.on('Community Course Member', {
// refresh: function(frm) {
// }
});

View File

@@ -1,96 +0,0 @@
{
"actions": [],
"autoname": "field:user_name",
"creation": "2021-03-02 11:24:49.612530",
"doctype": "DocType",
"editable_grid": 1,
"engine": "InnoDB",
"field_order": [
"enabled",
"full_name",
"user_name",
"email",
"short_intro",
"bio",
"photo",
"route"
],
"fields": [
{
"default": "1",
"fieldname": "enabled",
"fieldtype": "Check",
"label": "Enabled"
},
{
"fieldname": "full_name",
"fieldtype": "Data",
"in_list_view": 1,
"label": "Full Name",
"reqd": 1
},
{
"fieldname": "user_name",
"fieldtype": "Data",
"in_list_view": 1,
"label": "User Name",
"reqd": 1,
"unique": 1
},
{
"fieldname": "email",
"fieldtype": "Data",
"label": "Email",
"options": "Email",
"reqd": 1
},
{
"fieldname": "short_intro",
"fieldtype": "Data",
"label": "Short Intro"
},
{
"fieldname": "bio",
"fieldtype": "Markdown Editor",
"label": "Bio"
},
{
"fieldname": "photo",
"fieldtype": "Attach Image",
"label": "Photo"
},
{
"fieldname": "route",
"fieldtype": "Data",
"label": "Route"
}
],
"has_web_view": 1,
"index_web_pages_for_search": 1,
"is_published_field": "enabled",
"links": [],
"modified": "2021-04-06 11:50:41.551665",
"modified_by": "Administrator",
"module": "Community",
"name": "Community Course Member",
"owner": "Administrator",
"permissions": [
{
"create": 1,
"delete": 1,
"email": 1,
"export": 1,
"print": 1,
"read": 1,
"report": 1,
"role": "System Manager",
"share": 1,
"write": 1
}
],
"quick_entry": 1,
"route": "community-course-member",
"sort_field": "modified",
"sort_order": "DESC",
"track_changes": 1
}

View File

@@ -1,52 +0,0 @@
# -*- coding: utf-8 -*-
# Copyright (c) 2021, Frappe and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
import re
from frappe.website.website_generator import WebsiteGenerator
from frappe import _
class CommunityCourseMember(WebsiteGenerator):
def get_context(self, context):
context.abbr = ("").join([ s[0] for s in self.full_name.split() ])
return context
def validate(self):
self.validate_user_name()
if not self.route:
self.route = self.user_name
def validate_user_name(self):
if len(self.user_name) < 4:
frappe.throw(_("Username must be atleast 4 characters long."))
if not re.match("^[A-Za-z0-9_]*$", self.user_name):
frappe.throw(_("Username can only contain alphabets, numbers, and underscore."))
self.user_name = self.user_name.lower()
def after_insert(self):
if frappe.db.exists("User", self.email):
user = frappe.get_doc("User", self.email)
else:
user, update_password_link = self.create_user()
self.send_email(update_password_link)
def send_email(self, update_password_link):
args = {
'update_password_link': update_password_link,
'full_name': self.full_name,
}
frappe.sendmail(
recipients=self.email,
sender="Administrator",
subject=_("Set your Password"),
template="community_course_membership",
reference_doctype=self.doctype,
reference_name=self.name,
send_priority=0,
queue_separately=True,
args=args)

View File

@@ -1,25 +0,0 @@
{% extends "templates/web.html" %}
{% block page_content %}
<div class="py-20 row">
{% if photo %}
<div class="col-sm-2 border border-dark">
<img src="{{ photo }}" alt="{{ full_name }}">
</div>
{% else %}
<div class="col-sm-2">
<div class="standard-image" style="font-size: 30px;">{{ abbr }}</div>
</div>
{% endif %}
<div class="col">
<h1>{{ full_name }}</h1>
{% if short_intro %}
<p class="lead"> {{ short_intro }} </p>
{% endif %}
{% if bio %}
<p class="markdown-style"> {{ frappe.utils.md_to_html(bio) }} </p>
{% endif %}
</div>
</div>
{% endblock %}
<!-- this is a sample default web page template -->

View File

@@ -1,4 +0,0 @@
<div>
<a href="{{ doc.route }}">{{ doc.full_name }}</a>
</div>
<!-- this is a sample default list template -->

View File

@@ -1,10 +0,0 @@
# -*- coding: utf-8 -*-
# Copyright (c) 2021, Frappe and Contributors
# See license.txt
from __future__ import unicode_literals
# import frappe
import unittest
class TestCommunityCourseMember(unittest.TestCase):
pass

View File

@@ -13,13 +13,13 @@
"fieldtype": "Link", "fieldtype": "Link",
"in_list_view": 1, "in_list_view": 1,
"label": "Member", "label": "Member",
"options": "Community Member" "options": "User"
} }
], ],
"index_web_pages_for_search": 1, "index_web_pages_for_search": 1,
"istable": 1, "istable": 1,
"links": [], "links": [],
"modified": "2021-02-15 12:03:31.153575", "modified": "2021-05-21 12:15:51.286478",
"modified_by": "Administrator", "modified_by": "Administrator",
"module": "Community", "module": "Community",
"name": "Community Event Volunteer", "name": "Community Event Volunteer",

View File

@@ -1,8 +0,0 @@
// Copyright (c) 2021, Frappe and contributors
// For license information, please see license.txt
frappe.ui.form.on('Community Member', {
// refresh: function(frm) {
// }
});

View File

@@ -1,155 +0,0 @@
{
"actions": [],
"allow_guest_to_view": 1,
"allow_rename": 1,
"creation": "2021-02-12 15:47:23.591567",
"doctype": "DocType",
"editable_grid": 1,
"engine": "InnoDB",
"field_order": [
"full_name",
"email",
"enabled",
"column_break_4",
"username",
"email_preference",
"section_break_7",
"bio",
"section_break_9",
"role",
"photo",
"column_break_12",
"short_intro",
"route",
"abbr"
],
"fields": [
{
"default": "1",
"fieldname": "enabled",
"fieldtype": "Check",
"label": "Enabled"
},
{
"fieldname": "full_name",
"fieldtype": "Data",
"in_list_view": 1,
"in_standard_filter": 1,
"label": "Full Name",
"reqd": 1
},
{
"allow_in_quick_entry": 1,
"fieldname": "role",
"fieldtype": "Select",
"label": "Role",
"options": "\nBoard\nDirector\nVolunteer\nSpeaker"
},
{
"allow_in_quick_entry": 1,
"fieldname": "photo",
"fieldtype": "Attach Image",
"label": "Photo"
},
{
"fieldname": "short_intro",
"fieldtype": "Data",
"label": "Short Intro"
},
{
"allow_in_quick_entry": 1,
"fieldname": "bio",
"fieldtype": "Markdown Editor",
"label": "Bio"
},
{
"fieldname": "route",
"fieldtype": "Data",
"label": "Route"
},
{
"fieldname": "email",
"fieldtype": "Data",
"in_standard_filter": 1,
"label": "Email",
"options": "Email",
"reqd": 1,
"unique": 1
},
{
"allow_in_quick_entry": 1,
"fieldname": "username",
"fieldtype": "Data",
"in_list_view": 1,
"label": "User Name",
"unique": 1
},
{
"fieldname": "email_preference",
"fieldtype": "Select",
"label": "Email preference",
"options": "Email on every Message\nOne Digest Mail per day\nNever"
},
{
"fieldname": "column_break_4",
"fieldtype": "Column Break"
},
{
"fieldname": "section_break_7",
"fieldtype": "Section Break"
},
{
"fieldname": "section_break_9",
"fieldtype": "Section Break"
},
{
"fieldname": "column_break_12",
"fieldtype": "Column Break"
},
{
"fieldname": "abbr",
"fieldtype": "Data",
"label": "Abbr",
"read_only": 1
}
],
"index_web_pages_for_search": 1,
"links": [],
"modified": "2021-04-28 11:22:35.402217",
"modified_by": "Administrator",
"module": "Community",
"name": "Community Member",
"owner": "Administrator",
"permissions": [
{
"create": 1,
"delete": 1,
"email": 1,
"export": 1,
"print": 1,
"read": 1,
"report": 1,
"role": "System Manager",
"share": 1,
"write": 1
},
{
"create": 1,
"delete": 1,
"email": 1,
"export": 1,
"print": 1,
"read": 1,
"report": 1,
"role": "Website Manager",
"share": 1,
"write": 1
}
],
"quick_entry": 1,
"search_fields": "full_name",
"sort_field": "modified",
"sort_order": "DESC",
"title_field": "full_name",
"track_changes": 1
}

View File

@@ -1,104 +0,0 @@
# -*- coding: utf-8 -*-
# Copyright (c) 2021, Frappe and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
import re
from frappe import _
from frappe.model.document import Document
import random
from frappe.utils import cint
import hashlib
class CommunityMember(Document):
def validate(self):
self.validate_username()
self.abbr = ("").join([ s[0] for s in self.full_name.split() ])
if self.route != self.username:
self.route = self.username
def validate_username(self):
if not self.username:
self.username = create_username_from_email(self.email)
if self.username:
if len(self.username) < 4:
frappe.throw(_("Username must be atleast 4 characters long."))
if not re.match("^[A-Za-z0-9_]*$", self.username):
frappe.throw(_("Username can only contain alphabets, numbers and underscore."))
self.username = self.username.lower()
def get_course_count(self) -> int:
"""Returns the number of courses authored by this user.
"""
return frappe.db.count(
'LMS Course', {
'owner': self.email
})
def get_batch_count(self) -> int:
"""Returns the number of batches authored by this user.
"""
return frappe.db.count(
'LMS Batch Membership', {
'member': self.name,
'member_type': 'Mentor'
})
def get_photo_url(self):
return frappe.db.get_value("User", self.email, ["user_image"])
def get_palette(self):
palette = [
['--orange-avatar-bg', '--orange-avatar-color'],
['--pink-avatar-bg', '--pink-avatar-color'],
['--blue-avatar-bg', '--blue-avatar-color'],
['--green-avatar-bg', '--green-avatar-color'],
['--dark-green-avatar-bg', '--dark-green-avatar-color'],
['--red-avatar-bg', '--red-avatar-color'],
['--yellow-avatar-bg', '--yellow-avatar-color'],
['--purple-avatar-bg', '--purple-avatar-color'],
['--gray-avatar-bg', '--gray-avatar-color0']
]
encoded_name = str(self.full_name).encode("utf-8")
hash_name = hashlib.md5(encoded_name).hexdigest()
idx = cint((int(hash_name[4:6], 16) + 1) / 5.33)
return palette[idx % 8]
def __repr__(self):
return f"<CommunityMember: {self.email}>"
def create_member_from_user(doc, method):
username = doc.username
if ( doc.username and username_exists(doc.username)) or not doc.username:
username = create_username_from_email(doc.email)
elif len(doc.username) < 4 and doc.send_welcome_email == 1:
username = adjust_username(doc.username)
if username_exists(username):
username = username + str(random.randint(0,9))
member = frappe.get_doc({
"doctype": "Community Member",
"full_name": doc.full_name,
"username": username,
"email": doc.email,
"route": doc.username,
"owner": doc.email
})
member.save(ignore_permissions=True)
def username_exists(username):
return frappe.db.exists("Community Member", dict(username=username))
def create_username_from_email(email):
string = email.split("@")[0]
return ''.join(e for e in string if e.isalnum())
def adjust_username(username):
return username.ljust(4, str(random.randint(0,9)))

View File

@@ -1,25 +0,0 @@
{% extends "templates/web.html" %}
{% block page_content %}
<div class="py-20 row">
{% if photo %}
<div class="col-sm-2 border border-dark">
<img src="{{ photo }}" alt="{{ full_name }}">
</div>
{% else %}
<div class="col-sm-2">
<div class="standard-image" style="font-size: 30px;">{{ abbr }}</div>
</div>
{% endif %}
<div class="col">
<h1>{{ full_name }}</h1>
{% if short_intro %}
<p class="lead"> {{ short_intro }} </p>
{% endif %}
{% if bio %}
<p class="markdown-style"> {{ frappe.utils.md_to_html(bio) }} </p>
{% endif %}
</div>
</div>
{% endblock %}
<!-- this is a sample default web page template -->

View File

@@ -1,4 +0,0 @@
<div>
<a href="{{ doc.route }}">{{ doc.title or doc.name }}</a>
</div>
<!-- this is a sample default list template -->

View File

@@ -1,92 +0,0 @@
# -*- coding: utf-8 -*-
# Copyright (c) 2021, Frappe and Contributors
# See license.txt
from __future__ import unicode_literals
from community.lms.doctype.lms_course.test_lms_course import new_user
import frappe
import unittest
class TestCommunityMember(unittest.TestCase):
@classmethod
def setUpClass(self):
users = ["test_user@example.com","test_user1@example.com"]
for user in users:
if not frappe.db.exists("User", user):
new_user("Test User", user)
def test_member_created_from_user(self):
user = frappe.db.get_value("User","test_user@example.com", ["full_name", "email", "username"], as_dict=True)
self.assertTrue(frappe.db.exists("Community Member", {"username":user.username}))
member = frappe.db.get_value("Community Member",
filters={"email": user.email},
fieldname=["full_name", "email", "owner", "username", "route"],
as_dict=True
)
self.assertEqual(user.full_name, member.full_name)
self.assertEqual(member.owner, user.email)
self.assertEqual(user.username, member.username)
self.assertEqual(member.username, member.route)
def test_members_with_same_name(self):
user1 = frappe.db.get_value("User","test_user@example.com", ["email"], as_dict=True)
user2 = frappe.get_doc("User","test_user1@example.com", ["email"], as_dict=True)
self.assertTrue(frappe.db.exists("Community Member", {"email": user1.email} ))
self.assertTrue(frappe.db.exists("Community Member", {"email": user2.email }))
member1 = frappe.db.get_value("Community Member",
filters={"email": user1.email},
fieldname=["full_name", "email", "owner", "username", "route"],
as_dict=True
)
member2 = frappe.db.get_value("Community Member",
filters={"email": user2.email},
fieldname=["full_name", "email", "owner", "username", "route"],
as_dict=True
)
self.assertEqual(member1.full_name, member2.full_name)
self.assertEqual(member1.email, user1.email)
self.assertEqual(member2.email, user2.email)
self.assertNotEqual(member1.username, member2.username)
def test_username_validations(self):
user = new_user("Tst", "tst@example.com")
self.assertTrue(frappe.db.exists("Community Member", {"email":user.email} ))
member = frappe.db.get_value("Community Member",
filters={"email": user.email},
fieldname=["username"],
as_dict=True
)
self.assertEqual(len(member.username), 4)
frappe.delete_doc("User", user.email)
def test_user_without_username(self):
user = new_user("Test User", "test_user2@example.com")
self.assertTrue(frappe.db.exists("Community Member", {"email":user.email} ))
member = frappe.db.get_value("Community Member",
filters={"email": user.email},
fieldname=["username"],
as_dict=True
)
self.assertTrue(member.username)
frappe.delete_doc("User", user.email)
@classmethod
def tearDownClass(self):
users = ["test_user@example.com","test_user1@example.com"]
for user in users:
if frappe.db.exists("User", user):
frappe.delete_doc("User", user)
if frappe.db.exists("Community Member", {"email": user}):
frappe.delete_doc("Community Member", {"email": user})

View File

@@ -1,16 +1 @@
import frappe import frappe
def create_members_from_users():
users = frappe.get_all("User", {"enabled": 1}, ["email"])
for user in users:
if not frappe.db.get_value("Community Member", {"email": user.email}, "name"):
doc = frappe.get_doc("User", {"email": user.email})
username = doc.username if doc.username and len(doc.username) > 3 else ("").join([ s for s in doc.full_name.split() ])
if not frappe.db.exists("Community Member", username):
member = frappe.new_doc("Community Member")
member.full_name = doc.full_name
member.username = username
member.email = doc.email
member.route = username
member.owner = doc.email
member.insert(ignore_permissions=True)

View File

@@ -1,5 +0,0 @@
frappe.ready(function() {
frappe.web_form.after_save = () => {
window.location.href = frappe.web_form.get_value("username")
}
})

View File

@@ -1,100 +0,0 @@
{
"accept_payment": 0,
"allow_comments": 0,
"allow_delete": 0,
"allow_edit": 1,
"allow_incomplete": 0,
"allow_multiple": 0,
"allow_print": 0,
"amount": 0.0,
"amount_based_on_field": 0,
"apply_document_permissions": 0,
"breadcrumbs": "",
"button_label": "Save",
"creation": "2021-03-09 17:34:03.394301",
"doc_type": "Community Member",
"docstatus": 0,
"doctype": "Web Form",
"idx": 0,
"is_standard": 1,
"login_required": 1,
"max_attachment_size": 0,
"modified": "2021-03-22 12:04:22.571655",
"modified_by": "Administrator",
"module": "Community",
"name": "update-profile",
"owner": "Administrator",
"payment_button_label": "Buy Now",
"published": 1,
"route": "edit-profile",
"route_to_success_link": 0,
"show_attachments": 0,
"show_in_grid": 0,
"show_sidebar": 0,
"sidebar_items": [],
"success_message": "Profile updated successfully.",
"success_url": "/",
"title": "Update Profile",
"web_form_fields": [
{
"allow_read_on_all_link_options": 0,
"fieldname": "full_name",
"fieldtype": "Data",
"hidden": 0,
"label": "Full Name",
"max_length": 0,
"max_value": 0,
"read_only": 0,
"reqd": 1,
"show_in_filter": 0
},
{
"allow_read_on_all_link_options": 0,
"fieldname": "username",
"fieldtype": "Data",
"hidden": 0,
"label": "User Name",
"max_length": 0,
"max_value": 0,
"read_only": 0,
"reqd": 1,
"show_in_filter": 0
},
{
"allow_read_on_all_link_options": 0,
"fieldname": "short_intro",
"fieldtype": "Data",
"hidden": 0,
"label": "Short Intro",
"max_length": 0,
"max_value": 0,
"read_only": 0,
"reqd": 0,
"show_in_filter": 0
},
{
"allow_read_on_all_link_options": 0,
"fieldname": "bio",
"fieldtype": "Data",
"hidden": 0,
"label": "Bio",
"max_length": 0,
"max_value": 0,
"read_only": 0,
"reqd": 0,
"show_in_filter": 0
},
{
"allow_read_on_all_link_options": 0,
"fieldname": "photo",
"fieldtype": "Attach Image",
"hidden": 0,
"label": "Photo",
"max_length": 0,
"max_value": 0,
"read_only": 0,
"reqd": 0,
"show_in_filter": 0
}
]
}

View File

@@ -1,7 +0,0 @@
from __future__ import unicode_literals
import frappe
def get_context(context):
# do your magic here
pass

View File

@@ -1,14 +1,14 @@
{% set color = member.get_palette() %} {% set color = member.get_palette() %}
<a href="/{{member.username}}"> <a href="/{{member.username}}">
<span class="avatar {{ avatar_class }}" title="{{ member.full_name }}"> <span class="avatar {{ avatar_class }}" title="{{ member.full_name }}">
{% if member.get_photo_url() %} {% if member.user_image %}
<img class="avatar-frame standard-image" src="{{ member.get_photo_url() }}" title="{{ member.full_name }}"> <img class="avatar-frame standard-image" style="object-fit: cover;" src="{{ member.user_image }}" title="{{ member.full_name }}">
</img> </img>
{% else %} {% else %}
<span class="avatar-frame standard-image" title="{{ member.full_name }}" <span class="avatar-frame standard-image" title="{{ member.full_name }}"
style="background-color: var({{color[0]}}); color: var({{color[1]}});"> style="background-color: var({{color[0]}}); color: var({{color[1]}});">
{{ member.abbr }} {{ frappe.utils.get_abbr(member.full_name) }}
</span> </span>
{% endif %} {% endif %}
</a> </span>
</span> </a>

View File

@@ -23,7 +23,7 @@
"fieldname": "organizer", "fieldname": "organizer",
"fieldtype": "Link", "fieldtype": "Link",
"label": "Organizer", "label": "Organizer",
"options": "Community Member" "options": "User"
}, },
{ {
"fieldname": "year", "fieldname": "year",
@@ -34,7 +34,7 @@
], ],
"index_web_pages_for_search": 1, "index_web_pages_for_search": 1,
"links": [], "links": [],
"modified": "2021-04-14 11:43:23.515972", "modified": "2021-05-21 12:22:26.619776",
"modified_by": "Administrator", "modified_by": "Administrator",
"module": "Hackathon", "module": "Hackathon",
"name": "Community Hackathon", "name": "Community Hackathon",

View File

@@ -3,8 +3,9 @@
# For license information, please see license.txt # For license information, please see license.txt
from __future__ import unicode_literals from __future__ import unicode_literals
# import frappe import frappe
from frappe.model.document import Document from frappe.model.document import Document
from frappe import _
class CommunityProjectMember(Document): class CommunityProjectMember(Document):
def validate(self): def validate(self):

View File

@@ -84,22 +84,17 @@ web_include_css = "community.bundle.css"
# --------------- # ---------------
# Override standard doctype classes # Override standard doctype classes
# override_doctype_class = { override_doctype_class = {
# "ToDo": "custom_app.overrides.CustomToDo" "User": "community.overrides.user.CustomUser"
# } }
# Document Events # Document Events
# --------------- # ---------------
# Hook on document methods and events # Hook on document methods and events
doc_events = { doc_events = {
"User": {
"after_insert": "community.community.doctype.community_member.community_member.create_member_from_user" }
},
"LMS Message": {
"after_insert": "community.lms.doctype.lms_message.lms_message.publish_message"
}
}
# Scheduled Tasks # Scheduled Tasks
# --------------- # ---------------
@@ -141,12 +136,15 @@ primary_rules = [
{"from_route": "/hackathons/<hackathon>/<project>", "to_route": "hackathons/project"}, {"from_route": "/hackathons/<hackathon>/<project>", "to_route": "hackathons/project"},
{"from_route": "/dashboard", "to_route": ""}, {"from_route": "/dashboard", "to_route": ""},
{"from_route": "/add-a-new-batch", "to_route": "add-a-new-batch"}, {"from_route": "/add-a-new-batch", "to_route": "add-a-new-batch"},
{"from_route": "/courses/<course>/<batch>/learn", "to_route": "courses/learn"}, {"from_route": "/courses/<course>/home", "to_route": "batch/home"},
{"from_route": "/courses/<course>/<batch>/learn/<int:chapter>.<int:lesson>", "to_route": "courses/learn"}, {"from_route": "/courses/<course>/learn", "to_route": "batch/learn"},
{"from_route": "/courses/<course>/<batch>/schedule", "to_route": "courses/schedule"}, {"from_route": "/courses/<course>/learn/<int:chapter>.<int:lesson>", "to_route": "batch/learn"},
{"from_route": "/courses/<course>/<batch>/members", "to_route": "courses/members"}, {"from_route": "/courses/<course>/schedule", "to_route": "batch/schedule"},
{"from_route": "/courses/<course>/<batch>/discuss", "to_route": "courses/discuss"}, {"from_route": "/courses/<course>/members", "to_route": "batch/members"},
{"from_route": "/courses/<course>/<batch>/about", "to_route": "courses/about"} {"from_route": "/courses/<course>/discuss", "to_route": "batch/discuss"},
{"from_route": "/courses/<course>/about", "to_route": "batch/about"},
{"from_route": "/courses/<course>/progress", "to_route": "batch/progress"},
{"from_route": "/courses/<course>/join", "to_route": "batch/join"}
] ]
# Any frappe default URL is blocked by profile-rules, add it here to unblock it # Any frappe default URL is blocked by profile-rules, add it here to unblock it
@@ -167,6 +165,7 @@ whitelist = [
"/add-a-new-batch", "/add-a-new-batch",
"/new-sign-up", "/new-sign-up",
"/message" "/message"
"/about"
] ]
whitelist_rules = [{"from_route": p, "to_route": p[1:]} for p in whitelist] whitelist_rules = [{"from_route": p, "to_route": p[1:]} for p in whitelist]
@@ -178,3 +177,15 @@ profile_rules = [
website_route_rules = primary_rules + whitelist_rules + profile_rules website_route_rules = primary_rules + whitelist_rules + profile_rules
update_website_context = 'community.widgets.update_website_context' update_website_context = 'community.widgets.update_website_context'
## Specify the additional tabs to be included in the user profile page.
## Each entry must be a subclass of community.community.plugins.ProfileTab
# profile_tabs = []
## Specify the extension to be used to control what scripts and stylesheets
## to be included in lesson pages. The specified value must be be a
## subclass of community.community.plugins.PageExtension
# community_lesson_page_extension = None
## Markdown Macros for Lessons
# community_markdown_macro_renderers = {"Exercise": "myapp.mymodule.plugins.render_exercise"}

View File

@@ -15,13 +15,6 @@ def autosave_section(section, code):
doc.insert() doc.insert()
return {"name": doc.name} return {"name": doc.name}
@frappe.whitelist()
def get_section(name):
"""Saves the code edited in one of the sections.
"""
doc = frappe.get_doc("LMS Section", name)
return doc and doc.as_dict()
@frappe.whitelist() @frappe.whitelist()
def submit_solution(exercise, code): def submit_solution(exercise, code):
"""Submits a solution. """Submits a solution.
@@ -34,3 +27,21 @@ def submit_solution(exercise, code):
return return
doc = ex.submit(code) doc = ex.submit(code)
return {"name": doc.name, "creation": doc.creation} return {"name": doc.name, "creation": doc.creation}
@frappe.whitelist()
def save_current_lesson(course_name, lesson_name):
"""Saves the current lesson for a student/mentor.
"""
name = frappe.get_value(
doctype="LMS Batch Membership",
filters={
"course": course_name,
"member": frappe.session.user
},
fieldname="name")
if not name:
return
doc = frappe.get_doc("LMS Batch Membership", name)
doc.current_lesson = lesson_name
doc.save(ignore_permissions=True)
return {"current_lesson": doc.current_lesson}

View File

@@ -10,6 +10,6 @@ class Chapter(Document):
def get_lessons(self): def get_lessons(self):
rows = frappe.db.get_all("Lesson", rows = frappe.db.get_all("Lesson",
filters={"chapter": self.name}, filters={"chapter": self.name},
fields='*', fields='name',
order_by="index_") order_by="index_")
return [frappe.get_doc(dict(row, doctype='Lesson')) for row in rows] return [frappe.get_doc('Lesson', row['name']) for row in rows]

View File

@@ -1,58 +0,0 @@
{
"actions": [],
"creation": "2021-04-07 00:26:28.806520",
"doctype": "DocType",
"editable_grid": 1,
"engine": "InnoDB",
"field_order": [
"section",
"code",
"author"
],
"fields": [
{
"fieldname": "section",
"fieldtype": "Link",
"in_list_view": 1,
"label": "Section",
"options": "LMS Section"
},
{
"fieldname": "code",
"fieldtype": "Code",
"label": "Code"
},
{
"fieldname": "author",
"fieldtype": "Link",
"in_list_view": 1,
"label": "Author",
"options": "User"
}
],
"index_web_pages_for_search": 1,
"links": [],
"modified": "2021-04-14 11:26:19.628317",
"modified_by": "Administrator",
"module": "LMS",
"name": "Code Revision",
"owner": "Administrator",
"permissions": [
{
"create": 1,
"delete": 1,
"email": 1,
"export": 1,
"print": 1,
"read": 1,
"report": 1,
"role": "System Manager",
"share": 1,
"write": 1
}
],
"sort_field": "modified",
"sort_order": "DESC",
"title_field": "section",
"track_changes": 1
}

View File

@@ -1,10 +0,0 @@
# -*- coding: utf-8 -*-
# Copyright (c) 2021, FOSS United and Contributors
# See license.txt
from __future__ import unicode_literals
# import frappe
import unittest
class TestCodeRevision(unittest.TestCase):
pass

View File

@@ -15,7 +15,9 @@
"hints", "hints",
"tests", "tests",
"image", "image",
"lesson" "lesson",
"index_",
"index_label"
], ],
"fields": [ "fields": [
{ {
@@ -27,6 +29,7 @@
{ {
"fieldname": "course", "fieldname": "course",
"fieldtype": "Link", "fieldtype": "Link",
"in_list_view": 1,
"label": "Course", "label": "Course",
"options": "LMS Course" "options": "LMS Course"
}, },
@@ -73,13 +76,27 @@
{ {
"fieldname": "lesson", "fieldname": "lesson",
"fieldtype": "Link", "fieldtype": "Link",
"in_list_view": 1,
"label": "Lesson", "label": "Lesson",
"options": "Lesson" "options": "Lesson"
},
{
"fieldname": "index_",
"fieldtype": "Int",
"label": "Index",
"read_only": 1
},
{
"fieldname": "index_label",
"fieldtype": "Data",
"in_list_view": 1,
"label": "Index Label",
"read_only": 1
} }
], ],
"index_web_pages_for_search": 1, "index_web_pages_for_search": 1,
"links": [], "links": [],
"modified": "2021-05-20 13:23:12.340928", "modified": "2021-06-01 05:22:15.656013",
"modified_by": "Administrator", "modified_by": "Administrator",
"module": "LMS", "module": "LMS",
"name": "Exercise", "name": "Exercise",
@@ -99,8 +116,8 @@
} }
], ],
"search_fields": "title", "search_fields": "title",
"sort_field": "modified", "sort_field": "index_label",
"sort_order": "DESC", "sort_order": "ASC",
"title_field": "title", "title_field": "title",
"track_changes": 1 "track_changes": 1
} }

View File

@@ -3,12 +3,9 @@
import frappe import frappe
from frappe.model.document import Document from frappe.model.document import Document
from ..lms_sketch.livecode import livecode_to_svg # from ..lms_sketch.livecode import livecode_to_svg
class Exercise(Document): class Exercise(Document):
def before_save(self):
self.image = livecode_to_svg(None, self.answer)
def get_user_submission(self): def get_user_submission(self):
"""Returns the latest submission for this user. """Returns the latest submission for this user.
""" """
@@ -24,6 +21,7 @@ class Exercise(Document):
}, },
order_by="creation desc", order_by="creation desc",
page_length=1) page_length=1)
if result: if result:
return result[0] return result[0]
@@ -49,6 +47,7 @@ class Exercise(Document):
lesson=self.lesson, lesson=self.lesson,
batch=batch and batch.name, batch=batch and batch.name,
solution=code) solution=code)
doc.insert() doc.insert(ignore_permissions=True)
return doc return doc

View File

@@ -14,7 +14,9 @@ class TestExercise(unittest.TestCase):
course = frappe.get_doc({ course = frappe.get_doc({
"doctype": "LMS Course", "doctype": "LMS Course",
"name": "test-course", "name": "test-course",
"title": "Test Course" "title": "Test Course",
"short_introduction": "Test Course",
"description": "Test Course"
}) })
course.insert() course.insert()
e = frappe.get_doc({ e = frappe.get_doc({

View File

@@ -10,7 +10,8 @@
"exercise_title", "exercise_title",
"course", "course",
"batch", "batch",
"lesson" "lesson",
"image"
], ],
"fields": [ "fields": [
{ {
@@ -54,11 +55,17 @@
"fieldtype": "Link", "fieldtype": "Link",
"label": "Lesson", "label": "Lesson",
"options": "Lesson" "options": "Lesson"
},
{
"fieldname": "image",
"fieldtype": "Code",
"label": "Image",
"read_only": 1
} }
], ],
"index_web_pages_for_search": 1, "index_web_pages_for_search": 1,
"links": [], "links": [],
"modified": "2021-05-20 13:30:16.349278", "modified": "2021-05-21 11:28:45.833018",
"modified_by": "Administrator", "modified_by": "Administrator",
"module": "LMS", "module": "LMS",
"name": "Exercise Submission", "name": "Exercise Submission",

View File

@@ -1,8 +1,13 @@
# Copyright (c) 2021, FOSS United and contributors # Copyright (c) 2021, FOSS United and contributors
# For license information, please see license.txt # For license information, please see license.txt
# import frappe import frappe
from frappe.model.document import Document from frappe.model.document import Document
from ..lesson.lesson import update_progress
class ExerciseSubmission(Document): class ExerciseSubmission(Document):
pass
def after_insert(self):
course_details = frappe.get_doc("LMS Course", self.course)
if not (course_details.is_mentor(frappe.session.user) or frappe.flags.in_test):
update_progress(self.lesson)

View File

@@ -58,7 +58,8 @@ def create_invite_request(invite_email):
frappe.get_doc({ frappe.get_doc({
"doctype": "Invite Request", "doctype": "Invite Request",
"invite_email": invite_email "invite_email": invite_email,
"status": "Approved"
}).save(ignore_permissions=True) }).save(ignore_permissions=True)
return "OK" return "OK"

View File

@@ -18,7 +18,7 @@ class TestInviteRequest(unittest.TestCase):
filters={"invite_email": "test_invite@example.com"}, filters={"invite_email": "test_invite@example.com"},
fieldname=["invite_email", "status", "signup_email"], fieldname=["invite_email", "status", "signup_email"],
as_dict=True) as_dict=True)
self.assertEqual(invite.status, "Pending") self.assertEqual(invite.status, "Approved")
self.assertEqual(invite.signup_email, None) self.assertEqual(invite.signup_email, None)
def test_create_invite_request_update(self): def test_create_invite_request_update(self):
@@ -52,15 +52,8 @@ class TestInviteRequest(unittest.TestCase):
self.assertEqual(user.send_welcome_email, 0) self.assertEqual(user.send_welcome_email, 0)
self.assertEqual(user.user_type, "Website User") self.assertEqual(user.user_type, "Website User")
member = frappe.db.get_value("Community Member", {"email": "test_invite@example.com"})
self.assertTrue(member)
@classmethod @classmethod
def tearDownClass(self): def tearDownClass(self):
if frappe.db.exists("Community Member", {"email": "test_invite@example.com"}):
frappe.delete_doc("Community Member", {"email": "test_invite@example.com"})
if frappe.db.exists("User", "test_invite@example.com"): if frappe.db.exists("User", "test_invite@example.com"):
frappe.delete_doc("User", "test_invite@example.com") frappe.delete_doc("User", "test_invite@example.com")

View File

@@ -8,10 +8,13 @@
"field_order": [ "field_order": [
"chapter", "chapter",
"lesson_type", "lesson_type",
"include_in_preview",
"column_break_4",
"title", "title",
"index_", "index_",
"body", "index_label",
"sections" "section_break_6",
"body"
], ],
"fields": [ "fields": [
{ {
@@ -47,15 +50,30 @@
"label": "Body" "label": "Body"
}, },
{ {
"fieldname": "sections", "fieldname": "index_label",
"fieldtype": "Table", "fieldtype": "Data",
"label": "Sections", "in_list_view": 1,
"options": "LMS Section" "label": "Index Label",
"read_only": 1
},
{
"default": "0",
"fieldname": "include_in_preview",
"fieldtype": "Check",
"label": "Include In Preview"
},
{
"fieldname": "section_break_6",
"fieldtype": "Section Break"
},
{
"fieldname": "column_break_4",
"fieldtype": "Column Break"
} }
], ],
"index_web_pages_for_search": 1, "index_web_pages_for_search": 1,
"links": [], "links": [],
"modified": "2021-05-13 20:03:51.510605", "modified": "2021-06-11 19:03:23.138165",
"modified_by": "Administrator", "modified_by": "Administrator",
"module": "LMS", "module": "LMS",
"name": "Lesson", "name": "Lesson",

View File

@@ -5,41 +5,100 @@
from __future__ import unicode_literals from __future__ import unicode_literals
import frappe import frappe
from frappe.model.document import Document from frappe.model.document import Document
from ..lms_topic.section_parser import SectionParser from ...md import markdown_to_html, find_macros
class Lesson(Document): class Lesson(Document):
def before_save(self): def before_save(self):
sections = SectionParser().parse(self.body or "") macros = find_macros(self.body)
self.sections = [self.make_lms_section(i, s) for i, s in enumerate(sections)] exercises = [value for name, value in macros if name == "Exercise"]
for s in self.sections:
if s.type == "exercise": index = 1
e = s.get_exercise() for name in exercises:
e = frappe.get_doc("Exercise", name)
e.lesson = self.name e.lesson = self.name
e.index_ = index
e.save() e.save()
index += 1
self.update_orphan_exercises(exercises)
def get_sections(self): def update_orphan_exercises(self, active_exercises):
return sorted(self.get('sections'), key=lambda s: s.index) """Updates the exercises that were previously part of this lesson,
but not any more.
def make_lms_section(self, index, section):
s = frappe.new_doc('LMS Section', parent_doc=self, parentfield='sections')
s.type = section.type
s.id = section.id
s.label = section.label
s.contents = section.contents
s.index = index
return s
def get_next(self):
"""Returns the number for the next lesson.
The return value would be like 1.2, 2.1 etc.
It will be None if there is no next lesson.
""" """
linked_exercises = {row['name'] for row in frappe.get_all('Exercise', {"lesson": self.name})}
active_exercises = set(active_exercises)
orphan_exercises = linked_exercises - active_exercises
for name in orphan_exercises:
ex = frappe.get_doc("Exercise", name)
ex.lesson = None
ex.index_ = 0
ex.index_label = ""
ex.save()
def render_html(self):
return markdown_to_html(self.body)
def get_prev(self): def get_exercises(self):
"""Returns the number for the prev lesson. if not self.body:
return []
The return value would be like 1.2, 2.1 etc. macros = find_macros(self.body)
It will be None if there is no next lesson. exercises = [value for name, value in macros if name == "Exercise"]
""" return [frappe.get_doc("Exercise", name) for name in exercises]
def get_progress(self):
return frappe.db.get_value("LMS Course Progress", {"lesson": self.name, "owner": frappe.session.user}, "status")
def get_slugified_class(self):
if self.get_progress():
return ("").join([ s for s in self.get_progress().lower().split() ])
return
@frappe.whitelist()
def save_progress(lesson, course):
if not frappe.db.exists("LMS Batch Membership",
{
"member": frappe.session.user,
"course": course
}):
return
if frappe.db.exists("LMS Course Progress",
{
"lesson": lesson,
"owner": frappe.session.user
}):
return
lesson_details = frappe.get_doc("Lesson", lesson)
dynamic_content = find_macros(lesson_details.body)
status = "Complete"
if dynamic_content:
status = "Partially Complete"
frappe.get_doc({
"doctype": "LMS Course Progress",
"lesson": lesson_details.name,
"status": status
}).save(ignore_permissions=True)
def update_progress(lesson):
user = frappe.session.user
if not all_dynamic_content_submitted(lesson, user):
return
if frappe.db.exists("LMS Course Progress", {"lesson": lesson, "owner": user}):
course_progress = frappe.get_doc("LMS Course Progress", {"lesson": lesson, "owner": user})
course_progress.status = "Complete"
course_progress.save(ignore_permissions=True)
def all_dynamic_content_submitted(lesson, user):
exercise_names = frappe.get_list("Exercise", {"lesson": lesson}, pluck="name", ignore_permissions=True)
all_exercises_submitted = False
query = {
"exercise": ["in", exercise_names],
"owner": user
}
if frappe.db.count("Exercise Submission", query) == len(exercise_names):
all_exercises_submitted = True
return all_exercises_submitted

View File

@@ -6,11 +6,10 @@
"engine": "InnoDB", "engine": "InnoDB",
"field_order": [ "field_order": [
"course", "course",
"title",
"start_date", "start_date",
"start_time", "start_time",
"column_break_3", "column_break_3",
"code", "title",
"sessions_on", "sessions_on",
"end_time", "end_time",
"section_break_5", "section_break_5",
@@ -31,18 +30,10 @@
"label": "Course", "label": "Course",
"options": "LMS Course" "options": "LMS Course"
}, },
{
"fieldname": "code",
"fieldtype": "Data",
"label": "Code",
"read_only": 1,
"unique": 1
},
{ {
"fieldname": "title", "fieldname": "title",
"fieldtype": "Data", "fieldtype": "Data",
"label": "Title", "label": "Title"
"unique": 1
}, },
{ {
"fieldname": "description", "fieldname": "description",
@@ -84,7 +75,8 @@
}, },
{ {
"fieldname": "section_break_5", "fieldname": "section_break_5",
"fieldtype": "Section Break" "fieldtype": "Section Break",
"label": "Batch Description"
}, },
{ {
"fieldname": "column_break_9", "fieldname": "column_break_9",
@@ -92,7 +84,8 @@
}, },
{ {
"fieldname": "section_break_7", "fieldname": "section_break_7",
"fieldtype": "Section Break" "fieldtype": "Section Break",
"label": "Batch Settings"
}, },
{ {
"fieldname": "start_date", "fieldname": "start_date",
@@ -126,7 +119,7 @@
"link_fieldname": "batch" "link_fieldname": "batch"
} }
], ],
"modified": "2021-05-06 05:46:38.469120", "modified": "2021-06-16 10:51:05.403726",
"modified_by": "Administrator", "modified_by": "Administrator",
"module": "LMS", "module": "LMS",
"name": "LMS Batch", "name": "LMS Batch",

View File

@@ -5,7 +5,6 @@
from __future__ import unicode_literals from __future__ import unicode_literals
import frappe import frappe
from frappe.model.document import Document from frappe.model.document import Document
from community.www.courses.utils import get_member_with_email
from frappe import _ from frappe import _
from community.lms.doctype.lms_batch_membership.lms_batch_membership import create_membership from community.lms.doctype.lms_batch_membership.lms_batch_membership import create_membership
from community.query import find, find_all from community.query import find, find_all
@@ -13,8 +12,6 @@ from community.query import find, find_all
class LMSBatch(Document): class LMSBatch(Document):
def validate(self): def validate(self):
self.validate_if_mentor() self.validate_if_mentor()
if not self.code:
self.generate_code()
def validate_if_mentor(self): def validate_if_mentor(self):
course = frappe.get_doc("LMS Course", self.course) course = frappe.get_doc("LMS Course", self.course)
@@ -22,46 +19,55 @@ class LMSBatch(Document):
frappe.throw(_("You are not a mentor of the course {0}").format(course.title)) frappe.throw(_("You are not a mentor of the course {0}").format(course.title))
def after_insert(self): def after_insert(self):
create_membership(batch=self.name, member_type="Mentor") create_membership(batch=self.name, course=self.course, member_type="Mentor")
def generate_code(self): def is_member(self, email, member_type=None):
short_code = frappe.db.get_value("LMS Course", self.course, "short_code")
course_batches = frappe.get_all("LMS Batch",{"course":self.course})
self.code = short_code + str(len(course_batches) + 1)
def get_mentors(self):
memberships = frappe.get_all(
"LMS Batch Membership",
{"batch": self.name, "member_type": "Mentor"},
["member"])
member_names = [m['member'] for m in memberships]
return find_all("Community Member", name=["IN", member_names])
def is_member(self, email):
"""Checks if a person is part of a batch. """Checks if a person is part of a batch.
"""
member = find("Community Member", email=email)
return member and frappe.db.exists(
"LMS Batch Membership",
{"batch": self.name, "member": member.name})
@frappe.whitelist() If member_type is specified, checks if the person is a Student/Mentor.
def get_messages(batch): """
messages = frappe.get_all("LMS Message", {"batch": batch}, ["*"], order_by="creation")
filters = {
"batch": self.name,
"member": email
}
if member_type:
filters['member_type'] = member_type
return frappe.db.exists("LMS Batch Membership", filters)
def get_messages(self):
messages = frappe.get_all("LMS Message", {"batch": self.name}, ["*"], order_by="creation")
for message in messages: for message in messages:
message.message = frappe.utils.md_to_html(message.message) message.message = frappe.utils.md_to_html(message.message)
member_email = frappe.db.get_value("Community Member", message.author, ["email"]) if message.author == frappe.session.user:
if member_email == frappe.session.user:
message.author_name = "You" message.author_name = "You"
message.is_author = True message.is_author = True
return messages return messages
def get_membership(self, email):
"""Returns the membership document of given user.
"""
name = frappe.get_value(
doctype="LMS Batch Membership",
filters={
"batch": self.name,
"member": email
},
fieldname="name")
return frappe.get_doc("LMS Batch Membership", name)
def get_current_lesson(self, user):
"""Returns the name of the current lesson for the given user.
"""
membership = self.get_membership(user)
return membership and membership.current_lesson
@frappe.whitelist() @frappe.whitelist()
def save_message(message, batch): def save_message(message, batch):
doc = frappe.get_doc({ doc = frappe.get_doc({
"doctype": "LMS Message", "doctype": "LMS Message",
"batch": batch, "batch": batch,
"author": get_member_with_email(), "author": frappe.session.user,
"message": message "message": message
}) })
doc.save(ignore_permissions=True) doc.save(ignore_permissions=True)

View File

@@ -2,7 +2,13 @@
// For license information, please see license.txt // For license information, please see license.txt
frappe.ui.form.on('LMS Batch Membership', { frappe.ui.form.on('LMS Batch Membership', {
// refresh: function(frm) { onload: function(frm) {
frm.set_query('member', function(doc) {
// } return {
filters: {
"ignore_user_type": 1,
}
};
});
},
}); });

View File

@@ -6,11 +6,14 @@
"engine": "InnoDB", "engine": "InnoDB",
"field_order": [ "field_order": [
"batch", "batch",
"role",
"column_break_3",
"member", "member",
"member_name", "member_name",
"member_type" "member_username",
"column_break_3",
"course",
"member_type",
"role",
"current_lesson"
], ],
"fields": [ "fields": [
{ {
@@ -27,9 +30,10 @@
"in_list_view": 1, "in_list_view": 1,
"in_standard_filter": 1, "in_standard_filter": 1,
"label": "Member", "label": "Member",
"options": "Community Member" "options": "User"
}, },
{ {
"default": "Student",
"fieldname": "member_type", "fieldname": "member_type",
"fieldtype": "Select", "fieldtype": "Select",
"in_list_view": 1, "in_list_view": 1,
@@ -37,6 +41,7 @@
"options": "\nStudent\nMentor\nStaff" "options": "\nStudent\nMentor\nStaff"
}, },
{ {
"default": "Member",
"fieldname": "role", "fieldname": "role",
"fieldtype": "Select", "fieldtype": "Select",
"in_standard_filter": 1, "in_standard_filter": 1,
@@ -54,11 +59,32 @@
{ {
"fieldname": "column_break_3", "fieldname": "column_break_3",
"fieldtype": "Column Break" "fieldtype": "Column Break"
},
{
"fetch_from": "batch.course",
"fieldname": "course",
"fieldtype": "Data",
"in_list_view": 1,
"label": "Course",
"read_only": 1
},
{
"fieldname": "current_lesson",
"fieldtype": "Link",
"label": "Current Lesson",
"options": "Lesson"
},
{
"fetch_from": "member.username",
"fieldname": "member_username",
"fieldtype": "Data",
"label": "Memeber Username",
"read_only": 1
} }
], ],
"index_web_pages_for_search": 1, "index_web_pages_for_search": 1,
"links": [], "links": [],
"modified": "2021-04-26 12:52:59.826509", "modified": "2021-06-21 12:10:28.808803",
"modified_by": "Administrator", "modified_by": "Administrator",
"module": "LMS", "module": "LMS",
"name": "LMS Batch Membership", "name": "LMS Batch Membership",

View File

@@ -14,28 +14,57 @@ class LMSBatchMembership(Document):
self.validate_membership_in_different_batch_same_course() self.validate_membership_in_different_batch_same_course()
def validate_membership_in_same_batch(self): def validate_membership_in_same_batch(self):
previous_membership = frappe.db.get_value("LMS Batch Membership", {"member": self.member, "batch": self.batch, "name": ["!=", self.name]}, ["member_type","member"], as_dict=1) filters={
"member": self.member,
"course": self.course,
"name": ["!=", self.name]
}
if self.batch:
filters["batch"] = self.batch
previous_membership = frappe.db.get_value("LMS Batch Membership",
filters,
fieldname=["member_type","member"],
as_dict=1)
if previous_membership: if previous_membership:
member_name = frappe.db.get_value("Community Member", self.member, "full_name") member_name = frappe.db.get_value("User", self.member, "full_name")
frappe.throw(_("{0} is already a {1} of {2}").format(member_name, previous_membership.member_type, self.batch)) course_title = frappe.db.get_value("LMS Course", self.course, "title")
frappe.throw(_("{0} is already a {1} of the course {2}").format(member_name, previous_membership.member_type, course_title))
def validate_membership_in_different_batch_same_course(self): def validate_membership_in_different_batch_same_course(self):
course = frappe.db.get_value("LMS Batch", self.batch, "course") course = frappe.db.get_value("LMS Batch", self.batch, "course")
previous_membership = frappe.get_all("LMS Batch Membership", {"member": self.member}, ["batch", "member_type"]) previous_membership = frappe.get_all("LMS Batch Membership",
filters={
"member": self.member,
"name": ["!=", self.name]
},
fields=["batch", "member_type", "name"]
)
for membership in previous_membership: for membership in previous_membership:
batch_course = frappe.db.get_value("LMS Batch", membership.batch, "course") batch_course = frappe.db.get_value("LMS Batch", membership.batch, "course")
if batch_course == course and (membership.member_type == "Student" or self.member_type == "Student"): if batch_course == course and (membership.member_type == "Student" or self.member_type == "Student"):
member_name = frappe.db.get_value("Community Member", self.member, "full_name") member_name = frappe.db.get_value("User", self.member, "full_name")
frappe.throw(_("{0} is already a {1} of {2} course through {3} batch").format(member_name, membership.member_type, course, membership.batch)) frappe.throw(_("{0} is already a {1} of {2} course through {3} batch").format(member_name, membership.member_type, course, membership.batch))
def create_membership(batch, member=None, member_type="Student", role="Member"): @frappe.whitelist()
if not member: def create_membership(course, batch=None, member=None, member_type="Student", role="Member"):
member = frappe.db.get_value("Community Member", {"email": frappe.session.user}, "name")
frappe.get_doc({ frappe.get_doc({
"doctype": "LMS Batch Membership", "doctype": "LMS Batch Membership",
"batch": batch, "batch": batch,
"course": course,
"role": role, "role": role,
"member_type": member_type, "member_type": member_type,
"member": member "member": member or frappe.session.user
}).save(ignore_permissions=True) }).save(ignore_permissions=True)
return "OK" return "OK"
@frappe.whitelist()
def update_current_membership(batch, course, member):
all_memberships = frappe.get_all("LMS Batch Membership", {"member": member, "course": course})
for membership in all_memberships:
frappe.db.set_value("LMS Batch Membership", membership.name, "is_current", 0)
current_membership = frappe.get_all("LMS Batch Membership", {"batch": batch, "member": member})
if len(current_membership):
frappe.db.set_value("LMS Batch Membership", current_membership[0].name, "is_current", 1)

View File

@@ -3,8 +3,78 @@
# See license.txt # See license.txt
from __future__ import unicode_literals from __future__ import unicode_literals
# import frappe import frappe
import unittest import unittest
class TestLMSBatchMembership(unittest.TestCase): class TestLMSBatchMembership(unittest.TestCase):
pass def setUp(self):
frappe.db.sql("DELETE FROM `tabLMS Batch Membership`")
frappe.db.sql("DELETE FROM `tabLMS Batch`")
frappe.db.sql('delete from `tabLMS Course Mentor Mapping`')
frappe.db.sql("DELETE FROM `tabLMS Course`")
frappe.db.sql("DELETE FROM `tabUser` where email like '%@test.com'")
def new_course_batch(self):
course = frappe.get_doc({
"doctype": "LMS Course",
"name": "test-course",
"title": "Test Course",
"short_code": "XX",
"short_introduction": "Test Course",
"description": "Test Course"
})
course.insert()
self.new_user("mentor@test.com", "Test Mentor")
# without this, the creating batch will fail
course.add_mentor("mentor@test.com")
frappe.session.user = "mentor@test.com"
batch = frappe.get_doc({
"doctype": "LMS Batch",
"name": "test-batch",
"title": "Test Batch",
"course": course.name
})
batch.insert(ignore_permissions=True)
frappe.session.user = "Administrator"
return course, batch
def new_user(self, email="test@test.com", full_name="Test User"):
user = frappe.get_doc({
"doctype": "User",
"name": email,
"email": email,
"first_name": full_name,
})
user.insert()
return user
def add_membership(self, batch_name, member_name, member_type="Student"):
doc = frappe.get_doc({
"doctype": "LMS Batch Membership",
"batch": batch_name,
"member": member_name,
"member_type": member_type
})
doc.insert()
return doc
def test_membership(self):
course, batch = self.new_course_batch()
member = self.new_user("test01@test.com")
membership = self.add_membership(batch.name, member.name)
assert membership.course == course.name
assert membership.member_name == member.full_name
def test_membership_change_role(self):
course, batch = self.new_course_batch()
member = self.new_user("test01@test.com")
membership = self.add_membership(batch.name, member.name)
# it should be possible to change role
membership.role = "Admin"
membership.save()

View File

@@ -1,5 +1,18 @@
{ {
"actions": [], "actions": [
{
"action": "community.lms.doctype.lms_course.lms_course.reindex_lessons",
"action_type": "Server Action",
"group": "Reindex",
"label": "Reindex Lessons"
},
{
"action": "community.lms.doctype.lms_course.lms_course.reindex_exercises",
"action_type": "Server Action",
"group": "Reindex",
"label": "Reindex Exercises"
}
],
"allow_guest_to_view": 1, "allow_guest_to_view": 1,
"allow_rename": 1, "allow_rename": 1,
"creation": "2021-03-01 16:49:33.622422", "creation": "2021-03-01 16:49:33.622422",
@@ -9,6 +22,7 @@
"field_order": [ "field_order": [
"title", "title",
"is_published", "is_published",
"disable_self_learning",
"column_break_3", "column_break_3",
"short_code", "short_code",
"video_link", "video_link",
@@ -28,7 +42,8 @@
{ {
"fieldname": "description", "fieldname": "description",
"fieldtype": "Markdown Editor", "fieldtype": "Markdown Editor",
"label": "Description" "label": "Description",
"reqd": 1
}, },
{ {
"default": "0", "default": "0",
@@ -57,7 +72,14 @@
{ {
"fieldname": "short_introduction", "fieldname": "short_introduction",
"fieldtype": "Small Text", "fieldtype": "Small Text",
"label": "Short Introduction" "label": "Short Introduction",
"reqd": 1
},
{
"default": "0",
"fieldname": "disable_self_learning",
"fieldtype": "Check",
"label": "Disable Self Learning"
} }
], ],
"index_web_pages_for_search": 1, "index_web_pages_for_search": 1,
@@ -84,7 +106,7 @@
"link_fieldname": "course" "link_fieldname": "course"
} }
], ],
"modified": "2021-05-06 13:37:03.318829", "modified": "2021-06-21 11:34:04.552376",
"modified_by": "Administrator", "modified_by": "Administrator",
"module": "LMS", "module": "LMS",
"name": "LMS Course", "name": "LMS Course",

View File

@@ -5,8 +5,10 @@
from __future__ import unicode_literals from __future__ import unicode_literals
import frappe import frappe
from frappe.model.document import Document from frappe.model.document import Document
import json
from ...utils import slugify from ...utils import slugify
from community.query import find, find_all from community.query import find, find_all
from frappe.utils import flt
class LMSCourse(Document): class LMSCourse(Document):
@staticmethod @staticmethod
@@ -35,38 +37,15 @@ class LMSCourse(Document):
def __repr__(self): def __repr__(self):
return f"<Course#{self.name}>" return f"<Course#{self.name}>"
def get_topic(self, slug):
"""Returns the topic with given slug in this course as a Document.
"""
result = frappe.get_all(
"LMS Topic",
filters={"course": self.name, "slug": slug})
if result:
row = result[0]
return frappe.get_doc('LMS Topic', row['name'])
def has_mentor(self, email): def has_mentor(self, email):
"""Checks if this course has a mentor with given email. """Checks if this course has a mentor with given email.
""" """
if not email or email == "Guest": if not email or email == "Guest":
return False return False
member = self.get_community_member(email) mapping = frappe.get_all("LMS Course Mentor Mapping", {"course": self.name, "mentor": email})
if not member:
return False
mapping = frappe.get_all("LMS Course Mentor Mapping", {"course": self.name, "mentor": member})
return mapping != [] return mapping != []
def get_community_member(self, email):
"""Returns the name of Community Member document for a give user.
"""
try:
return frappe.db.get_value("Community Member", {"email": email}, "name")
except frappe.DoesNotExistError:
return None
def add_mentor(self, email): def add_mentor(self, email):
"""Adds a new mentor to the course. """Adds a new mentor to the course.
""" """
@@ -79,14 +58,10 @@ class LMSCourse(Document):
if self.has_mentor(email): if self.has_mentor(email):
return return
member = self.get_community_member(email)
if not member:
return False
doc = frappe.get_doc({ doc = frappe.get_doc({
"doctype": "LMS Course Mentor Mapping", "doctype": "LMS Course Mentor Mapping",
"course": self.name, "course": self.name,
"mentor": member "mentor": email
}) })
doc.insert() doc.insert()
@@ -96,7 +71,7 @@ class LMSCourse(Document):
course_mentors = [] course_mentors = []
mentors = frappe.get_all("LMS Course Mentor Mapping", {"course": self.name}, ["mentor"]) mentors = frappe.get_all("LMS Course Mentor Mapping", {"course": self.name}, ["mentor"])
for mentor in mentors: for mentor in mentors:
member = frappe.get_doc("Community Member", mentor.mentor) member = frappe.get_doc("User", mentor.mentor)
# TODO: change this to count query # TODO: change this to count query
member.batch_count = len(frappe.get_all("LMS Batch Membership", {"member": member.name, "member_type": "Mentor"})) member.batch_count = len(frappe.get_all("LMS Batch Membership", {"member": member.name, "member_type": "Mentor"}))
course_mentors.append(member) course_mentors.append(member)
@@ -107,11 +82,10 @@ class LMSCourse(Document):
""" """
if not email: if not email:
return False return False
member = self.get_community_member(email) return frappe.db.count("LMS Course Mentor Mapping",
return frappe.db.exists({ {
"doctype": "LMS Course Mentor Mapping",
"course": self.name, "course": self.name,
"mentor": member "mentor": email
}) })
def get_student_batch(self, email): def get_student_batch(self, email):
@@ -120,38 +94,26 @@ class LMSCourse(Document):
Returns None if the student is not part of any batch. Returns None if the student is not part of any batch.
""" """
if not email: if not email:
return False return
member = self.get_community_member(email)
result = frappe.db.get_all(
"LMS Batch Membership",
filters={
"member": member,
"member_type": "Student",
},
fields=['batch']
)
batches = [row['batch'] for row in result]
# filter the batches that are for this course batch_name = frappe.get_value(
result = frappe.db.get_all( doctype="LMS Batch Membership",
"LMS Batch",
filters={ filters={
"course": self.name, "course": self.name,
"name": ["IN", batches] "member_type": "Student",
}) "member": email
batches = [row['name'] for row in result] },
if batches: fieldname="batch")
return frappe.get_doc("LMS Batch", batches[0]) return batch_name and frappe.get_doc("LMS Batch", batch_name)
def get_instructor(self): def get_instructor(self):
member_name = self.get_community_member(self.owner) return frappe.get_doc("User", self.owner)
return frappe.get_doc("Community Member", member_name)
def get_chapters(self): def get_chapters(self):
"""Returns all chapters of this course. """Returns all chapters of this course.
""" """
# TODO: chapters should have a way to specify the order # TODO: chapters should have a way to specify the order
return find_all("Chapter", course=self.name, order_by="creation") return find_all("Chapter", course=self.name, order_by="index_")
def get_batch(self, batch_name): def get_batch(self, batch_name):
return find("LMS Batch", name=batch_name, course=self.name) return find("LMS Batch", name=batch_name, course=self.name)
@@ -160,10 +122,9 @@ class LMSCourse(Document):
batches = find_all("LMS Batch", course=self.name) batches = find_all("LMS Batch", course=self.name)
if mentor: if mentor:
# TODO: optimize this # TODO: optimize this
member = self.get_community_member(email=mentor)
memberships = frappe.db.get_all( memberships = frappe.db.get_all(
"LMS Batch Membership", "LMS Batch Membership",
{"member": member}, {"member": mentor},
["batch"]) ["batch"])
batch_names = {m.batch for m in memberships} batch_names = {m.batch for m in memberships}
return [b for b in batches if b.name in batch_names] return [b for b in batches if b.name in batch_names]
@@ -191,6 +152,93 @@ class LMSCourse(Document):
"name") "name")
return lesson_name and frappe.get_doc("Lesson", lesson_name) return lesson_name and frappe.get_doc("Lesson", lesson_name)
def get_lesson_index(self, lesson_name):
"""Returns the {chapter_index}.{lesson_index} for the lesson.
"""
lesson = frappe.get_doc("Lesson", lesson_name)
chapter = frappe.get_doc("Chapter", lesson.chapter)
return f"{chapter.index_}.{lesson.index_}"
def reindex_lessons(self):
for i, c in enumerate(self.get_chapters(), start=1):
c.index_ = i
c.save()
self._reindex_lessons_in_chapter(c)
def _reindex_lessons_in_chapter(self, c):
for i, lesson in enumerate(c.get_lessons(), start=1):
lesson.index = i
lesson.index_label = f"{c.index_}.{i}"
lesson.save()
def reindex_exercises(self):
for i, c in enumerate(self.get_chapters(), start=1):
if c.index_ != i:
c.index_ = i
c.save()
self._reindex_exercises_in_chapter(c)
def _reindex_exercises_in_chapter(self, c):
i = 1
for lesson in c.get_lessons():
for exercise in lesson.get_exercises():
exercise.index_ = i
exercise.index_label = f"{c.index_}.{i}"
exercise.save()
i += 1
def get_learn_url(self, lesson_number):
if not lesson_number:
return
return f"/courses/{self.name}/learn/{lesson_number}"
def get_membership(self, member, batch=None):
filters = {
"member": member,
"course": self.name
}
if batch:
filters["batch"] = batch
return frappe.db.get_value("LMS Batch Membership", filters, ["name","batch", "current_lesson"], as_dict=True)
def get_all_memberships(self, member=frappe.session.user):
all_memberships = frappe.get_all("LMS Batch Membership", {"member": member, "course": self.name}, ["batch"])
for membership in all_memberships:
membership.batch_title = frappe.db.get_value("LMS Batch", membership.batch, "title")
print(all_memberships)
return all_memberships
def get_mentors(self, batch=None):
filters = {
"course": self.name,
"member_type": "Mentor"
}
if batch:
filters["batch"] = batch
memberships = frappe.get_all(
"LMS Batch Membership",
filters,
["member"])
member_names = [m['member'] for m in memberships]
return find_all("User", name=["IN", member_names])
def get_students(self, batch=None):
"""Returns (email, full_name, username) of all the students of this batch as a list of dict.
"""
filters = {
"course": self.name,
"member_type": "Student"
}
if batch:
filters["batch"] = batch
memberships = frappe.get_all(
"LMS Batch Membership",
filters,
["member"])
member_names = [m['member'] for m in memberships]
return find_all("User", name=["IN", member_names])
def get_outline(self): def get_outline(self):
return CourseOutline(self) return CourseOutline(self)
@@ -201,6 +249,7 @@ class CourseOutline:
self.lessons = self.get_lessons() self.lessons = self.get_lessons()
def get_next(self, current): def get_next(self, current):
current = flt(current)
numbers = sorted(lesson['number'] for lesson in self.lessons) numbers = sorted(lesson['number'] for lesson in self.lessons)
try: try:
index = numbers.index(current) index = numbers.index(current)
@@ -209,6 +258,7 @@ class CourseOutline:
return None return None
def get_prev(self, current): def get_prev(self, current):
current = flt(current)
numbers = sorted(lesson['number'] for lesson in self.lessons) numbers = sorted(lesson['number'] for lesson in self.lessons)
try: try:
index = numbers.index(current) index = numbers.index(current)
@@ -221,7 +271,8 @@ class CourseOutline:
def get_chapters(self): def get_chapters(self):
return frappe.db.get_all("Chapter", return frappe.db.get_all("Chapter",
filters={"course": self.course.name}, filters={"course": self.course.name},
fields=["name", "title", "index_"]) fields=["name", "title", "index_"],
order_by="index_")
def get_lessons(self): def get_lessons(self):
chapters = [c['name'] for c in self.chapters] chapters = [c['name'] for c in self.chapters]
@@ -231,5 +282,19 @@ class CourseOutline:
chapter_numbers = {c['name']: c['index_'] for c in self.chapters} chapter_numbers = {c['name']: c['index_'] for c in self.chapters}
for lesson in lessons: for lesson in lessons:
lesson['number'] = "{}.{}".format(chapter_numbers[lesson['chapter']], lesson['index_']) lesson['number'] = flt("{}.{}".format(chapter_numbers[lesson['chapter']], lesson['index_']))
return lessons return lessons
@frappe.whitelist()
def reindex_lessons(doc):
course_data = json.loads(doc)
course = frappe.get_doc("LMS Course", course_data['name'])
course.reindex_lessons()
frappe.msgprint("All lessons in this course have been re-indexed.")
@frappe.whitelist()
def reindex_exercises(doc):
course_data = json.loads(doc)
course = frappe.get_doc("LMS Course", course_data['name'])
course.reindex_exercises()
frappe.msgprint("All exercises in this course have been re-indexed.")

View File

@@ -11,12 +11,13 @@ class TestLMSCourse(unittest.TestCase):
def setUp(self): def setUp(self):
frappe.db.sql('delete from `tabLMS Course Mentor Mapping`') frappe.db.sql('delete from `tabLMS Course Mentor Mapping`')
frappe.db.sql('delete from `tabLMS Course`') frappe.db.sql('delete from `tabLMS Course`')
frappe.db.sql('delete from `tabCommunity Member`')
def new_course(self, title): def new_course(self, title):
doc = frappe.get_doc({ doc = frappe.get_doc({
"doctype": "LMS Course", "doctype": "LMS Course",
"title": title "title": title,
"short_introduction": title,
"description": title
}) })
doc.insert() doc.insert()
return doc return doc
@@ -25,7 +26,6 @@ class TestLMSCourse(unittest.TestCase):
course = self.new_course("Test Course") course = self.new_course("Test Course")
assert course.title == "Test Course" assert course.title == "Test Course"
assert course.name == "test-course" assert course.name == "test-course"
assert course.get_mentors() == []
def test_find_all(self): def test_find_all(self):
courses = LMSCourse.find_all() courses = LMSCourse.find_all()

View File

@@ -23,7 +23,7 @@
"fieldtype": "Link", "fieldtype": "Link",
"in_standard_filter": 1, "in_standard_filter": 1,
"label": "Mentor", "label": "Mentor",
"options": "Community Member" "options": "User"
}, },
{ {
"fetch_from": "mentor.full_name", "fetch_from": "mentor.full_name",
@@ -36,7 +36,7 @@
], ],
"index_web_pages_for_search": 1, "index_web_pages_for_search": 1,
"links": [], "links": [],
"modified": "2021-04-20 12:46:48.460934", "modified": "2021-05-21 11:48:43.340315",
"modified_by": "Administrator", "modified_by": "Administrator",
"module": "LMS", "module": "LMS",
"name": "LMS Course Mentor Mapping", "name": "LMS Course Mentor Mapping",

View File

@@ -1,7 +1,7 @@
// Copyright (c) 2021, FOSS United and contributors // Copyright (c) 2021, FOSS United and contributors
// For license information, please see license.txt // For license information, please see license.txt
frappe.ui.form.on('Code Revision', { frappe.ui.form.on('LMS Course Progress', {
// refresh: function(frm) { // refresh: function(frm) {
// } // }

View File

@@ -0,0 +1,78 @@
{
"actions": [],
"creation": "2021-05-31 17:20:13.388453",
"doctype": "DocType",
"editable_grid": 1,
"engine": "InnoDB",
"field_order": [
"status",
"column_break_3",
"lesson",
"chapter",
"course"
],
"fields": [
{
"fetch_from": "chapter.course",
"fieldname": "course",
"fieldtype": "Link",
"in_list_view": 1,
"in_standard_filter": 1,
"label": "Course",
"options": "LMS Course",
"read_only": 1
},
{
"fetch_from": "lesson.chapter",
"fieldname": "chapter",
"fieldtype": "Link",
"in_list_view": 1,
"label": "Chapter",
"options": "Chapter",
"read_only": 1
},
{
"fieldname": "lesson",
"fieldtype": "Link",
"in_list_view": 1,
"label": "Lesson",
"options": "Lesson"
},
{
"fieldname": "status",
"fieldtype": "Select",
"in_list_view": 1,
"in_standard_filter": 1,
"label": "Status",
"options": "Complete\nPartially Complete\nIncomplete"
},
{
"fieldname": "column_break_3",
"fieldtype": "Column Break"
}
],
"index_web_pages_for_search": 1,
"links": [],
"modified": "2021-06-02 13:05:31.114939",
"modified_by": "Administrator",
"module": "LMS",
"name": "LMS Course Progress",
"owner": "Administrator",
"permissions": [
{
"create": 1,
"delete": 1,
"email": 1,
"export": 1,
"print": 1,
"read": 1,
"report": 1,
"role": "System Manager",
"share": 1,
"write": 1
}
],
"sort_field": "modified",
"sort_order": "DESC",
"track_changes": 1
}

View File

@@ -1,10 +1,8 @@
# -*- coding: utf-8 -*-
# Copyright (c) 2021, FOSS United and contributors # Copyright (c) 2021, FOSS United and contributors
# For license information, please see license.txt # For license information, please see license.txt
from __future__ import unicode_literals
# import frappe # import frappe
from frappe.model.document import Document from frappe.model.document import Document
class CodeRevision(Document): class LMSCourseProgress(Document):
pass pass

View File

@@ -1,10 +1,8 @@
# -*- coding: utf-8 -*-
# Copyright (c) 2021, FOSS United and Contributors # Copyright (c) 2021, FOSS United and Contributors
# See license.txt # See license.txt
from __future__ import unicode_literals
# import frappe # import frappe
import unittest import unittest
class TestLMSTopic(unittest.TestCase): class TestLMSCourseProgress(unittest.TestCase):
pass pass

View File

@@ -19,7 +19,7 @@
"fieldtype": "Link", "fieldtype": "Link",
"in_standard_filter": 1, "in_standard_filter": 1,
"label": "Member", "label": "Member",
"options": "Community Member" "options": "User"
}, },
{ {
"fieldname": "course", "fieldname": "course",
@@ -52,7 +52,7 @@
"fieldname": "reviewed_by", "fieldname": "reviewed_by",
"fieldtype": "Link", "fieldtype": "Link",
"label": "Reviewed By", "label": "Reviewed By",
"options": "Community Member" "options": "User"
}, },
{ {
"fieldname": "comments", "fieldname": "comments",
@@ -62,7 +62,7 @@
], ],
"index_web_pages_for_search": 1, "index_web_pages_for_search": 1,
"links": [], "links": [],
"modified": "2021-04-19 09:27:03.814016", "modified": "2021-05-21 11:49:12.543502",
"modified_by": "Administrator", "modified_by": "Administrator",
"module": "LMS", "module": "LMS",
"name": "LMS Mentor Request", "name": "LMS Mentor Request",

View File

@@ -25,7 +25,7 @@ class LMSMentorRequest(Document):
}) })
mapping.save() mapping.save()
def send_creation_email(self, member): def send_creation_email(self):
email_template = self.get_email_template('mentor_request_creation') email_template = self.get_email_template('mentor_request_creation')
if not email_template: if not email_template:
return return
@@ -33,7 +33,7 @@ class LMSMentorRequest(Document):
course_details = frappe.db.get_value("LMS Course", self.course, ["owner", "slug", "title"], as_dict=True) course_details = frappe.db.get_value("LMS Course", self.course, ["owner", "slug", "title"], as_dict=True)
message = frappe.render_template(email_template.response, message = frappe.render_template(email_template.response,
{ {
'member_name': member.full_name, 'member_name': frappe.db.get_value("User", frappe.session.user, "full_name"),
'course_url': '/courses/' + course_details.slug, 'course_url': '/courses/' + course_details.slug,
'course': course_details.title 'course': course_details.title
}) })
@@ -59,12 +59,10 @@ class LMSMentorRequest(Document):
'course': course_details.title 'course': course_details.title
}) })
member_email = frappe.db.get_value("Community Member", self.member, "email")
if self.status == 'Approved' or self.status == 'Rejected': if self.status == 'Approved' or self.status == 'Rejected':
reviewed_by = frappe.db.get_value('Community Member', self.reviewed_by, 'email')
email_args = { email_args = {
"recipients": member_email, "recipients": self.member,
"cc": [course_details.owner, reviewed_by], "cc": [course_details.owner, self.reviewed_by],
"subject": email_template.subject, "subject": email_template.subject,
"header": email_template.subject, "header": email_template.subject,
"message": message "message": message
@@ -73,7 +71,7 @@ class LMSMentorRequest(Document):
elif self.status == 'Withdrawn': elif self.status == 'Withdrawn':
email_args = { email_args = {
"recipients": [member_email, course_details.owner], "recipients": [self.member, course_details.owner],
"subject": email_template.subject, "subject": email_template.subject,
"header": email_template.subject, "header": email_template.subject,
"message": message "message": message
@@ -89,7 +87,7 @@ class LMSMentorRequest(Document):
def has_requested(course): def has_requested(course):
return frappe.db.count('LMS Mentor Request', return frappe.db.count('LMS Mentor Request',
filters = { filters = {
'member': get_member().name, 'member': frappe.session.user,
'course': course, 'course': course,
'status': ['in', ('Pending', 'Approved')] 'status': ['in', ('Pending', 'Approved')]
} }
@@ -98,15 +96,14 @@ def has_requested(course):
@frappe.whitelist() @frappe.whitelist()
def create_request(course): def create_request(course):
if not has_requested(course): if not has_requested(course):
member = get_member()
request = frappe.get_doc({ request = frappe.get_doc({
'doctype': 'LMS Mentor Request', 'doctype': 'LMS Mentor Request',
'member': member.name, 'member': frappe.session.user,
'course': course, 'course': course,
'status': 'Pending' 'status': 'Pending'
}) })
request.save(ignore_permissions=True) request.save(ignore_permissions=True)
request.send_creation_email(member) request.send_creation_email()
return 'OK' return 'OK'
else: else:
@@ -114,13 +111,12 @@ def create_request(course):
@frappe.whitelist() @frappe.whitelist()
def cancel_request(course): def cancel_request(course):
request = frappe.get_doc('LMS Mentor Request', {'member': get_member().name, 'course': course, 'status': ['in', ('Pending', 'Approved')]}) request = frappe.get_doc('LMS Mentor Request',{
'member': frappe.session.user,
'course': course,
'status': ['in', ('Pending', 'Approved')]
}
)
request.status = 'Withdrawn' request.status = 'Withdrawn'
request.save(ignore_permissions=True) request.save(ignore_permissions=True)
return 'OK' return 'OK'
def get_member():
try:
return frappe.get_doc('Community Member', {'email': frappe.session.user})
except frappe.DoesNotExistError:
return

View File

@@ -26,7 +26,7 @@
"fieldtype": "Link", "fieldtype": "Link",
"in_list_view": 1, "in_list_view": 1,
"label": "Author", "label": "Author",
"options": "Community Member" "options": "User"
}, },
{ {
"fieldname": "message", "fieldname": "message",
@@ -58,7 +58,7 @@
], ],
"index_web_pages_for_search": 1, "index_web_pages_for_search": 1,
"links": [], "links": [],
"modified": "2021-04-28 10:17:57.618127", "modified": "2021-05-21 11:49:34.911479",
"modified_by": "Administrator", "modified_by": "Administrator",
"module": "LMS", "module": "LMS",
"name": "LMS Message", "name": "LMS Message",

View File

@@ -7,17 +7,61 @@ import frappe
from frappe.model.document import Document from frappe.model.document import Document
from frappe import _ from frappe import _
from frappe.utils import add_days, nowdate from frappe.utils import add_days, nowdate
from community.www.courses.utils import get_batch_members
class LMSMessage(Document): class LMSMessage(Document):
""" def after_insert(self): def after_insert(self):
self.send_email() """ self.publish_message()
#Todo: Adding email preference field for users
#self.send_email()
def publish_message(self):
template = self.get_message_template()
message = frappe._dict({
"author_name": self.author_name,
"message_time": frappe.utils.format_datetime(self.creation, "dd-mm-yyyy HH:mm"),
"message": frappe.utils.md_to_html(self.message)
})
js = """
$(".msger-input").val("");
var template = `{0}`;
var message = {1};
var session_user = ("{2}" == frappe.session.user) ? true : false;
message.author_name = session_user ? "You" : message.author_name
message.is_author = session_user;
template = frappe.render_template(template, {{
"message": message
}})
$(".messages").append(template);
var message_element = document.getElementsByClassName("messages")[0]
message_element.scrollTo(0, message_element.scrollHeight);
""".format(template, message, self.owner)
frappe.publish_realtime(event="eval_js", message=js, after_commit=True)
def get_message_template(self):
return """
<li class="{% if message.is_author %} ours {% endif %}">
<div class="d-flex justify-content-between">
<div class="font-weight-bold">
{{ message.author_name }}
</div>
<small class="">
{{ message.message_time }}
</small>
</div>
<div class="message-para">
{{ message.message }}
</div>
</li>
"""
def send_email(self): def send_email(self):
membership = frappe.get_all("LMS Batch Membership", {"batch": self.batch}, ["member"]) membership = frappe.get_all("LMS Batch Membership", {"batch": self.batch}, ["member"])
for entry in membership: for entry in membership:
member = frappe.get_doc("Community Member", entry.member) member = frappe.get_doc("User", entry.member)
if member.name != self.author and member.email_preference == "Email on every Message": if member.name != self.author:
#Todo: wrap sendmail in frappe.enqueue, else messages takes long to display.
frappe.sendmail( frappe.sendmail(
recipients = member.email, recipients = member.email,
subject = _("New Message on ") + self.batch, subject = _("New Message on ") + self.batch,
@@ -30,14 +74,16 @@ class LMSMessage(Document):
"course": frappe.db.get_value("LMS Batch", self.batch, ["course"]) "course": frappe.db.get_value("LMS Batch", self.batch, ["course"])
} }
) )
def send_daily_digest(): def send_daily_digest():
#Todo: Optimize this
emails = frappe._dict() emails = frappe._dict()
messages = frappe.get_all("LMS Message", {"creation": [">=", add_days(nowdate(), -1)]}, ["message", "batch", "author", "creation"]) messages = frappe.get_all("LMS Message", {"creation": [">=", add_days(nowdate(), -1)]}, ["message", "batch", "author", "creation"])
for message in messages: for message in messages:
membership = frappe.get_all("LMS Batch Membership", {"batch": message.batch}, ["member"]) membership = frappe.get_all("LMS Batch Membership", {"batch": message.batch}, ["member"])
for entry in membership: for entry in membership:
member = frappe.db.get_value("Community Member", entry.member, ["name", "email_preference", "email"], as_dict=1) member = frappe.db.get_value("User", entry.member, ["name", "email"], as_dict=1)
if member.name != message.author and member.email_preference == "One Digest Mail per day": if member.name != message.author:
if member.name in emails.keys(): if member.name in emails.keys():
emails[member.name]["messages"].append(message) emails[member.name]["messages"].append(message)
else: else:
@@ -53,7 +99,7 @@ def send_daily_digest():
else: else:
group_by_batch[message.batch] = [message] group_by_batch[message.batch] = [message]
frappe.sendmail( frappe.sendmail(
recipients = frappe.db.get_value("Community Member", email, "email"), recipients = frappe.db.get_value("User", email, "email"),
subject = _("Message Digest"), subject = _("Message Digest"),
header = _("Message Digest"), header = _("Message Digest"),
template = "lms_daily_digest", template = "lms_daily_digest",
@@ -62,43 +108,3 @@ def send_daily_digest():
}, },
delayed = False delayed = False
) )
def publish_message(doc, method):
email = frappe.db.get_value("Community Member", doc.author, "email")
template = get_message_template()
message = frappe._dict()
message.author_name = doc.author_name
message.message_time = frappe.utils.pretty_date(doc.creation)
message.message = frappe.utils.md_to_html(doc.message)
js = """
$(".msger-input").val("");
var template = `{0}`;
var message = {1};
var session_user = ("{2}" == frappe.session.user) ? true : false;
message.author_name = session_user ? "You" : message.author_name
message.is_author = session_user;
template = frappe.render_template(template, {{
"message": message
}})
$(".message-section").append(template);
""".format(template, message, email)
frappe.publish_realtime(event="eval_js", message=js, after_commit=True)
def get_message_template():
return """
<div class="discussion {% if message.is_author %} is-author {% endif %}">
<div class="d-flex justify-content-between">
<div class="font-weight-bold">
{{ message.author_name }}
</div>
<div class="text-muted">
{{ message.message_time }}
</div>
</div>
<div class="mt-5">
{{ message.message }}
</div>
</div>
"""

View File

@@ -1,66 +0,0 @@
{
"actions": [],
"creation": "2021-03-05 15:10:53.906006",
"doctype": "DocType",
"engine": "InnoDB",
"field_order": [
"label",
"type",
"contents",
"code",
"attrs",
"index",
"id"
],
"fields": [
{
"fieldname": "label",
"fieldtype": "Data",
"in_list_view": 1,
"label": "Label"
},
{
"fieldname": "type",
"fieldtype": "Data",
"in_list_view": 1,
"label": "Type"
},
{
"fieldname": "contents",
"fieldtype": "Markdown Editor",
"label": "Contents"
},
{
"fieldname": "code",
"fieldtype": "Code",
"label": "Code"
},
{
"fieldname": "attrs",
"fieldtype": "Long Text",
"label": "attrs"
},
{
"fieldname": "index",
"fieldtype": "Int",
"label": "Index"
},
{
"fieldname": "id",
"fieldtype": "Data",
"label": "id"
}
],
"index_web_pages_for_search": 1,
"istable": 1,
"links": [],
"modified": "2021-05-19 18:55:26.019625",
"modified_by": "Administrator",
"module": "LMS",
"name": "LMS Section",
"owner": "Administrator",
"permissions": [],
"sort_field": "modified",
"sort_order": "DESC",
"track_changes": 1
}

View File

@@ -1,33 +0,0 @@
# -*- coding: utf-8 -*-
# Copyright (c) 2021, FOSS United and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from frappe.model.document import Document
class LMSSection(Document):
def __repr__(self):
return f"<LMSSection {self.label!r}>"
def get_exercise(self):
if self.type == "exercise":
return frappe.get_doc("Exercise", self.id)
def get_latest_code_for_user(self):
"""Returns the latest code for the logged in user.
"""
if not frappe.session.user or frappe.session.user == "Guest":
return self.contents
result = frappe.get_all('Code Revision',
fields=["code"],
filters={
"author": frappe.session.user,
"section": self.name
},
order_by="creation desc",
page_length=1)
if result:
return result[0]['code']
else:
return self.contents

View File

@@ -1,8 +0,0 @@
// Copyright (c) 2021, FOSS United and contributors
// For license information, please see license.txt
frappe.ui.form.on('LMS Topic', {
// refresh: function(frm) {
// }
});

View File

@@ -1,89 +0,0 @@
{
"actions": [],
"allow_guest_to_view": 1,
"creation": "2021-03-02 07:20:41.686573",
"doctype": "DocType",
"editable_grid": 1,
"engine": "InnoDB",
"field_order": [
"course",
"title",
"slug",
"preview",
"description",
"order",
"sections"
],
"fields": [
{
"fieldname": "title",
"fieldtype": "Data",
"in_list_view": 1,
"label": "Title",
"reqd": 1
},
{
"fieldname": "description",
"fieldtype": "Markdown Editor",
"label": "Description"
},
{
"fieldname": "course",
"fieldtype": "Link",
"in_list_view": 1,
"label": "Course",
"options": "LMS Course",
"reqd": 1
},
{
"fieldname": "order",
"fieldtype": "Int",
"label": "Order"
},
{
"fieldname": "preview",
"fieldtype": "Markdown Editor",
"label": "Preview"
},
{
"fieldname": "sections",
"fieldtype": "Table",
"label": "Sections",
"options": "LMS Section"
},
{
"description": "The slug of the topic. Autogenerated from the title if not specified.",
"fieldname": "slug",
"fieldtype": "Data",
"label": "Slug"
}
],
"index_web_pages_for_search": 1,
"links": [],
"modified": "2021-04-06 14:12:48.514062",
"modified_by": "Administrator",
"module": "LMS",
"name": "LMS Topic",
"owner": "Administrator",
"permissions": [
{
"create": 1,
"delete": 1,
"email": 1,
"export": 1,
"print": 1,
"read": 1,
"report": 1,
"role": "System Manager",
"share": 1,
"write": 1
}
],
"search_fields": "title",
"sort_field": "creation",
"sort_order": "ASC",
"title_field": "title",
"track_changes": 1,
"track_seen": 1,
"track_views": 1
}

View File

@@ -1,43 +0,0 @@
# -*- coding: utf-8 -*-
# Copyright (c) 2021, FOSS United and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from frappe.model.document import Document
from .section_parser import SectionParser
from ...utils import slugify
class LMSTopic(Document):
def before_save(self):
course = self.get_course()
if not self.slug:
self.slug = self.generate_slug(title=self.title)
sections = SectionParser().parse(self.description or "")
self.sections = [self.make_lms_section(i, s) for i, s in enumerate(sections)]
def get_course(self):
return frappe.get_doc("LMS Course", self.course)
def generate_slug(self, title):
result = frappe.get_all(
'LMS Topic',
filters={'course': self.course},
fields=['slug'])
slugs = set([row['slug'] for row in result])
return slugify(title, used_slugs=slugs)
def get_sections(self):
return sorted(self.sections, key=lambda s: s.index)
def make_lms_section(self, index, section):
s = frappe.new_doc('LMS Section', parent_doc=self, parentfield='sections')
s.type = section.type
s.label = section.label
s.contents = section.contents
s.index = index
return s

View File

@@ -1,84 +0,0 @@
"""Utility to split the text in the topic into multiple sections.
{{ section(type="example", id="foo") }}
circle(100, 100, 50)
{{ end }}
"""
from __future__ import annotations
from dataclasses import dataclass
import re
from typing import List, Tuple, Dict, Iterator
RE_SECTION = re.compile(r"^\{\{\s(\w+)\s*(?:\((.*)\))?\s*\}\}\s*")
class SectionParser:
def parse(self, text: str) -> Iterator[Section]:
"""Parses given text into sections and return an iterator over sections.
"""
lines = text.splitlines()
marked_lines = self.parse_lines(lines)
return self.group_sections(marked_lines)
def parse_lines(self, lines: List[str]) -> List[Tuple[str, str, str]]:
for line in lines:
m = RE_SECTION.match(line)
if m:
yield m.group(1), self.parse_attrs(m.group(2)), None
else:
yield None, None, line
def parse_attrs(self, attrs_str: str) -> Dict[str, str]:
# XXX-Anand: Hack
code = "dict({})".format(attrs_str or "")
return eval(code)
def group_sections(self, marked_lines) -> Iterator[Section]:
index = 0
def make_section(type='text', id=None, label=None, **attrs):
nonlocal index
index += 1
id = id or f"section-{index}"
label = label or id
return Section(
type=type,
id=id,
label=label,
attrs=attrs)
section = make_section("text")
for mark, attrs, line in marked_lines:
if not mark:
section.append(line)
continue
yield section
if mark == 'end':
section = make_section(type='text')
else:
section = make_section(**attrs)
yield section
@dataclass
class Section:
"""One section of the Topic.
"""
type: str
id: str
label: str
contents: str = ""
attrs: dict = None
def append(self, line):
if not line.endswith("\n"):
line = line + "\n"
self.contents += line
def __repr__(self):
attrs = dict(type=self.type, id=self.id, label=self.label, **self.attrs)
attrs_str = ", ".join(f'{k}="{v}"' for k, v in attrs.items())
return f'<Section({attrs_str})>'

107
community/lms/md.py Normal file
View File

@@ -0,0 +1,107 @@
"""
The md module extends markdown to add macros.
Macros can be added to the markdown text in the following format.
{{ MacroName("macro-argument") }}
These macros will be rendered using a pluggable mechanism.
Apps can provide a hook community_markdown_macro_renderers, a
dictionary mapping the macro name to the function that to render
that macro. The function will get the argument passed to the macro
as argument.
"""
import frappe
import re
from bs4 import BeautifulSoup
import markdown
from markdown import Extension
from markdown.inlinepatterns import InlineProcessor
import xml.etree.ElementTree as etree
def markdown_to_html(text):
"""Renders markdown text into html.
"""
return markdown.markdown(text, extensions=['fenced_code', MacroExtension()])
def find_macros(text):
"""Returns all macros in the given text.
>>> find_macros(text)
[
('YouTubeVideo': 'abcd1234')
('Exercise', 'two-circles'),
('Exercise', 'four-circles')
]
"""
macros = re.findall(MACRO_RE, text)
# remove the quotes around the argument
return [(name, _remove_quotes(arg)) for name, arg in macros]
def _remove_quotes(value):
"""Removes quotes around a value.
Also strips the whitespace.
>>> _remove_quotes('"hello"')
'hello'
>>> _remove_quotes("'hello'")
'hello'
>>> _remove_quotes("hello")
'hello'
"""
return value.strip(" '\"")
def get_macro_registry():
d = frappe.get_hooks("community_markdown_macro_renderers") or {}
return {name: frappe.get_attr(klass[0]) for name, klass in d.items()}
def render_macro(macro_name, macro_argument):
# stripping the quotes on either side of the argument
macro_argument = _remove_quotes(macro_argument)
registry = get_macro_registry()
if macro_name in registry:
return registry[macro_name](macro_argument)
else:
return f"<p>Unknown macro: {macro_name}</p>"
MACRO_RE = r'{{ *(\w+)\(([^{}]*)\) *}}'
class MacroExtension(Extension):
"""MacroExtension is a markdown extension to support macro syntax.
"""
def extendMarkdown(self, md):
self.md = md
pattern = MacroInlineProcessor(MACRO_RE)
pattern.md = md
md.inlinePatterns.register(pattern, 'macro', 75)
class MacroInlineProcessor(InlineProcessor):
"""MacroInlineProcessor is class that is handles the logic
of how to render each macro occurence in the markdown text.
"""
def handleMatch(self, m, data):
"""Handles each macro match and return rendered contents
for that macro as an etree node.
"""
macro = m.group(1)
arg = m.group(2)
html = render_macro(macro, arg)
html = sanitize_html(str(html))
e = etree.fromstring(html)
return e, m.start(0), m.end(0)
def sanitize_html(html):
"""Sanotize the html using BeautifulSoup.
The markdown processor request the correct markup and crashes on
any broken tags. This makes sures that all those things are fixed
before passing to the etree parser.
"""
soup = BeautifulSoup(html, features="lxml")
nodes = soup.body.children
return "<div>" + "\n".join(str(node) for node in nodes) + "</div>"

View File

@@ -2,4 +2,4 @@
""" """
from .doctype.lms_course.lms_course import LMSCourse as Course from .doctype.lms_course.lms_course import LMSCourse as Course
from .doctype.lms_sketch.lms_sketch import LMSSketch as Sketch from .doctype.lms_sketch.lms_sketch import LMSSketch as Sketch
from .doctype.lms_batch_membership.lms_batch_membership import LMSBatchMembership as Membership

View File

@@ -11,7 +11,7 @@
"apply_document_permissions": 0, "apply_document_permissions": 0,
"button_label": "Save", "button_label": "Save",
"creation": "2021-04-20 11:37:49.135114", "creation": "2021-04-20 11:37:49.135114",
"custom_css": ".datepicker.active {\n background-color: white;\n}", "custom_css": ".datepicker.active {\n background-color: white;\n}\n\n[data-doctype=\"Web Form\"] {\n max-width: 720px;\n margin: 6rem auto;\n}",
"doc_type": "LMS Batch", "doc_type": "LMS Batch",
"docstatus": 0, "docstatus": 0,
"doctype": "Web Form", "doctype": "Web Form",
@@ -19,7 +19,7 @@
"is_standard": 1, "is_standard": 1,
"login_required": 1, "login_required": 1,
"max_attachment_size": 0, "max_attachment_size": 0,
"modified": "2021-04-30 11:22:18.188712", "modified": "2021-06-15 18:49:50.530001",
"modified_by": "Administrator", "modified_by": "Administrator",
"module": "LMS", "module": "LMS",
"name": "add-a-new-batch", "name": "add-a-new-batch",
@@ -39,12 +39,12 @@
"allow_read_on_all_link_options": 0, "allow_read_on_all_link_options": 0,
"fieldname": "course", "fieldname": "course",
"fieldtype": "Data", "fieldtype": "Data",
"hidden": 0, "hidden": 1,
"label": "Course", "label": "Course",
"max_length": 0, "max_length": 0,
"max_value": 0, "max_value": 0,
"options": "", "options": "LMS Course",
"read_only": 1, "read_only": 0,
"reqd": 0, "reqd": 0,
"show_in_filter": 0 "show_in_filter": 0
}, },

View File

@@ -1,3 +0,0 @@
frappe.ready(function() {
// bind events here
})

View File

@@ -1,48 +0,0 @@
{
"accept_payment": 0,
"allow_comments": 0,
"allow_delete": 0,
"allow_edit": 0,
"allow_incomplete": 0,
"allow_multiple": 0,
"allow_print": 0,
"amount": 0.0,
"amount_based_on_field": 0,
"apply_document_permissions": 0,
"button_label": "Save",
"creation": "2021-04-15 13:32:14.171328",
"doc_type": "LMS Batch Membership",
"docstatus": 0,
"doctype": "Web Form",
"idx": 0,
"is_standard": 1,
"login_required": 1,
"max_attachment_size": 0,
"modified": "2021-04-15 13:32:14.171328",
"modified_by": "Administrator",
"module": "LMS",
"name": "join-a-batch",
"owner": "Administrator",
"payment_button_label": "Buy Now",
"published": 1,
"route": "join-a-batch",
"route_to_success_link": 0,
"show_attachments": 0,
"show_in_grid": 0,
"show_sidebar": 0,
"sidebar_items": [],
"success_url": "/join-a-batch",
"title": "Join a Batch",
"web_form_fields": [
{
"allow_read_on_all_link_options": 0,
"fieldtype": "Attach",
"hidden": 0,
"max_length": 0,
"max_value": 0,
"read_only": 0,
"reqd": 0,
"show_in_filter": 0
}
]
}

View File

@@ -1,7 +0,0 @@
from __future__ import unicode_literals
import frappe
def get_context(context):
# do your magic here
pass

View File

@@ -0,0 +1,4 @@
<div class="p-5 batch-header">
<h3>{{batch_name}}</h3>
<div class="text-muted">{{member_count}} members</div>
</div>

View File

@@ -0,0 +1,65 @@
<div class="mt-5">
<a class="anchor_style" href="/courses">Courses</a> /{% if course.is_mentor(frappe.session.user) %} <a
class="anchor_style" href="/courses/{{ course.name }}"> {{ course.title }}</a> {% else %} <span class="text-muted">
{{ course.title }}</span> {% endif %}
{% set all_memberships = course.get_all_memberships() %}
{% if all_memberships | length > 1 %}
<a class="nav-link pull-right" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true"
aria-expanded="false">
Switch Batch
</a>
<div class="dropdown-menu" aria-labelledby="navbarDropdown">
{% for data in all_memberships %}
{% if data.batch != membership.batch %}
<a class="dropdown-item switch-batch" href="/courses/{{ course.name }}/home?batch={{ data.batch }}">{{ data.batch_title }}</a>
{% endif %}
{% endfor %}
</div>
{% endif %}
</div>
{% if not membership %}
{% set display_class = "hide" %}
{% else %}
{% set display_class = "" %}
{% endif %}
<ul class="nav nav-tabs mt-4">
<li class="nav-item">
<a class="nav-link" id="home" href="/courses/{{course.name}}/home{{ course.query_parameter }}">Home</a>
</li>
<li class="nav-item">
{% set lesson_index = course.get_lesson_index(membership.current_lesson) if membership and membership.current_lesson else '1.1' %}
<a class="nav-link" id="learn"
href="{{ course.get_learn_url(lesson_index) }}{{ course.query_parameter }}">Lessons</a>
</li>
<!-- <li class="nav-item">
<a class="nav-link" id="schedule" href="/courses/{{course.name}}/schedule">Schedule</a>
</li> -->
<li class="nav-item {{ display_class }}">
<a class="nav-link" id="members" href="/courses/{{course.name}}/members{{ course.query_parameter }}">Members</a>
</li>
<!-- <li class="nav-item {{ display_class }}">
<a class="nav-link" id="discussion" href="/courses/{{course.name}}/discuss">Discussion</a>
</li> -->
<!-- <li class="nav-item">
<a class="nav-link" id="about" href="/courses/{{course.name}}/about">About</a>
</li> -->
{% if membership and membership.batch and course.is_mentor(frappe.session.user) %}
<li class="nav-item">
<a class="nav-link" id="progress" href="/courses/{{course.name}}/progress{{ course.query_parameter }}">Progress</a>
</li>
{% endif %}
</ul>
{% block script %}
<script>
frappe.ready(() => {
var selector = document.querySelector(`a[href="${decodeURIComponent(window.location.pathname)}{{ course.query_parameter }}"]`)
if (selector) {
selector.classList.add('active');
}
else {
$("#learn").addClass('active')
}
})
</script>
{% endblock %}

View File

@@ -1,15 +1,53 @@
<div class="chapter-teaser"> <div class="chapter-teaser">
<div class="teaser-body"> <div class="teaser-body">
<h3 class="chapter-title"><span class="chapter-number">{{index}}</span> {{ chapter.title }}</h3> <div class="chapter-title mb-5 font-weight-bold"><span class="mr-1">{{index}}.</span> {{ chapter.title }}</div>
<div class="chapter-description"> <div class="chapter-description">
{{ chapter.description or "" }} {{ chapter.description or "" }}
</div> </div>
<div class="chapter-lessons"> <div class="chapter-lessons">
{% for lesson in chapter.get_lessons() %} {% for lesson in chapter.get_lessons() %}
<div class="lesson-teaser"> <div class="lesson-teaser">
{{lesson.title}} <a {% if show_link or lesson.include_in_preview %}
href="{{ course.get_learn_url(course.get_lesson_index(lesson.name)) }}{{course.query_parameter}}" {% else %} href="" class="no-preview"
{% endif %} data-course="{{ course.name }}">{{ lesson.title }}</a>
{% if show_progress and not course.is_mentor(frappe.session.user) and lesson.get_progress() %}
<span class="ml-5 badge p-2 {{ lesson.get_slugified_class() }}"> {{ lesson.get_progress() }}</span>
{% endif %}
</div> </div>
{% endfor %} {% endfor %}
</div> </div>
</div> </div>
</div> </div>
<script>
frappe.ready(() => {
var d;
$(".no-preview").click((e) => {
e.preventDefault();
e.stopPropagation();
e.stopImmediatePropagation();
var message = __("Please enroll for this course to access the lesson.");
var label = __("Checkout Upcoming Batches");
var action = "checkout_upcoming_batches";
d = frappe.msgprint({
title: __("This lesson is not available for preview!"),
message: message,
primary_action: {
"label": label,
"client_action": action,
}
});
})
window.redirect_to_login = () => {
window.location.href = `/login?redirect-to=/courses/${$(".no-preview").attr("data-course")}`
}
window.checkout_upcoming_batches = () => {
if ($(".upcoming").length > 0) {
$('html,body').animate({ scrollTop: $(".upcoming").offset().top }, 300);
}
frappe.hide_msgprint();
}
})
</script>

View File

@@ -0,0 +1,7 @@
<div class="mt-5">
<h3> Course Outline </h3>
{% for chapter in course.get_chapters() %}
{{ widgets.ChapterTeaser(index=loop.index, chapter=chapter, course=course, batch=batch, show_link=show_link, show_progress=show_progress)}}
{% endfor %}
</div>

View File

@@ -6,6 +6,10 @@
</div> </div>
</div> </div>
<div class="course-footer"> <div class="course-footer">
{% set batch = course.get_student_batch(frappe.session.user) %}
{% if batch %}
<a class="btn btn-secondary pull-right" href="/courses/{{course.name}}/{{batch.name}}/learn">Resume Course</a>
{% endif %}
<div class="course-author"> <div class="course-author">
{% with author = course.get_instructor() %} {% with author = course.get_instructor() %}
{{ widgets.Avatar(member=author, avatar_class="avatar-medium") }} <a href="/{{author.username}}">{{ author.full_name }}</a> {{ widgets.Avatar(member=author, avatar_class="avatar-medium") }} <a href="/{{author.username}}">{{ author.full_name }}</a>

View File

@@ -1,7 +1,7 @@
{% from "www/macros/livecode.html" import LiveCodeEditorJS, LiveCodeEditor with context %} {% from "www/macros/livecode.html" import LiveCodeEditorJS, LiveCodeEditor with context %}
<div class="exercise"> <div class="exercise">
<h2>{{ exercise.title }}</h2> <h2>Exercise {{exercise.index_label}}: {{ exercise.title }}</h2>
<div class="exercise-description">{{frappe.utils.md_to_html(exercise.description)}}</div> <div class="exercise-description">{{frappe.utils.md_to_html(exercise.description)}}</div>
{% if exercise.image %} {% if exercise.image %}
@@ -11,7 +11,7 @@
{% set submission = exercise.get_user_submission() %} {% set submission = exercise.get_user_submission() %}
{{ LiveCodeEditor(exercise.name, {{ LiveCodeEditor(exercise.name,
code=exercise.code, code=submission.solution if submission else exercise.code,
reset_code=exercise.code, reset_code=exercise.code,
is_exercise=True, is_exercise=True,
last_submitted=submission and submission.creation) }} last_submitted=submission and submission.creation) }}

View File

@@ -0,0 +1,6 @@
<div class="instructor">
{{ widgets.Avatar(member=instructor, avatar_class="avatar-medium") }}
<a class="ml-1 instructor-title" href="/{{instructor.username}}">{{ instructor.full_name }}</a>
<div class="instructor-subtitle">Course Creator</div>
<!-- <div class="instructor-subtitle">Created {{instructor.get_course_count()}} courses</div> -->
</div>

View File

@@ -0,0 +1,30 @@
<div class="batch">
<div class="batch-details">
<div class="">Session every {{batch.sessions_on}}</div>
<div>{{frappe.utils.format_time(batch.start_time, "short")}} -
{{frappe.utils.format_time(batch.end_time, "short")}}
</div>
<div>Starting {{frappe.utils.format_date(batch.start_date, "medium")}}</div>
<div class="course-type" style="color: #888; padding: 10px 0px;">mentors</div>
{% for m in course.get_mentors(batch.name) %}
<div>
{{ widgets.Avatar(member=m, avatar_class="avatar-medium" ) }}
<span class="instructor-title">{{m.full_name}}</span>
</div>
{% endfor %}
</div>
{% if can_manage or can_join %}
<div class="cta">
<div class="">
{% if can_manage %}
<a href="/courses/{{ course.name }}/home?batch={{ batch.name }}" class="btn btn-primary manage-batch" data-batch="{{ batch.name | urlencode }}"
data-course="{{ course.name | urlencode }}">Manage</a>
{% elif can_join %}
<button class="join-batch btn btn-secondary" data-batch="{{ batch.name | urlencode }}"
data-course="{{ course.name | urlencode }}">Join this Batch</button>
{% endif %}
</div>
</div>
{% endif %}
</div>

View File

@@ -0,0 +1,42 @@
import frappe
from frappe.core.doctype.user.user import User
from frappe.utils import cint
import hashlib
class CustomUser(User):
def get_course_count(self) -> int:
"""Returns the number of courses authored by this user.
"""
return frappe.db.count(
'LMS Course', {
'owner': self.email
})
def get_palette(self):
palette = [
['--orange-avatar-bg', '--orange-avatar-color'],
['--pink-avatar-bg', '--pink-avatar-color'],
['--blue-avatar-bg', '--blue-avatar-color'],
['--green-avatar-bg', '--green-avatar-color'],
['--dark-green-avatar-bg', '--dark-green-avatar-color'],
['--red-avatar-bg', '--red-avatar-color'],
['--yellow-avatar-bg', '--yellow-avatar-color'],
['--purple-avatar-bg', '--purple-avatar-color'],
['--gray-avatar-bg', '--gray-avatar-color0']
]
encoded_name = str(self.full_name).encode("utf-8")
hash_name = hashlib.md5(encoded_name).hexdigest()
idx = cint((int(hash_name[4:6], 16) + 1) / 5.33)
return palette[idx % 8]
def get_batch_count(self) -> int:
"""Returns the number of batches authored by this user.
"""
return frappe.db.count(
'LMS Batch Membership', {
'member': self.name,
'member_type': 'Mentor'
})

View File

@@ -2,3 +2,7 @@ community.patches.set_email_preferences
community.patches.change_name_for_community_members community.patches.change_name_for_community_members
community.patches.save_abbr_for_community_members community.patches.save_abbr_for_community_members
community.patches.create_mentor_request_email_templates community.patches.create_mentor_request_email_templates
community.patches.replace_member_with_user_in_batch_membership
community.patches.replace_member_with_user_in_course_mentor_mapping
community.patches.replace_member_with_user_in_lms_message
community.patches.replace_member_with_user_in_mentor_request

View File

@@ -0,0 +1,9 @@
from __future__ import unicode_literals
import frappe
def execute():
frappe.reload_doc("lms", "doctype", "lms_batch_membership")
memberships = frappe.get_all("LMS Batch Membership", ["member", "name"])
for membership in memberships:
email = frappe.db.get_value("Community Member", membership.member, "email")
frappe.db.set_value("LMS Batch Membership", membership.name, "member", email)

View File

@@ -0,0 +1,9 @@
from __future__ import unicode_literals
import frappe
def execute():
frappe.reload_doc("lms", "doctype", "lms_course_mentor_mapping")
mappings = frappe.get_all("LMS Course Mentor Mapping", ["mentor", "name"])
for mapping in mappings:
email = frappe.db.get_value("Community Member", mapping.mentor, "email")
frappe.db.set_value("LMS Course Mentor Mapping", mapping.name, "mentor", email)

View File

@@ -0,0 +1,10 @@
from __future__ import unicode_literals
import frappe
def execute():
frappe.reload_doc("lms", "doctype", "lms_message")
messages = frappe.get_all("LMS Message", ["author", "name"])
for message in messages:
user = frappe.db.get_value("Community Member", message.author, ["email", "full_name"], as_dict=True)
frappe.db.set_value("LMS Message", message.name, "author", user.email)
frappe.db.set_value("LMS Message", message.name, "author_name", user.full_name)

View File

@@ -0,0 +1,10 @@
from __future__ import unicode_literals
import frappe
def execute():
frappe.reload_doc("lms", "doctype", "lms_mentor_request")
requests = frappe.get_all("LMS Mentor Request", ["member", "name"])
for request in requests:
user = frappe.db.get_value("Community Member", request.member, ["email", "full_name"], as_dict=True)
frappe.db.set_value("LMS Mentor Request", request.name, "member", user.email)
frappe.db.set_value("LMS Mentor Request", request.name, "member_name", user.full_name)

66
community/plugins.py Normal file
View File

@@ -0,0 +1,66 @@
"""
The plugins module provides various plugins to change the default
behaviour some parts of the community app.
A site specify what plugins to use using appropriate entries in the frappe
hooks, written in the `hooks.py`.
This module exposes two plugins: ProfileTab and PageExtension.
The ProfileTab is used to specify any additional tabs to be displayed
on the profile page of the user.
The PageExtension is used to load additinal stylesheets and scripts to
be loaded in a webpage.
"""
class PageExtension:
"""PageExtension is a plugin to inject custom styles and scripts
into a web page.
The subclasses should overwrite the `render_header()` and
`render_footer()` methods to inject whatever styles/scripts into
the webpage.
"""
def render_header(self):
"""Returns the HTML snippet to be included in the head section
of the web page.
Typically used to include the stylesheets and javascripts to be
included in the <head> of the webpage.
"""
return ""
def render_footer(self):
"""Returns the HTML snippet to be included in the body tag at
the end of web page.
Typically used to include javascripts that need to be executed
after the page is loaded.
"""
return ""
class ProfileTab:
"""Base class for profile tabs.
Every subclass of ProfileTab must implement two methods:
- get_title()
- render()
"""
def __init__(self, user):
self.user = user
def get_title(self):
"""Returns the title of the tab.
Every subclass must implement this.
"""
raise NotImplementedError()
def render(self):
"""Renders the contents of the tab as HTML.
Every subclass must implement this.
"""
raise NotImplementedError()

View File

@@ -23,8 +23,7 @@
--cta-color: var(--c4); --cta-color: var(--c4);
--send-message: var(--c7); --send-message: var(--c7);
--received-message: var(--c8); --received-message: var(--c8);
--control-bg: var(--gray-100);
--primary-color: #08B74F !important;
} }
body { body {
@@ -84,6 +83,7 @@ body {
border-radius: 10px; border-radius: 10px;
margin: 10px 0px; margin: 10px 0px;
background: white; background: white;
box-shadow: 0px 5px 10px rgb(0 0 0 / 10%);
border: 1px solid #ddc; border: 1px solid #ddc;
} }
@@ -99,14 +99,6 @@ body {
border-top: 1px solid #ddc; border-top: 1px solid #ddc;
} }
.batch .cta button {
background: var(--cta-color);
color: white;
border: none;
border-radius: 5px;
padding: 5px 10px;
}
.batch .right { .batch .right {
float: right; float: right;
} }
@@ -129,44 +121,13 @@ img.profile-photo {
max-width: 100% max-width: 100%
} }
/* override style of base */
.message { .message {
border: 1px dashed var(--text-color); border: 1px dashed var(--text-color);
padding: 20px; padding: 20px;
border-radius: 10px; border-radius: 10px;
} }
.dashboard__profile {
width: 150px;
height: 155px;
border-radius: 50%;
}
.dashboard__profileSmall {
width: 59px;
height: 57px;
border-radius: 50%;
}
.dashboard__abbr {
font-size: 50px;
width: 155px;
height: 155px;
border-radius: 50%;
}
.dashboard__abbrSmall {
font-size: 20px;
width: 59px;
height: 57px;
border-radius: 50%;
}
.msger-inputarea { .msger-inputarea {
position: absolute;
bottom: 0;
width: 100%; width: 100%;
display: flex; display: flex;
padding: 10px; padding: 10px;
@@ -184,37 +145,6 @@ img.profile-photo {
flex: 1; flex: 1;
background: #ddd; background: #ddd;
} }
.msger-send-btn {
margin-left: 10px;
background: var(--cta-color);
color: #fff;
font-weight: bold;
cursor: pointer;
transition: background 0.23s;
}
.discussion {
border: 1px solid var(--text-color);
padding: 10px;
margin: 10px;
border-radius: 10px;
background: var(--received-message);
width: 50%;
display: flex;
flex-direction: column;
}
.is-author {
float: right;
background: var(--send-message);
}
.batch-header {
position: fixed;
top: 0;
background: var(--bg);
width: 100%;
}
.message-section { .message-section {
margin-left: 3%; margin-left: 3%;
@@ -227,3 +157,106 @@ img.profile-photo {
font-weight: 600; font-weight: 600;
line-height: 51px; line-height: 51px;
} }
section {
padding: 5rem 0 5rem 0;
}
.messages-container {
margin: 0 auto;
border: 1px solid black;
}
.messages {
overflow: auto;
height: 450px;
display: flex;
flex-direction: column;
align-items: flex-start;
padding: 8px;
list-style-type: none;
}
.messages li {
background: #F7F5F5;
border-radius: 8px;
padding: 8px;
margin: 2px 8px 2px 0;
width: 40%;
}
.messages li.ours {
align-self: flex-end;
margin: 2px 0 2px 8px;
background: var(--primary-color);
color: #fff
}
.message-para {
font-size: 20px;
}
.batch-header {
background: #eee;
border: 2px solid #ddd;
}
.page-card {
max-width: 360px;
padding: 15px;
margin: 70px auto;
border: 1px solid #d1d8dd;
border-radius: 4px;
background-color: #fff;
box-shadow: 0px 3px 6px rgba(0, 0, 0, 0.1);
}
.page-card .page-card-head {
padding: 10px 15px;
margin: -15px;
margin-bottom: 15px;
border-bottom: 1px solid #d1d8dd;
}
.page-card .page-card-head .indicator {
color: #36414C;
font-size: 14px;
}
.page-card .page-card-head .indicator::before {
margin: 0 6px 0.5px 0px;
}
.page-card .btn {
margin-top: 30px;
}
.partiallycomplete {
background: #FEF4E2;
color: #976417;
}
.partiallycomplete img {
background: #976417;
}
.complete {
background: #EAF5EE;
color: #38A160;
}
.complete img {
background: #38A160;
}
.incomplete {
background: #FEECEC;
color: #E24C4C;
}
.incomplete img {
background: #E24C4C;
}
.progress-image {
margin-right: 3px;
border-radius: 50px;
padding: 5px;
}

View File

@@ -1,5 +1,3 @@
@primary-color: #08B74F;
h2 { h2 {
margin: 20px 0px; margin: 20px 0px;
color: black; color: black;
@@ -12,6 +10,7 @@ h2 {
.teaser-body { .teaser-body {
padding: 20px; padding: 20px;
box-shadow: 0px 5px 10px rgb(0 0 0 / 10%)
} }
.teaser-footer { .teaser-footer {
padding: 20px; padding: 20px;
@@ -68,6 +67,20 @@ h2 {
} }
} }
.anchor_style {
color: inherit;
}
.anchor_style:hover {
text-decoration: none
}
.no-preview:hover {
cursor: pointer;
color: #2490ef;
}
section { section {
padding: 60px 0px; padding: 60px 0px;
} }
@@ -164,7 +177,6 @@ section.lightgray {
// } // }
.instructor-title { .instructor-title {
font-weight: bold;
color: black; color: black;
} }
@@ -181,11 +193,8 @@ section.lightgray {
.chapter-number { .chapter-number {
background: var(--text-color); background: var(--text-color);
color: white; color: white;
border-radius: 50%;
height: 24px; height: 24px;
min-width: 24px; min-width: 24px;
align-items: center;
padding: 5px 8px 2px 8px;
margin-right: 5px; margin-right: 5px;
} }
@@ -259,6 +268,7 @@ section.lightgray {
background-color: rgba(255, 255, 255, 0); background-color: rgba(255, 255, 255, 0);
max-height: 300px; max-height: 300px;
white-space: pre-wrap; white-space: pre-wrap;
word-wrap: break-word;
margin: 0px; margin: 0px;
margin-left: 20px; margin-left: 20px;
padding: 4px; padding: 4px;
@@ -289,9 +299,7 @@ section.lightgray {
} }
.lesson-teaser { .lesson-teaser {
font-weight: bold; line-height: 40px;
color: black;
padding-left: 20px;
} }
#hero h1 { #hero h1 {
@@ -312,3 +320,34 @@ section.lightgray {
border: 1px solid #ddd; border: 1px solid #ddd;
margin-bottom: 20px; margin-bottom: 20px;
} }
.svg-200 svg {
width: 200px;
height: 200px;
}
.livecode-editor-small .livecode-editor {
.CodeMirror-scroll {
max-height: 160px;
min-height: 160px;
}
canvas {
width: 150px;
height: 150px;
}
}
.mentor-dashboard {
margin-top: 20px;
.submission {
margin: 40px 0px 0px 20px;
}
}
.no-preview-message {
width: fit-content;
margin: 50px 0px 50px;
color: black;
}

View File

@@ -1,6 +1,5 @@
/* Define all your css variables here. */ /* Define all your css variables here. */
:root { :root {
--primary-color: #08B74F;
--tag-color: #737373; --tag-color: #737373;
--sidebar-bg: #F6F6F6; --sidebar-bg: #F6F6F6;
--sidebar-border: #C4C4C4; --sidebar-border: #C4C4C4;

Binary file not shown.

After

Width:  |  Height:  |  Size: 206 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 922 B

View File

@@ -0,0 +1,13 @@
<div class="discussion {% if message.is_author %} is-author {% endif %}">
<div class="d-flex justify-content-between">
<div class="font-weight-bold">
{{ message.author_name }}
</div>
<div class="text-muted">
{{ message.message_time }}
</div>
</div>
<div class="mt-5">
{{ message.message }}
</div>
</div>

View File

@@ -0,0 +1,40 @@
{% extends "templates/base.html" %}
{% block title %}About{% endblock %}
{% block head_include %}
<meta name="description" content="Courses" />
<meta name="keywords" content="" />
<link rel="stylesheet" href="/assets/frappe/css/font-awesome.css">
{% endblock %}
{% block content %}
<div class="container">
{{ widgets.BatchTabs(course=course, batch=batch) }}
<div class="tab-content" id="about">
{{ CourseBasicDetail(course)}}
<div class="d-flex align-items-center">
<div class="col-lg-4 col-md-12">
<div class="sidebar">
{{ widgets.InstructorSection(instructor=course.get_instructor()) }}
</div>
</div>
</div>
</div>
</div>
{% endblock %}
{% macro CourseBasicDetail(course) %}
<h2>{{course.title}}</h2>
<div class="course-description">
{{course.short_introduction}}
</div>
{% if course.video_link %}
<div class="preview-video">
<iframe width="560" height="315" src="{{course.video_link}}" title="YouTube video player" frameborder="0"
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
allowfullscreen></iframe>
</div>
{% endif %}
<h2>About the Course</h2>
<div>{{frappe.utils.md_to_html(course.description)}}</div>
{% endmacro %}

View File

@@ -0,0 +1,5 @@
import frappe
from . import utils
def get_context(context):
utils.get_common_context(context)

View File

@@ -1,6 +1,4 @@
{% extends "templates/base.html" %} {% extends "templates/base.html" %}
{% from "www/macros/sidebar.html" import Sidebar %}
{% from "www/macros/common_macro.html" import BatchHearder %}
{% block title %}Discuss{% endblock %} {% block title %}Discuss{% endblock %}
{% block head_include %} {% block head_include %}
@@ -11,15 +9,14 @@
{% endblock %} {% endblock %}
{% block content %} {% block content %}
{{ Sidebar(course_slug, batch_code) }}
<div class=""> <div class="container">
<div class="batch-header"> {{ widgets.BatchTabs(course=course, membership=membership) }}
{{ BatchHearder(course.name, member_count) }} <div class="messages-container mt-5">
</div> {{ widgets.BatchHeader(batch_name=batch.title, member_count=member_count)}}
<div class="messages"> <ol class="messages">
<div class="message-section">
{{ Messages(messages) }} {{ Messages(messages) }}
</div> </ol>
{{ TextArea() }} {{ TextArea() }}
</div> </div>
</div> </div>
@@ -27,25 +24,25 @@
{% macro Messages(messages) %} {% macro Messages(messages) %}
{% for message in messages %} {% for message in messages %}
<div class="discussion {% if message.is_author %} is-author {% endif %}"> <li class="{% if message.is_author %} ours {% endif %}">
<div class="d-flex justify-content-between"> <div class="d-flex justify-content-between">
<div class="font-weight-bold"> <div class="font-weight-bold">
{{ message.author_name }} {{ message.author_name }}
</div> </div>
<div class="text-muted"> <small class="">
{{ frappe.utils.pretty_date(message.creation) }} {{ frappe.utils.format_datetime(message.creation, "dd-mm-yyyy HH:mm") }}
</small>
</div> </div>
</div> <div class="message-para">
<div class="mt-5">
{{ message.message }} {{ message.message }}
</div> </div>
</div> </li>
{% endfor %} {% endfor %}
{% endmacro %} {% endmacro %}
{% macro TextArea() %} {% macro TextArea() %}
<form class="msger-inputarea"> <form class="msger-inputarea mb-1">
<input type="text" class="msger-input" placeholder="Write your message..."> <input type="text" class="msger-input" placeholder="Write your message...">
<button type="submit" class="msger-send-btn" data-batch="{{batch.name | urlencode }}">Send</button> <button type="submit" class="btn btn-primary msger-send-btn" data-batch="{{batch.name | urlencode }}">Send</button>
</form> </form>
{% endmacro %} {% endmacro %}

View File

@@ -11,7 +11,9 @@ frappe.ready(() => {
}) })
setTimeout(() => { setTimeout(() => {
window.scrollTo(0, document.body.scrollHeight); var message_element = document.getElementsByClassName("messages")[0]
message_element.scrollTo(0, message_element.scrollHeight);
document.getElementsByClassName("messages-container")[0].scrollIntoView({block: "center"})
}, 300); }, 300);
$(".msger-send-btn").click((e) => { $(".msger-send-btn").click((e) => {

View File

@@ -0,0 +1,8 @@
import frappe
from . import utils
def get_context(context):
utils.get_common_context(context)
context.messages = context.batch.get_messages()
if not context.membership:
utils.redirect_to_lesson(context.course)

View File

@@ -0,0 +1,61 @@
{% extends "templates/base.html" %}
{% block title %} Batch {% endblock %}
{% block head_include %}
<meta name="description" content="Courses" />
<meta name="keywords" content="" />
<link rel="stylesheet" href="/assets/frappe/css/font-awesome.css">
{% endblock %}
{% block content %}
<div class="container mt-5">
{{ widgets.BatchTabs(course=course, membership=membership) }}
<div class="course-details mt-5">
{{ widgets.CourseOutline(course=course, batch=batch, show_link=True, show_progress=True) }}
</div>
{% if batch %}
<div class="w-25">
<h3>Batch Schedule</h3>
{{ widgets.RenderBatch(course=course, batch=batch) }}
</div>
{% if batch.description %}
<div class="mt-5">
<h3>Batch Details</h3>
{{ frappe.utils.md_to_html(batch.description) }}
</div>
{% endif %}
{% endif %}
{% if course.is_mentor(frappe.session.user) %}
{% set invite_link = frappe.utils.get_url() + "/courses/" + course.name + "/join?batch=" + batch.name %}
<div class="">
<h3> Invite Members </h3>
<a href="" class="" id="invite-link" data-link="{{ invite_link }}">Get Batch Invitation
Link</a>
<small id="copy-message" class="text-muted" style="display: none;">Copied to Clipboard.</small>
</div>
{% endif %}
</div>
<script>
frappe.ready(() => {
$("#invite-link").click((e) => {
e.preventDefault();
var link_element = $("#invite-link");
var input_element = document.createElement("input");
input_element.value = link_element.attr("data-link")
document.body.appendChild(input_element);
input_element.select();
document.execCommand("copy");
input_element.remove();
$("#copy-message").slideDown(function () {
setTimeout(function () {
$("#copy-message").slideUp();
}, 2000);
});
})
})
</script>
{% endblock %}

View File

@@ -0,0 +1,5 @@
import frappe
from . import utils
def get_context(context):
utils.get_common_context(context)

Some files were not shown because too many files have changed in this diff Show More