Merge branch 'master' into iamsobanjaved/django-42-lts

This commit is contained in:
Awais Qureshi
2024-01-31 13:46:58 +05:00
committed by GitHub
30 changed files with 634 additions and 247 deletions

View File

@@ -3,7 +3,6 @@ Serializers for the content libraries REST API
"""
from rest_framework import serializers
from cms.djangoapps.contentstore.helpers import xblock_studio_url, xblock_type_display_name
from common.djangoapps.student.auth import has_studio_read_access
from xmodule.modulestore.django import modulestore
from xmodule.modulestore.exceptions import ItemNotFoundError
@@ -34,6 +33,8 @@ class StagedContentSerializer(serializers.ModelSerializer):
def get_block_type_display(self, obj):
""" Get the friendly name for this XBlock/component type """
from cms.djangoapps.contentstore.helpers import xblock_type_display_name
return xblock_type_display_name(obj.block_type)
@@ -50,6 +51,8 @@ class UserClipboardSerializer(serializers.Serializer):
def get_source_edit_url(self, obj) -> str:
""" Get the URL where the user can edit the given XBlock, if it exists """
from cms.djangoapps.contentstore.helpers import xblock_studio_url
request = self.context.get("request", None)
user = request.user if request else None
if not user:

View File

@@ -65,6 +65,7 @@ You have the following settings to customize the behavior of your reports.
- ``ANONYMOUS_SURVEY_REPORT``: This is a boolean to specify if you want to use your LMS domain as ID for your report or to send the information anonymously with a UUID. By default, this setting is False.
- ``SURVEY_REPORT_ENABLE``: This is a boolean to specify if you want to enable or disable the survey report feature completely. The banner will disappear and the report generation will be disabled if set to False. By default, this setting is True.
About the Survey Report Admin Banner
-------------------------------------
@@ -74,4 +75,4 @@ This app implements a banner to make it easy for the Open edX operators to gener
.. image:: docs/_images/survey_report_banner.png
:alt: Survey Report Banner
**Note:** The banner will appear if a survey report is not sent in the months defined in the ``context_processor`` file, by default, is set to appear monthly.
**Note:** The banner will appear if a survey report is not sent in the months defined in the ``context_processor`` file, by default, is set to appear every 6 months.

View File

@@ -4,6 +4,7 @@ Django Admin page for SurveyReport.
from django.contrib import admin
from django.conf import settings
from .models import SurveyReport
from .api import send_report_to_external_api
@@ -21,7 +22,7 @@ class SurveyReportAdmin(admin.ModelAdmin):
)
list_display = (
'id', 'summary', 'created_at', 'state'
'id', 'summary', 'created_at', 'report_state'
)
actions = ['send_report']
@@ -80,4 +81,18 @@ class SurveyReportAdmin(admin.ModelAdmin):
del actions['delete_selected']
return actions
admin.site.register(SurveyReport, SurveyReportAdmin)
def report_state(self, obj):
"""
Method to define the custom State column with the new "send" state,
to avoid modifying the current models.
"""
try:
if obj.surveyreportupload_set.last().is_uploaded():
return "Sent"
except AttributeError:
return obj.state.capitalize()
report_state.short_description = 'State'
if settings.SURVEY_REPORT_ENABLE:
admin.site.register(SurveyReport, SurveyReportAdmin)

View File

@@ -45,6 +45,8 @@ def get_report_data() -> dict:
def generate_report() -> None:
""" Generate a report with relevant data."""
if not settings.SURVEY_REPORT_ENABLE:
raise Exception("Survey report generation is not enabled")
data = {}
survey_report = SurveyReport(**data)
survey_report.save()

View File

@@ -1,34 +1,64 @@
"""
This is the survey report contex_processor modules
This module provides context processors for integrating survey report functionality
into Django admin sites.
This is meant to determine the visibility of the survey report banner
across all admin pages in case a survey report has not been generated
It includes functions for determining whether to display a survey report banner and
calculating the date threshold for displaying the banner.
Functions:
- admin_extra_context(request):
Sends extra context to every admin site, determining whether to display the
survey report banner based on defined settings and conditions.
- should_show_survey_report_banner():
Determines whether to show the survey report banner based on the threshold.
- get_months_threshold(months):
Calculates the date threshold based on the specified number of months.
Dependencies:
- Django: settings, reverse, shortcuts
- datetime: datetime
- dateutil.relativedelta: relativedelta
Usage:
This module is designed to be imported into Django projects with admin functionality.
It enhances the admin interface by providing dynamic context for displaying a survey
report banner based on defined conditions and settings.
"""
from datetime import datetime
from dateutil.relativedelta import relativedelta # for months test
from .models import SurveyReport
from django.urls import reverse
from django.conf import settings
from django.urls import reverse
from datetime import datetime
from dateutil.relativedelta import relativedelta
from .models import SurveyReport
def admin_extra_context(request):
"""
This function sends extra context to every admin site
The current treshhold to show the banner is one month but this can be redefined in the future
This function sends extra context to every admin site.
The current threshold to show the banner is one month but this can be redefined in the future.
"""
months = settings.SURVEY_REPORT_CHECK_THRESHOLD
if not request.path.startswith(reverse('admin:index')):
return {'show_survey_report_banner': False, }
if not settings.SURVEY_REPORT_ENABLE or not request.path.startswith(reverse('admin:index')):
return {'show_survey_report_banner': False}
return {'show_survey_report_banner': should_show_survey_report_banner()}
def should_show_survey_report_banner():
"""
Determine whether to show the survey report banner based on the threshold.
"""
months_threshold = get_months_threshold(settings.SURVEY_REPORT_CHECK_THRESHOLD)
try:
latest_report = SurveyReport.objects.latest('created_at')
months_treshhold = datetime.today().date() - relativedelta(months=months) # Calculate date one month ago
show_survey_report_banner = latest_report.created_at.date() <= months_treshhold
return latest_report.created_at.date() <= months_threshold
except SurveyReport.DoesNotExist:
show_survey_report_banner = True
return True
return {'show_survey_report_banner': show_survey_report_banner, }
def get_months_threshold(months):
"""
Calculate the date threshold based on the specified number of months.
"""
return datetime.today().date() - relativedelta(months=months)

View File

@@ -11,64 +11,11 @@
<p>If you agree and want to send a report you can click the button below. You can always send reports and see the status of reports you have sent in the past at <a href="/admin/survey_report/surveyreport/">admin/survey_report/surveyreport/</a> .</p>
</div>
<div style="display: flex; justify-content: flex-end; padding: 0 37px 17px;">
<button id="dismissButton" type="button" style="background-color:var(--close-button-bg); color: var(--button-fg); border: none; border-radius: 4px; padding: 10px 20px; margin-right: 10px; cursor: pointer;">Dismiss</button>
<form id='survey_report_form' method="POST" action="/survey_report/generate_report" style="margin: 0; padding: 0;">
<form id='survey_report_form' method="POST" action="/survey_report/generate_report" style="margin: 0; padding: 0;">
{% csrf_token %}
<button type="submit" style="background-color: #377D4D; color: var(--button-fg); border: none; border-radius: 4px; padding: 10px 20px; cursor: pointer;">Send Report</button>
</form>
</div>
</div>
<div id="thankYouMessage" style="display: none; background-color: var(--darkened-bg); padding: 20px 40px; margin-bottom: 30px;box-shadow: rgb(0 0 0 / 18%) 0px 3px 5px;">
<div style="display: flex; align-items: center;">
<svg xmlns="http://www.w3.org/2000/svg" width="30" height="30" viewBox="0 0 24 24">
<g fill="#377D4D"><path d="M22 12c0 5.523-4.477 10-10 10S2 17.523 2 12S6.477 2 12 2s10 4.477 10 10Z"></path>
<path d="M16.03 8.97a.75.75 0 0 1 0 1.06l-5 5a.75.75 0 0 1-1.06 0l-2-2a.75.75 0 1 1 1.06-1.06l1.47 1.47l2.235-2.236L14.97 8.97a.75.75 0 0 1 1.06 0Z" fill="#FFF"></path>
</g>
</svg>
<span style="font-size: 16px; margin-left: 15px;">Thank you for your collaboration and support! Your contribution is greatly appreciated and will help us continue to improve.</span>
</div>
</div>
{% endif %}
<!-- The original content of the block -->
<script>
$(document).ready(function(){
$('#dismissButton').click(function() {
$('#originalContent').slideUp('slow', function() {
// If you want to do something after the slide-up, do it here.
// For example, you can hide the entire div:
// $(this).hide();
});
});
// When the form is submitted
$("#survey_report_form").submit(function(event){
event.preventDefault(); // Prevent the form from submitting traditionally
// Make the AJAX request
$.ajax({
url: $(this).attr("action"),
type: $(this).attr("method"),
data: $(this).serialize(),
success: function(response){
// Hide the original content block
$("#originalContent").slideUp(400, function() {
//$(this).css('display', 'none');
// Show the thank-you message block with slide down effect
$("#thankYouMessage").slideDown(400, function() {
// Wait for 3 seconds (3000 milliseconds) and then slide up the thank-you message
setTimeout(function() {
$("#thankYouMessage").slideUp(400);
}, 3000);
});
});
},
error: function(error){
// Handle any errors
console.error("Error sending report:", error);
}
});
});
});
</script>
{% endblock %}

View File

@@ -5,7 +5,7 @@
<li>
<form method="POST" action="{% url 'openedx.generate_survey_report' %}" class="inline">
{% csrf_token %}
<input type="submit" value="Generate Report" class="default" name="_generatereport">
<input type="submit" value="Generate and Send Report" class="default" name="_sendreport">
</form>
</li>
</ul>