repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
39
1.84M
func_code_tokens
listlengths
15
672k
func_documentation_string
stringlengths
1
47.2k
func_documentation_tokens
listlengths
1
3.92k
split_name
stringclasses
1 value
func_code_url
stringlengths
85
339
django-danceschool/django-danceschool
danceschool/guestlist/models.py
GuestList.getDayStart
def getDayStart(self, dateTime): ''' Ensure local time and get the beginning of the day ''' return ensure_localtime(dateTime).replace(hour=0,minute=0,second=0,microsecond=0)
python
def getDayStart(self, dateTime): return ensure_localtime(dateTime).replace(hour=0,minute=0,second=0,microsecond=0)
[ "def", "getDayStart", "(", "self", ",", "dateTime", ")", ":", "return", "ensure_localtime", "(", "dateTime", ")", ".", "replace", "(", "hour", "=", "0", ",", "minute", "=", "0", ",", "second", "=", "0", ",", "microsecond", "=", "0", ")" ]
Ensure local time and get the beginning of the day
[ "Ensure", "local", "time", "and", "get", "the", "beginning", "of", "the", "day" ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/guestlist/models.py#L69-L71
django-danceschool/django-danceschool
danceschool/guestlist/models.py
GuestList.getComponentFilters
def getComponentFilters(self,component,event=None,dateTime=None): ''' Get a parsimonious set of intervals and the associated Q() objects based on the occurrences of a specified event, and the rule that implicitly defines the start and end of each interval. ''' # Limit to the staff member or staff category specified by the rule. if component.staffMember: filters = Q(pk=component.staffMember.pk) else: filters = Q(eventstaffmember__category=component.staffCategory) # Handle 'Always' and 'EventOnly' rules first, because they do not require an analysis of intervals. if component.admissionRule == 'EventOnly' and event: # Skip the analysis of intervals and include only those who are staffed for the event. return Q(filters & Q(eventstaffmember__event=event)) elif component.admissionRule in ['Always','EventOnly']: # If 'Always' or no event is specified, include all associated staff return Q(filters) # Start with the event occurrence intervals, or with the specified time. if event: intervals = [(x.startTime,x.endTime) for x in event.eventoccurrence_set.all()] elif dateTime: intervals = [(dateTime,dateTime)] else: raise ValueError(_('Must provide either an event or a datetime to get interval queries.')) if component.admissionRule == 'Day': # The complete days of each event occurrence intervals = [ (self.getDayStart(x[0]),self.getDayStart(x[1]) + timedelta(days=1)) for x in intervals ] elif component.admissionRule == 'Week': # The complete weeks of each event occurrence intervals = [ ( self.getDayStart(x[0]) - timedelta(days=x[0].weekday()), self.getDayStart(x[1]) - timedelta(days=x[1].weekday() - 7) ) for x in intervals ] elif component.admissionRule == 'Month': # The complete month of each event occurrence intervals = [ ( self.getDayStart(x[0]).replace(day=1), self.getDayStart(x[1]).replace(day=1) + relativedelta(months=1) ) for x in intervals ] elif component.admissionRule == 'Year': # The complete years of each event occurrence intervals = [ ( self.getDayStart(x[0]).replace(month=1,day=1), self.getDayStart(x[1]).replace(year=x[1].year + 1,month=1,day=1) ) for x in intervals ] else: # This is a failsafe that will always evaluate as False. return Q(pk__isnull=True) # Use intervaltree to create the most parsimonious set of intervals for this interval # and then filter on those intervals intervals = [sorted(x) for x in intervals] tree = IntervalTree.from_tuples(intervals) tree.merge_overlaps() # Since we are OR appending, start with something that is always False. intervalFilters = Q(pk__isnull=True) for item in tree.items(): intervalFilters = intervalFilters | Q( Q(eventstaffmember__event__eventoccurrence__endTime__gte=item[0]) & Q(eventstaffmember__event__eventoccurrence__startTime__lte=item[1]) ) return Q(filters & intervalFilters)
python
def getComponentFilters(self,component,event=None,dateTime=None): if component.staffMember: filters = Q(pk=component.staffMember.pk) else: filters = Q(eventstaffmember__category=component.staffCategory) if component.admissionRule == 'EventOnly' and event: return Q(filters & Q(eventstaffmember__event=event)) elif component.admissionRule in ['Always','EventOnly']: return Q(filters) if event: intervals = [(x.startTime,x.endTime) for x in event.eventoccurrence_set.all()] elif dateTime: intervals = [(dateTime,dateTime)] else: raise ValueError(_('Must provide either an event or a datetime to get interval queries.')) if component.admissionRule == 'Day': intervals = [ (self.getDayStart(x[0]),self.getDayStart(x[1]) + timedelta(days=1)) for x in intervals ] elif component.admissionRule == 'Week': intervals = [ ( self.getDayStart(x[0]) - timedelta(days=x[0].weekday()), self.getDayStart(x[1]) - timedelta(days=x[1].weekday() - 7) ) for x in intervals ] elif component.admissionRule == 'Month': intervals = [ ( self.getDayStart(x[0]).replace(day=1), self.getDayStart(x[1]).replace(day=1) + relativedelta(months=1) ) for x in intervals ] elif component.admissionRule == 'Year': intervals = [ ( self.getDayStart(x[0]).replace(month=1,day=1), self.getDayStart(x[1]).replace(year=x[1].year + 1,month=1,day=1) ) for x in intervals ] else: return Q(pk__isnull=True) intervals = [sorted(x) for x in intervals] tree = IntervalTree.from_tuples(intervals) tree.merge_overlaps() intervalFilters = Q(pk__isnull=True) for item in tree.items(): intervalFilters = intervalFilters | Q( Q(eventstaffmember__event__eventoccurrence__endTime__gte=item[0]) & Q(eventstaffmember__event__eventoccurrence__startTime__lte=item[1]) ) return Q(filters & intervalFilters)
[ "def", "getComponentFilters", "(", "self", ",", "component", ",", "event", "=", "None", ",", "dateTime", "=", "None", ")", ":", "# Limit to the staff member or staff category specified by the rule.", "if", "component", ".", "staffMember", ":", "filters", "=", "Q", "(", "pk", "=", "component", ".", "staffMember", ".", "pk", ")", "else", ":", "filters", "=", "Q", "(", "eventstaffmember__category", "=", "component", ".", "staffCategory", ")", "# Handle 'Always' and 'EventOnly' rules first, because they do not require an analysis of intervals.", "if", "component", ".", "admissionRule", "==", "'EventOnly'", "and", "event", ":", "# Skip the analysis of intervals and include only those who are staffed for the event.", "return", "Q", "(", "filters", "&", "Q", "(", "eventstaffmember__event", "=", "event", ")", ")", "elif", "component", ".", "admissionRule", "in", "[", "'Always'", ",", "'EventOnly'", "]", ":", "# If 'Always' or no event is specified, include all associated staff", "return", "Q", "(", "filters", ")", "# Start with the event occurrence intervals, or with the specified time.", "if", "event", ":", "intervals", "=", "[", "(", "x", ".", "startTime", ",", "x", ".", "endTime", ")", "for", "x", "in", "event", ".", "eventoccurrence_set", ".", "all", "(", ")", "]", "elif", "dateTime", ":", "intervals", "=", "[", "(", "dateTime", ",", "dateTime", ")", "]", "else", ":", "raise", "ValueError", "(", "_", "(", "'Must provide either an event or a datetime to get interval queries.'", ")", ")", "if", "component", ".", "admissionRule", "==", "'Day'", ":", "# The complete days of each event occurrence", "intervals", "=", "[", "(", "self", ".", "getDayStart", "(", "x", "[", "0", "]", ")", ",", "self", ".", "getDayStart", "(", "x", "[", "1", "]", ")", "+", "timedelta", "(", "days", "=", "1", ")", ")", "for", "x", "in", "intervals", "]", "elif", "component", ".", "admissionRule", "==", "'Week'", ":", "# The complete weeks of each event occurrence", "intervals", "=", "[", "(", "self", ".", "getDayStart", "(", "x", "[", "0", "]", ")", "-", "timedelta", "(", "days", "=", "x", "[", "0", "]", ".", "weekday", "(", ")", ")", ",", "self", ".", "getDayStart", "(", "x", "[", "1", "]", ")", "-", "timedelta", "(", "days", "=", "x", "[", "1", "]", ".", "weekday", "(", ")", "-", "7", ")", ")", "for", "x", "in", "intervals", "]", "elif", "component", ".", "admissionRule", "==", "'Month'", ":", "# The complete month of each event occurrence", "intervals", "=", "[", "(", "self", ".", "getDayStart", "(", "x", "[", "0", "]", ")", ".", "replace", "(", "day", "=", "1", ")", ",", "self", ".", "getDayStart", "(", "x", "[", "1", "]", ")", ".", "replace", "(", "day", "=", "1", ")", "+", "relativedelta", "(", "months", "=", "1", ")", ")", "for", "x", "in", "intervals", "]", "elif", "component", ".", "admissionRule", "==", "'Year'", ":", "# The complete years of each event occurrence", "intervals", "=", "[", "(", "self", ".", "getDayStart", "(", "x", "[", "0", "]", ")", ".", "replace", "(", "month", "=", "1", ",", "day", "=", "1", ")", ",", "self", ".", "getDayStart", "(", "x", "[", "1", "]", ")", ".", "replace", "(", "year", "=", "x", "[", "1", "]", ".", "year", "+", "1", ",", "month", "=", "1", ",", "day", "=", "1", ")", ")", "for", "x", "in", "intervals", "]", "else", ":", "# This is a failsafe that will always evaluate as False.", "return", "Q", "(", "pk__isnull", "=", "True", ")", "# Use intervaltree to create the most parsimonious set of intervals for this interval", "# and then filter on those intervals", "intervals", "=", "[", "sorted", "(", "x", ")", "for", "x", "in", "intervals", "]", "tree", "=", "IntervalTree", ".", "from_tuples", "(", "intervals", ")", "tree", ".", "merge_overlaps", "(", ")", "# Since we are OR appending, start with something that is always False.", "intervalFilters", "=", "Q", "(", "pk__isnull", "=", "True", ")", "for", "item", "in", "tree", ".", "items", "(", ")", ":", "intervalFilters", "=", "intervalFilters", "|", "Q", "(", "Q", "(", "eventstaffmember__event__eventoccurrence__endTime__gte", "=", "item", "[", "0", "]", ")", "&", "Q", "(", "eventstaffmember__event__eventoccurrence__startTime__lte", "=", "item", "[", "1", "]", ")", ")", "return", "Q", "(", "filters", "&", "intervalFilters", ")" ]
Get a parsimonious set of intervals and the associated Q() objects based on the occurrences of a specified event, and the rule that implicitly defines the start and end of each interval.
[ "Get", "a", "parsimonious", "set", "of", "intervals", "and", "the", "associated", "Q", "()", "objects", "based", "on", "the", "occurrences", "of", "a", "specified", "event", "and", "the", "rule", "that", "implicitly", "defines", "the", "start", "and", "end", "of", "each", "interval", "." ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/guestlist/models.py#L73-L150
django-danceschool/django-danceschool
danceschool/guestlist/models.py
GuestList.getListForEvent
def getListForEvent(self, event=None): ''' Get the list of names associated with a particular event. ''' names = list(self.guestlistname_set.annotate( guestType=Case( When(notes__isnull=False, then=F('notes')), default=Value(ugettext('Manually Added')), output_field=models.CharField() ) ).values('firstName','lastName','guestType')) # Component-by-component, OR append filters to an initial filter that always # evaluates to False. components = self.guestlistcomponent_set.all() filters = Q(pk__isnull=True) # Add prior staff based on the component rule. for component in components: if event and self.appliesToEvent(event): filters = filters | self.getComponentFilters(component,event=event) else: filters = filters | self.getComponentFilters(component,dateTime=timezone.now()) # Add all event staff if that box is checked (no need for separate components) if self.includeStaff and event and self.appliesToEvent(event): filters = filters | Q(eventstaffmember__event=event) # Execute the constructed query and add the names of staff names += list(StaffMember.objects.filter(filters).annotate( guestType=Case( When(eventstaffmember__event=event, then=Concat(Value('Event Staff: '), 'eventstaffmember__category__name')), default=Value(ugettext('Other Staff')), output_field=models.CharField() ) ).distinct().values('firstName','lastName','guestType')) if self.includeRegistrants and event and self.appliesToEvent(event): names += list(Registration.objects.filter(eventregistration__event=event).annotate( guestType=Value(_('Registered'),output_field=models.CharField()) ).values('firstName','lastName','guestType')) return names
python
def getListForEvent(self, event=None): names = list(self.guestlistname_set.annotate( guestType=Case( When(notes__isnull=False, then=F('notes')), default=Value(ugettext('Manually Added')), output_field=models.CharField() ) ).values('firstName','lastName','guestType')) components = self.guestlistcomponent_set.all() filters = Q(pk__isnull=True) for component in components: if event and self.appliesToEvent(event): filters = filters | self.getComponentFilters(component,event=event) else: filters = filters | self.getComponentFilters(component,dateTime=timezone.now()) if self.includeStaff and event and self.appliesToEvent(event): filters = filters | Q(eventstaffmember__event=event) names += list(StaffMember.objects.filter(filters).annotate( guestType=Case( When(eventstaffmember__event=event, then=Concat(Value('Event Staff: '), 'eventstaffmember__category__name')), default=Value(ugettext('Other Staff')), output_field=models.CharField() ) ).distinct().values('firstName','lastName','guestType')) if self.includeRegistrants and event and self.appliesToEvent(event): names += list(Registration.objects.filter(eventregistration__event=event).annotate( guestType=Value(_('Registered'),output_field=models.CharField()) ).values('firstName','lastName','guestType')) return names
[ "def", "getListForEvent", "(", "self", ",", "event", "=", "None", ")", ":", "names", "=", "list", "(", "self", ".", "guestlistname_set", ".", "annotate", "(", "guestType", "=", "Case", "(", "When", "(", "notes__isnull", "=", "False", ",", "then", "=", "F", "(", "'notes'", ")", ")", ",", "default", "=", "Value", "(", "ugettext", "(", "'Manually Added'", ")", ")", ",", "output_field", "=", "models", ".", "CharField", "(", ")", ")", ")", ".", "values", "(", "'firstName'", ",", "'lastName'", ",", "'guestType'", ")", ")", "# Component-by-component, OR append filters to an initial filter that always", "# evaluates to False.", "components", "=", "self", ".", "guestlistcomponent_set", ".", "all", "(", ")", "filters", "=", "Q", "(", "pk__isnull", "=", "True", ")", "# Add prior staff based on the component rule.", "for", "component", "in", "components", ":", "if", "event", "and", "self", ".", "appliesToEvent", "(", "event", ")", ":", "filters", "=", "filters", "|", "self", ".", "getComponentFilters", "(", "component", ",", "event", "=", "event", ")", "else", ":", "filters", "=", "filters", "|", "self", ".", "getComponentFilters", "(", "component", ",", "dateTime", "=", "timezone", ".", "now", "(", ")", ")", "# Add all event staff if that box is checked (no need for separate components)", "if", "self", ".", "includeStaff", "and", "event", "and", "self", ".", "appliesToEvent", "(", "event", ")", ":", "filters", "=", "filters", "|", "Q", "(", "eventstaffmember__event", "=", "event", ")", "# Execute the constructed query and add the names of staff", "names", "+=", "list", "(", "StaffMember", ".", "objects", ".", "filter", "(", "filters", ")", ".", "annotate", "(", "guestType", "=", "Case", "(", "When", "(", "eventstaffmember__event", "=", "event", ",", "then", "=", "Concat", "(", "Value", "(", "'Event Staff: '", ")", ",", "'eventstaffmember__category__name'", ")", ")", ",", "default", "=", "Value", "(", "ugettext", "(", "'Other Staff'", ")", ")", ",", "output_field", "=", "models", ".", "CharField", "(", ")", ")", ")", ".", "distinct", "(", ")", ".", "values", "(", "'firstName'", ",", "'lastName'", ",", "'guestType'", ")", ")", "if", "self", ".", "includeRegistrants", "and", "event", "and", "self", ".", "appliesToEvent", "(", "event", ")", ":", "names", "+=", "list", "(", "Registration", ".", "objects", ".", "filter", "(", "eventregistration__event", "=", "event", ")", ".", "annotate", "(", "guestType", "=", "Value", "(", "_", "(", "'Registered'", ")", ",", "output_field", "=", "models", ".", "CharField", "(", ")", ")", ")", ".", "values", "(", "'firstName'", ",", "'lastName'", ",", "'guestType'", ")", ")", "return", "names" ]
Get the list of names associated with a particular event.
[ "Get", "the", "list", "of", "names", "associated", "with", "a", "particular", "event", "." ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/guestlist/models.py#L152-L191
django-danceschool/django-danceschool
danceschool/guestlist/models.py
GuestListComponent.clean
def clean(self): ''' Either staffCategory or staffMember must be filled in, but not both. ''' if not self.staffCategory and not self.staffMember: raise ValidationError(_('Either staff category or staff member must be specified.')) if self.staffCategory and self.staffMember: raise ValidationError(_('Specify either a staff category or a staff member, not both.'))
python
def clean(self): if not self.staffCategory and not self.staffMember: raise ValidationError(_('Either staff category or staff member must be specified.')) if self.staffCategory and self.staffMember: raise ValidationError(_('Specify either a staff category or a staff member, not both.'))
[ "def", "clean", "(", "self", ")", ":", "if", "not", "self", ".", "staffCategory", "and", "not", "self", ".", "staffMember", ":", "raise", "ValidationError", "(", "_", "(", "'Either staff category or staff member must be specified.'", ")", ")", "if", "self", ".", "staffCategory", "and", "self", ".", "staffMember", ":", "raise", "ValidationError", "(", "_", "(", "'Specify either a staff category or a staff member, not both.'", ")", ")" ]
Either staffCategory or staffMember must be filled in, but not both.
[ "Either", "staffCategory", "or", "staffMember", "must", "be", "filled", "in", "but", "not", "both", "." ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/guestlist/models.py#L237-L242
django-danceschool/django-danceschool
danceschool/core/ajax.py
updateSeriesAttributes
def updateSeriesAttributes(request): ''' This function handles the filtering of available series classes and seriesteachers when a series is chosen on the Substitute Teacher reporting form. ''' if request.method == 'POST' and request.POST.get('event'): series_option = request.POST.get('event') or None seriesClasses = EventOccurrence.objects.filter(event__id=series_option) seriesTeachers = SeriesTeacher.objects.filter(event__id=series_option) else: # Only return attributes for valid requests return JsonResponse({}) outClasses = {} for option in seriesClasses: outClasses[str(option.id)] = option.__str__() outTeachers = {} for option in seriesTeachers: outTeachers[str(option.id)] = option.__str__() return JsonResponse({ 'id_occurrences': outClasses, 'id_replacedStaffMember': outTeachers, })
python
def updateSeriesAttributes(request): if request.method == 'POST' and request.POST.get('event'): series_option = request.POST.get('event') or None seriesClasses = EventOccurrence.objects.filter(event__id=series_option) seriesTeachers = SeriesTeacher.objects.filter(event__id=series_option) else: return JsonResponse({}) outClasses = {} for option in seriesClasses: outClasses[str(option.id)] = option.__str__() outTeachers = {} for option in seriesTeachers: outTeachers[str(option.id)] = option.__str__() return JsonResponse({ 'id_occurrences': outClasses, 'id_replacedStaffMember': outTeachers, })
[ "def", "updateSeriesAttributes", "(", "request", ")", ":", "if", "request", ".", "method", "==", "'POST'", "and", "request", ".", "POST", ".", "get", "(", "'event'", ")", ":", "series_option", "=", "request", ".", "POST", ".", "get", "(", "'event'", ")", "or", "None", "seriesClasses", "=", "EventOccurrence", ".", "objects", ".", "filter", "(", "event__id", "=", "series_option", ")", "seriesTeachers", "=", "SeriesTeacher", ".", "objects", ".", "filter", "(", "event__id", "=", "series_option", ")", "else", ":", "# Only return attributes for valid requests\r", "return", "JsonResponse", "(", "{", "}", ")", "outClasses", "=", "{", "}", "for", "option", "in", "seriesClasses", ":", "outClasses", "[", "str", "(", "option", ".", "id", ")", "]", "=", "option", ".", "__str__", "(", ")", "outTeachers", "=", "{", "}", "for", "option", "in", "seriesTeachers", ":", "outTeachers", "[", "str", "(", "option", ".", "id", ")", "]", "=", "option", ".", "__str__", "(", ")", "return", "JsonResponse", "(", "{", "'id_occurrences'", ":", "outClasses", ",", "'id_replacedStaffMember'", ":", "outTeachers", ",", "}", ")" ]
This function handles the filtering of available series classes and seriesteachers when a series is chosen on the Substitute Teacher reporting form.
[ "This", "function", "handles", "the", "filtering", "of", "available", "series", "classes", "and", "seriesteachers", "when", "a", "series", "is", "chosen", "on", "the", "Substitute", "Teacher", "reporting", "form", "." ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/core/ajax.py#L54-L78
django-danceschool/django-danceschool
danceschool/core/ajax.py
processCheckIn
def processCheckIn(request): ''' This function handles the Ajax call made when a user is marked as checked in ''' if request.method == 'POST': event_id = request.POST.get('event_id') reg_ids = request.POST.getlist('reg_id') if not event_id: return HttpResponse(_("Error at start.")) # Get all possible registrations, so that we can set those that are not included to False (and set those that are included to True) all_eventreg = list(EventRegistration.objects.filter(event__id=event_id)) for this_reg in all_eventreg: if str(this_reg.registration.id) in reg_ids and not this_reg.checkedIn: this_reg.checkedIn = True this_reg.save() elif str(this_reg.registration.id) not in reg_ids and this_reg.checkedIn: this_reg.checkedIn = False this_reg.save() return HttpResponse("OK.")
python
def processCheckIn(request): if request.method == 'POST': event_id = request.POST.get('event_id') reg_ids = request.POST.getlist('reg_id') if not event_id: return HttpResponse(_("Error at start.")) all_eventreg = list(EventRegistration.objects.filter(event__id=event_id)) for this_reg in all_eventreg: if str(this_reg.registration.id) in reg_ids and not this_reg.checkedIn: this_reg.checkedIn = True this_reg.save() elif str(this_reg.registration.id) not in reg_ids and this_reg.checkedIn: this_reg.checkedIn = False this_reg.save() return HttpResponse("OK.")
[ "def", "processCheckIn", "(", "request", ")", ":", "if", "request", ".", "method", "==", "'POST'", ":", "event_id", "=", "request", ".", "POST", ".", "get", "(", "'event_id'", ")", "reg_ids", "=", "request", ".", "POST", ".", "getlist", "(", "'reg_id'", ")", "if", "not", "event_id", ":", "return", "HttpResponse", "(", "_", "(", "\"Error at start.\"", ")", ")", "# Get all possible registrations, so that we can set those that are not included to False (and set those that are included to True)\r", "all_eventreg", "=", "list", "(", "EventRegistration", ".", "objects", ".", "filter", "(", "event__id", "=", "event_id", ")", ")", "for", "this_reg", "in", "all_eventreg", ":", "if", "str", "(", "this_reg", ".", "registration", ".", "id", ")", "in", "reg_ids", "and", "not", "this_reg", ".", "checkedIn", ":", "this_reg", ".", "checkedIn", "=", "True", "this_reg", ".", "save", "(", ")", "elif", "str", "(", "this_reg", ".", "registration", ".", "id", ")", "not", "in", "reg_ids", "and", "this_reg", ".", "checkedIn", ":", "this_reg", ".", "checkedIn", "=", "False", "this_reg", ".", "save", "(", ")", "return", "HttpResponse", "(", "\"OK.\"", ")" ]
This function handles the Ajax call made when a user is marked as checked in
[ "This", "function", "handles", "the", "Ajax", "call", "made", "when", "a", "user", "is", "marked", "as", "checked", "in" ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/core/ajax.py#L81-L103
django-danceschool/django-danceschool
danceschool/core/ajax.py
getEmailTemplate
def getEmailTemplate(request): ''' This function handles the Ajax call made when a user wants a specific email template ''' if request.method != 'POST': return HttpResponse(_('Error, no POST data.')) if not hasattr(request,'user'): return HttpResponse(_('Error, not authenticated.')) template_id = request.POST.get('template') if not template_id: return HttpResponse(_("Error, no template ID provided.")) try: this_template = EmailTemplate.objects.get(id=template_id) except ObjectDoesNotExist: return HttpResponse(_("Error getting template.")) if this_template.groupRequired and this_template.groupRequired not in request.user.groups.all(): return HttpResponse(_("Error, no permission to access this template.")) if this_template.hideFromForm: return HttpResponse(_("Error, no permission to access this template.")) return JsonResponse({ 'subject': this_template.subject, 'content': this_template.content, 'html_content': this_template.html_content, 'richTextChoice': this_template.richTextChoice, })
python
def getEmailTemplate(request): if request.method != 'POST': return HttpResponse(_('Error, no POST data.')) if not hasattr(request,'user'): return HttpResponse(_('Error, not authenticated.')) template_id = request.POST.get('template') if not template_id: return HttpResponse(_("Error, no template ID provided.")) try: this_template = EmailTemplate.objects.get(id=template_id) except ObjectDoesNotExist: return HttpResponse(_("Error getting template.")) if this_template.groupRequired and this_template.groupRequired not in request.user.groups.all(): return HttpResponse(_("Error, no permission to access this template.")) if this_template.hideFromForm: return HttpResponse(_("Error, no permission to access this template.")) return JsonResponse({ 'subject': this_template.subject, 'content': this_template.content, 'html_content': this_template.html_content, 'richTextChoice': this_template.richTextChoice, })
[ "def", "getEmailTemplate", "(", "request", ")", ":", "if", "request", ".", "method", "!=", "'POST'", ":", "return", "HttpResponse", "(", "_", "(", "'Error, no POST data.'", ")", ")", "if", "not", "hasattr", "(", "request", ",", "'user'", ")", ":", "return", "HttpResponse", "(", "_", "(", "'Error, not authenticated.'", ")", ")", "template_id", "=", "request", ".", "POST", ".", "get", "(", "'template'", ")", "if", "not", "template_id", ":", "return", "HttpResponse", "(", "_", "(", "\"Error, no template ID provided.\"", ")", ")", "try", ":", "this_template", "=", "EmailTemplate", ".", "objects", ".", "get", "(", "id", "=", "template_id", ")", "except", "ObjectDoesNotExist", ":", "return", "HttpResponse", "(", "_", "(", "\"Error getting template.\"", ")", ")", "if", "this_template", ".", "groupRequired", "and", "this_template", ".", "groupRequired", "not", "in", "request", ".", "user", ".", "groups", ".", "all", "(", ")", ":", "return", "HttpResponse", "(", "_", "(", "\"Error, no permission to access this template.\"", ")", ")", "if", "this_template", ".", "hideFromForm", ":", "return", "HttpResponse", "(", "_", "(", "\"Error, no permission to access this template.\"", ")", ")", "return", "JsonResponse", "(", "{", "'subject'", ":", "this_template", ".", "subject", ",", "'content'", ":", "this_template", ".", "content", ",", "'html_content'", ":", "this_template", ".", "html_content", ",", "'richTextChoice'", ":", "this_template", ".", "richTextChoice", ",", "}", ")" ]
This function handles the Ajax call made when a user wants a specific email template
[ "This", "function", "handles", "the", "Ajax", "call", "made", "when", "a", "user", "wants", "a", "specific", "email", "template" ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/core/ajax.py#L106-L136
django-danceschool/django-danceschool
danceschool/payments/paypal/management/commands/setup_paypal.py
Command.boolean_input
def boolean_input(self, question, default=None): ''' Method for yes/no boolean inputs ''' result = input("%s: " % question) if not result and default is not None: return default while len(result) < 1 or result[0].lower() not in "yn": result = input("Please answer yes or no: ") return result[0].lower() == "y"
python
def boolean_input(self, question, default=None): result = input("%s: " % question) if not result and default is not None: return default while len(result) < 1 or result[0].lower() not in "yn": result = input("Please answer yes or no: ") return result[0].lower() == "y"
[ "def", "boolean_input", "(", "self", ",", "question", ",", "default", "=", "None", ")", ":", "result", "=", "input", "(", "\"%s: \"", "%", "question", ")", "if", "not", "result", "and", "default", "is", "not", "None", ":", "return", "default", "while", "len", "(", "result", ")", "<", "1", "or", "result", "[", "0", "]", ".", "lower", "(", ")", "not", "in", "\"yn\"", ":", "result", "=", "input", "(", "\"Please answer yes or no: \"", ")", "return", "result", "[", "0", "]", ".", "lower", "(", ")", "==", "\"y\"" ]
Method for yes/no boolean inputs
[ "Method", "for", "yes", "/", "no", "boolean", "inputs" ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/payments/paypal/management/commands/setup_paypal.py#L16-L25
django-danceschool/django-danceschool
danceschool/financial/helpers.py
createExpenseItemsForVenueRental
def createExpenseItemsForVenueRental(request=None, datetimeTuple=None, rule=None, event=None): ''' For each Location or Room-related Repeated Expense Rule, look for Events in the designated time window that do not already have expenses associated with them. For hourly rental expenses, then generate new expenses that are associated with this rule. For non-hourly expenses, generate new expenses based on the non-overlapping intervals of days, weeks or months for which there is not already an ExpenseItem associated with the rule in question. ''' # These are used repeatedly, so they are put at the top submissionUser = getattr(request, 'user', None) rental_category = getConstant('financial__venueRentalExpenseCat') # Return the number of new expense items created generate_count = 0 # First, construct the set of rules that need to be checked for affiliated events rule_filters = Q(disabled=False) & Q(rentalRate__gt=0) & \ (Q(locationrentalinfo__isnull=False) | Q(roomrentalinfo__isnull=False)) if rule: rule_filters = rule_filters & Q(id=rule.id) rulesToCheck = RepeatedExpenseRule.objects.filter(rule_filters).distinct() # These are the filters place on Events that overlap the window in which # expenses are being generated. event_timefilters = Q() if datetimeTuple and len(datetimeTuple) == 2: timelist = list(datetimeTuple) timelist.sort() event_timefilters = event_timefilters & ( Q(startTime__gte=timelist[0]) & Q(startTime__lte=timelist[1]) ) if event: event_timefilters = event_timefilters & Q(id=event.id) # Now, we loop through the set of rules that need to be applied, then loop through the # Events in the window in question that occurred at the location indicated by the rule. for rule in rulesToCheck: venue = ( getattr(rule, 'location', None) if isinstance(rule, RoomRentalInfo) else getattr(rule, 'location', None) ) loc = getattr(venue, 'location') if isinstance(venue, Room) else venue event_locfilter = Q(room=venue) if isinstance(venue, Room) else Q(location=venue) # Find or create the TransactionParty associated with the location. loc_party = TransactionParty.objects.get_or_create( location=loc, defaults={'name': loc.name} )[0] if rule.advanceDays: if rule.advanceDaysReference == RepeatedExpenseRule.MilestoneChoices.end: event_timefilters = event_timefilters & \ Q(endTime__lte=timezone.now() + timedelta(days=rule.advanceDays)) elif rule.advanceDaysReference == RepeatedExpenseRule.MilestoneChoices.start: event_timefilters = event_timefilters & \ Q(startTime__lte=timezone.now() + timedelta(days=rule.advanceDays)) if rule.priorDays: if rule.priorDaysReference == RepeatedExpenseRule.MilestoneChoices.end: event_timefilters = event_timefilters & \ Q(endTime__gte=timezone.now() - timedelta(days=rule.priorDays)) elif rule.priorDaysReference == RepeatedExpenseRule.MilestoneChoices.start: event_timefilters = event_timefilters & \ Q(startTime__gte=timezone.now() - timedelta(days=rule.priorDays)) if rule.startDate: event_timefilters = event_timefilters & Q( event__startTime__gte=timezone.now().replace( year=rule.startDate.year, month=rule.startDate.month, day=rule.startDate.day, hour=0, minute=0, second=0, microsecond=0, ) ) if rule.endDate: event_timefilters = event_timefilters & Q( event__startTime__lte=timezone.now().replace( year=rule.endDate.year, month=rule.endDate.month, day=rule.endDate.day, hour=0, minute=0, second=0, microsecond=0, ) ) # For construction of expense descriptions replacements = { 'type': _('Event/Series venue rental'), 'of': _('of'), 'location': venue.name, 'for': _('for'), } # Loop through Events for which there are not already directly allocated # expenses under this rule, and create new ExpenseItems for them depending # on whether the rule requires hourly expenses or non-hourly ones to # be generated. events = Event.objects.filter(event_locfilter & event_timefilters).exclude( Q(expenseitem__expenseRule=rule)).distinct() if rule.applyRateRule == rule.RateRuleChoices.hourly: for this_event in events: # Hourly expenses are always generated without checking for # overlapping windows, because the periods over which hourly expenses # are defined are disjoint. However, hourly expenses are allocated # directly to events, so we just need to create expenses for any events # that do not already have an Expense Item generate under this rule. replacements['name'] = this_event.name replacements['dates'] = this_event.localStartTime.strftime('%Y-%m-%d') if ( event.localStartTime.strftime('%Y-%m-%d') != \ this_event.localEndTime.strftime('%Y-%m-%d') ): replacements['dates'] += ' %s %s' % ( _('to'), this_event.localEndTime.strftime('%Y-%m-%d') ) ExpenseItem.objects.create( event=this_event, category=rental_category, payTo=loc_party, expenseRule=rule, description='%(type)s %(of)s %(location)s %(for)s: %(name)s, %(dates)s' % \ replacements, submissionUser=submissionUser, total=this_event.duration * rule.rentalRate, accrualDate=this_event.startTime, ) generate_count += 1 else: # Non-hourly expenses are generated by constructing the time # intervals in which the occurrence occurs, and removing from that # interval any intervals in which an expense has already been # generated under this rule (so, for example, monthly rentals will # now show up multiple times). So, we just need to construct the set # of intervals for which to construct expenses intervals = [ (x.localStartTime, x.localEndTime) for x in \ EventOccurrence.objects.filter(event__in=events) ] remaining_intervals = rule.getWindowsAndTotals(intervals) for startTime, endTime, total, description in remaining_intervals: replacements['when'] = description ExpenseItem.objects.create( category=rental_category, payTo=loc_party, expenseRule=rule, periodStart=startTime, periodEnd=endTime, description='%(type)s %(of)s %(location)s %(for)s %(when)s' % replacements, submissionUser=submissionUser, total=total, accrualDate=startTime, ) generate_count += 1 rulesToCheck.update(lastRun=timezone.now()) return generate_count
python
def createExpenseItemsForVenueRental(request=None, datetimeTuple=None, rule=None, event=None): submissionUser = getattr(request, 'user', None) rental_category = getConstant('financial__venueRentalExpenseCat') generate_count = 0 rule_filters = Q(disabled=False) & Q(rentalRate__gt=0) & \ (Q(locationrentalinfo__isnull=False) | Q(roomrentalinfo__isnull=False)) if rule: rule_filters = rule_filters & Q(id=rule.id) rulesToCheck = RepeatedExpenseRule.objects.filter(rule_filters).distinct() event_timefilters = Q() if datetimeTuple and len(datetimeTuple) == 2: timelist = list(datetimeTuple) timelist.sort() event_timefilters = event_timefilters & ( Q(startTime__gte=timelist[0]) & Q(startTime__lte=timelist[1]) ) if event: event_timefilters = event_timefilters & Q(id=event.id) for rule in rulesToCheck: venue = ( getattr(rule, 'location', None) if isinstance(rule, RoomRentalInfo) else getattr(rule, 'location', None) ) loc = getattr(venue, 'location') if isinstance(venue, Room) else venue event_locfilter = Q(room=venue) if isinstance(venue, Room) else Q(location=venue) loc_party = TransactionParty.objects.get_or_create( location=loc, defaults={'name': loc.name} )[0] if rule.advanceDays: if rule.advanceDaysReference == RepeatedExpenseRule.MilestoneChoices.end: event_timefilters = event_timefilters & \ Q(endTime__lte=timezone.now() + timedelta(days=rule.advanceDays)) elif rule.advanceDaysReference == RepeatedExpenseRule.MilestoneChoices.start: event_timefilters = event_timefilters & \ Q(startTime__lte=timezone.now() + timedelta(days=rule.advanceDays)) if rule.priorDays: if rule.priorDaysReference == RepeatedExpenseRule.MilestoneChoices.end: event_timefilters = event_timefilters & \ Q(endTime__gte=timezone.now() - timedelta(days=rule.priorDays)) elif rule.priorDaysReference == RepeatedExpenseRule.MilestoneChoices.start: event_timefilters = event_timefilters & \ Q(startTime__gte=timezone.now() - timedelta(days=rule.priorDays)) if rule.startDate: event_timefilters = event_timefilters & Q( event__startTime__gte=timezone.now().replace( year=rule.startDate.year, month=rule.startDate.month, day=rule.startDate.day, hour=0, minute=0, second=0, microsecond=0, ) ) if rule.endDate: event_timefilters = event_timefilters & Q( event__startTime__lte=timezone.now().replace( year=rule.endDate.year, month=rule.endDate.month, day=rule.endDate.day, hour=0, minute=0, second=0, microsecond=0, ) ) replacements = { 'type': _('Event/Series venue rental'), 'of': _('of'), 'location': venue.name, 'for': _('for'), } events = Event.objects.filter(event_locfilter & event_timefilters).exclude( Q(expenseitem__expenseRule=rule)).distinct() if rule.applyRateRule == rule.RateRuleChoices.hourly: for this_event in events: replacements['name'] = this_event.name replacements['dates'] = this_event.localStartTime.strftime('%Y-%m-%d') if ( event.localStartTime.strftime('%Y-%m-%d') != \ this_event.localEndTime.strftime('%Y-%m-%d') ): replacements['dates'] += ' %s %s' % ( _('to'), this_event.localEndTime.strftime('%Y-%m-%d') ) ExpenseItem.objects.create( event=this_event, category=rental_category, payTo=loc_party, expenseRule=rule, description='%(type)s %(of)s %(location)s %(for)s: %(name)s, %(dates)s' % \ replacements, submissionUser=submissionUser, total=this_event.duration * rule.rentalRate, accrualDate=this_event.startTime, ) generate_count += 1 else: intervals = [ (x.localStartTime, x.localEndTime) for x in \ EventOccurrence.objects.filter(event__in=events) ] remaining_intervals = rule.getWindowsAndTotals(intervals) for startTime, endTime, total, description in remaining_intervals: replacements['when'] = description ExpenseItem.objects.create( category=rental_category, payTo=loc_party, expenseRule=rule, periodStart=startTime, periodEnd=endTime, description='%(type)s %(of)s %(location)s %(for)s %(when)s' % replacements, submissionUser=submissionUser, total=total, accrualDate=startTime, ) generate_count += 1 rulesToCheck.update(lastRun=timezone.now()) return generate_count
[ "def", "createExpenseItemsForVenueRental", "(", "request", "=", "None", ",", "datetimeTuple", "=", "None", ",", "rule", "=", "None", ",", "event", "=", "None", ")", ":", "# These are used repeatedly, so they are put at the top\r", "submissionUser", "=", "getattr", "(", "request", ",", "'user'", ",", "None", ")", "rental_category", "=", "getConstant", "(", "'financial__venueRentalExpenseCat'", ")", "# Return the number of new expense items created\r", "generate_count", "=", "0", "# First, construct the set of rules that need to be checked for affiliated events\r", "rule_filters", "=", "Q", "(", "disabled", "=", "False", ")", "&", "Q", "(", "rentalRate__gt", "=", "0", ")", "&", "(", "Q", "(", "locationrentalinfo__isnull", "=", "False", ")", "|", "Q", "(", "roomrentalinfo__isnull", "=", "False", ")", ")", "if", "rule", ":", "rule_filters", "=", "rule_filters", "&", "Q", "(", "id", "=", "rule", ".", "id", ")", "rulesToCheck", "=", "RepeatedExpenseRule", ".", "objects", ".", "filter", "(", "rule_filters", ")", ".", "distinct", "(", ")", "# These are the filters place on Events that overlap the window in which\r", "# expenses are being generated.\r", "event_timefilters", "=", "Q", "(", ")", "if", "datetimeTuple", "and", "len", "(", "datetimeTuple", ")", "==", "2", ":", "timelist", "=", "list", "(", "datetimeTuple", ")", "timelist", ".", "sort", "(", ")", "event_timefilters", "=", "event_timefilters", "&", "(", "Q", "(", "startTime__gte", "=", "timelist", "[", "0", "]", ")", "&", "Q", "(", "startTime__lte", "=", "timelist", "[", "1", "]", ")", ")", "if", "event", ":", "event_timefilters", "=", "event_timefilters", "&", "Q", "(", "id", "=", "event", ".", "id", ")", "# Now, we loop through the set of rules that need to be applied, then loop through the\r", "# Events in the window in question that occurred at the location indicated by the rule.\r", "for", "rule", "in", "rulesToCheck", ":", "venue", "=", "(", "getattr", "(", "rule", ",", "'location'", ",", "None", ")", "if", "isinstance", "(", "rule", ",", "RoomRentalInfo", ")", "else", "getattr", "(", "rule", ",", "'location'", ",", "None", ")", ")", "loc", "=", "getattr", "(", "venue", ",", "'location'", ")", "if", "isinstance", "(", "venue", ",", "Room", ")", "else", "venue", "event_locfilter", "=", "Q", "(", "room", "=", "venue", ")", "if", "isinstance", "(", "venue", ",", "Room", ")", "else", "Q", "(", "location", "=", "venue", ")", "# Find or create the TransactionParty associated with the location.\r", "loc_party", "=", "TransactionParty", ".", "objects", ".", "get_or_create", "(", "location", "=", "loc", ",", "defaults", "=", "{", "'name'", ":", "loc", ".", "name", "}", ")", "[", "0", "]", "if", "rule", ".", "advanceDays", ":", "if", "rule", ".", "advanceDaysReference", "==", "RepeatedExpenseRule", ".", "MilestoneChoices", ".", "end", ":", "event_timefilters", "=", "event_timefilters", "&", "Q", "(", "endTime__lte", "=", "timezone", ".", "now", "(", ")", "+", "timedelta", "(", "days", "=", "rule", ".", "advanceDays", ")", ")", "elif", "rule", ".", "advanceDaysReference", "==", "RepeatedExpenseRule", ".", "MilestoneChoices", ".", "start", ":", "event_timefilters", "=", "event_timefilters", "&", "Q", "(", "startTime__lte", "=", "timezone", ".", "now", "(", ")", "+", "timedelta", "(", "days", "=", "rule", ".", "advanceDays", ")", ")", "if", "rule", ".", "priorDays", ":", "if", "rule", ".", "priorDaysReference", "==", "RepeatedExpenseRule", ".", "MilestoneChoices", ".", "end", ":", "event_timefilters", "=", "event_timefilters", "&", "Q", "(", "endTime__gte", "=", "timezone", ".", "now", "(", ")", "-", "timedelta", "(", "days", "=", "rule", ".", "priorDays", ")", ")", "elif", "rule", ".", "priorDaysReference", "==", "RepeatedExpenseRule", ".", "MilestoneChoices", ".", "start", ":", "event_timefilters", "=", "event_timefilters", "&", "Q", "(", "startTime__gte", "=", "timezone", ".", "now", "(", ")", "-", "timedelta", "(", "days", "=", "rule", ".", "priorDays", ")", ")", "if", "rule", ".", "startDate", ":", "event_timefilters", "=", "event_timefilters", "&", "Q", "(", "event__startTime__gte", "=", "timezone", ".", "now", "(", ")", ".", "replace", "(", "year", "=", "rule", ".", "startDate", ".", "year", ",", "month", "=", "rule", ".", "startDate", ".", "month", ",", "day", "=", "rule", ".", "startDate", ".", "day", ",", "hour", "=", "0", ",", "minute", "=", "0", ",", "second", "=", "0", ",", "microsecond", "=", "0", ",", ")", ")", "if", "rule", ".", "endDate", ":", "event_timefilters", "=", "event_timefilters", "&", "Q", "(", "event__startTime__lte", "=", "timezone", ".", "now", "(", ")", ".", "replace", "(", "year", "=", "rule", ".", "endDate", ".", "year", ",", "month", "=", "rule", ".", "endDate", ".", "month", ",", "day", "=", "rule", ".", "endDate", ".", "day", ",", "hour", "=", "0", ",", "minute", "=", "0", ",", "second", "=", "0", ",", "microsecond", "=", "0", ",", ")", ")", "# For construction of expense descriptions\r", "replacements", "=", "{", "'type'", ":", "_", "(", "'Event/Series venue rental'", ")", ",", "'of'", ":", "_", "(", "'of'", ")", ",", "'location'", ":", "venue", ".", "name", ",", "'for'", ":", "_", "(", "'for'", ")", ",", "}", "# Loop through Events for which there are not already directly allocated\r", "# expenses under this rule, and create new ExpenseItems for them depending\r", "# on whether the rule requires hourly expenses or non-hourly ones to\r", "# be generated.\r", "events", "=", "Event", ".", "objects", ".", "filter", "(", "event_locfilter", "&", "event_timefilters", ")", ".", "exclude", "(", "Q", "(", "expenseitem__expenseRule", "=", "rule", ")", ")", ".", "distinct", "(", ")", "if", "rule", ".", "applyRateRule", "==", "rule", ".", "RateRuleChoices", ".", "hourly", ":", "for", "this_event", "in", "events", ":", "# Hourly expenses are always generated without checking for\r", "# overlapping windows, because the periods over which hourly expenses\r", "# are defined are disjoint. However, hourly expenses are allocated\r", "# directly to events, so we just need to create expenses for any events\r", "# that do not already have an Expense Item generate under this rule.\r", "replacements", "[", "'name'", "]", "=", "this_event", ".", "name", "replacements", "[", "'dates'", "]", "=", "this_event", ".", "localStartTime", ".", "strftime", "(", "'%Y-%m-%d'", ")", "if", "(", "event", ".", "localStartTime", ".", "strftime", "(", "'%Y-%m-%d'", ")", "!=", "this_event", ".", "localEndTime", ".", "strftime", "(", "'%Y-%m-%d'", ")", ")", ":", "replacements", "[", "'dates'", "]", "+=", "' %s %s'", "%", "(", "_", "(", "'to'", ")", ",", "this_event", ".", "localEndTime", ".", "strftime", "(", "'%Y-%m-%d'", ")", ")", "ExpenseItem", ".", "objects", ".", "create", "(", "event", "=", "this_event", ",", "category", "=", "rental_category", ",", "payTo", "=", "loc_party", ",", "expenseRule", "=", "rule", ",", "description", "=", "'%(type)s %(of)s %(location)s %(for)s: %(name)s, %(dates)s'", "%", "replacements", ",", "submissionUser", "=", "submissionUser", ",", "total", "=", "this_event", ".", "duration", "*", "rule", ".", "rentalRate", ",", "accrualDate", "=", "this_event", ".", "startTime", ",", ")", "generate_count", "+=", "1", "else", ":", "# Non-hourly expenses are generated by constructing the time\r", "# intervals in which the occurrence occurs, and removing from that\r", "# interval any intervals in which an expense has already been\r", "# generated under this rule (so, for example, monthly rentals will\r", "# now show up multiple times). So, we just need to construct the set\r", "# of intervals for which to construct expenses\r", "intervals", "=", "[", "(", "x", ".", "localStartTime", ",", "x", ".", "localEndTime", ")", "for", "x", "in", "EventOccurrence", ".", "objects", ".", "filter", "(", "event__in", "=", "events", ")", "]", "remaining_intervals", "=", "rule", ".", "getWindowsAndTotals", "(", "intervals", ")", "for", "startTime", ",", "endTime", ",", "total", ",", "description", "in", "remaining_intervals", ":", "replacements", "[", "'when'", "]", "=", "description", "ExpenseItem", ".", "objects", ".", "create", "(", "category", "=", "rental_category", ",", "payTo", "=", "loc_party", ",", "expenseRule", "=", "rule", ",", "periodStart", "=", "startTime", ",", "periodEnd", "=", "endTime", ",", "description", "=", "'%(type)s %(of)s %(location)s %(for)s %(when)s'", "%", "replacements", ",", "submissionUser", "=", "submissionUser", ",", "total", "=", "total", ",", "accrualDate", "=", "startTime", ",", ")", "generate_count", "+=", "1", "rulesToCheck", ".", "update", "(", "lastRun", "=", "timezone", ".", "now", "(", ")", ")", "return", "generate_count" ]
For each Location or Room-related Repeated Expense Rule, look for Events in the designated time window that do not already have expenses associated with them. For hourly rental expenses, then generate new expenses that are associated with this rule. For non-hourly expenses, generate new expenses based on the non-overlapping intervals of days, weeks or months for which there is not already an ExpenseItem associated with the rule in question.
[ "For", "each", "Location", "or", "Room", "-", "related", "Repeated", "Expense", "Rule", "look", "for", "Events", "in", "the", "designated", "time", "window", "that", "do", "not", "already", "have", "expenses", "associated", "with", "them", ".", "For", "hourly", "rental", "expenses", "then", "generate", "new", "expenses", "that", "are", "associated", "with", "this", "rule", ".", "For", "non", "-", "hourly", "expenses", "generate", "new", "expenses", "based", "on", "the", "non", "-", "overlapping", "intervals", "of", "days", "weeks", "or", "months", "for", "which", "there", "is", "not", "already", "an", "ExpenseItem", "associated", "with", "the", "rule", "in", "question", "." ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/financial/helpers.py#L121-L277
django-danceschool/django-danceschool
danceschool/financial/helpers.py
createExpenseItemsForEvents
def createExpenseItemsForEvents(request=None, datetimeTuple=None, rule=None, event=None): ''' For each StaffMember-related Repeated Expense Rule, look for EventStaffMember instances in the designated time window that do not already have expenses associated with them. For hourly rental expenses, then generate new expenses that are associated with this rule. For non-hourly expenses, generate new expenses based on the non-overlapping intervals of days, weeks or months for which there is not already an ExpenseItem associated with the rule in question. ''' # This is used repeatedly, so it is put at the top submissionUser = getattr(request, 'user', None) # Return the number of new expense items created generate_count = 0 # First, construct the set of rules that need to be checked for affiliated events rule_filters = Q(disabled=False) & Q(rentalRate__gt=0) & \ Q(Q(staffmemberwageinfo__isnull=False) | Q(staffdefaultwage__isnull=False)) if rule: rule_filters = rule_filters & Q(id=rule.id) rulesToCheck = RepeatedExpenseRule.objects.filter( rule_filters).distinct().order_by( '-staffmemberwageinfo__category', '-staffdefaultwage__category' ) # These are the filters placed on Events that overlap the window in which # expenses are being generated. event_timefilters = Q() if datetimeTuple and len(datetimeTuple) == 2: timelist = list(datetimeTuple) timelist.sort() event_timefilters = event_timefilters & ( Q(event__startTime__gte=timelist[0]) & Q(event__startTime__lte=timelist[1]) ) if event: event_timefilters = event_timefilters & Q(event__id=event.id) # Now, we loop through the set of rules that need to be applied, then loop # through the Events in the window in question that involved the staff # member indicated by the rule. for rule in rulesToCheck: staffMember = getattr(rule, 'staffMember', None) staffCategory = getattr(rule, 'category', None) # No need to continue if expenses are not to be generated if ( (not staffMember and not staffCategory) or ( not staffMember and not getConstant('financial__autoGenerateFromStaffCategoryDefaults') ) ): continue # For construction of expense descriptions replacements = { 'type': _('Staff'), 'to': _('payment to'), 'for': _('for'), } # This is the generic category for all Event staff, but it may be overridden below expense_category = getConstant('financial__otherStaffExpenseCat') if staffCategory: if staffMember: # This staff member in this category eventstaff_filter = Q(staffMember=staffMember) & Q(category=staffCategory) elif getConstant('financial__autoGenerateFromStaffCategoryDefaults'): # Any staff member who does not already have a rule specified this category eventstaff_filter = ( Q(category=staffCategory) & ~Q(staffMember__expenserules__category=staffCategory) ) replacements['type'] = staffCategory.name # For standard categories of staff, map the EventStaffCategory to # an ExpenseCategory using the stored constants. Otherwise, the # ExpenseCategory is a generic one. if staffCategory == getConstant('general__eventStaffCategoryAssistant'): expense_category = getConstant('financial__assistantClassInstructionExpenseCat') elif staffCategory in [ getConstant('general__eventStaffCategoryInstructor'), getConstant('general__eventStaffCategorySubstitute') ]: expense_category = getConstant('financial__classInstructionExpenseCat') else: # We don't want to generate duplicate expenses when there is both a category-limited # rule and a non-limited rule for the same person, so we have to construct the list # of categories that are to be excluded if no category is specified by this rule. coveredCategories = list(staffMember.expenserules.filter( category__isnull=False).values_list('category__id', flat=True)) eventstaff_filter = Q(staffMember=staffMember) & ~Q(category__id__in=coveredCategories) if rule.advanceDays is not None: if rule.advanceDaysReference == RepeatedExpenseRule.MilestoneChoices.end: event_timefilters = event_timefilters & Q( event__endTime__lte=timezone.now() + timedelta(days=rule.advanceDays) ) elif rule.advanceDaysReference == RepeatedExpenseRule.MilestoneChoices.start: event_timefilters = event_timefilters & Q( event__startTime__lte=timezone.now() + timedelta(days=rule.advanceDays) ) if rule.priorDays is not None: if rule.priorDaysReference == RepeatedExpenseRule.MilestoneChoices.end: event_timefilters = event_timefilters & Q( event__endTime__gte=timezone.now() - timedelta(days=rule.priorDays) ) elif rule.priorDaysReference == RepeatedExpenseRule.MilestoneChoices.start: event_timefilters = event_timefilters & Q( event__startTime__gte=timezone.now() - timedelta(days=rule.priorDays) ) if rule.startDate: event_timefilters = event_timefilters & Q(event__startTime__gte=timezone.now().replace( year=rule.startDate.year, month=rule.startDate.month, day=rule.startDate.day, hour=0, minute=0, second=0, microsecond=0, )) if rule.endDate: event_timefilters = event_timefilters & Q(event__startTime__lte=timezone.now().replace( year=rule.endDate.year, month=rule.endDate.month, day=rule.endDate.day, hour=0, minute=0, second=0, microsecond=0, )) # Loop through EventStaffMembers for which there are not already # directly allocated expenses under this rule, and create new # ExpenseItems for them depending on whether the rule requires hourly # expenses or non-hourly ones to be generated. staffers = EventStaffMember.objects.filter(eventstaff_filter & event_timefilters).exclude( Q(event__expenseitem__expenseRule=rule)).distinct() if rule.applyRateRule == rule.RateRuleChoices.hourly: for staffer in staffers: # Hourly expenses are always generated without checking for # overlapping windows, because the periods over which hourly # expenses are defined are disjoint. However, hourly expenses # are allocated directly to events, so we just need to create # expenses for any events that do not already have an Expense # Item generate under this rule. replacements['event'] = staffer.event.name replacements['name'] = staffer.staffMember.fullName replacements['dates'] = staffer.event.startTime.strftime('%Y-%m-%d') if ( staffer.event.startTime.strftime('%Y-%m-%d') != staffer.event.endTime.strftime('%Y-%m-%d') ): replacements['dates'] += ' %s %s' % ( _('to'), staffer.event.endTime.strftime('%Y-%m-%d') ) # Find or create the TransactionParty associated with the staff member. staffer_party = TransactionParty.objects.get_or_create( staffMember=staffer.staffMember, defaults={ 'name': staffer.staffMember.fullName, 'user': getattr(staffer.staffMember, 'userAccount', None) } )[0] params = { 'event': staffer.event, 'category': expense_category, 'expenseRule': rule, 'description': '%(type)s %(to)s %(name)s %(for)s: %(event)s, %(dates)s' % \ replacements, 'submissionUser': submissionUser, 'hours': staffer.netHours, 'wageRate': rule.rentalRate, 'total': staffer.netHours * rule.rentalRate, 'accrualDate': staffer.event.startTime, 'payTo': staffer_party, } ExpenseItem.objects.create(**params) generate_count += 1 else: # Non-hourly expenses are generated by constructing the time # intervals in which the occurrence occurs, and removing from that # interval any intervals in which an expense has already been # generated under this rule (so, for example, monthly rentals will # now show up multiple times). So, we just need to construct the set # of intervals for which to construct expenses. We first need to # split the set of EventStaffMember objects by StaffMember (in case # this rule is not person-specific) and then run this provedure # separated by StaffMember. members = StaffMember.objects.filter(eventstaffmember__in=staffers) for member in members: events = [x.event for x in staffers.filter(staffMember=member)] # Find or create the TransactionParty associated with the staff member. staffer_party = TransactionParty.objects.get_or_create( staffMember=member, defaults={ 'name': member.fullName, 'user': getattr(member, 'userAccount', None) } )[0] intervals = [ (x.localStartTime, x.localEndTime) for x in EventOccurrence.objects.filter(event__in=events) ] remaining_intervals = rule.getWindowsAndTotals(intervals) for startTime, endTime, total, description in remaining_intervals: replacements['when'] = description replacements['name'] = member.fullName params = { 'category': expense_category, 'expenseRule': rule, 'periodStart': startTime, 'periodEnd': endTime, 'description': '%(type)s %(to)s %(name)s %(for)s %(when)s' % replacements, 'submissionUser': submissionUser, 'total': total, 'accrualDate': startTime, 'payTo': staffer_party, } ExpenseItem.objects.create(**params) generate_count += 1 rulesToCheck.update(lastRun=timezone.now()) return generate_count
python
def createExpenseItemsForEvents(request=None, datetimeTuple=None, rule=None, event=None): submissionUser = getattr(request, 'user', None) generate_count = 0 rule_filters = Q(disabled=False) & Q(rentalRate__gt=0) & \ Q(Q(staffmemberwageinfo__isnull=False) | Q(staffdefaultwage__isnull=False)) if rule: rule_filters = rule_filters & Q(id=rule.id) rulesToCheck = RepeatedExpenseRule.objects.filter( rule_filters).distinct().order_by( '-staffmemberwageinfo__category', '-staffdefaultwage__category' ) event_timefilters = Q() if datetimeTuple and len(datetimeTuple) == 2: timelist = list(datetimeTuple) timelist.sort() event_timefilters = event_timefilters & ( Q(event__startTime__gte=timelist[0]) & Q(event__startTime__lte=timelist[1]) ) if event: event_timefilters = event_timefilters & Q(event__id=event.id) for rule in rulesToCheck: staffMember = getattr(rule, 'staffMember', None) staffCategory = getattr(rule, 'category', None) if ( (not staffMember and not staffCategory) or ( not staffMember and not getConstant('financial__autoGenerateFromStaffCategoryDefaults') ) ): continue replacements = { 'type': _('Staff'), 'to': _('payment to'), 'for': _('for'), } expense_category = getConstant('financial__otherStaffExpenseCat') if staffCategory: if staffMember: eventstaff_filter = Q(staffMember=staffMember) & Q(category=staffCategory) elif getConstant('financial__autoGenerateFromStaffCategoryDefaults'): eventstaff_filter = ( Q(category=staffCategory) & ~Q(staffMember__expenserules__category=staffCategory) ) replacements['type'] = staffCategory.name if staffCategory == getConstant('general__eventStaffCategoryAssistant'): expense_category = getConstant('financial__assistantClassInstructionExpenseCat') elif staffCategory in [ getConstant('general__eventStaffCategoryInstructor'), getConstant('general__eventStaffCategorySubstitute') ]: expense_category = getConstant('financial__classInstructionExpenseCat') else: coveredCategories = list(staffMember.expenserules.filter( category__isnull=False).values_list('category__id', flat=True)) eventstaff_filter = Q(staffMember=staffMember) & ~Q(category__id__in=coveredCategories) if rule.advanceDays is not None: if rule.advanceDaysReference == RepeatedExpenseRule.MilestoneChoices.end: event_timefilters = event_timefilters & Q( event__endTime__lte=timezone.now() + timedelta(days=rule.advanceDays) ) elif rule.advanceDaysReference == RepeatedExpenseRule.MilestoneChoices.start: event_timefilters = event_timefilters & Q( event__startTime__lte=timezone.now() + timedelta(days=rule.advanceDays) ) if rule.priorDays is not None: if rule.priorDaysReference == RepeatedExpenseRule.MilestoneChoices.end: event_timefilters = event_timefilters & Q( event__endTime__gte=timezone.now() - timedelta(days=rule.priorDays) ) elif rule.priorDaysReference == RepeatedExpenseRule.MilestoneChoices.start: event_timefilters = event_timefilters & Q( event__startTime__gte=timezone.now() - timedelta(days=rule.priorDays) ) if rule.startDate: event_timefilters = event_timefilters & Q(event__startTime__gte=timezone.now().replace( year=rule.startDate.year, month=rule.startDate.month, day=rule.startDate.day, hour=0, minute=0, second=0, microsecond=0, )) if rule.endDate: event_timefilters = event_timefilters & Q(event__startTime__lte=timezone.now().replace( year=rule.endDate.year, month=rule.endDate.month, day=rule.endDate.day, hour=0, minute=0, second=0, microsecond=0, )) staffers = EventStaffMember.objects.filter(eventstaff_filter & event_timefilters).exclude( Q(event__expenseitem__expenseRule=rule)).distinct() if rule.applyRateRule == rule.RateRuleChoices.hourly: for staffer in staffers: replacements['event'] = staffer.event.name replacements['name'] = staffer.staffMember.fullName replacements['dates'] = staffer.event.startTime.strftime('%Y-%m-%d') if ( staffer.event.startTime.strftime('%Y-%m-%d') != staffer.event.endTime.strftime('%Y-%m-%d') ): replacements['dates'] += ' %s %s' % ( _('to'), staffer.event.endTime.strftime('%Y-%m-%d') ) staffer_party = TransactionParty.objects.get_or_create( staffMember=staffer.staffMember, defaults={ 'name': staffer.staffMember.fullName, 'user': getattr(staffer.staffMember, 'userAccount', None) } )[0] params = { 'event': staffer.event, 'category': expense_category, 'expenseRule': rule, 'description': '%(type)s %(to)s %(name)s %(for)s: %(event)s, %(dates)s' % \ replacements, 'submissionUser': submissionUser, 'hours': staffer.netHours, 'wageRate': rule.rentalRate, 'total': staffer.netHours * rule.rentalRate, 'accrualDate': staffer.event.startTime, 'payTo': staffer_party, } ExpenseItem.objects.create(**params) generate_count += 1 else: members = StaffMember.objects.filter(eventstaffmember__in=staffers) for member in members: events = [x.event for x in staffers.filter(staffMember=member)] staffer_party = TransactionParty.objects.get_or_create( staffMember=member, defaults={ 'name': member.fullName, 'user': getattr(member, 'userAccount', None) } )[0] intervals = [ (x.localStartTime, x.localEndTime) for x in EventOccurrence.objects.filter(event__in=events) ] remaining_intervals = rule.getWindowsAndTotals(intervals) for startTime, endTime, total, description in remaining_intervals: replacements['when'] = description replacements['name'] = member.fullName params = { 'category': expense_category, 'expenseRule': rule, 'periodStart': startTime, 'periodEnd': endTime, 'description': '%(type)s %(to)s %(name)s %(for)s %(when)s' % replacements, 'submissionUser': submissionUser, 'total': total, 'accrualDate': startTime, 'payTo': staffer_party, } ExpenseItem.objects.create(**params) generate_count += 1 rulesToCheck.update(lastRun=timezone.now()) return generate_count
[ "def", "createExpenseItemsForEvents", "(", "request", "=", "None", ",", "datetimeTuple", "=", "None", ",", "rule", "=", "None", ",", "event", "=", "None", ")", ":", "# This is used repeatedly, so it is put at the top\r", "submissionUser", "=", "getattr", "(", "request", ",", "'user'", ",", "None", ")", "# Return the number of new expense items created\r", "generate_count", "=", "0", "# First, construct the set of rules that need to be checked for affiliated events\r", "rule_filters", "=", "Q", "(", "disabled", "=", "False", ")", "&", "Q", "(", "rentalRate__gt", "=", "0", ")", "&", "Q", "(", "Q", "(", "staffmemberwageinfo__isnull", "=", "False", ")", "|", "Q", "(", "staffdefaultwage__isnull", "=", "False", ")", ")", "if", "rule", ":", "rule_filters", "=", "rule_filters", "&", "Q", "(", "id", "=", "rule", ".", "id", ")", "rulesToCheck", "=", "RepeatedExpenseRule", ".", "objects", ".", "filter", "(", "rule_filters", ")", ".", "distinct", "(", ")", ".", "order_by", "(", "'-staffmemberwageinfo__category'", ",", "'-staffdefaultwage__category'", ")", "# These are the filters placed on Events that overlap the window in which\r", "# expenses are being generated.\r", "event_timefilters", "=", "Q", "(", ")", "if", "datetimeTuple", "and", "len", "(", "datetimeTuple", ")", "==", "2", ":", "timelist", "=", "list", "(", "datetimeTuple", ")", "timelist", ".", "sort", "(", ")", "event_timefilters", "=", "event_timefilters", "&", "(", "Q", "(", "event__startTime__gte", "=", "timelist", "[", "0", "]", ")", "&", "Q", "(", "event__startTime__lte", "=", "timelist", "[", "1", "]", ")", ")", "if", "event", ":", "event_timefilters", "=", "event_timefilters", "&", "Q", "(", "event__id", "=", "event", ".", "id", ")", "# Now, we loop through the set of rules that need to be applied, then loop\r", "# through the Events in the window in question that involved the staff\r", "# member indicated by the rule.\r", "for", "rule", "in", "rulesToCheck", ":", "staffMember", "=", "getattr", "(", "rule", ",", "'staffMember'", ",", "None", ")", "staffCategory", "=", "getattr", "(", "rule", ",", "'category'", ",", "None", ")", "# No need to continue if expenses are not to be generated\r", "if", "(", "(", "not", "staffMember", "and", "not", "staffCategory", ")", "or", "(", "not", "staffMember", "and", "not", "getConstant", "(", "'financial__autoGenerateFromStaffCategoryDefaults'", ")", ")", ")", ":", "continue", "# For construction of expense descriptions\r", "replacements", "=", "{", "'type'", ":", "_", "(", "'Staff'", ")", ",", "'to'", ":", "_", "(", "'payment to'", ")", ",", "'for'", ":", "_", "(", "'for'", ")", ",", "}", "# This is the generic category for all Event staff, but it may be overridden below\r", "expense_category", "=", "getConstant", "(", "'financial__otherStaffExpenseCat'", ")", "if", "staffCategory", ":", "if", "staffMember", ":", "# This staff member in this category\r", "eventstaff_filter", "=", "Q", "(", "staffMember", "=", "staffMember", ")", "&", "Q", "(", "category", "=", "staffCategory", ")", "elif", "getConstant", "(", "'financial__autoGenerateFromStaffCategoryDefaults'", ")", ":", "# Any staff member who does not already have a rule specified this category\r", "eventstaff_filter", "=", "(", "Q", "(", "category", "=", "staffCategory", ")", "&", "~", "Q", "(", "staffMember__expenserules__category", "=", "staffCategory", ")", ")", "replacements", "[", "'type'", "]", "=", "staffCategory", ".", "name", "# For standard categories of staff, map the EventStaffCategory to\r", "# an ExpenseCategory using the stored constants. Otherwise, the\r", "# ExpenseCategory is a generic one.\r", "if", "staffCategory", "==", "getConstant", "(", "'general__eventStaffCategoryAssistant'", ")", ":", "expense_category", "=", "getConstant", "(", "'financial__assistantClassInstructionExpenseCat'", ")", "elif", "staffCategory", "in", "[", "getConstant", "(", "'general__eventStaffCategoryInstructor'", ")", ",", "getConstant", "(", "'general__eventStaffCategorySubstitute'", ")", "]", ":", "expense_category", "=", "getConstant", "(", "'financial__classInstructionExpenseCat'", ")", "else", ":", "# We don't want to generate duplicate expenses when there is both a category-limited\r", "# rule and a non-limited rule for the same person, so we have to construct the list\r", "# of categories that are to be excluded if no category is specified by this rule.\r", "coveredCategories", "=", "list", "(", "staffMember", ".", "expenserules", ".", "filter", "(", "category__isnull", "=", "False", ")", ".", "values_list", "(", "'category__id'", ",", "flat", "=", "True", ")", ")", "eventstaff_filter", "=", "Q", "(", "staffMember", "=", "staffMember", ")", "&", "~", "Q", "(", "category__id__in", "=", "coveredCategories", ")", "if", "rule", ".", "advanceDays", "is", "not", "None", ":", "if", "rule", ".", "advanceDaysReference", "==", "RepeatedExpenseRule", ".", "MilestoneChoices", ".", "end", ":", "event_timefilters", "=", "event_timefilters", "&", "Q", "(", "event__endTime__lte", "=", "timezone", ".", "now", "(", ")", "+", "timedelta", "(", "days", "=", "rule", ".", "advanceDays", ")", ")", "elif", "rule", ".", "advanceDaysReference", "==", "RepeatedExpenseRule", ".", "MilestoneChoices", ".", "start", ":", "event_timefilters", "=", "event_timefilters", "&", "Q", "(", "event__startTime__lte", "=", "timezone", ".", "now", "(", ")", "+", "timedelta", "(", "days", "=", "rule", ".", "advanceDays", ")", ")", "if", "rule", ".", "priorDays", "is", "not", "None", ":", "if", "rule", ".", "priorDaysReference", "==", "RepeatedExpenseRule", ".", "MilestoneChoices", ".", "end", ":", "event_timefilters", "=", "event_timefilters", "&", "Q", "(", "event__endTime__gte", "=", "timezone", ".", "now", "(", ")", "-", "timedelta", "(", "days", "=", "rule", ".", "priorDays", ")", ")", "elif", "rule", ".", "priorDaysReference", "==", "RepeatedExpenseRule", ".", "MilestoneChoices", ".", "start", ":", "event_timefilters", "=", "event_timefilters", "&", "Q", "(", "event__startTime__gte", "=", "timezone", ".", "now", "(", ")", "-", "timedelta", "(", "days", "=", "rule", ".", "priorDays", ")", ")", "if", "rule", ".", "startDate", ":", "event_timefilters", "=", "event_timefilters", "&", "Q", "(", "event__startTime__gte", "=", "timezone", ".", "now", "(", ")", ".", "replace", "(", "year", "=", "rule", ".", "startDate", ".", "year", ",", "month", "=", "rule", ".", "startDate", ".", "month", ",", "day", "=", "rule", ".", "startDate", ".", "day", ",", "hour", "=", "0", ",", "minute", "=", "0", ",", "second", "=", "0", ",", "microsecond", "=", "0", ",", ")", ")", "if", "rule", ".", "endDate", ":", "event_timefilters", "=", "event_timefilters", "&", "Q", "(", "event__startTime__lte", "=", "timezone", ".", "now", "(", ")", ".", "replace", "(", "year", "=", "rule", ".", "endDate", ".", "year", ",", "month", "=", "rule", ".", "endDate", ".", "month", ",", "day", "=", "rule", ".", "endDate", ".", "day", ",", "hour", "=", "0", ",", "minute", "=", "0", ",", "second", "=", "0", ",", "microsecond", "=", "0", ",", ")", ")", "# Loop through EventStaffMembers for which there are not already\r", "# directly allocated expenses under this rule, and create new\r", "# ExpenseItems for them depending on whether the rule requires hourly\r", "# expenses or non-hourly ones to be generated.\r", "staffers", "=", "EventStaffMember", ".", "objects", ".", "filter", "(", "eventstaff_filter", "&", "event_timefilters", ")", ".", "exclude", "(", "Q", "(", "event__expenseitem__expenseRule", "=", "rule", ")", ")", ".", "distinct", "(", ")", "if", "rule", ".", "applyRateRule", "==", "rule", ".", "RateRuleChoices", ".", "hourly", ":", "for", "staffer", "in", "staffers", ":", "# Hourly expenses are always generated without checking for\r", "# overlapping windows, because the periods over which hourly\r", "# expenses are defined are disjoint. However, hourly expenses\r", "# are allocated directly to events, so we just need to create\r", "# expenses for any events that do not already have an Expense\r", "# Item generate under this rule.\r", "replacements", "[", "'event'", "]", "=", "staffer", ".", "event", ".", "name", "replacements", "[", "'name'", "]", "=", "staffer", ".", "staffMember", ".", "fullName", "replacements", "[", "'dates'", "]", "=", "staffer", ".", "event", ".", "startTime", ".", "strftime", "(", "'%Y-%m-%d'", ")", "if", "(", "staffer", ".", "event", ".", "startTime", ".", "strftime", "(", "'%Y-%m-%d'", ")", "!=", "staffer", ".", "event", ".", "endTime", ".", "strftime", "(", "'%Y-%m-%d'", ")", ")", ":", "replacements", "[", "'dates'", "]", "+=", "' %s %s'", "%", "(", "_", "(", "'to'", ")", ",", "staffer", ".", "event", ".", "endTime", ".", "strftime", "(", "'%Y-%m-%d'", ")", ")", "# Find or create the TransactionParty associated with the staff member.\r", "staffer_party", "=", "TransactionParty", ".", "objects", ".", "get_or_create", "(", "staffMember", "=", "staffer", ".", "staffMember", ",", "defaults", "=", "{", "'name'", ":", "staffer", ".", "staffMember", ".", "fullName", ",", "'user'", ":", "getattr", "(", "staffer", ".", "staffMember", ",", "'userAccount'", ",", "None", ")", "}", ")", "[", "0", "]", "params", "=", "{", "'event'", ":", "staffer", ".", "event", ",", "'category'", ":", "expense_category", ",", "'expenseRule'", ":", "rule", ",", "'description'", ":", "'%(type)s %(to)s %(name)s %(for)s: %(event)s, %(dates)s'", "%", "replacements", ",", "'submissionUser'", ":", "submissionUser", ",", "'hours'", ":", "staffer", ".", "netHours", ",", "'wageRate'", ":", "rule", ".", "rentalRate", ",", "'total'", ":", "staffer", ".", "netHours", "*", "rule", ".", "rentalRate", ",", "'accrualDate'", ":", "staffer", ".", "event", ".", "startTime", ",", "'payTo'", ":", "staffer_party", ",", "}", "ExpenseItem", ".", "objects", ".", "create", "(", "*", "*", "params", ")", "generate_count", "+=", "1", "else", ":", "# Non-hourly expenses are generated by constructing the time\r", "# intervals in which the occurrence occurs, and removing from that\r", "# interval any intervals in which an expense has already been\r", "# generated under this rule (so, for example, monthly rentals will\r", "# now show up multiple times). So, we just need to construct the set\r", "# of intervals for which to construct expenses. We first need to\r", "# split the set of EventStaffMember objects by StaffMember (in case\r", "# this rule is not person-specific) and then run this provedure\r", "# separated by StaffMember.\r", "members", "=", "StaffMember", ".", "objects", ".", "filter", "(", "eventstaffmember__in", "=", "staffers", ")", "for", "member", "in", "members", ":", "events", "=", "[", "x", ".", "event", "for", "x", "in", "staffers", ".", "filter", "(", "staffMember", "=", "member", ")", "]", "# Find or create the TransactionParty associated with the staff member.\r", "staffer_party", "=", "TransactionParty", ".", "objects", ".", "get_or_create", "(", "staffMember", "=", "member", ",", "defaults", "=", "{", "'name'", ":", "member", ".", "fullName", ",", "'user'", ":", "getattr", "(", "member", ",", "'userAccount'", ",", "None", ")", "}", ")", "[", "0", "]", "intervals", "=", "[", "(", "x", ".", "localStartTime", ",", "x", ".", "localEndTime", ")", "for", "x", "in", "EventOccurrence", ".", "objects", ".", "filter", "(", "event__in", "=", "events", ")", "]", "remaining_intervals", "=", "rule", ".", "getWindowsAndTotals", "(", "intervals", ")", "for", "startTime", ",", "endTime", ",", "total", ",", "description", "in", "remaining_intervals", ":", "replacements", "[", "'when'", "]", "=", "description", "replacements", "[", "'name'", "]", "=", "member", ".", "fullName", "params", "=", "{", "'category'", ":", "expense_category", ",", "'expenseRule'", ":", "rule", ",", "'periodStart'", ":", "startTime", ",", "'periodEnd'", ":", "endTime", ",", "'description'", ":", "'%(type)s %(to)s %(name)s %(for)s %(when)s'", "%", "replacements", ",", "'submissionUser'", ":", "submissionUser", ",", "'total'", ":", "total", ",", "'accrualDate'", ":", "startTime", ",", "'payTo'", ":", "staffer_party", ",", "}", "ExpenseItem", ".", "objects", ".", "create", "(", "*", "*", "params", ")", "generate_count", "+=", "1", "rulesToCheck", ".", "update", "(", "lastRun", "=", "timezone", ".", "now", "(", ")", ")", "return", "generate_count" ]
For each StaffMember-related Repeated Expense Rule, look for EventStaffMember instances in the designated time window that do not already have expenses associated with them. For hourly rental expenses, then generate new expenses that are associated with this rule. For non-hourly expenses, generate new expenses based on the non-overlapping intervals of days, weeks or months for which there is not already an ExpenseItem associated with the rule in question.
[ "For", "each", "StaffMember", "-", "related", "Repeated", "Expense", "Rule", "look", "for", "EventStaffMember", "instances", "in", "the", "designated", "time", "window", "that", "do", "not", "already", "have", "expenses", "associated", "with", "them", ".", "For", "hourly", "rental", "expenses", "then", "generate", "new", "expenses", "that", "are", "associated", "with", "this", "rule", ".", "For", "non", "-", "hourly", "expenses", "generate", "new", "expenses", "based", "on", "the", "non", "-", "overlapping", "intervals", "of", "days", "weeks", "or", "months", "for", "which", "there", "is", "not", "already", "an", "ExpenseItem", "associated", "with", "the", "rule", "in", "question", "." ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/financial/helpers.py#L280-L508
django-danceschool/django-danceschool
danceschool/financial/helpers.py
createGenericExpenseItems
def createGenericExpenseItems(request=None, datetimeTuple=None, rule=None): ''' Generic repeated expenses are created by just entering an expense at each exact point specified by the rule, without regard for whether events are scheduled in the specified window, ''' # These are used repeatedly, so they are put at the top submissionUser = getattr(request, 'user', None) # Return the number of new expense items created generate_count = 0 # First, construct the set of rules that need to be checked for affiliated events rule_filters = Q(disabled=False) & Q(rentalRate__gt=0) & \ Q(genericrepeatedexpense__isnull=False) if rule: rule_filters = rule_filters & Q(id=rule.id) rulesToCheck = RepeatedExpenseRule.objects.filter(rule_filters).distinct() # These are the filters place on Events that overlap the window in which # expenses are being generated. if datetimeTuple and len(datetimeTuple) == 2: timelist = list(datetimeTuple) timelist.sort() else: timelist = None # Now, we loop through the set of rules that need to be applied, check for an # existing expense item at each point specified by the rule, and create a new # expense if one does not exist. for rule in rulesToCheck: limits = timelist or [ensure_timezone(datetime.min), ensure_timezone(datetime.max)] if rule.advanceDays: limits[1] = min(limits[1], timezone.now() + timedelta(days=rule.advanceDays)) if rule.priorDays: limits[0] = max(limits[0], timezone.now() - timedelta(days=rule.priorDays)) if rule.startDate: limits[0] = max( limits[0], timezone.now().replace( year=rule.startDate.year, month=rule.startDate.month, day=rule.startDate.day, hour=0, minute=0, second=0, microsecond=0, ) ) if rule.endDate: limits[1] = min( limits[1], timezone.now().replace( year=rule.endDate.year, month=rule.endDate.month, day=rule.endDate.day, hour=0, minute=0, second=0, microsecond=0, ) ) # Find the first start time greater than the lower bound time. if rule.applyRateRule == RepeatedExpenseRule.RateRuleChoices.hourly: this_time = limits[0].replace(minute=0, second=0, microsecond=0) if this_time < limits[0]: this_time += timedelta(hours=1) elif rule.applyRateRule == RepeatedExpenseRule.RateRuleChoices.daily: this_time = limits[0].replace(hour=rule.dayStarts, minute=0, second=0, microsecond=0) if this_time < limits[0]: this_time += timedelta(days=1) elif rule.applyRateRule == RepeatedExpenseRule.RateRuleChoices.weekly: offset = limits[0].weekday() - rule.weekStarts this_time = limits[0].replace( day=limits[0].day - offset, hour=rule.dayStarts, minute=0, second=0, microsecond=0 ) if this_time < limits[0]: this_time += timedelta(days=7) else: this_time = limits[0].replace( day=rule.monthStarts, hour=rule.dayStarts, minute=0, second=0, microsecond=0 ) if this_time < limits[0]: this_time += relativedelta(months=1) while this_time <= limits[1]: defaults_dict = { 'category': rule.category, 'description': rule.name, 'submissionUser': submissionUser, 'total': rule.rentalRate, 'accrualDate': this_time, 'payTo': rule.payTo, } item, created = ExpenseItem.objects.get_or_create( expenseRule=rule, periodStart=this_time, periodEnd=this_time, defaults=defaults_dict ) if created: generate_count += 1 if rule.applyRateRule == RepeatedExpenseRule.RateRuleChoices.hourly: this_time += timedelta(hours=1) elif rule.applyRateRule == RepeatedExpenseRule.RateRuleChoices.daily: this_time += timedelta(days=1) elif rule.applyRateRule == RepeatedExpenseRule.RateRuleChoices.weekly: this_time += timedelta(days=7) else: this_time += relativedelta(months=1) rulesToCheck.update(lastRun=timezone.now()) return generate_count
python
def createGenericExpenseItems(request=None, datetimeTuple=None, rule=None): submissionUser = getattr(request, 'user', None) generate_count = 0 rule_filters = Q(disabled=False) & Q(rentalRate__gt=0) & \ Q(genericrepeatedexpense__isnull=False) if rule: rule_filters = rule_filters & Q(id=rule.id) rulesToCheck = RepeatedExpenseRule.objects.filter(rule_filters).distinct() if datetimeTuple and len(datetimeTuple) == 2: timelist = list(datetimeTuple) timelist.sort() else: timelist = None for rule in rulesToCheck: limits = timelist or [ensure_timezone(datetime.min), ensure_timezone(datetime.max)] if rule.advanceDays: limits[1] = min(limits[1], timezone.now() + timedelta(days=rule.advanceDays)) if rule.priorDays: limits[0] = max(limits[0], timezone.now() - timedelta(days=rule.priorDays)) if rule.startDate: limits[0] = max( limits[0], timezone.now().replace( year=rule.startDate.year, month=rule.startDate.month, day=rule.startDate.day, hour=0, minute=0, second=0, microsecond=0, ) ) if rule.endDate: limits[1] = min( limits[1], timezone.now().replace( year=rule.endDate.year, month=rule.endDate.month, day=rule.endDate.day, hour=0, minute=0, second=0, microsecond=0, ) ) if rule.applyRateRule == RepeatedExpenseRule.RateRuleChoices.hourly: this_time = limits[0].replace(minute=0, second=0, microsecond=0) if this_time < limits[0]: this_time += timedelta(hours=1) elif rule.applyRateRule == RepeatedExpenseRule.RateRuleChoices.daily: this_time = limits[0].replace(hour=rule.dayStarts, minute=0, second=0, microsecond=0) if this_time < limits[0]: this_time += timedelta(days=1) elif rule.applyRateRule == RepeatedExpenseRule.RateRuleChoices.weekly: offset = limits[0].weekday() - rule.weekStarts this_time = limits[0].replace( day=limits[0].day - offset, hour=rule.dayStarts, minute=0, second=0, microsecond=0 ) if this_time < limits[0]: this_time += timedelta(days=7) else: this_time = limits[0].replace( day=rule.monthStarts, hour=rule.dayStarts, minute=0, second=0, microsecond=0 ) if this_time < limits[0]: this_time += relativedelta(months=1) while this_time <= limits[1]: defaults_dict = { 'category': rule.category, 'description': rule.name, 'submissionUser': submissionUser, 'total': rule.rentalRate, 'accrualDate': this_time, 'payTo': rule.payTo, } item, created = ExpenseItem.objects.get_or_create( expenseRule=rule, periodStart=this_time, periodEnd=this_time, defaults=defaults_dict ) if created: generate_count += 1 if rule.applyRateRule == RepeatedExpenseRule.RateRuleChoices.hourly: this_time += timedelta(hours=1) elif rule.applyRateRule == RepeatedExpenseRule.RateRuleChoices.daily: this_time += timedelta(days=1) elif rule.applyRateRule == RepeatedExpenseRule.RateRuleChoices.weekly: this_time += timedelta(days=7) else: this_time += relativedelta(months=1) rulesToCheck.update(lastRun=timezone.now()) return generate_count
[ "def", "createGenericExpenseItems", "(", "request", "=", "None", ",", "datetimeTuple", "=", "None", ",", "rule", "=", "None", ")", ":", "# These are used repeatedly, so they are put at the top\r", "submissionUser", "=", "getattr", "(", "request", ",", "'user'", ",", "None", ")", "# Return the number of new expense items created\r", "generate_count", "=", "0", "# First, construct the set of rules that need to be checked for affiliated events\r", "rule_filters", "=", "Q", "(", "disabled", "=", "False", ")", "&", "Q", "(", "rentalRate__gt", "=", "0", ")", "&", "Q", "(", "genericrepeatedexpense__isnull", "=", "False", ")", "if", "rule", ":", "rule_filters", "=", "rule_filters", "&", "Q", "(", "id", "=", "rule", ".", "id", ")", "rulesToCheck", "=", "RepeatedExpenseRule", ".", "objects", ".", "filter", "(", "rule_filters", ")", ".", "distinct", "(", ")", "# These are the filters place on Events that overlap the window in which\r", "# expenses are being generated.\r", "if", "datetimeTuple", "and", "len", "(", "datetimeTuple", ")", "==", "2", ":", "timelist", "=", "list", "(", "datetimeTuple", ")", "timelist", ".", "sort", "(", ")", "else", ":", "timelist", "=", "None", "# Now, we loop through the set of rules that need to be applied, check for an\r", "# existing expense item at each point specified by the rule, and create a new\r", "# expense if one does not exist.\r", "for", "rule", "in", "rulesToCheck", ":", "limits", "=", "timelist", "or", "[", "ensure_timezone", "(", "datetime", ".", "min", ")", ",", "ensure_timezone", "(", "datetime", ".", "max", ")", "]", "if", "rule", ".", "advanceDays", ":", "limits", "[", "1", "]", "=", "min", "(", "limits", "[", "1", "]", ",", "timezone", ".", "now", "(", ")", "+", "timedelta", "(", "days", "=", "rule", ".", "advanceDays", ")", ")", "if", "rule", ".", "priorDays", ":", "limits", "[", "0", "]", "=", "max", "(", "limits", "[", "0", "]", ",", "timezone", ".", "now", "(", ")", "-", "timedelta", "(", "days", "=", "rule", ".", "priorDays", ")", ")", "if", "rule", ".", "startDate", ":", "limits", "[", "0", "]", "=", "max", "(", "limits", "[", "0", "]", ",", "timezone", ".", "now", "(", ")", ".", "replace", "(", "year", "=", "rule", ".", "startDate", ".", "year", ",", "month", "=", "rule", ".", "startDate", ".", "month", ",", "day", "=", "rule", ".", "startDate", ".", "day", ",", "hour", "=", "0", ",", "minute", "=", "0", ",", "second", "=", "0", ",", "microsecond", "=", "0", ",", ")", ")", "if", "rule", ".", "endDate", ":", "limits", "[", "1", "]", "=", "min", "(", "limits", "[", "1", "]", ",", "timezone", ".", "now", "(", ")", ".", "replace", "(", "year", "=", "rule", ".", "endDate", ".", "year", ",", "month", "=", "rule", ".", "endDate", ".", "month", ",", "day", "=", "rule", ".", "endDate", ".", "day", ",", "hour", "=", "0", ",", "minute", "=", "0", ",", "second", "=", "0", ",", "microsecond", "=", "0", ",", ")", ")", "# Find the first start time greater than the lower bound time.\r", "if", "rule", ".", "applyRateRule", "==", "RepeatedExpenseRule", ".", "RateRuleChoices", ".", "hourly", ":", "this_time", "=", "limits", "[", "0", "]", ".", "replace", "(", "minute", "=", "0", ",", "second", "=", "0", ",", "microsecond", "=", "0", ")", "if", "this_time", "<", "limits", "[", "0", "]", ":", "this_time", "+=", "timedelta", "(", "hours", "=", "1", ")", "elif", "rule", ".", "applyRateRule", "==", "RepeatedExpenseRule", ".", "RateRuleChoices", ".", "daily", ":", "this_time", "=", "limits", "[", "0", "]", ".", "replace", "(", "hour", "=", "rule", ".", "dayStarts", ",", "minute", "=", "0", ",", "second", "=", "0", ",", "microsecond", "=", "0", ")", "if", "this_time", "<", "limits", "[", "0", "]", ":", "this_time", "+=", "timedelta", "(", "days", "=", "1", ")", "elif", "rule", ".", "applyRateRule", "==", "RepeatedExpenseRule", ".", "RateRuleChoices", ".", "weekly", ":", "offset", "=", "limits", "[", "0", "]", ".", "weekday", "(", ")", "-", "rule", ".", "weekStarts", "this_time", "=", "limits", "[", "0", "]", ".", "replace", "(", "day", "=", "limits", "[", "0", "]", ".", "day", "-", "offset", ",", "hour", "=", "rule", ".", "dayStarts", ",", "minute", "=", "0", ",", "second", "=", "0", ",", "microsecond", "=", "0", ")", "if", "this_time", "<", "limits", "[", "0", "]", ":", "this_time", "+=", "timedelta", "(", "days", "=", "7", ")", "else", ":", "this_time", "=", "limits", "[", "0", "]", ".", "replace", "(", "day", "=", "rule", ".", "monthStarts", ",", "hour", "=", "rule", ".", "dayStarts", ",", "minute", "=", "0", ",", "second", "=", "0", ",", "microsecond", "=", "0", ")", "if", "this_time", "<", "limits", "[", "0", "]", ":", "this_time", "+=", "relativedelta", "(", "months", "=", "1", ")", "while", "this_time", "<=", "limits", "[", "1", "]", ":", "defaults_dict", "=", "{", "'category'", ":", "rule", ".", "category", ",", "'description'", ":", "rule", ".", "name", ",", "'submissionUser'", ":", "submissionUser", ",", "'total'", ":", "rule", ".", "rentalRate", ",", "'accrualDate'", ":", "this_time", ",", "'payTo'", ":", "rule", ".", "payTo", ",", "}", "item", ",", "created", "=", "ExpenseItem", ".", "objects", ".", "get_or_create", "(", "expenseRule", "=", "rule", ",", "periodStart", "=", "this_time", ",", "periodEnd", "=", "this_time", ",", "defaults", "=", "defaults_dict", ")", "if", "created", ":", "generate_count", "+=", "1", "if", "rule", ".", "applyRateRule", "==", "RepeatedExpenseRule", ".", "RateRuleChoices", ".", "hourly", ":", "this_time", "+=", "timedelta", "(", "hours", "=", "1", ")", "elif", "rule", ".", "applyRateRule", "==", "RepeatedExpenseRule", ".", "RateRuleChoices", ".", "daily", ":", "this_time", "+=", "timedelta", "(", "days", "=", "1", ")", "elif", "rule", ".", "applyRateRule", "==", "RepeatedExpenseRule", ".", "RateRuleChoices", ".", "weekly", ":", "this_time", "+=", "timedelta", "(", "days", "=", "7", ")", "else", ":", "this_time", "+=", "relativedelta", "(", "months", "=", "1", ")", "rulesToCheck", ".", "update", "(", "lastRun", "=", "timezone", ".", "now", "(", ")", ")", "return", "generate_count" ]
Generic repeated expenses are created by just entering an expense at each exact point specified by the rule, without regard for whether events are scheduled in the specified window,
[ "Generic", "repeated", "expenses", "are", "created", "by", "just", "entering", "an", "expense", "at", "each", "exact", "point", "specified", "by", "the", "rule", "without", "regard", "for", "whether", "events", "are", "scheduled", "in", "the", "specified", "window" ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/financial/helpers.py#L511-L618
django-danceschool/django-danceschool
danceschool/vouchers/views.py
GiftCertificateCustomizeView.dispatch
def dispatch(self,request,*args,**kwargs): ''' Check that a valid Invoice ID has been passed in session data, and that said invoice is marked as paid. ''' paymentSession = request.session.get(INVOICE_VALIDATION_STR, {}) self.invoiceID = paymentSession.get('invoiceID') self.amount = paymentSession.get('amount',0) self.success_url = paymentSession.get('success_url',reverse('registration')) # Check that Invoice matching passed ID exists try: i = Invoice.objects.get(id=self.invoiceID) except ObjectDoesNotExist: return HttpResponseBadRequest(_('Invalid invoice information passed.')) if i.unpaid or i.amountPaid != self.amount: return HttpResponseBadRequest(_('Passed invoice is not paid.')) return super(GiftCertificateCustomizeView,self).dispatch(request,*args,**kwargs)
python
def dispatch(self,request,*args,**kwargs): paymentSession = request.session.get(INVOICE_VALIDATION_STR, {}) self.invoiceID = paymentSession.get('invoiceID') self.amount = paymentSession.get('amount',0) self.success_url = paymentSession.get('success_url',reverse('registration')) try: i = Invoice.objects.get(id=self.invoiceID) except ObjectDoesNotExist: return HttpResponseBadRequest(_('Invalid invoice information passed.')) if i.unpaid or i.amountPaid != self.amount: return HttpResponseBadRequest(_('Passed invoice is not paid.')) return super(GiftCertificateCustomizeView,self).dispatch(request,*args,**kwargs)
[ "def", "dispatch", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "paymentSession", "=", "request", ".", "session", ".", "get", "(", "INVOICE_VALIDATION_STR", ",", "{", "}", ")", "self", ".", "invoiceID", "=", "paymentSession", ".", "get", "(", "'invoiceID'", ")", "self", ".", "amount", "=", "paymentSession", ".", "get", "(", "'amount'", ",", "0", ")", "self", ".", "success_url", "=", "paymentSession", ".", "get", "(", "'success_url'", ",", "reverse", "(", "'registration'", ")", ")", "# Check that Invoice matching passed ID exists", "try", ":", "i", "=", "Invoice", ".", "objects", ".", "get", "(", "id", "=", "self", ".", "invoiceID", ")", "except", "ObjectDoesNotExist", ":", "return", "HttpResponseBadRequest", "(", "_", "(", "'Invalid invoice information passed.'", ")", ")", "if", "i", ".", "unpaid", "or", "i", ".", "amountPaid", "!=", "self", ".", "amount", ":", "return", "HttpResponseBadRequest", "(", "_", "(", "'Passed invoice is not paid.'", ")", ")", "return", "super", "(", "GiftCertificateCustomizeView", ",", "self", ")", ".", "dispatch", "(", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
Check that a valid Invoice ID has been passed in session data, and that said invoice is marked as paid.
[ "Check", "that", "a", "valid", "Invoice", "ID", "has", "been", "passed", "in", "session", "data", "and", "that", "said", "invoice", "is", "marked", "as", "paid", "." ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/vouchers/views.py#L31-L50
django-danceschool/django-danceschool
danceschool/vouchers/views.py
GiftCertificateCustomizeView.form_valid
def form_valid(self,form): ''' Create the gift certificate voucher with the indicated information and send the email as directed. ''' emailTo = form.cleaned_data.get('emailTo') emailType = form.cleaned_data.get('emailType') recipientName = form.cleaned_data.get('recipientName') fromName = form.cleaned_data.get('fromName') message = form.cleaned_data.get('message') logger.info('Processing gift certificate.') try: voucher = Voucher.create_new_code( prefix='GC_', name=_('Gift certificate: %s%s for %s' % (getConstant('general__currencySymbol'),self.amount, emailTo)), category=getConstant('vouchers__giftCertCategory'), originalAmount=self.amount, singleUse=False, forFirstTimeCustomersOnly=False, expirationDate=None, ) except IntegrityError: logger.error('Error creating gift certificate voucher for Invoice #%s' % self.invoiceId) emailErrorMessage(_('Gift certificate transaction not completed'), self.invoiceId) template = getConstant('vouchers__giftCertTemplate') # Attempt to attach a PDF of the gift certificate rf = RequestFactory() pdf_request = rf.get('/') pdf_kwargs = { 'currencySymbol': getConstant('general__currencySymbol'), 'businessName': getConstant('contact__businessName'), 'certificateAmount': voucher.originalAmount, 'certificateCode': voucher.voucherId, 'certificateMessage': message, 'recipientName': recipientName, 'fromName': fromName, } if recipientName: pdf_kwargs.update({}) attachment = GiftCertificatePDFView(request=pdf_request).get(request=pdf_request,**pdf_kwargs).content or None if attachment: attachment_name = 'gift_certificate.pdf' else: attachment_name = None # Send a confirmation email email_class = EmailRecipientMixin() email_class.email_recipient( subject=template.subject, content=template.content, send_html=template.send_html, html_content=template.html_content, from_address=template.defaultFromAddress, from_name=template.defaultFromName, cc=template.defaultCC, to=emailTo, currencySymbol=getConstant('general__currencySymbol'), businessName=getConstant('contact__businessName'), certificateAmount=voucher.originalAmount, certificateCode=voucher.voucherId, certificateMessage=message, recipientName=recipientName, fromName=fromName, emailType=emailType, recipient_name=recipientName, attachment_name=attachment_name, attachment=attachment ) # Remove the invoice session data self.request.session.pop(INVOICE_VALIDATION_STR,None) return HttpResponseRedirect(self.get_success_url())
python
def form_valid(self,form): emailTo = form.cleaned_data.get('emailTo') emailType = form.cleaned_data.get('emailType') recipientName = form.cleaned_data.get('recipientName') fromName = form.cleaned_data.get('fromName') message = form.cleaned_data.get('message') logger.info('Processing gift certificate.') try: voucher = Voucher.create_new_code( prefix='GC_', name=_('Gift certificate: %s%s for %s' % (getConstant('general__currencySymbol'),self.amount, emailTo)), category=getConstant('vouchers__giftCertCategory'), originalAmount=self.amount, singleUse=False, forFirstTimeCustomersOnly=False, expirationDate=None, ) except IntegrityError: logger.error('Error creating gift certificate voucher for Invoice emailErrorMessage(_('Gift certificate transaction not completed'), self.invoiceId) template = getConstant('vouchers__giftCertTemplate') rf = RequestFactory() pdf_request = rf.get('/') pdf_kwargs = { 'currencySymbol': getConstant('general__currencySymbol'), 'businessName': getConstant('contact__businessName'), 'certificateAmount': voucher.originalAmount, 'certificateCode': voucher.voucherId, 'certificateMessage': message, 'recipientName': recipientName, 'fromName': fromName, } if recipientName: pdf_kwargs.update({}) attachment = GiftCertificatePDFView(request=pdf_request).get(request=pdf_request,**pdf_kwargs).content or None if attachment: attachment_name = 'gift_certificate.pdf' else: attachment_name = None email_class = EmailRecipientMixin() email_class.email_recipient( subject=template.subject, content=template.content, send_html=template.send_html, html_content=template.html_content, from_address=template.defaultFromAddress, from_name=template.defaultFromName, cc=template.defaultCC, to=emailTo, currencySymbol=getConstant('general__currencySymbol'), businessName=getConstant('contact__businessName'), certificateAmount=voucher.originalAmount, certificateCode=voucher.voucherId, certificateMessage=message, recipientName=recipientName, fromName=fromName, emailType=emailType, recipient_name=recipientName, attachment_name=attachment_name, attachment=attachment ) self.request.session.pop(INVOICE_VALIDATION_STR,None) return HttpResponseRedirect(self.get_success_url())
[ "def", "form_valid", "(", "self", ",", "form", ")", ":", "emailTo", "=", "form", ".", "cleaned_data", ".", "get", "(", "'emailTo'", ")", "emailType", "=", "form", ".", "cleaned_data", ".", "get", "(", "'emailType'", ")", "recipientName", "=", "form", ".", "cleaned_data", ".", "get", "(", "'recipientName'", ")", "fromName", "=", "form", ".", "cleaned_data", ".", "get", "(", "'fromName'", ")", "message", "=", "form", ".", "cleaned_data", ".", "get", "(", "'message'", ")", "logger", ".", "info", "(", "'Processing gift certificate.'", ")", "try", ":", "voucher", "=", "Voucher", ".", "create_new_code", "(", "prefix", "=", "'GC_'", ",", "name", "=", "_", "(", "'Gift certificate: %s%s for %s'", "%", "(", "getConstant", "(", "'general__currencySymbol'", ")", ",", "self", ".", "amount", ",", "emailTo", ")", ")", ",", "category", "=", "getConstant", "(", "'vouchers__giftCertCategory'", ")", ",", "originalAmount", "=", "self", ".", "amount", ",", "singleUse", "=", "False", ",", "forFirstTimeCustomersOnly", "=", "False", ",", "expirationDate", "=", "None", ",", ")", "except", "IntegrityError", ":", "logger", ".", "error", "(", "'Error creating gift certificate voucher for Invoice #%s'", "%", "self", ".", "invoiceId", ")", "emailErrorMessage", "(", "_", "(", "'Gift certificate transaction not completed'", ")", ",", "self", ".", "invoiceId", ")", "template", "=", "getConstant", "(", "'vouchers__giftCertTemplate'", ")", "# Attempt to attach a PDF of the gift certificate", "rf", "=", "RequestFactory", "(", ")", "pdf_request", "=", "rf", ".", "get", "(", "'/'", ")", "pdf_kwargs", "=", "{", "'currencySymbol'", ":", "getConstant", "(", "'general__currencySymbol'", ")", ",", "'businessName'", ":", "getConstant", "(", "'contact__businessName'", ")", ",", "'certificateAmount'", ":", "voucher", ".", "originalAmount", ",", "'certificateCode'", ":", "voucher", ".", "voucherId", ",", "'certificateMessage'", ":", "message", ",", "'recipientName'", ":", "recipientName", ",", "'fromName'", ":", "fromName", ",", "}", "if", "recipientName", ":", "pdf_kwargs", ".", "update", "(", "{", "}", ")", "attachment", "=", "GiftCertificatePDFView", "(", "request", "=", "pdf_request", ")", ".", "get", "(", "request", "=", "pdf_request", ",", "*", "*", "pdf_kwargs", ")", ".", "content", "or", "None", "if", "attachment", ":", "attachment_name", "=", "'gift_certificate.pdf'", "else", ":", "attachment_name", "=", "None", "# Send a confirmation email", "email_class", "=", "EmailRecipientMixin", "(", ")", "email_class", ".", "email_recipient", "(", "subject", "=", "template", ".", "subject", ",", "content", "=", "template", ".", "content", ",", "send_html", "=", "template", ".", "send_html", ",", "html_content", "=", "template", ".", "html_content", ",", "from_address", "=", "template", ".", "defaultFromAddress", ",", "from_name", "=", "template", ".", "defaultFromName", ",", "cc", "=", "template", ".", "defaultCC", ",", "to", "=", "emailTo", ",", "currencySymbol", "=", "getConstant", "(", "'general__currencySymbol'", ")", ",", "businessName", "=", "getConstant", "(", "'contact__businessName'", ")", ",", "certificateAmount", "=", "voucher", ".", "originalAmount", ",", "certificateCode", "=", "voucher", ".", "voucherId", ",", "certificateMessage", "=", "message", ",", "recipientName", "=", "recipientName", ",", "fromName", "=", "fromName", ",", "emailType", "=", "emailType", ",", "recipient_name", "=", "recipientName", ",", "attachment_name", "=", "attachment_name", ",", "attachment", "=", "attachment", ")", "# Remove the invoice session data", "self", ".", "request", ".", "session", ".", "pop", "(", "INVOICE_VALIDATION_STR", ",", "None", ")", "return", "HttpResponseRedirect", "(", "self", ".", "get_success_url", "(", ")", ")" ]
Create the gift certificate voucher with the indicated information and send the email as directed.
[ "Create", "the", "gift", "certificate", "voucher", "with", "the", "indicated", "information", "and", "send", "the", "email", "as", "directed", "." ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/vouchers/views.py#L52-L131
django-danceschool/django-danceschool
danceschool/core/tasks.py
updateSeriesRegistrationStatus
def updateSeriesRegistrationStatus(): ''' Every hour, check if the series that are currently open for registration should be closed. ''' from .models import Series if not getConstant('general__enableCronTasks'): return logger.info('Checking status of Series that are open for registration.') open_series = Series.objects.filter().filter(**{'registrationOpen': True}) for series in open_series: series.updateRegistrationStatus()
python
def updateSeriesRegistrationStatus(): from .models import Series if not getConstant('general__enableCronTasks'): return logger.info('Checking status of Series that are open for registration.') open_series = Series.objects.filter().filter(**{'registrationOpen': True}) for series in open_series: series.updateRegistrationStatus()
[ "def", "updateSeriesRegistrationStatus", "(", ")", ":", "from", ".", "models", "import", "Series", "if", "not", "getConstant", "(", "'general__enableCronTasks'", ")", ":", "return", "logger", ".", "info", "(", "'Checking status of Series that are open for registration.'", ")", "open_series", "=", "Series", ".", "objects", ".", "filter", "(", ")", ".", "filter", "(", "*", "*", "{", "'registrationOpen'", ":", "True", "}", ")", "for", "series", "in", "open_series", ":", "series", ".", "updateRegistrationStatus", "(", ")" ]
Every hour, check if the series that are currently open for registration should be closed.
[ "Every", "hour", "check", "if", "the", "series", "that", "are", "currently", "open", "for", "registration", "should", "be", "closed", "." ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/core/tasks.py#L19-L34
django-danceschool/django-danceschool
danceschool/core/tasks.py
clearExpiredTemporaryRegistrations
def clearExpiredTemporaryRegistrations(): ''' Every hour, look for TemporaryRegistrations that have expired and delete them. To ensure that there are no issues that arise from slight differences between session expiration dates and TemporaryRegistration expiration dates, only delete instances that have been expired for one minute. ''' from .models import TemporaryRegistration if not getConstant('general__enableCronTasks'): return if getConstant('registration__deleteExpiredTemporaryRegistrations'): TemporaryRegistration.objects.filter(expirationDate__lte=timezone.now() - timedelta(minutes=1)).delete() call_command('clearsessions')
python
def clearExpiredTemporaryRegistrations(): from .models import TemporaryRegistration if not getConstant('general__enableCronTasks'): return if getConstant('registration__deleteExpiredTemporaryRegistrations'): TemporaryRegistration.objects.filter(expirationDate__lte=timezone.now() - timedelta(minutes=1)).delete() call_command('clearsessions')
[ "def", "clearExpiredTemporaryRegistrations", "(", ")", ":", "from", ".", "models", "import", "TemporaryRegistration", "if", "not", "getConstant", "(", "'general__enableCronTasks'", ")", ":", "return", "if", "getConstant", "(", "'registration__deleteExpiredTemporaryRegistrations'", ")", ":", "TemporaryRegistration", ".", "objects", ".", "filter", "(", "expirationDate__lte", "=", "timezone", ".", "now", "(", ")", "-", "timedelta", "(", "minutes", "=", "1", ")", ")", ".", "delete", "(", ")", "call_command", "(", "'clearsessions'", ")" ]
Every hour, look for TemporaryRegistrations that have expired and delete them. To ensure that there are no issues that arise from slight differences between session expiration dates and TemporaryRegistration expiration dates, only delete instances that have been expired for one minute.
[ "Every", "hour", "look", "for", "TemporaryRegistrations", "that", "have", "expired", "and", "delete", "them", ".", "To", "ensure", "that", "there", "are", "no", "issues", "that", "arise", "from", "slight", "differences", "between", "session", "expiration", "dates", "and", "TemporaryRegistration", "expiration", "dates", "only", "delete", "instances", "that", "have", "been", "expired", "for", "one", "minute", "." ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/core/tasks.py#L38-L52
django-danceschool/django-danceschool
danceschool/financial/tasks.py
updateFinancialItems
def updateFinancialItems(): ''' Every hour, create any necessary revenue items and expense items for activities that need them. ''' if not getConstant('general__enableCronTasks'): return logger.info('Creating automatically-generated financial items.') if getConstant('financial__autoGenerateExpensesEventStaff'): createExpenseItemsForEvents() if getConstant('financial__autoGenerateExpensesVenueRental'): createExpenseItemsForVenueRental() if getConstant('financial__autoGenerateRevenueRegistrations'): createRevenueItemsForRegistrations()
python
def updateFinancialItems(): if not getConstant('general__enableCronTasks'): return logger.info('Creating automatically-generated financial items.') if getConstant('financial__autoGenerateExpensesEventStaff'): createExpenseItemsForEvents() if getConstant('financial__autoGenerateExpensesVenueRental'): createExpenseItemsForVenueRental() if getConstant('financial__autoGenerateRevenueRegistrations'): createRevenueItemsForRegistrations()
[ "def", "updateFinancialItems", "(", ")", ":", "if", "not", "getConstant", "(", "'general__enableCronTasks'", ")", ":", "return", "logger", ".", "info", "(", "'Creating automatically-generated financial items.'", ")", "if", "getConstant", "(", "'financial__autoGenerateExpensesEventStaff'", ")", ":", "createExpenseItemsForEvents", "(", ")", "if", "getConstant", "(", "'financial__autoGenerateExpensesVenueRental'", ")", ":", "createExpenseItemsForVenueRental", "(", ")", "if", "getConstant", "(", "'financial__autoGenerateRevenueRegistrations'", ")", ":", "createRevenueItemsForRegistrations", "(", ")" ]
Every hour, create any necessary revenue items and expense items for activities that need them.
[ "Every", "hour", "create", "any", "necessary", "revenue", "items", "and", "expense", "items", "for", "activities", "that", "need", "them", "." ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/financial/tasks.py#L15-L30
django-danceschool/django-danceschool
danceschool/core/helpers.py
emailErrorMessage
def emailErrorMessage(subject,message): ''' Useful for sending error messages via email. ''' if not getConstant('email__enableErrorEmails'): logger.info('Not sending error email: error emails are not enabled.') return send_from = getConstant('email__errorEmailFrom') send_to = getConstant('email__errorEmailTo') if not send_from or not send_to: logger.error('Cannot send error emails because addresses have not been specified.') return try: send_mail(subject,message, send_from, [send_to], fail_silently=False) logger.debug('Error email sent.') except Exception as e: logger.error('Error email was not sent: %s' % e)
python
def emailErrorMessage(subject,message): if not getConstant('email__enableErrorEmails'): logger.info('Not sending error email: error emails are not enabled.') return send_from = getConstant('email__errorEmailFrom') send_to = getConstant('email__errorEmailTo') if not send_from or not send_to: logger.error('Cannot send error emails because addresses have not been specified.') return try: send_mail(subject,message, send_from, [send_to], fail_silently=False) logger.debug('Error email sent.') except Exception as e: logger.error('Error email was not sent: %s' % e)
[ "def", "emailErrorMessage", "(", "subject", ",", "message", ")", ":", "if", "not", "getConstant", "(", "'email__enableErrorEmails'", ")", ":", "logger", ".", "info", "(", "'Not sending error email: error emails are not enabled.'", ")", "return", "send_from", "=", "getConstant", "(", "'email__errorEmailFrom'", ")", "send_to", "=", "getConstant", "(", "'email__errorEmailTo'", ")", "if", "not", "send_from", "or", "not", "send_to", ":", "logger", ".", "error", "(", "'Cannot send error emails because addresses have not been specified.'", ")", "return", "try", ":", "send_mail", "(", "subject", ",", "message", ",", "send_from", ",", "[", "send_to", "]", ",", "fail_silently", "=", "False", ")", "logger", ".", "debug", "(", "'Error email sent.'", ")", "except", "Exception", "as", "e", ":", "logger", ".", "error", "(", "'Error email was not sent: %s'", "%", "e", ")" ]
Useful for sending error messages via email.
[ "Useful", "for", "sending", "error", "messages", "via", "email", "." ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/core/helpers.py#L15-L36
django-danceschool/django-danceschool
danceschool/core/helpers.py
getReturnPage
def getReturnPage(siteHistory,prior=False): ''' This helper function is called in various places to get the return page from current session data. The session data (in the 'SITE_HISTORY' key) is a required argument. ''' expiry = parse_datetime( siteHistory.get('expiry',''), ) if prior: returnPage = siteHistory.get('priorPage',None) returnPageName = siteHistory.get('priorPageName',None) else: returnPage = siteHistory.get('returnPage',None) returnPageName = siteHistory.get('returnPageName',None) if expiry and expiry >= timezone.now() and returnPage[0]: return { 'url': reverse(returnPage[0],kwargs=returnPage[1]), 'title': returnPageName, } else: return {'url': None, 'title': None}
python
def getReturnPage(siteHistory,prior=False): expiry = parse_datetime( siteHistory.get('expiry',''), ) if prior: returnPage = siteHistory.get('priorPage',None) returnPageName = siteHistory.get('priorPageName',None) else: returnPage = siteHistory.get('returnPage',None) returnPageName = siteHistory.get('returnPageName',None) if expiry and expiry >= timezone.now() and returnPage[0]: return { 'url': reverse(returnPage[0],kwargs=returnPage[1]), 'title': returnPageName, } else: return {'url': None, 'title': None}
[ "def", "getReturnPage", "(", "siteHistory", ",", "prior", "=", "False", ")", ":", "expiry", "=", "parse_datetime", "(", "siteHistory", ".", "get", "(", "'expiry'", ",", "''", ")", ",", ")", "if", "prior", ":", "returnPage", "=", "siteHistory", ".", "get", "(", "'priorPage'", ",", "None", ")", "returnPageName", "=", "siteHistory", ".", "get", "(", "'priorPageName'", ",", "None", ")", "else", ":", "returnPage", "=", "siteHistory", ".", "get", "(", "'returnPage'", ",", "None", ")", "returnPageName", "=", "siteHistory", ".", "get", "(", "'returnPageName'", ",", "None", ")", "if", "expiry", "and", "expiry", ">=", "timezone", ".", "now", "(", ")", "and", "returnPage", "[", "0", "]", ":", "return", "{", "'url'", ":", "reverse", "(", "returnPage", "[", "0", "]", ",", "kwargs", "=", "returnPage", "[", "1", "]", ")", ",", "'title'", ":", "returnPageName", ",", "}", "else", ":", "return", "{", "'url'", ":", "None", ",", "'title'", ":", "None", "}" ]
This helper function is called in various places to get the return page from current session data. The session data (in the 'SITE_HISTORY' key) is a required argument.
[ "This", "helper", "function", "is", "called", "in", "various", "places", "to", "get", "the", "return", "page", "from", "current", "session", "data", ".", "The", "session", "data", "(", "in", "the", "SITE_HISTORY", "key", ")", "is", "a", "required", "argument", "." ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/core/helpers.py#L39-L61
django-danceschool/django-danceschool
danceschool/financial/views.py
FinancesByPeriodView.get
def get(self,request,*args,**kwargs): ''' Allow passing of basis and time limitations ''' try: year = int(self.kwargs.get('year')) except (ValueError, TypeError): year = getIntFromGet(request,'year') kwargs.update({ 'year': year, 'basis': request.GET.get('basis'), }) if kwargs.get('basis') not in EXPENSE_BASES.keys(): kwargs['basis'] = 'accrualDate' return super().get(request, *args, **kwargs)
python
def get(self,request,*args,**kwargs): try: year = int(self.kwargs.get('year')) except (ValueError, TypeError): year = getIntFromGet(request,'year') kwargs.update({ 'year': year, 'basis': request.GET.get('basis'), }) if kwargs.get('basis') not in EXPENSE_BASES.keys(): kwargs['basis'] = 'accrualDate' return super().get(request, *args, **kwargs)
[ "def", "get", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "try", ":", "year", "=", "int", "(", "self", ".", "kwargs", ".", "get", "(", "'year'", ")", ")", "except", "(", "ValueError", ",", "TypeError", ")", ":", "year", "=", "getIntFromGet", "(", "request", ",", "'year'", ")", "kwargs", ".", "update", "(", "{", "'year'", ":", "year", ",", "'basis'", ":", "request", ".", "GET", ".", "get", "(", "'basis'", ")", ",", "}", ")", "if", "kwargs", ".", "get", "(", "'basis'", ")", "not", "in", "EXPENSE_BASES", ".", "keys", "(", ")", ":", "kwargs", "[", "'basis'", "]", "=", "'accrualDate'", "return", "super", "(", ")", ".", "get", "(", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
Allow passing of basis and time limitations
[ "Allow", "passing", "of", "basis", "and", "time", "limitations" ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/financial/views.py#L303-L320
django-danceschool/django-danceschool
danceschool/financial/views.py
FinancialDetailView.get
def get(self,request,*args,**kwargs): ''' Pass any permissable GET data. URL parameters override GET parameters ''' try: year = int(self.kwargs.get('year')) except (ValueError, TypeError): year = getIntFromGet(request,'year') if self.kwargs.get('month'): try: month = int(self.kwargs.get('month')) except (ValueError, TypeError): try: month = list(month_name).index(self.kwargs.get('month').title()) except (ValueError, TypeError): month = None else: month = getIntFromGet(request, 'month') try: event_id = int(self.kwargs.get('event')) except (ValueError, TypeError): event_id = getIntFromGet(request, 'event') event = None if event_id: try: event = Event.objects.get(id=event_id) except ObjectDoesNotExist: pass kwargs.update({ 'year': year, 'month': month, 'startDate': getDateTimeFromGet(request,'startDate'), 'endDate': getDateTimeFromGet(request,'endDate'), 'basis': request.GET.get('basis'), 'event': event, }) if kwargs.get('basis') not in EXPENSE_BASES.keys(): kwargs['basis'] = 'accrualDate' context = self.get_context_data(**kwargs) return self.render_to_response(context)
python
def get(self,request,*args,**kwargs): try: year = int(self.kwargs.get('year')) except (ValueError, TypeError): year = getIntFromGet(request,'year') if self.kwargs.get('month'): try: month = int(self.kwargs.get('month')) except (ValueError, TypeError): try: month = list(month_name).index(self.kwargs.get('month').title()) except (ValueError, TypeError): month = None else: month = getIntFromGet(request, 'month') try: event_id = int(self.kwargs.get('event')) except (ValueError, TypeError): event_id = getIntFromGet(request, 'event') event = None if event_id: try: event = Event.objects.get(id=event_id) except ObjectDoesNotExist: pass kwargs.update({ 'year': year, 'month': month, 'startDate': getDateTimeFromGet(request,'startDate'), 'endDate': getDateTimeFromGet(request,'endDate'), 'basis': request.GET.get('basis'), 'event': event, }) if kwargs.get('basis') not in EXPENSE_BASES.keys(): kwargs['basis'] = 'accrualDate' context = self.get_context_data(**kwargs) return self.render_to_response(context)
[ "def", "get", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "try", ":", "year", "=", "int", "(", "self", ".", "kwargs", ".", "get", "(", "'year'", ")", ")", "except", "(", "ValueError", ",", "TypeError", ")", ":", "year", "=", "getIntFromGet", "(", "request", ",", "'year'", ")", "if", "self", ".", "kwargs", ".", "get", "(", "'month'", ")", ":", "try", ":", "month", "=", "int", "(", "self", ".", "kwargs", ".", "get", "(", "'month'", ")", ")", "except", "(", "ValueError", ",", "TypeError", ")", ":", "try", ":", "month", "=", "list", "(", "month_name", ")", ".", "index", "(", "self", ".", "kwargs", ".", "get", "(", "'month'", ")", ".", "title", "(", ")", ")", "except", "(", "ValueError", ",", "TypeError", ")", ":", "month", "=", "None", "else", ":", "month", "=", "getIntFromGet", "(", "request", ",", "'month'", ")", "try", ":", "event_id", "=", "int", "(", "self", ".", "kwargs", ".", "get", "(", "'event'", ")", ")", "except", "(", "ValueError", ",", "TypeError", ")", ":", "event_id", "=", "getIntFromGet", "(", "request", ",", "'event'", ")", "event", "=", "None", "if", "event_id", ":", "try", ":", "event", "=", "Event", ".", "objects", ".", "get", "(", "id", "=", "event_id", ")", "except", "ObjectDoesNotExist", ":", "pass", "kwargs", ".", "update", "(", "{", "'year'", ":", "year", ",", "'month'", ":", "month", ",", "'startDate'", ":", "getDateTimeFromGet", "(", "request", ",", "'startDate'", ")", ",", "'endDate'", ":", "getDateTimeFromGet", "(", "request", ",", "'endDate'", ")", ",", "'basis'", ":", "request", ".", "GET", ".", "get", "(", "'basis'", ")", ",", "'event'", ":", "event", ",", "}", ")", "if", "kwargs", ".", "get", "(", "'basis'", ")", "not", "in", "EXPENSE_BASES", ".", "keys", "(", ")", ":", "kwargs", "[", "'basis'", "]", "=", "'accrualDate'", "context", "=", "self", ".", "get_context_data", "(", "*", "*", "kwargs", ")", "return", "self", ".", "render_to_response", "(", "context", ")" ]
Pass any permissable GET data. URL parameters override GET parameters
[ "Pass", "any", "permissable", "GET", "data", ".", "URL", "parameters", "override", "GET", "parameters" ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/financial/views.py#L428-L473
django-danceschool/django-danceschool
danceschool/financial/views.py
CompensationActionView.get_form_kwargs
def get_form_kwargs(self, **kwargs): ''' pass the list of staff members along to the form ''' kwargs = super(CompensationActionView, self).get_form_kwargs(**kwargs) kwargs['staffmembers'] = self.queryset return kwargs
python
def get_form_kwargs(self, **kwargs): kwargs = super(CompensationActionView, self).get_form_kwargs(**kwargs) kwargs['staffmembers'] = self.queryset return kwargs
[ "def", "get_form_kwargs", "(", "self", ",", "*", "*", "kwargs", ")", ":", "kwargs", "=", "super", "(", "CompensationActionView", ",", "self", ")", ".", "get_form_kwargs", "(", "*", "*", "kwargs", ")", "kwargs", "[", "'staffmembers'", "]", "=", "self", ".", "queryset", "return", "kwargs" ]
pass the list of staff members along to the form
[ "pass", "the", "list", "of", "staff", "members", "along", "to", "the", "form" ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/financial/views.py#L631-L635
django-danceschool/django-danceschool
danceschool/private_events/forms.py
EventOccurrenceCustomFormSet.setReminder
def setReminder(self,occurrence): ''' This function is called to create the actual reminders for each occurrence that is created. ''' sendReminderTo = self[0].cleaned_data['sendReminderTo'] sendReminderWhen = self[0].cleaned_data['sendReminderWhen'] sendReminderGroup = self[0].cleaned_data['sendReminderGroup'] sendReminderUsers = self[0].cleaned_data['sendReminderUsers'] # Set the new reminder's time new_reminder_time = occurrence.startTime - timedelta(minutes=int(float(sendReminderWhen))) new_reminder = EventReminder(eventOccurrence=occurrence,time=new_reminder_time) new_reminder.save() # Set reminders based on the choice the user made if sendReminderTo == 'all': user_set = User.objects.filter(Q(staffmember__isnull=False) | Q(is_staff=True)) elif sendReminderTo == 'me': user_set = User.objects.filter(id=occurrence.event.submissionUser.id) elif sendReminderTo == 'users': user_set = User.objects.filter(**{'id__in': sendReminderUsers}) elif sendReminderTo == 'group': user_set = User.objects.filter(**{'groups': sendReminderGroup}) else: user_set = [] for user in user_set: new_reminder.notifyList.add(user)
python
def setReminder(self,occurrence): sendReminderTo = self[0].cleaned_data['sendReminderTo'] sendReminderWhen = self[0].cleaned_data['sendReminderWhen'] sendReminderGroup = self[0].cleaned_data['sendReminderGroup'] sendReminderUsers = self[0].cleaned_data['sendReminderUsers'] new_reminder_time = occurrence.startTime - timedelta(minutes=int(float(sendReminderWhen))) new_reminder = EventReminder(eventOccurrence=occurrence,time=new_reminder_time) new_reminder.save() if sendReminderTo == 'all': user_set = User.objects.filter(Q(staffmember__isnull=False) | Q(is_staff=True)) elif sendReminderTo == 'me': user_set = User.objects.filter(id=occurrence.event.submissionUser.id) elif sendReminderTo == 'users': user_set = User.objects.filter(**{'id__in': sendReminderUsers}) elif sendReminderTo == 'group': user_set = User.objects.filter(**{'groups': sendReminderGroup}) else: user_set = [] for user in user_set: new_reminder.notifyList.add(user)
[ "def", "setReminder", "(", "self", ",", "occurrence", ")", ":", "sendReminderTo", "=", "self", "[", "0", "]", ".", "cleaned_data", "[", "'sendReminderTo'", "]", "sendReminderWhen", "=", "self", "[", "0", "]", ".", "cleaned_data", "[", "'sendReminderWhen'", "]", "sendReminderGroup", "=", "self", "[", "0", "]", ".", "cleaned_data", "[", "'sendReminderGroup'", "]", "sendReminderUsers", "=", "self", "[", "0", "]", ".", "cleaned_data", "[", "'sendReminderUsers'", "]", "# Set the new reminder's time\r", "new_reminder_time", "=", "occurrence", ".", "startTime", "-", "timedelta", "(", "minutes", "=", "int", "(", "float", "(", "sendReminderWhen", ")", ")", ")", "new_reminder", "=", "EventReminder", "(", "eventOccurrence", "=", "occurrence", ",", "time", "=", "new_reminder_time", ")", "new_reminder", ".", "save", "(", ")", "# Set reminders based on the choice the user made\r", "if", "sendReminderTo", "==", "'all'", ":", "user_set", "=", "User", ".", "objects", ".", "filter", "(", "Q", "(", "staffmember__isnull", "=", "False", ")", "|", "Q", "(", "is_staff", "=", "True", ")", ")", "elif", "sendReminderTo", "==", "'me'", ":", "user_set", "=", "User", ".", "objects", ".", "filter", "(", "id", "=", "occurrence", ".", "event", ".", "submissionUser", ".", "id", ")", "elif", "sendReminderTo", "==", "'users'", ":", "user_set", "=", "User", ".", "objects", ".", "filter", "(", "*", "*", "{", "'id__in'", ":", "sendReminderUsers", "}", ")", "elif", "sendReminderTo", "==", "'group'", ":", "user_set", "=", "User", ".", "objects", ".", "filter", "(", "*", "*", "{", "'groups'", ":", "sendReminderGroup", "}", ")", "else", ":", "user_set", "=", "[", "]", "for", "user", "in", "user_set", ":", "new_reminder", ".", "notifyList", ".", "add", "(", "user", ")" ]
This function is called to create the actual reminders for each occurrence that is created.
[ "This", "function", "is", "called", "to", "create", "the", "actual", "reminders", "for", "each", "occurrence", "that", "is", "created", "." ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/private_events/forms.py#L181-L208
django-danceschool/django-danceschool
danceschool/core/utils/requests.py
getIntFromGet
def getIntFromGet(request,key): ''' This function just parses the request GET data for the requested key, and returns it as an integer, returning none if the key is not available or is in incorrect format. ''' try: return int(request.GET.get(key)) except (ValueError, TypeError): return None
python
def getIntFromGet(request,key): try: return int(request.GET.get(key)) except (ValueError, TypeError): return None
[ "def", "getIntFromGet", "(", "request", ",", "key", ")", ":", "try", ":", "return", "int", "(", "request", ".", "GET", ".", "get", "(", "key", ")", ")", "except", "(", "ValueError", ",", "TypeError", ")", ":", "return", "None" ]
This function just parses the request GET data for the requested key, and returns it as an integer, returning none if the key is not available or is in incorrect format.
[ "This", "function", "just", "parses", "the", "request", "GET", "data", "for", "the", "requested", "key", "and", "returns", "it", "as", "an", "integer", "returning", "none", "if", "the", "key", "is", "not", "available", "or", "is", "in", "incorrect", "format", "." ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/core/utils/requests.py#L7-L16
django-danceschool/django-danceschool
danceschool/core/utils/requests.py
getDateTimeFromGet
def getDateTimeFromGet(request,key): ''' This function just parses the request GET data for the requested key, and returns it in datetime format, returning none if the key is not available or is in incorrect format. ''' if request.GET.get(key,''): try: return ensure_timezone(datetime.strptime(unquote(request.GET.get(key,'')),'%Y-%m-%d')) except (ValueError, TypeError): pass return None
python
def getDateTimeFromGet(request,key): if request.GET.get(key,''): try: return ensure_timezone(datetime.strptime(unquote(request.GET.get(key,'')),'%Y-%m-%d')) except (ValueError, TypeError): pass return None
[ "def", "getDateTimeFromGet", "(", "request", ",", "key", ")", ":", "if", "request", ".", "GET", ".", "get", "(", "key", ",", "''", ")", ":", "try", ":", "return", "ensure_timezone", "(", "datetime", ".", "strptime", "(", "unquote", "(", "request", ".", "GET", ".", "get", "(", "key", ",", "''", ")", ")", ",", "'%Y-%m-%d'", ")", ")", "except", "(", "ValueError", ",", "TypeError", ")", ":", "pass", "return", "None" ]
This function just parses the request GET data for the requested key, and returns it in datetime format, returning none if the key is not available or is in incorrect format.
[ "This", "function", "just", "parses", "the", "request", "GET", "data", "for", "the", "requested", "key", "and", "returns", "it", "in", "datetime", "format", "returning", "none", "if", "the", "key", "is", "not", "available", "or", "is", "in", "incorrect", "format", "." ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/core/utils/requests.py#L19-L30
django-danceschool/django-danceschool
danceschool/private_lessons/handlers.py
finalizePrivateLessonRegistration
def finalizePrivateLessonRegistration(sender,**kwargs): ''' Once a private lesson registration is finalized, mark the slots that were used to book the private lesson as booked and associate them with the final registration. No need to notify students in this instance because they are already receiving a notification of their registration. ''' finalReg = kwargs.pop('registration') for er in finalReg.eventregistration_set.filter( event__privatelessonevent__isnull=False ): er.event.finalizeBooking(eventRegistration=er,notifyStudent=False)
python
def finalizePrivateLessonRegistration(sender,**kwargs): finalReg = kwargs.pop('registration') for er in finalReg.eventregistration_set.filter( event__privatelessonevent__isnull=False ): er.event.finalizeBooking(eventRegistration=er,notifyStudent=False)
[ "def", "finalizePrivateLessonRegistration", "(", "sender", ",", "*", "*", "kwargs", ")", ":", "finalReg", "=", "kwargs", ".", "pop", "(", "'registration'", ")", "for", "er", "in", "finalReg", ".", "eventregistration_set", ".", "filter", "(", "event__privatelessonevent__isnull", "=", "False", ")", ":", "er", ".", "event", ".", "finalizeBooking", "(", "eventRegistration", "=", "er", ",", "notifyStudent", "=", "False", ")" ]
Once a private lesson registration is finalized, mark the slots that were used to book the private lesson as booked and associate them with the final registration. No need to notify students in this instance because they are already receiving a notification of their registration.
[ "Once", "a", "private", "lesson", "registration", "is", "finalized", "mark", "the", "slots", "that", "were", "used", "to", "book", "the", "private", "lesson", "as", "booked", "and", "associate", "them", "with", "the", "final", "registration", ".", "No", "need", "to", "notify", "students", "in", "this", "instance", "because", "they", "are", "already", "receiving", "a", "notification", "of", "their", "registration", "." ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/private_lessons/handlers.py#L6-L19
django-danceschool/django-danceschool
danceschool/payments/stripe/cms_plugins.py
StripeGiftCertificateFormPlugin.render
def render(self, context, instance, placeholder): ''' Create a UUID and check if a voucher with that ID exists before rendering ''' context = super(StripeGiftCertificateFormPlugin, self).render(context, instance, placeholder) context.update({ 'stripe_key': getattr(settings,'STRIPE_PUBLIC_KEY',''), 'business_name': getConstant('contact__businessName'), 'currencyCode': getConstant('general__currencyCode'), }) return context
python
def render(self, context, instance, placeholder): context = super(StripeGiftCertificateFormPlugin, self).render(context, instance, placeholder) context.update({ 'stripe_key': getattr(settings,'STRIPE_PUBLIC_KEY',''), 'business_name': getConstant('contact__businessName'), 'currencyCode': getConstant('general__currencyCode'), }) return context
[ "def", "render", "(", "self", ",", "context", ",", "instance", ",", "placeholder", ")", ":", "context", "=", "super", "(", "StripeGiftCertificateFormPlugin", ",", "self", ")", ".", "render", "(", "context", ",", "instance", ",", "placeholder", ")", "context", ".", "update", "(", "{", "'stripe_key'", ":", "getattr", "(", "settings", ",", "'STRIPE_PUBLIC_KEY'", ",", "''", ")", ",", "'business_name'", ":", "getConstant", "(", "'contact__businessName'", ")", ",", "'currencyCode'", ":", "getConstant", "(", "'general__currencyCode'", ")", ",", "}", ")", "return", "context" ]
Create a UUID and check if a voucher with that ID exists before rendering
[ "Create", "a", "UUID", "and", "check", "if", "a", "voucher", "with", "that", "ID", "exists", "before", "rendering" ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/payments/stripe/cms_plugins.py#L18-L28
django-danceschool/django-danceschool
danceschool/core/utils/emails.py
get_text_for_html
def get_text_for_html(html_content): ''' Take the HTML content (from, for example, an email) and construct a simple plain text version of that content (for example, for inclusion in a multipart email message). ''' soup = BeautifulSoup(html_content) # kill all script and style elements for script in soup(["script", "style"]): script.extract() # rip it out # Replace all links with HREF with the link text and the href in brackets for a in soup.findAll('a', href=True): a.replaceWith('%s <%s>' % (a.string, a.get('href'))) # get text text = soup.get_text() # break into lines and remove leading and trailing space on each lines = (line.strip() for line in text.splitlines()) # break multi-headlines into a line each chunks = (phrase.strip() for line in lines for phrase in line.split(" ")) # drop blank lines text = '\n'.join(chunk for chunk in chunks if chunk) return text
python
def get_text_for_html(html_content): soup = BeautifulSoup(html_content) for script in soup(["script", "style"]): script.extract() for a in soup.findAll('a', href=True): a.replaceWith('%s <%s>' % (a.string, a.get('href'))) text = soup.get_text() lines = (line.strip() for line in text.splitlines()) chunks = (phrase.strip() for line in lines for phrase in line.split(" ")) text = '\n'.join(chunk for chunk in chunks if chunk) return text
[ "def", "get_text_for_html", "(", "html_content", ")", ":", "soup", "=", "BeautifulSoup", "(", "html_content", ")", "# kill all script and style elements\r", "for", "script", "in", "soup", "(", "[", "\"script\"", ",", "\"style\"", "]", ")", ":", "script", ".", "extract", "(", ")", "# rip it out\r", "# Replace all links with HREF with the link text and the href in brackets\r", "for", "a", "in", "soup", ".", "findAll", "(", "'a'", ",", "href", "=", "True", ")", ":", "a", ".", "replaceWith", "(", "'%s <%s>'", "%", "(", "a", ".", "string", ",", "a", ".", "get", "(", "'href'", ")", ")", ")", "# get text\r", "text", "=", "soup", ".", "get_text", "(", ")", "# break into lines and remove leading and trailing space on each\r", "lines", "=", "(", "line", ".", "strip", "(", ")", "for", "line", "in", "text", ".", "splitlines", "(", ")", ")", "# break multi-headlines into a line each\r", "chunks", "=", "(", "phrase", ".", "strip", "(", ")", "for", "line", "in", "lines", "for", "phrase", "in", "line", ".", "split", "(", "\" \"", ")", ")", "# drop blank lines\r", "text", "=", "'\\n'", ".", "join", "(", "chunk", "for", "chunk", "in", "chunks", "if", "chunk", ")", "return", "text" ]
Take the HTML content (from, for example, an email) and construct a simple plain text version of that content (for example, for inclusion in a multipart email message).
[ "Take", "the", "HTML", "content", "(", "from", "for", "example", "an", "email", ")", "and", "construct", "a", "simple", "plain", "text", "version", "of", "that", "content", "(", "for", "example", "for", "inclusion", "in", "a", "multipart", "email", "message", ")", "." ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/core/utils/emails.py#L4-L31
django-danceschool/django-danceschool
danceschool/financial/admin.py
resetStaffCompensationInfo
def resetStaffCompensationInfo(self, request, queryset): ''' This action is added to the list for staff member to permit bulk reseting to category defaults of compensation information for staff members. ''' selected = request.POST.getlist(admin.ACTION_CHECKBOX_NAME) ct = ContentType.objects.get_for_model(queryset.model) return HttpResponseRedirect(reverse('resetCompensationRules') + "?ct=%s&ids=%s" % (ct.pk, ",".join(selected)))
python
def resetStaffCompensationInfo(self, request, queryset): selected = request.POST.getlist(admin.ACTION_CHECKBOX_NAME) ct = ContentType.objects.get_for_model(queryset.model) return HttpResponseRedirect(reverse('resetCompensationRules') + "?ct=%s&ids=%s" % (ct.pk, ",".join(selected)))
[ "def", "resetStaffCompensationInfo", "(", "self", ",", "request", ",", "queryset", ")", ":", "selected", "=", "request", ".", "POST", ".", "getlist", "(", "admin", ".", "ACTION_CHECKBOX_NAME", ")", "ct", "=", "ContentType", ".", "objects", ".", "get_for_model", "(", "queryset", ".", "model", ")", "return", "HttpResponseRedirect", "(", "reverse", "(", "'resetCompensationRules'", ")", "+", "\"?ct=%s&ids=%s\"", "%", "(", "ct", ".", "pk", ",", "\",\"", ".", "join", "(", "selected", ")", ")", ")" ]
This action is added to the list for staff member to permit bulk reseting to category defaults of compensation information for staff members.
[ "This", "action", "is", "added", "to", "the", "list", "for", "staff", "member", "to", "permit", "bulk", "reseting", "to", "category", "defaults", "of", "compensation", "information", "for", "staff", "members", "." ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/financial/admin.py#L382-L389
django-danceschool/django-danceschool
danceschool/financial/admin.py
RepeatedExpenseRuleChildAdmin.get_fieldsets
def get_fieldsets(self, request, obj=None): ''' Override polymorphic default to put the subclass-specific fields first ''' # If subclass declares fieldsets, this is respected if (hasattr(self, 'declared_fieldset') and self.declared_fieldsets) \ or not self.base_fieldsets: return super(PolymorphicChildModelAdmin, self).get_fieldsets(request, obj) other_fields = self.get_subclass_fields(request, obj) if other_fields: return ( (self.extra_fieldset_title, {'fields': other_fields}), ) + self.base_fieldsets else: return self.base_fieldsets
python
def get_fieldsets(self, request, obj=None): if (hasattr(self, 'declared_fieldset') and self.declared_fieldsets) \ or not self.base_fieldsets: return super(PolymorphicChildModelAdmin, self).get_fieldsets(request, obj) other_fields = self.get_subclass_fields(request, obj) if other_fields: return ( (self.extra_fieldset_title, {'fields': other_fields}), ) + self.base_fieldsets else: return self.base_fieldsets
[ "def", "get_fieldsets", "(", "self", ",", "request", ",", "obj", "=", "None", ")", ":", "# If subclass declares fieldsets, this is respected", "if", "(", "hasattr", "(", "self", ",", "'declared_fieldset'", ")", "and", "self", ".", "declared_fieldsets", ")", "or", "not", "self", ".", "base_fieldsets", ":", "return", "super", "(", "PolymorphicChildModelAdmin", ",", "self", ")", ".", "get_fieldsets", "(", "request", ",", "obj", ")", "other_fields", "=", "self", ".", "get_subclass_fields", "(", "request", ",", "obj", ")", "if", "other_fields", ":", "return", "(", "(", "self", ".", "extra_fieldset_title", ",", "{", "'fields'", ":", "other_fields", "}", ")", ",", ")", "+", "self", ".", "base_fieldsets", "else", ":", "return", "self", ".", "base_fieldsets" ]
Override polymorphic default to put the subclass-specific fields first
[ "Override", "polymorphic", "default", "to", "put", "the", "subclass", "-", "specific", "fields", "first" ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/financial/admin.py#L427-L441
django-danceschool/django-danceschool
danceschool/core/management/commands/setupschool.py
Command.pattern_input
def pattern_input(self, question, message='Invalid entry', pattern='^[a-zA-Z0-9_ ]+$', default='',required=True): ''' Method for input disallowing special characters, with optionally specifiable regex pattern and error message. ''' result = '' requiredFlag = True while (not result and requiredFlag): result = input('%s: ' % question) if result and pattern and not re.match(pattern, result): self.stdout.write(self.style.ERROR(message)) result = '' elif not result and default: # Return default for fields with default return default elif not result and required: # Ask again for required fields self.stdout.write(self.style.ERROR('Answer is required.')) elif not required: # No need to re-ask for non-required fields requiredFlag = False return result
python
def pattern_input(self, question, message='Invalid entry', pattern='^[a-zA-Z0-9_ ]+$', default='',required=True): result = '' requiredFlag = True while (not result and requiredFlag): result = input('%s: ' % question) if result and pattern and not re.match(pattern, result): self.stdout.write(self.style.ERROR(message)) result = '' elif not result and default: return default elif not result and required: self.stdout.write(self.style.ERROR('Answer is required.')) elif not required: requiredFlag = False return result
[ "def", "pattern_input", "(", "self", ",", "question", ",", "message", "=", "'Invalid entry'", ",", "pattern", "=", "'^[a-zA-Z0-9_ ]+$'", ",", "default", "=", "''", ",", "required", "=", "True", ")", ":", "result", "=", "''", "requiredFlag", "=", "True", "while", "(", "not", "result", "and", "requiredFlag", ")", ":", "result", "=", "input", "(", "'%s: '", "%", "question", ")", "if", "result", "and", "pattern", "and", "not", "re", ".", "match", "(", "pattern", ",", "result", ")", ":", "self", ".", "stdout", ".", "write", "(", "self", ".", "style", ".", "ERROR", "(", "message", ")", ")", "result", "=", "''", "elif", "not", "result", "and", "default", ":", "# Return default for fields with default", "return", "default", "elif", "not", "result", "and", "required", ":", "# Ask again for required fields", "self", ".", "stdout", ".", "write", "(", "self", ".", "style", ".", "ERROR", "(", "'Answer is required.'", ")", ")", "elif", "not", "required", ":", "# No need to re-ask for non-required fields", "requiredFlag", "=", "False", "return", "result" ]
Method for input disallowing special characters, with optionally specifiable regex pattern and error message.
[ "Method", "for", "input", "disallowing", "special", "characters", "with", "optionally", "specifiable", "regex", "pattern", "and", "error", "message", "." ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/core/management/commands/setupschool.py#L36-L58
django-danceschool/django-danceschool
danceschool/core/management/commands/setupschool.py
Command.float_input
def float_input(self, question, message='Invalid entry', default=None, required=True): ''' Method for floating point inputs with optionally specifiable error message. ''' float_result = None requiredFlag = True while (float_result is None and requiredFlag): result = input('%s: ' % question) if not result and not required: float_result = None requiredFlag = False if not result and default: float_result = default if float_result is None and requiredFlag: try: float_result = float(result) except ValueError: self.stdout.write(self.style.ERROR(message)) float_result = None return float_result
python
def float_input(self, question, message='Invalid entry', default=None, required=True): float_result = None requiredFlag = True while (float_result is None and requiredFlag): result = input('%s: ' % question) if not result and not required: float_result = None requiredFlag = False if not result and default: float_result = default if float_result is None and requiredFlag: try: float_result = float(result) except ValueError: self.stdout.write(self.style.ERROR(message)) float_result = None return float_result
[ "def", "float_input", "(", "self", ",", "question", ",", "message", "=", "'Invalid entry'", ",", "default", "=", "None", ",", "required", "=", "True", ")", ":", "float_result", "=", "None", "requiredFlag", "=", "True", "while", "(", "float_result", "is", "None", "and", "requiredFlag", ")", ":", "result", "=", "input", "(", "'%s: '", "%", "question", ")", "if", "not", "result", "and", "not", "required", ":", "float_result", "=", "None", "requiredFlag", "=", "False", "if", "not", "result", "and", "default", ":", "float_result", "=", "default", "if", "float_result", "is", "None", "and", "requiredFlag", ":", "try", ":", "float_result", "=", "float", "(", "result", ")", "except", "ValueError", ":", "self", ".", "stdout", ".", "write", "(", "self", ".", "style", ".", "ERROR", "(", "message", ")", ")", "float_result", "=", "None", "return", "float_result" ]
Method for floating point inputs with optionally specifiable error message.
[ "Method", "for", "floating", "point", "inputs", "with", "optionally", "specifiable", "error", "message", "." ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/core/management/commands/setupschool.py#L60-L81
django-danceschool/django-danceschool
danceschool/core/utils/timezone.py
ensure_timezone
def ensure_timezone(dateTime,timeZone=None): ''' Since this project is designed to be used in both time-zone aware and naive environments, this utility just returns a datetime as either aware or naive depending on whether time zone support is enabled. ''' if is_aware(dateTime) and not getattr(settings,'USE_TZ',False): return make_naive(dateTime,timezone=timeZone) if is_naive(dateTime) and getattr(settings,'USE_TZ',False): return make_aware(dateTime,timezone=timeZone) # If neither condition is met, then we can return what was passed return dateTime
python
def ensure_timezone(dateTime,timeZone=None): if is_aware(dateTime) and not getattr(settings,'USE_TZ',False): return make_naive(dateTime,timezone=timeZone) if is_naive(dateTime) and getattr(settings,'USE_TZ',False): return make_aware(dateTime,timezone=timeZone) return dateTime
[ "def", "ensure_timezone", "(", "dateTime", ",", "timeZone", "=", "None", ")", ":", "if", "is_aware", "(", "dateTime", ")", "and", "not", "getattr", "(", "settings", ",", "'USE_TZ'", ",", "False", ")", ":", "return", "make_naive", "(", "dateTime", ",", "timezone", "=", "timeZone", ")", "if", "is_naive", "(", "dateTime", ")", "and", "getattr", "(", "settings", ",", "'USE_TZ'", ",", "False", ")", ":", "return", "make_aware", "(", "dateTime", ",", "timezone", "=", "timeZone", ")", "# If neither condition is met, then we can return what was passed\r", "return", "dateTime" ]
Since this project is designed to be used in both time-zone aware and naive environments, this utility just returns a datetime as either aware or naive depending on whether time zone support is enabled.
[ "Since", "this", "project", "is", "designed", "to", "be", "used", "in", "both", "time", "-", "zone", "aware", "and", "naive", "environments", "this", "utility", "just", "returns", "a", "datetime", "as", "either", "aware", "or", "naive", "depending", "on", "whether", "time", "zone", "support", "is", "enabled", "." ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/core/utils/timezone.py#L5-L17
django-danceschool/django-danceschool
danceschool/payments/paypal/cms_plugins.py
GiftCertificateFormPlugin.render
def render(self, context, instance, placeholder): ''' Create a UUID and check if a voucher with that ID exists before rendering ''' context = super(GiftCertificateFormPlugin, self).render(context, instance, placeholder) # Paypal "live" mode is "production" to checkout.js mode = getattr(settings,'PAYPAL_MODE', 'sandbox') if mode == 'live': mode = 'production' context.update({ 'paypal_mode': mode, }) return context
python
def render(self, context, instance, placeholder): context = super(GiftCertificateFormPlugin, self).render(context, instance, placeholder) mode = getattr(settings,'PAYPAL_MODE', 'sandbox') if mode == 'live': mode = 'production' context.update({ 'paypal_mode': mode, }) return context
[ "def", "render", "(", "self", ",", "context", ",", "instance", ",", "placeholder", ")", ":", "context", "=", "super", "(", "GiftCertificateFormPlugin", ",", "self", ")", ".", "render", "(", "context", ",", "instance", ",", "placeholder", ")", "# Paypal \"live\" mode is \"production\" to checkout.js\r", "mode", "=", "getattr", "(", "settings", ",", "'PAYPAL_MODE'", ",", "'sandbox'", ")", "if", "mode", "==", "'live'", ":", "mode", "=", "'production'", "context", ".", "update", "(", "{", "'paypal_mode'", ":", "mode", ",", "}", ")", "return", "context" ]
Create a UUID and check if a voucher with that ID exists before rendering
[ "Create", "a", "UUID", "and", "check", "if", "a", "voucher", "with", "that", "ID", "exists", "before", "rendering" ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/payments/paypal/cms_plugins.py#L17-L30
django-danceschool/django-danceschool
danceschool/financial/migrations/0012_auto_20181216_1615.py
getFullName
def getFullName(obj): ''' This function replaces the fullName property for StaffMembers and the get_full_name() method for Users, since those methods are not available in the migration. ''' if hasattr(obj, 'firstName') and hasattr(obj, 'lastName'): return ' '.join([obj.firstName or '', obj.lastName or '']) return ' '.join([getattr(obj, 'first_name', ''),getattr(obj, 'last_name', '')])
python
def getFullName(obj): if hasattr(obj, 'firstName') and hasattr(obj, 'lastName'): return ' '.join([obj.firstName or '', obj.lastName or '']) return ' '.join([getattr(obj, 'first_name', ''),getattr(obj, 'last_name', '')])
[ "def", "getFullName", "(", "obj", ")", ":", "if", "hasattr", "(", "obj", ",", "'firstName'", ")", "and", "hasattr", "(", "obj", ",", "'lastName'", ")", ":", "return", "' '", ".", "join", "(", "[", "obj", ".", "firstName", "or", "''", ",", "obj", ".", "lastName", "or", "''", "]", ")", "return", "' '", ".", "join", "(", "[", "getattr", "(", "obj", ",", "'first_name'", ",", "''", ")", ",", "getattr", "(", "obj", ",", "'last_name'", ",", "''", ")", "]", ")" ]
This function replaces the fullName property for StaffMembers and the get_full_name() method for Users, since those methods are not available in the migration.
[ "This", "function", "replaces", "the", "fullName", "property", "for", "StaffMembers", "and", "the", "get_full_name", "()", "method", "for", "Users", "since", "those", "methods", "are", "not", "available", "in", "the", "migration", "." ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/financial/migrations/0012_auto_20181216_1615.py#L13-L21
django-danceschool/django-danceschool
danceschool/financial/migrations/0012_auto_20181216_1615.py
createPartyFromName
def createPartyFromName(apps, name): ''' For creating/matching TransactionParty objects using names alone. Look for staff members with the same name and match to them first if there is exactly one match. Then, look for users and match them if there is exactly one match. Otherwise, just generate a TransactionParty for the name only. ''' TransactionParty = apps.get_model('financial', 'TransactionParty') StaffMember = apps.get_model('core', 'StaffMember') User = apps.get_model('auth', 'User') firstName = name.split(' ')[0] lastName = ' '.join(name.split(' ')[1:]) members = StaffMember.objects.filter( firstName__istartswith=firstName, lastName__istartswith=lastName ) users = User.objects.filter( first_name__istartswith=firstName, last_name__istartswith=lastName ) if members.count() == 1: this_member = members.first() party = TransactionParty.objects.get_or_create( staffMember=this_member, defaults={ 'name': getFullName(this_member), 'user': this_member.userAccount, } )[0] elif users.count() == 1: this_user = users.first() party = TransactionParty.objects.get_or_create( user=this_user, defaults={ 'name': getFullName(this_user), 'staffMember': getattr(this_user, 'staffmember', None), } )[0] else: party = TransactionParty.objects.get_or_create( name=name )[0] return party
python
def createPartyFromName(apps, name): TransactionParty = apps.get_model('financial', 'TransactionParty') StaffMember = apps.get_model('core', 'StaffMember') User = apps.get_model('auth', 'User') firstName = name.split(' ')[0] lastName = ' '.join(name.split(' ')[1:]) members = StaffMember.objects.filter( firstName__istartswith=firstName, lastName__istartswith=lastName ) users = User.objects.filter( first_name__istartswith=firstName, last_name__istartswith=lastName ) if members.count() == 1: this_member = members.first() party = TransactionParty.objects.get_or_create( staffMember=this_member, defaults={ 'name': getFullName(this_member), 'user': this_member.userAccount, } )[0] elif users.count() == 1: this_user = users.first() party = TransactionParty.objects.get_or_create( user=this_user, defaults={ 'name': getFullName(this_user), 'staffMember': getattr(this_user, 'staffmember', None), } )[0] else: party = TransactionParty.objects.get_or_create( name=name )[0] return party
[ "def", "createPartyFromName", "(", "apps", ",", "name", ")", ":", "TransactionParty", "=", "apps", ".", "get_model", "(", "'financial'", ",", "'TransactionParty'", ")", "StaffMember", "=", "apps", ".", "get_model", "(", "'core'", ",", "'StaffMember'", ")", "User", "=", "apps", ".", "get_model", "(", "'auth'", ",", "'User'", ")", "firstName", "=", "name", ".", "split", "(", "' '", ")", "[", "0", "]", "lastName", "=", "' '", ".", "join", "(", "name", ".", "split", "(", "' '", ")", "[", "1", ":", "]", ")", "members", "=", "StaffMember", ".", "objects", ".", "filter", "(", "firstName__istartswith", "=", "firstName", ",", "lastName__istartswith", "=", "lastName", ")", "users", "=", "User", ".", "objects", ".", "filter", "(", "first_name__istartswith", "=", "firstName", ",", "last_name__istartswith", "=", "lastName", ")", "if", "members", ".", "count", "(", ")", "==", "1", ":", "this_member", "=", "members", ".", "first", "(", ")", "party", "=", "TransactionParty", ".", "objects", ".", "get_or_create", "(", "staffMember", "=", "this_member", ",", "defaults", "=", "{", "'name'", ":", "getFullName", "(", "this_member", ")", ",", "'user'", ":", "this_member", ".", "userAccount", ",", "}", ")", "[", "0", "]", "elif", "users", ".", "count", "(", ")", "==", "1", ":", "this_user", "=", "users", ".", "first", "(", ")", "party", "=", "TransactionParty", ".", "objects", ".", "get_or_create", "(", "user", "=", "this_user", ",", "defaults", "=", "{", "'name'", ":", "getFullName", "(", "this_user", ")", ",", "'staffMember'", ":", "getattr", "(", "this_user", ",", "'staffmember'", ",", "None", ")", ",", "}", ")", "[", "0", "]", "else", ":", "party", "=", "TransactionParty", ".", "objects", ".", "get_or_create", "(", "name", "=", "name", ")", "[", "0", "]", "return", "party" ]
For creating/matching TransactionParty objects using names alone. Look for staff members with the same name and match to them first if there is exactly one match. Then, look for users and match them if there is exactly one match. Otherwise, just generate a TransactionParty for the name only.
[ "For", "creating", "/", "matching", "TransactionParty", "objects", "using", "names", "alone", ".", "Look", "for", "staff", "members", "with", "the", "same", "name", "and", "match", "to", "them", "first", "if", "there", "is", "exactly", "one", "match", ".", "Then", "look", "for", "users", "and", "match", "them", "if", "there", "is", "exactly", "one", "match", ".", "Otherwise", "just", "generate", "a", "TransactionParty", "for", "the", "name", "only", "." ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/financial/migrations/0012_auto_20181216_1615.py#L24-L68
django-danceschool/django-danceschool
danceschool/financial/migrations/0012_auto_20181216_1615.py
update_payTo
def update_payTo(apps, schema_editor): ''' With the new TransactionParty model, the senders and recipients of financial transactions are held in one place. So, we need to loop through old ExpenseItems, RevenueItems, and GenericRepeatedExpense and move their old party references to the new party model. ''' TransactionParty = apps.get_model('financial', 'TransactionParty') ExpenseItem = apps.get_model('financial', 'ExpenseItem') RevenueItem = apps.get_model('financial', 'RevenueItem') GenericRepeatedExpense = apps.get_model('financial', 'GenericRepeatedExpense') # First, update expense items and Generic repeated expense rules for item in chain( ExpenseItem.objects.filter( Q(payToUser__isnull=False) | Q(payToLocation__isnull=False) | Q(payToName__isnull=False) ), GenericRepeatedExpense.objects.filter( Q(payToUser__isnull=False) | Q(payToLocation__isnull=False) | Q(payToName__isnull=False) ), ): if getattr(item, 'payToUser', None): party = TransactionParty.objects.get_or_create( user=item.payToUser, defaults={ 'name': getFullName(item.payToUser), 'staffMember': getattr(item.payToUser, 'staffmember', None), } )[0] elif getattr(item, 'payToLocation', None): party = TransactionParty.objects.get_or_create( location=item.payToLocation, defaults={ 'name': item.payToLocation.name, } )[0] elif getattr(item, 'payToName', None): party = createPartyFromName(apps, item.payToName) item.payTo = party item.save() # Finally, update revenue items for item in RevenueItem.objects.filter( Q(receivedFromName__isnull=False) ): party = createPartyFromName(apps, item.receivedFromName) item.receivedFrom = party item.save()
python
def update_payTo(apps, schema_editor): TransactionParty = apps.get_model('financial', 'TransactionParty') ExpenseItem = apps.get_model('financial', 'ExpenseItem') RevenueItem = apps.get_model('financial', 'RevenueItem') GenericRepeatedExpense = apps.get_model('financial', 'GenericRepeatedExpense') for item in chain( ExpenseItem.objects.filter( Q(payToUser__isnull=False) | Q(payToLocation__isnull=False) | Q(payToName__isnull=False) ), GenericRepeatedExpense.objects.filter( Q(payToUser__isnull=False) | Q(payToLocation__isnull=False) | Q(payToName__isnull=False) ), ): if getattr(item, 'payToUser', None): party = TransactionParty.objects.get_or_create( user=item.payToUser, defaults={ 'name': getFullName(item.payToUser), 'staffMember': getattr(item.payToUser, 'staffmember', None), } )[0] elif getattr(item, 'payToLocation', None): party = TransactionParty.objects.get_or_create( location=item.payToLocation, defaults={ 'name': item.payToLocation.name, } )[0] elif getattr(item, 'payToName', None): party = createPartyFromName(apps, item.payToName) item.payTo = party item.save() for item in RevenueItem.objects.filter( Q(receivedFromName__isnull=False) ): party = createPartyFromName(apps, item.receivedFromName) item.receivedFrom = party item.save()
[ "def", "update_payTo", "(", "apps", ",", "schema_editor", ")", ":", "TransactionParty", "=", "apps", ".", "get_model", "(", "'financial'", ",", "'TransactionParty'", ")", "ExpenseItem", "=", "apps", ".", "get_model", "(", "'financial'", ",", "'ExpenseItem'", ")", "RevenueItem", "=", "apps", ".", "get_model", "(", "'financial'", ",", "'RevenueItem'", ")", "GenericRepeatedExpense", "=", "apps", ".", "get_model", "(", "'financial'", ",", "'GenericRepeatedExpense'", ")", "# First, update expense items and Generic repeated expense rules", "for", "item", "in", "chain", "(", "ExpenseItem", ".", "objects", ".", "filter", "(", "Q", "(", "payToUser__isnull", "=", "False", ")", "|", "Q", "(", "payToLocation__isnull", "=", "False", ")", "|", "Q", "(", "payToName__isnull", "=", "False", ")", ")", ",", "GenericRepeatedExpense", ".", "objects", ".", "filter", "(", "Q", "(", "payToUser__isnull", "=", "False", ")", "|", "Q", "(", "payToLocation__isnull", "=", "False", ")", "|", "Q", "(", "payToName__isnull", "=", "False", ")", ")", ",", ")", ":", "if", "getattr", "(", "item", ",", "'payToUser'", ",", "None", ")", ":", "party", "=", "TransactionParty", ".", "objects", ".", "get_or_create", "(", "user", "=", "item", ".", "payToUser", ",", "defaults", "=", "{", "'name'", ":", "getFullName", "(", "item", ".", "payToUser", ")", ",", "'staffMember'", ":", "getattr", "(", "item", ".", "payToUser", ",", "'staffmember'", ",", "None", ")", ",", "}", ")", "[", "0", "]", "elif", "getattr", "(", "item", ",", "'payToLocation'", ",", "None", ")", ":", "party", "=", "TransactionParty", ".", "objects", ".", "get_or_create", "(", "location", "=", "item", ".", "payToLocation", ",", "defaults", "=", "{", "'name'", ":", "item", ".", "payToLocation", ".", "name", ",", "}", ")", "[", "0", "]", "elif", "getattr", "(", "item", ",", "'payToName'", ",", "None", ")", ":", "party", "=", "createPartyFromName", "(", "apps", ",", "item", ".", "payToName", ")", "item", ".", "payTo", "=", "party", "item", ".", "save", "(", ")", "# Finally, update revenue items", "for", "item", "in", "RevenueItem", ".", "objects", ".", "filter", "(", "Q", "(", "receivedFromName__isnull", "=", "False", ")", ")", ":", "party", "=", "createPartyFromName", "(", "apps", ",", "item", ".", "receivedFromName", ")", "item", ".", "receivedFrom", "=", "party", "item", ".", "save", "(", ")" ]
With the new TransactionParty model, the senders and recipients of financial transactions are held in one place. So, we need to loop through old ExpenseItems, RevenueItems, and GenericRepeatedExpense and move their old party references to the new party model.
[ "With", "the", "new", "TransactionParty", "model", "the", "senders", "and", "recipients", "of", "financial", "transactions", "are", "held", "in", "one", "place", ".", "So", "we", "need", "to", "loop", "through", "old", "ExpenseItems", "RevenueItems", "and", "GenericRepeatedExpense", "and", "move", "their", "old", "party", "references", "to", "the", "new", "party", "model", "." ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/financial/migrations/0012_auto_20181216_1615.py#L71-L119
django-danceschool/django-danceschool
danceschool/discounts/migrations/0005_auto_20170830_1159.py
create_initial_category
def create_initial_category(apps, schema_editor): ''' Create a default category for existing discounts ''' DiscountCategory = apps.get_model('discounts','DiscountCategory') db_alias = schema_editor.connection.alias DiscountCategory.objects.using(db_alias).create( id=1,name='General Discounts',order=1,cannotCombine=False )
python
def create_initial_category(apps, schema_editor): DiscountCategory = apps.get_model('discounts','DiscountCategory') db_alias = schema_editor.connection.alias DiscountCategory.objects.using(db_alias).create( id=1,name='General Discounts',order=1,cannotCombine=False )
[ "def", "create_initial_category", "(", "apps", ",", "schema_editor", ")", ":", "DiscountCategory", "=", "apps", ".", "get_model", "(", "'discounts'", ",", "'DiscountCategory'", ")", "db_alias", "=", "schema_editor", ".", "connection", ".", "alias", "DiscountCategory", ".", "objects", ".", "using", "(", "db_alias", ")", ".", "create", "(", "id", "=", "1", ",", "name", "=", "'General Discounts'", ",", "order", "=", "1", ",", "cannotCombine", "=", "False", ")" ]
Create a default category for existing discounts
[ "Create", "a", "default", "category", "for", "existing", "discounts" ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/discounts/migrations/0005_auto_20170830_1159.py#L10-L16
django-danceschool/django-danceschool
danceschool/core/classreg.py
ClassRegistrationView.dispatch
def dispatch(self, request, *args, **kwargs): ''' Check that registration is online before proceeding. If this is a POST request, determine whether the response should be provided in JSON form. ''' self.returnJson = (request.POST.get('json') in ['true', True]) regonline = getConstant('registration__registrationEnabled') if not regonline: returnUrl = reverse('registrationOffline') if self.returnJson: return JsonResponse({'status': 'success', 'redirect': returnUrl}) return HttpResponseRedirect(returnUrl) return super().dispatch(request, *args, **kwargs)
python
def dispatch(self, request, *args, **kwargs): self.returnJson = (request.POST.get('json') in ['true', True]) regonline = getConstant('registration__registrationEnabled') if not regonline: returnUrl = reverse('registrationOffline') if self.returnJson: return JsonResponse({'status': 'success', 'redirect': returnUrl}) return HttpResponseRedirect(returnUrl) return super().dispatch(request, *args, **kwargs)
[ "def", "dispatch", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "returnJson", "=", "(", "request", ".", "POST", ".", "get", "(", "'json'", ")", "in", "[", "'true'", ",", "True", "]", ")", "regonline", "=", "getConstant", "(", "'registration__registrationEnabled'", ")", "if", "not", "regonline", ":", "returnUrl", "=", "reverse", "(", "'registrationOffline'", ")", "if", "self", ".", "returnJson", ":", "return", "JsonResponse", "(", "{", "'status'", ":", "'success'", ",", "'redirect'", ":", "returnUrl", "}", ")", "return", "HttpResponseRedirect", "(", "returnUrl", ")", "return", "super", "(", ")", ".", "dispatch", "(", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
Check that registration is online before proceeding. If this is a POST request, determine whether the response should be provided in JSON form.
[ "Check", "that", "registration", "is", "online", "before", "proceeding", ".", "If", "this", "is", "a", "POST", "request", "determine", "whether", "the", "response", "should", "be", "provided", "in", "JSON", "form", "." ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/core/classreg.py#L65-L80
django-danceschool/django-danceschool
danceschool/core/classreg.py
ClassRegistrationView.get_context_data
def get_context_data(self,**kwargs): ''' Add the event and series listing data ''' context = self.get_listing() context['showDescriptionRule'] = getConstant('registration__showDescriptionRule') or 'all' context.update(kwargs) # Update the site session data so that registration processes know to send return links to # the registration page. set_return_page() is in SiteHistoryMixin. self.set_return_page('registration',_('Registration')) return super(ClassRegistrationView,self).get_context_data(**context)
python
def get_context_data(self,**kwargs): context = self.get_listing() context['showDescriptionRule'] = getConstant('registration__showDescriptionRule') or 'all' context.update(kwargs) self.set_return_page('registration',_('Registration')) return super(ClassRegistrationView,self).get_context_data(**context)
[ "def", "get_context_data", "(", "self", ",", "*", "*", "kwargs", ")", ":", "context", "=", "self", ".", "get_listing", "(", ")", "context", "[", "'showDescriptionRule'", "]", "=", "getConstant", "(", "'registration__showDescriptionRule'", ")", "or", "'all'", "context", ".", "update", "(", "kwargs", ")", "# Update the site session data so that registration processes know to send return links to", "# the registration page. set_return_page() is in SiteHistoryMixin.", "self", ".", "set_return_page", "(", "'registration'", ",", "_", "(", "'Registration'", ")", ")", "return", "super", "(", "ClassRegistrationView", ",", "self", ")", ".", "get_context_data", "(", "*", "*", "context", ")" ]
Add the event and series listing data
[ "Add", "the", "event", "and", "series", "listing", "data" ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/core/classreg.py#L82-L92
django-danceschool/django-danceschool
danceschool/core/classreg.py
ClassRegistrationView.get_form_kwargs
def get_form_kwargs(self, **kwargs): ''' Tell the form which fields to render ''' kwargs = super(ClassRegistrationView, self).get_form_kwargs(**kwargs) kwargs['user'] = self.request.user if hasattr(self.request,'user') else None listing = self.get_listing() kwargs.update({ 'openEvents': listing['openEvents'], 'closedEvents': listing['closedEvents'], }) return kwargs
python
def get_form_kwargs(self, **kwargs): kwargs = super(ClassRegistrationView, self).get_form_kwargs(**kwargs) kwargs['user'] = self.request.user if hasattr(self.request,'user') else None listing = self.get_listing() kwargs.update({ 'openEvents': listing['openEvents'], 'closedEvents': listing['closedEvents'], }) return kwargs
[ "def", "get_form_kwargs", "(", "self", ",", "*", "*", "kwargs", ")", ":", "kwargs", "=", "super", "(", "ClassRegistrationView", ",", "self", ")", ".", "get_form_kwargs", "(", "*", "*", "kwargs", ")", "kwargs", "[", "'user'", "]", "=", "self", ".", "request", ".", "user", "if", "hasattr", "(", "self", ".", "request", ",", "'user'", ")", "else", "None", "listing", "=", "self", ".", "get_listing", "(", ")", "kwargs", ".", "update", "(", "{", "'openEvents'", ":", "listing", "[", "'openEvents'", "]", ",", "'closedEvents'", ":", "listing", "[", "'closedEvents'", "]", ",", "}", ")", "return", "kwargs" ]
Tell the form which fields to render
[ "Tell", "the", "form", "which", "fields", "to", "render" ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/core/classreg.py#L94-L105
django-danceschool/django-danceschool
danceschool/core/classreg.py
ClassRegistrationView.form_valid
def form_valid(self,form): ''' If the form is valid, pass its contents on to the next view. In order to permit the registration form to be overridden flexibly, but without permitting storage of arbitrary data keys that could lead to potential security issues, a form class for this view can optionally specify a list of keys that are permitted. If no such list is specified as instance.permitted_event_keys, then the default list are used. ''' regSession = self.request.session.get(REG_VALIDATION_STR, {}) # The session expires after a period of inactivity that is specified in preferences. expiry = timezone.now() + timedelta(minutes=getConstant('registration__sessionExpiryMinutes')) permitted_keys = getattr(form,'permitted_event_keys',['role',]) try: event_listing = { int(key.split("_")[-1]): {k:v for k,v in json.loads(value[0]).items() if k in permitted_keys} for key,value in form.cleaned_data.items() if 'event' in key and value } non_event_listing = {key: value for key,value in form.cleaned_data.items() if 'event' not in key} except (ValueError, TypeError) as e: form.add_error(None,ValidationError(_('Invalid event information passed.'),code='invalid')) return super(ClassRegistrationView,self).form_invalid(form) associated_events = Event.objects.filter(id__in=[k for k in event_listing.keys()]) # Include the submission user if the user is authenticated if self.request.user.is_authenticated: submissionUser = self.request.user else: submissionUser = None reg = TemporaryRegistration( submissionUser=submissionUser,dateTime=timezone.now(), payAtDoor=non_event_listing.pop('payAtDoor',False), expirationDate=expiry, ) # Anything passed by this form that is not an Event field (any extra fields) are # passed directly into the TemporaryRegistration's data. reg.data = non_event_listing or {} if regSession.get('marketing_id'): reg.data.update({'marketing_id': regSession.pop('marketing_id',None)}) eventRegs = [] grossPrice = 0 for key,value in event_listing.items(): this_event = associated_events.get(id=key) # Check if registration is still feasible based on both completed registrations # and registrations that are not yet complete this_role_id = value.get('role',None) if 'role' in permitted_keys else None soldOut = this_event.soldOutForRole(role=this_role_id,includeTemporaryRegs=True) if soldOut: if self.request.user.has_perm('core.override_register_soldout'): # This message will be displayed on the Step 2 page by default. messages.warning(self.request,_( 'Registration for \'%s\' is sold out. Based on your user permission level, ' % this_event.name + 'you may proceed with registration. However, if you do not wish to exceed ' + 'the listed capacity of the event, please do not proceed.' )) else: # For users without permissions, don't allow registration for sold out things # at all. form.add_error(None, ValidationError(_('Registration for "%s" is tentatively sold out while others complete their registration. Please try again later.' % this_event.name),code='invalid')) return super(ClassRegistrationView,self).form_invalid(form) dropInList = [int(k.split("_")[-1]) for k,v in value.items() if k.startswith('dropin_') and v is True] # If nothing is sold out, then proceed to create a TemporaryRegistration and # TemporaryEventRegistration objects for the items selected by this form. The # expiration date is set to be identical to that of the session. logger.debug('Creating temporary event registration for: %s' % key) if len(dropInList) > 0: tr = TemporaryEventRegistration( event=this_event, dropIn=True, price=this_event.getBasePrice(dropIns=len(dropInList)) ) else: tr = TemporaryEventRegistration( event=this_event, price=this_event.getBasePrice(payAtDoor=reg.payAtDoor), role_id=this_role_id ) # If it's possible to store additional data and such data exist, then store them. tr.data = {k: v for k,v in value.items() if k in permitted_keys and k != 'role'} eventRegs.append(tr) grossPrice += tr.price # If we got this far with no issues, then save reg.priceWithDiscount = grossPrice reg.save() for er in eventRegs: er.registration = reg er.save() regSession["temporaryRegistrationId"] = reg.id regSession["temporaryRegistrationExpiry"] = expiry.strftime('%Y-%m-%dT%H:%M:%S%z') self.request.session[REG_VALIDATION_STR] = regSession if self.returnJson: return JsonResponse({ 'status': 'success', 'redirect': self.get_success_url() }) return HttpResponseRedirect(self.get_success_url())
python
def form_valid(self,form): regSession = self.request.session.get(REG_VALIDATION_STR, {}) expiry = timezone.now() + timedelta(minutes=getConstant('registration__sessionExpiryMinutes')) permitted_keys = getattr(form,'permitted_event_keys',['role',]) try: event_listing = { int(key.split("_")[-1]): {k:v for k,v in json.loads(value[0]).items() if k in permitted_keys} for key,value in form.cleaned_data.items() if 'event' in key and value } non_event_listing = {key: value for key,value in form.cleaned_data.items() if 'event' not in key} except (ValueError, TypeError) as e: form.add_error(None,ValidationError(_('Invalid event information passed.'),code='invalid')) return super(ClassRegistrationView,self).form_invalid(form) associated_events = Event.objects.filter(id__in=[k for k in event_listing.keys()]) if self.request.user.is_authenticated: submissionUser = self.request.user else: submissionUser = None reg = TemporaryRegistration( submissionUser=submissionUser,dateTime=timezone.now(), payAtDoor=non_event_listing.pop('payAtDoor',False), expirationDate=expiry, ) reg.data = non_event_listing or {} if regSession.get('marketing_id'): reg.data.update({'marketing_id': regSession.pop('marketing_id',None)}) eventRegs = [] grossPrice = 0 for key,value in event_listing.items(): this_event = associated_events.get(id=key) this_role_id = value.get('role',None) if 'role' in permitted_keys else None soldOut = this_event.soldOutForRole(role=this_role_id,includeTemporaryRegs=True) if soldOut: if self.request.user.has_perm('core.override_register_soldout'): messages.warning(self.request,_( 'Registration for \'%s\' is sold out. Based on your user permission level, ' % this_event.name + 'you may proceed with registration. However, if you do not wish to exceed ' + 'the listed capacity of the event, please do not proceed.' )) else: form.add_error(None, ValidationError(_('Registration for "%s" is tentatively sold out while others complete their registration. Please try again later.' % this_event.name),code='invalid')) return super(ClassRegistrationView,self).form_invalid(form) dropInList = [int(k.split("_")[-1]) for k,v in value.items() if k.startswith('dropin_') and v is True] logger.debug('Creating temporary event registration for: %s' % key) if len(dropInList) > 0: tr = TemporaryEventRegistration( event=this_event, dropIn=True, price=this_event.getBasePrice(dropIns=len(dropInList)) ) else: tr = TemporaryEventRegistration( event=this_event, price=this_event.getBasePrice(payAtDoor=reg.payAtDoor), role_id=this_role_id ) tr.data = {k: v for k,v in value.items() if k in permitted_keys and k != 'role'} eventRegs.append(tr) grossPrice += tr.price reg.priceWithDiscount = grossPrice reg.save() for er in eventRegs: er.registration = reg er.save() regSession["temporaryRegistrationId"] = reg.id regSession["temporaryRegistrationExpiry"] = expiry.strftime('%Y-%m-%dT%H:%M:%S%z') self.request.session[REG_VALIDATION_STR] = regSession if self.returnJson: return JsonResponse({ 'status': 'success', 'redirect': self.get_success_url() }) return HttpResponseRedirect(self.get_success_url())
[ "def", "form_valid", "(", "self", ",", "form", ")", ":", "regSession", "=", "self", ".", "request", ".", "session", ".", "get", "(", "REG_VALIDATION_STR", ",", "{", "}", ")", "# The session expires after a period of inactivity that is specified in preferences.", "expiry", "=", "timezone", ".", "now", "(", ")", "+", "timedelta", "(", "minutes", "=", "getConstant", "(", "'registration__sessionExpiryMinutes'", ")", ")", "permitted_keys", "=", "getattr", "(", "form", ",", "'permitted_event_keys'", ",", "[", "'role'", ",", "]", ")", "try", ":", "event_listing", "=", "{", "int", "(", "key", ".", "split", "(", "\"_\"", ")", "[", "-", "1", "]", ")", ":", "{", "k", ":", "v", "for", "k", ",", "v", "in", "json", ".", "loads", "(", "value", "[", "0", "]", ")", ".", "items", "(", ")", "if", "k", "in", "permitted_keys", "}", "for", "key", ",", "value", "in", "form", ".", "cleaned_data", ".", "items", "(", ")", "if", "'event'", "in", "key", "and", "value", "}", "non_event_listing", "=", "{", "key", ":", "value", "for", "key", ",", "value", "in", "form", ".", "cleaned_data", ".", "items", "(", ")", "if", "'event'", "not", "in", "key", "}", "except", "(", "ValueError", ",", "TypeError", ")", "as", "e", ":", "form", ".", "add_error", "(", "None", ",", "ValidationError", "(", "_", "(", "'Invalid event information passed.'", ")", ",", "code", "=", "'invalid'", ")", ")", "return", "super", "(", "ClassRegistrationView", ",", "self", ")", ".", "form_invalid", "(", "form", ")", "associated_events", "=", "Event", ".", "objects", ".", "filter", "(", "id__in", "=", "[", "k", "for", "k", "in", "event_listing", ".", "keys", "(", ")", "]", ")", "# Include the submission user if the user is authenticated", "if", "self", ".", "request", ".", "user", ".", "is_authenticated", ":", "submissionUser", "=", "self", ".", "request", ".", "user", "else", ":", "submissionUser", "=", "None", "reg", "=", "TemporaryRegistration", "(", "submissionUser", "=", "submissionUser", ",", "dateTime", "=", "timezone", ".", "now", "(", ")", ",", "payAtDoor", "=", "non_event_listing", ".", "pop", "(", "'payAtDoor'", ",", "False", ")", ",", "expirationDate", "=", "expiry", ",", ")", "# Anything passed by this form that is not an Event field (any extra fields) are", "# passed directly into the TemporaryRegistration's data.", "reg", ".", "data", "=", "non_event_listing", "or", "{", "}", "if", "regSession", ".", "get", "(", "'marketing_id'", ")", ":", "reg", ".", "data", ".", "update", "(", "{", "'marketing_id'", ":", "regSession", ".", "pop", "(", "'marketing_id'", ",", "None", ")", "}", ")", "eventRegs", "=", "[", "]", "grossPrice", "=", "0", "for", "key", ",", "value", "in", "event_listing", ".", "items", "(", ")", ":", "this_event", "=", "associated_events", ".", "get", "(", "id", "=", "key", ")", "# Check if registration is still feasible based on both completed registrations", "# and registrations that are not yet complete", "this_role_id", "=", "value", ".", "get", "(", "'role'", ",", "None", ")", "if", "'role'", "in", "permitted_keys", "else", "None", "soldOut", "=", "this_event", ".", "soldOutForRole", "(", "role", "=", "this_role_id", ",", "includeTemporaryRegs", "=", "True", ")", "if", "soldOut", ":", "if", "self", ".", "request", ".", "user", ".", "has_perm", "(", "'core.override_register_soldout'", ")", ":", "# This message will be displayed on the Step 2 page by default.", "messages", ".", "warning", "(", "self", ".", "request", ",", "_", "(", "'Registration for \\'%s\\' is sold out. Based on your user permission level, '", "%", "this_event", ".", "name", "+", "'you may proceed with registration. However, if you do not wish to exceed '", "+", "'the listed capacity of the event, please do not proceed.'", ")", ")", "else", ":", "# For users without permissions, don't allow registration for sold out things", "# at all.", "form", ".", "add_error", "(", "None", ",", "ValidationError", "(", "_", "(", "'Registration for \"%s\" is tentatively sold out while others complete their registration. Please try again later.'", "%", "this_event", ".", "name", ")", ",", "code", "=", "'invalid'", ")", ")", "return", "super", "(", "ClassRegistrationView", ",", "self", ")", ".", "form_invalid", "(", "form", ")", "dropInList", "=", "[", "int", "(", "k", ".", "split", "(", "\"_\"", ")", "[", "-", "1", "]", ")", "for", "k", ",", "v", "in", "value", ".", "items", "(", ")", "if", "k", ".", "startswith", "(", "'dropin_'", ")", "and", "v", "is", "True", "]", "# If nothing is sold out, then proceed to create a TemporaryRegistration and", "# TemporaryEventRegistration objects for the items selected by this form. The", "# expiration date is set to be identical to that of the session.", "logger", ".", "debug", "(", "'Creating temporary event registration for: %s'", "%", "key", ")", "if", "len", "(", "dropInList", ")", ">", "0", ":", "tr", "=", "TemporaryEventRegistration", "(", "event", "=", "this_event", ",", "dropIn", "=", "True", ",", "price", "=", "this_event", ".", "getBasePrice", "(", "dropIns", "=", "len", "(", "dropInList", ")", ")", ")", "else", ":", "tr", "=", "TemporaryEventRegistration", "(", "event", "=", "this_event", ",", "price", "=", "this_event", ".", "getBasePrice", "(", "payAtDoor", "=", "reg", ".", "payAtDoor", ")", ",", "role_id", "=", "this_role_id", ")", "# If it's possible to store additional data and such data exist, then store them.", "tr", ".", "data", "=", "{", "k", ":", "v", "for", "k", ",", "v", "in", "value", ".", "items", "(", ")", "if", "k", "in", "permitted_keys", "and", "k", "!=", "'role'", "}", "eventRegs", ".", "append", "(", "tr", ")", "grossPrice", "+=", "tr", ".", "price", "# If we got this far with no issues, then save", "reg", ".", "priceWithDiscount", "=", "grossPrice", "reg", ".", "save", "(", ")", "for", "er", "in", "eventRegs", ":", "er", ".", "registration", "=", "reg", "er", ".", "save", "(", ")", "regSession", "[", "\"temporaryRegistrationId\"", "]", "=", "reg", ".", "id", "regSession", "[", "\"temporaryRegistrationExpiry\"", "]", "=", "expiry", ".", "strftime", "(", "'%Y-%m-%dT%H:%M:%S%z'", ")", "self", ".", "request", ".", "session", "[", "REG_VALIDATION_STR", "]", "=", "regSession", "if", "self", ".", "returnJson", ":", "return", "JsonResponse", "(", "{", "'status'", ":", "'success'", ",", "'redirect'", ":", "self", ".", "get_success_url", "(", ")", "}", ")", "return", "HttpResponseRedirect", "(", "self", ".", "get_success_url", "(", ")", ")" ]
If the form is valid, pass its contents on to the next view. In order to permit the registration form to be overridden flexibly, but without permitting storage of arbitrary data keys that could lead to potential security issues, a form class for this view can optionally specify a list of keys that are permitted. If no such list is specified as instance.permitted_event_keys, then the default list are used.
[ "If", "the", "form", "is", "valid", "pass", "its", "contents", "on", "to", "the", "next", "view", ".", "In", "order", "to", "permit", "the", "registration", "form", "to", "be", "overridden", "flexibly", "but", "without", "permitting", "storage", "of", "arbitrary", "data", "keys", "that", "could", "lead", "to", "potential", "security", "issues", "a", "form", "class", "for", "this", "view", "can", "optionally", "specify", "a", "list", "of", "keys", "that", "are", "permitted", ".", "If", "no", "such", "list", "is", "specified", "as", "instance", ".", "permitted_event_keys", "then", "the", "default", "list", "are", "used", "." ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/core/classreg.py#L118-L223
django-danceschool/django-danceschool
danceschool/core/classreg.py
ClassRegistrationView.get_allEvents
def get_allEvents(self): ''' Splitting this method out to get the set of events to filter allows one to subclass for different subsets of events without copying other logic ''' if not hasattr(self,'allEvents'): timeFilters = {'endTime__gte': timezone.now()} if getConstant('registration__displayLimitDays') or 0 > 0: timeFilters['startTime__lte'] = timezone.now() + timedelta(days=getConstant('registration__displayLimitDays')) # Get the Event listing here to avoid duplicate queries self.allEvents = Event.objects.filter( **timeFilters ).filter( Q(instance_of=PublicEvent) | Q(instance_of=Series) ).annotate( **self.get_annotations() ).exclude( Q(status=Event.RegStatus.hidden) | Q(status=Event.RegStatus.regHidden) | Q(status=Event.RegStatus.linkOnly) ).order_by(*self.get_ordering()) return self.allEvents
python
def get_allEvents(self): if not hasattr(self,'allEvents'): timeFilters = {'endTime__gte': timezone.now()} if getConstant('registration__displayLimitDays') or 0 > 0: timeFilters['startTime__lte'] = timezone.now() + timedelta(days=getConstant('registration__displayLimitDays')) self.allEvents = Event.objects.filter( **timeFilters ).filter( Q(instance_of=PublicEvent) | Q(instance_of=Series) ).annotate( **self.get_annotations() ).exclude( Q(status=Event.RegStatus.hidden) | Q(status=Event.RegStatus.regHidden) | Q(status=Event.RegStatus.linkOnly) ).order_by(*self.get_ordering()) return self.allEvents
[ "def", "get_allEvents", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'allEvents'", ")", ":", "timeFilters", "=", "{", "'endTime__gte'", ":", "timezone", ".", "now", "(", ")", "}", "if", "getConstant", "(", "'registration__displayLimitDays'", ")", "or", "0", ">", "0", ":", "timeFilters", "[", "'startTime__lte'", "]", "=", "timezone", ".", "now", "(", ")", "+", "timedelta", "(", "days", "=", "getConstant", "(", "'registration__displayLimitDays'", ")", ")", "# Get the Event listing here to avoid duplicate queries", "self", ".", "allEvents", "=", "Event", ".", "objects", ".", "filter", "(", "*", "*", "timeFilters", ")", ".", "filter", "(", "Q", "(", "instance_of", "=", "PublicEvent", ")", "|", "Q", "(", "instance_of", "=", "Series", ")", ")", ".", "annotate", "(", "*", "*", "self", ".", "get_annotations", "(", ")", ")", ".", "exclude", "(", "Q", "(", "status", "=", "Event", ".", "RegStatus", ".", "hidden", ")", "|", "Q", "(", "status", "=", "Event", ".", "RegStatus", ".", "regHidden", ")", "|", "Q", "(", "status", "=", "Event", ".", "RegStatus", ".", "linkOnly", ")", ")", ".", "order_by", "(", "*", "self", ".", "get_ordering", "(", ")", ")", "return", "self", ".", "allEvents" ]
Splitting this method out to get the set of events to filter allows one to subclass for different subsets of events without copying other logic
[ "Splitting", "this", "method", "out", "to", "get", "the", "set", "of", "events", "to", "filter", "allows", "one", "to", "subclass", "for", "different", "subsets", "of", "events", "without", "copying", "other", "logic" ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/core/classreg.py#L228-L254
django-danceschool/django-danceschool
danceschool/core/classreg.py
ClassRegistrationView.get_listing
def get_listing(self): ''' This function gets all of the information that we need to either render or validate the form. It is structured to avoid duplicate DB queries ''' if not hasattr(self,'listing'): allEvents = self.get_allEvents() openEvents = allEvents.filter(registrationOpen=True) closedEvents = allEvents.filter(registrationOpen=False) publicEvents = allEvents.instance_of(PublicEvent) allSeries = allEvents.instance_of(Series) self.listing = { 'allEvents': allEvents, 'openEvents': openEvents, 'closedEvents': closedEvents, 'publicEvents': publicEvents, 'allSeries': allSeries, 'regOpenEvents': publicEvents.filter(registrationOpen=True).filter( Q(publicevent__category__isnull=True) | Q(publicevent__category__separateOnRegistrationPage=False) ), 'regClosedEvents': publicEvents.filter(registrationOpen=False).filter( Q(publicevent__category__isnull=True) | Q(publicevent__category__separateOnRegistrationPage=False) ), 'categorySeparateEvents': publicEvents.filter( publicevent__category__separateOnRegistrationPage=True ).order_by('publicevent__category'), 'regOpenSeries': allSeries.filter(registrationOpen=True).filter( Q(series__category__isnull=True) | Q(series__category__separateOnRegistrationPage=False) ), 'regClosedSeries': allSeries.filter(registrationOpen=False).filter( Q(series__category__isnull=True) | Q(series__category__separateOnRegistrationPage=False) ), 'categorySeparateSeries': allSeries.filter( series__category__separateOnRegistrationPage=True ).order_by('series__category'), } return self.listing
python
def get_listing(self): if not hasattr(self,'listing'): allEvents = self.get_allEvents() openEvents = allEvents.filter(registrationOpen=True) closedEvents = allEvents.filter(registrationOpen=False) publicEvents = allEvents.instance_of(PublicEvent) allSeries = allEvents.instance_of(Series) self.listing = { 'allEvents': allEvents, 'openEvents': openEvents, 'closedEvents': closedEvents, 'publicEvents': publicEvents, 'allSeries': allSeries, 'regOpenEvents': publicEvents.filter(registrationOpen=True).filter( Q(publicevent__category__isnull=True) | Q(publicevent__category__separateOnRegistrationPage=False) ), 'regClosedEvents': publicEvents.filter(registrationOpen=False).filter( Q(publicevent__category__isnull=True) | Q(publicevent__category__separateOnRegistrationPage=False) ), 'categorySeparateEvents': publicEvents.filter( publicevent__category__separateOnRegistrationPage=True ).order_by('publicevent__category'), 'regOpenSeries': allSeries.filter(registrationOpen=True).filter( Q(series__category__isnull=True) | Q(series__category__separateOnRegistrationPage=False) ), 'regClosedSeries': allSeries.filter(registrationOpen=False).filter( Q(series__category__isnull=True) | Q(series__category__separateOnRegistrationPage=False) ), 'categorySeparateSeries': allSeries.filter( series__category__separateOnRegistrationPage=True ).order_by('series__category'), } return self.listing
[ "def", "get_listing", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'listing'", ")", ":", "allEvents", "=", "self", ".", "get_allEvents", "(", ")", "openEvents", "=", "allEvents", ".", "filter", "(", "registrationOpen", "=", "True", ")", "closedEvents", "=", "allEvents", ".", "filter", "(", "registrationOpen", "=", "False", ")", "publicEvents", "=", "allEvents", ".", "instance_of", "(", "PublicEvent", ")", "allSeries", "=", "allEvents", ".", "instance_of", "(", "Series", ")", "self", ".", "listing", "=", "{", "'allEvents'", ":", "allEvents", ",", "'openEvents'", ":", "openEvents", ",", "'closedEvents'", ":", "closedEvents", ",", "'publicEvents'", ":", "publicEvents", ",", "'allSeries'", ":", "allSeries", ",", "'regOpenEvents'", ":", "publicEvents", ".", "filter", "(", "registrationOpen", "=", "True", ")", ".", "filter", "(", "Q", "(", "publicevent__category__isnull", "=", "True", ")", "|", "Q", "(", "publicevent__category__separateOnRegistrationPage", "=", "False", ")", ")", ",", "'regClosedEvents'", ":", "publicEvents", ".", "filter", "(", "registrationOpen", "=", "False", ")", ".", "filter", "(", "Q", "(", "publicevent__category__isnull", "=", "True", ")", "|", "Q", "(", "publicevent__category__separateOnRegistrationPage", "=", "False", ")", ")", ",", "'categorySeparateEvents'", ":", "publicEvents", ".", "filter", "(", "publicevent__category__separateOnRegistrationPage", "=", "True", ")", ".", "order_by", "(", "'publicevent__category'", ")", ",", "'regOpenSeries'", ":", "allSeries", ".", "filter", "(", "registrationOpen", "=", "True", ")", ".", "filter", "(", "Q", "(", "series__category__isnull", "=", "True", ")", "|", "Q", "(", "series__category__separateOnRegistrationPage", "=", "False", ")", ")", ",", "'regClosedSeries'", ":", "allSeries", ".", "filter", "(", "registrationOpen", "=", "False", ")", ".", "filter", "(", "Q", "(", "series__category__isnull", "=", "True", ")", "|", "Q", "(", "series__category__separateOnRegistrationPage", "=", "False", ")", ")", ",", "'categorySeparateSeries'", ":", "allSeries", ".", "filter", "(", "series__category__separateOnRegistrationPage", "=", "True", ")", ".", "order_by", "(", "'series__category'", ")", ",", "}", "return", "self", ".", "listing" ]
This function gets all of the information that we need to either render or validate the form. It is structured to avoid duplicate DB queries
[ "This", "function", "gets", "all", "of", "the", "information", "that", "we", "need", "to", "either", "render", "or", "validate", "the", "form", ".", "It", "is", "structured", "to", "avoid", "duplicate", "DB", "queries" ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/core/classreg.py#L256-L295
django-danceschool/django-danceschool
danceschool/core/classreg.py
RegistrationSummaryView.dispatch
def dispatch(self,request,*args,**kwargs): ''' Always check that the temporary registration has not expired ''' regSession = self.request.session.get(REG_VALIDATION_STR,{}) if not regSession: return HttpResponseRedirect(reverse('registration')) try: reg = TemporaryRegistration.objects.get( id=self.request.session[REG_VALIDATION_STR].get('temporaryRegistrationId') ) except ObjectDoesNotExist: messages.error(request,_('Invalid registration identifier passed to summary view.')) return HttpResponseRedirect(reverse('registration')) expiry = parse_datetime( self.request.session[REG_VALIDATION_STR].get('temporaryRegistrationExpiry',''), ) if not expiry or expiry < timezone.now(): messages.info(request,_('Your registration session has expired. Please try again.')) return HttpResponseRedirect(reverse('registration')) # If OK, pass the registration and proceed kwargs.update({ 'reg': reg, }) return super(RegistrationSummaryView,self).dispatch(request, *args, **kwargs)
python
def dispatch(self,request,*args,**kwargs): regSession = self.request.session.get(REG_VALIDATION_STR,{}) if not regSession: return HttpResponseRedirect(reverse('registration')) try: reg = TemporaryRegistration.objects.get( id=self.request.session[REG_VALIDATION_STR].get('temporaryRegistrationId') ) except ObjectDoesNotExist: messages.error(request,_('Invalid registration identifier passed to summary view.')) return HttpResponseRedirect(reverse('registration')) expiry = parse_datetime( self.request.session[REG_VALIDATION_STR].get('temporaryRegistrationExpiry',''), ) if not expiry or expiry < timezone.now(): messages.info(request,_('Your registration session has expired. Please try again.')) return HttpResponseRedirect(reverse('registration')) kwargs.update({ 'reg': reg, }) return super(RegistrationSummaryView,self).dispatch(request, *args, **kwargs)
[ "def", "dispatch", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "regSession", "=", "self", ".", "request", ".", "session", ".", "get", "(", "REG_VALIDATION_STR", ",", "{", "}", ")", "if", "not", "regSession", ":", "return", "HttpResponseRedirect", "(", "reverse", "(", "'registration'", ")", ")", "try", ":", "reg", "=", "TemporaryRegistration", ".", "objects", ".", "get", "(", "id", "=", "self", ".", "request", ".", "session", "[", "REG_VALIDATION_STR", "]", ".", "get", "(", "'temporaryRegistrationId'", ")", ")", "except", "ObjectDoesNotExist", ":", "messages", ".", "error", "(", "request", ",", "_", "(", "'Invalid registration identifier passed to summary view.'", ")", ")", "return", "HttpResponseRedirect", "(", "reverse", "(", "'registration'", ")", ")", "expiry", "=", "parse_datetime", "(", "self", ".", "request", ".", "session", "[", "REG_VALIDATION_STR", "]", ".", "get", "(", "'temporaryRegistrationExpiry'", ",", "''", ")", ",", ")", "if", "not", "expiry", "or", "expiry", "<", "timezone", ".", "now", "(", ")", ":", "messages", ".", "info", "(", "request", ",", "_", "(", "'Your registration session has expired. Please try again.'", ")", ")", "return", "HttpResponseRedirect", "(", "reverse", "(", "'registration'", ")", ")", "# If OK, pass the registration and proceed", "kwargs", ".", "update", "(", "{", "'reg'", ":", "reg", ",", "}", ")", "return", "super", "(", "RegistrationSummaryView", ",", "self", ")", ".", "dispatch", "(", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
Always check that the temporary registration has not expired
[ "Always", "check", "that", "the", "temporary", "registration", "has", "not", "expired" ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/core/classreg.py#L321-L347
django-danceschool/django-danceschool
danceschool/core/classreg.py
RegistrationSummaryView.get_context_data
def get_context_data(self,**kwargs): ''' Pass the initial kwargs, then update with the needed registration info. ''' context_data = super(RegistrationSummaryView,self).get_context_data(**kwargs) regSession = self.request.session[REG_VALIDATION_STR] reg_id = regSession["temp_reg_id"] reg = TemporaryRegistration.objects.get(id=reg_id) discount_codes = regSession.get('discount_codes',None) discount_amount = regSession.get('total_discount_amount',0) voucher_names = regSession.get('voucher_names',[]) total_voucher_amount = regSession.get('total_voucher_amount',0) addons = regSession.get('addons',[]) if reg.priceWithDiscount == 0: # Create a new Invoice if one does not already exist. new_invoice = Invoice.get_or_create_from_registration(reg,status=Invoice.PaymentStatus.paid) new_invoice.processPayment(0,0,forceFinalize=True) isFree = True else: isFree = False context_data.update({ 'registration': reg, "totalPrice": reg.totalPrice, 'subtotal': reg.priceWithDiscount, 'taxes': reg.addTaxes, "netPrice": reg.priceWithDiscountAndTaxes, "addonItems": addons, "discount_codes": discount_codes, "discount_code_amount": discount_amount, "voucher_names": voucher_names, "total_voucher_amount": total_voucher_amount, "total_discount_amount": discount_amount + total_voucher_amount, "currencyCode": getConstant('general__currencyCode'), 'payAtDoor': reg.payAtDoor, 'is_free': isFree, }) if self.request.user: door_permission = self.request.user.has_perm('core.accept_door_payments') invoice_permission = self.request.user.has_perm('core.send_invoices') if door_permission or invoice_permission: context_data['form'] = DoorAmountForm( user=self.request.user, doorPortion=door_permission, invoicePortion=invoice_permission, payerEmail=reg.email, discountAmount=max(reg.totalPrice - reg.priceWithDiscount,0), ) return context_data
python
def get_context_data(self,**kwargs): context_data = super(RegistrationSummaryView,self).get_context_data(**kwargs) regSession = self.request.session[REG_VALIDATION_STR] reg_id = regSession["temp_reg_id"] reg = TemporaryRegistration.objects.get(id=reg_id) discount_codes = regSession.get('discount_codes',None) discount_amount = regSession.get('total_discount_amount',0) voucher_names = regSession.get('voucher_names',[]) total_voucher_amount = regSession.get('total_voucher_amount',0) addons = regSession.get('addons',[]) if reg.priceWithDiscount == 0: new_invoice = Invoice.get_or_create_from_registration(reg,status=Invoice.PaymentStatus.paid) new_invoice.processPayment(0,0,forceFinalize=True) isFree = True else: isFree = False context_data.update({ 'registration': reg, "totalPrice": reg.totalPrice, 'subtotal': reg.priceWithDiscount, 'taxes': reg.addTaxes, "netPrice": reg.priceWithDiscountAndTaxes, "addonItems": addons, "discount_codes": discount_codes, "discount_code_amount": discount_amount, "voucher_names": voucher_names, "total_voucher_amount": total_voucher_amount, "total_discount_amount": discount_amount + total_voucher_amount, "currencyCode": getConstant('general__currencyCode'), 'payAtDoor': reg.payAtDoor, 'is_free': isFree, }) if self.request.user: door_permission = self.request.user.has_perm('core.accept_door_payments') invoice_permission = self.request.user.has_perm('core.send_invoices') if door_permission or invoice_permission: context_data['form'] = DoorAmountForm( user=self.request.user, doorPortion=door_permission, invoicePortion=invoice_permission, payerEmail=reg.email, discountAmount=max(reg.totalPrice - reg.priceWithDiscount,0), ) return context_data
[ "def", "get_context_data", "(", "self", ",", "*", "*", "kwargs", ")", ":", "context_data", "=", "super", "(", "RegistrationSummaryView", ",", "self", ")", ".", "get_context_data", "(", "*", "*", "kwargs", ")", "regSession", "=", "self", ".", "request", ".", "session", "[", "REG_VALIDATION_STR", "]", "reg_id", "=", "regSession", "[", "\"temp_reg_id\"", "]", "reg", "=", "TemporaryRegistration", ".", "objects", ".", "get", "(", "id", "=", "reg_id", ")", "discount_codes", "=", "regSession", ".", "get", "(", "'discount_codes'", ",", "None", ")", "discount_amount", "=", "regSession", ".", "get", "(", "'total_discount_amount'", ",", "0", ")", "voucher_names", "=", "regSession", ".", "get", "(", "'voucher_names'", ",", "[", "]", ")", "total_voucher_amount", "=", "regSession", ".", "get", "(", "'total_voucher_amount'", ",", "0", ")", "addons", "=", "regSession", ".", "get", "(", "'addons'", ",", "[", "]", ")", "if", "reg", ".", "priceWithDiscount", "==", "0", ":", "# Create a new Invoice if one does not already exist.", "new_invoice", "=", "Invoice", ".", "get_or_create_from_registration", "(", "reg", ",", "status", "=", "Invoice", ".", "PaymentStatus", ".", "paid", ")", "new_invoice", ".", "processPayment", "(", "0", ",", "0", ",", "forceFinalize", "=", "True", ")", "isFree", "=", "True", "else", ":", "isFree", "=", "False", "context_data", ".", "update", "(", "{", "'registration'", ":", "reg", ",", "\"totalPrice\"", ":", "reg", ".", "totalPrice", ",", "'subtotal'", ":", "reg", ".", "priceWithDiscount", ",", "'taxes'", ":", "reg", ".", "addTaxes", ",", "\"netPrice\"", ":", "reg", ".", "priceWithDiscountAndTaxes", ",", "\"addonItems\"", ":", "addons", ",", "\"discount_codes\"", ":", "discount_codes", ",", "\"discount_code_amount\"", ":", "discount_amount", ",", "\"voucher_names\"", ":", "voucher_names", ",", "\"total_voucher_amount\"", ":", "total_voucher_amount", ",", "\"total_discount_amount\"", ":", "discount_amount", "+", "total_voucher_amount", ",", "\"currencyCode\"", ":", "getConstant", "(", "'general__currencyCode'", ")", ",", "'payAtDoor'", ":", "reg", ".", "payAtDoor", ",", "'is_free'", ":", "isFree", ",", "}", ")", "if", "self", ".", "request", ".", "user", ":", "door_permission", "=", "self", ".", "request", ".", "user", ".", "has_perm", "(", "'core.accept_door_payments'", ")", "invoice_permission", "=", "self", ".", "request", ".", "user", ".", "has_perm", "(", "'core.send_invoices'", ")", "if", "door_permission", "or", "invoice_permission", ":", "context_data", "[", "'form'", "]", "=", "DoorAmountForm", "(", "user", "=", "self", ".", "request", ".", "user", ",", "doorPortion", "=", "door_permission", ",", "invoicePortion", "=", "invoice_permission", ",", "payerEmail", "=", "reg", ".", "email", ",", "discountAmount", "=", "max", "(", "reg", ".", "totalPrice", "-", "reg", ".", "priceWithDiscount", ",", "0", ")", ",", ")", "return", "context_data" ]
Pass the initial kwargs, then update with the needed registration info.
[ "Pass", "the", "initial", "kwargs", "then", "update", "with", "the", "needed", "registration", "info", "." ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/core/classreg.py#L440-L492
django-danceschool/django-danceschool
danceschool/core/classreg.py
StudentInfoView.dispatch
def dispatch(self, request, *args, **kwargs): ''' Require session data to be set to proceed, otherwise go back to step 1. Because they have the same expiration date, this also implies that the TemporaryRegistration object is not yet expired. ''' if REG_VALIDATION_STR not in request.session: return HttpResponseRedirect(reverse('registration')) try: self.temporaryRegistration = TemporaryRegistration.objects.get( id=self.request.session[REG_VALIDATION_STR].get('temporaryRegistrationId') ) except ObjectDoesNotExist: messages.error(request,_('Invalid registration identifier passed to sign-up form.')) return HttpResponseRedirect(reverse('registration')) expiry = parse_datetime( self.request.session[REG_VALIDATION_STR].get('temporaryRegistrationExpiry',''), ) if not expiry or expiry < timezone.now(): messages.info(request,_('Your registration session has expired. Please try again.')) return HttpResponseRedirect(reverse('registration')) return super(StudentInfoView,self).dispatch(request,*args,**kwargs)
python
def dispatch(self, request, *args, **kwargs): if REG_VALIDATION_STR not in request.session: return HttpResponseRedirect(reverse('registration')) try: self.temporaryRegistration = TemporaryRegistration.objects.get( id=self.request.session[REG_VALIDATION_STR].get('temporaryRegistrationId') ) except ObjectDoesNotExist: messages.error(request,_('Invalid registration identifier passed to sign-up form.')) return HttpResponseRedirect(reverse('registration')) expiry = parse_datetime( self.request.session[REG_VALIDATION_STR].get('temporaryRegistrationExpiry',''), ) if not expiry or expiry < timezone.now(): messages.info(request,_('Your registration session has expired. Please try again.')) return HttpResponseRedirect(reverse('registration')) return super(StudentInfoView,self).dispatch(request,*args,**kwargs)
[ "def", "dispatch", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "REG_VALIDATION_STR", "not", "in", "request", ".", "session", ":", "return", "HttpResponseRedirect", "(", "reverse", "(", "'registration'", ")", ")", "try", ":", "self", ".", "temporaryRegistration", "=", "TemporaryRegistration", ".", "objects", ".", "get", "(", "id", "=", "self", ".", "request", ".", "session", "[", "REG_VALIDATION_STR", "]", ".", "get", "(", "'temporaryRegistrationId'", ")", ")", "except", "ObjectDoesNotExist", ":", "messages", ".", "error", "(", "request", ",", "_", "(", "'Invalid registration identifier passed to sign-up form.'", ")", ")", "return", "HttpResponseRedirect", "(", "reverse", "(", "'registration'", ")", ")", "expiry", "=", "parse_datetime", "(", "self", ".", "request", ".", "session", "[", "REG_VALIDATION_STR", "]", ".", "get", "(", "'temporaryRegistrationExpiry'", ",", "''", ")", ",", ")", "if", "not", "expiry", "or", "expiry", "<", "timezone", ".", "now", "(", ")", ":", "messages", ".", "info", "(", "request", ",", "_", "(", "'Your registration session has expired. Please try again.'", ")", ")", "return", "HttpResponseRedirect", "(", "reverse", "(", "'registration'", ")", ")", "return", "super", "(", "StudentInfoView", ",", "self", ")", ".", "dispatch", "(", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
Require session data to be set to proceed, otherwise go back to step 1. Because they have the same expiration date, this also implies that the TemporaryRegistration object is not yet expired.
[ "Require", "session", "data", "to", "be", "set", "to", "proceed", "otherwise", "go", "back", "to", "step", "1", ".", "Because", "they", "have", "the", "same", "expiration", "date", "this", "also", "implies", "that", "the", "TemporaryRegistration", "object", "is", "not", "yet", "expired", "." ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/core/classreg.py#L557-L581
django-danceschool/django-danceschool
danceschool/core/classreg.py
StudentInfoView.get_form_kwargs
def get_form_kwargs(self, **kwargs): ''' Pass along the request data to the form ''' kwargs = super(StudentInfoView, self).get_form_kwargs(**kwargs) kwargs['request'] = self.request kwargs['registration'] = self.temporaryRegistration return kwargs
python
def get_form_kwargs(self, **kwargs): kwargs = super(StudentInfoView, self).get_form_kwargs(**kwargs) kwargs['request'] = self.request kwargs['registration'] = self.temporaryRegistration return kwargs
[ "def", "get_form_kwargs", "(", "self", ",", "*", "*", "kwargs", ")", ":", "kwargs", "=", "super", "(", "StudentInfoView", ",", "self", ")", ".", "get_form_kwargs", "(", "*", "*", "kwargs", ")", "kwargs", "[", "'request'", "]", "=", "self", ".", "request", "kwargs", "[", "'registration'", "]", "=", "self", ".", "temporaryRegistration", "return", "kwargs" ]
Pass along the request data to the form
[ "Pass", "along", "the", "request", "data", "to", "the", "form" ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/core/classreg.py#L656-L661
django-danceschool/django-danceschool
danceschool/core/classreg.py
StudentInfoView.form_valid
def form_valid(self,form): ''' Even if this form is valid, the handlers for this form may have added messages to the request. In that case, then the page should be handled as if the form were invalid. Otherwise, update the session data with the form data and then move to the next view ''' reg = self.temporaryRegistration # The session expires after a period of inactivity that is specified in preferences. expiry = timezone.now() + timedelta(minutes=getConstant('registration__sessionExpiryMinutes')) self.request.session[REG_VALIDATION_STR]["temporaryRegistrationExpiry"] = \ expiry.strftime('%Y-%m-%dT%H:%M:%S%z') self.request.session.modified = True # Update the expiration date for this registration, and pass in the data from # this form. reg.expirationDate = expiry reg.firstName = form.cleaned_data.pop('firstName') reg.lastName = form.cleaned_data.pop('lastName') reg.email = form.cleaned_data.pop('email') reg.phone = form.cleaned_data.pop('phone', None) reg.student = form.cleaned_data.pop('student',False) reg.comments = form.cleaned_data.pop('comments',None) reg.howHeardAboutUs = form.cleaned_data.pop('howHeardAboutUs',None) # Anything else in the form goes to the TemporaryRegistration data. reg.data.update(form.cleaned_data) reg.save() # This signal (formerly the post_temporary_registration signal) allows # vouchers to be applied temporarily, and it can be used for other tasks post_student_info.send(sender=StudentInfoView,registration=reg) return HttpResponseRedirect(self.get_success_url())
python
def form_valid(self,form): reg = self.temporaryRegistration expiry = timezone.now() + timedelta(minutes=getConstant('registration__sessionExpiryMinutes')) self.request.session[REG_VALIDATION_STR]["temporaryRegistrationExpiry"] = \ expiry.strftime('%Y-%m-%dT%H:%M:%S%z') self.request.session.modified = True reg.expirationDate = expiry reg.firstName = form.cleaned_data.pop('firstName') reg.lastName = form.cleaned_data.pop('lastName') reg.email = form.cleaned_data.pop('email') reg.phone = form.cleaned_data.pop('phone', None) reg.student = form.cleaned_data.pop('student',False) reg.comments = form.cleaned_data.pop('comments',None) reg.howHeardAboutUs = form.cleaned_data.pop('howHeardAboutUs',None) reg.data.update(form.cleaned_data) reg.save() post_student_info.send(sender=StudentInfoView,registration=reg) return HttpResponseRedirect(self.get_success_url())
[ "def", "form_valid", "(", "self", ",", "form", ")", ":", "reg", "=", "self", ".", "temporaryRegistration", "# The session expires after a period of inactivity that is specified in preferences.", "expiry", "=", "timezone", ".", "now", "(", ")", "+", "timedelta", "(", "minutes", "=", "getConstant", "(", "'registration__sessionExpiryMinutes'", ")", ")", "self", ".", "request", ".", "session", "[", "REG_VALIDATION_STR", "]", "[", "\"temporaryRegistrationExpiry\"", "]", "=", "expiry", ".", "strftime", "(", "'%Y-%m-%dT%H:%M:%S%z'", ")", "self", ".", "request", ".", "session", ".", "modified", "=", "True", "# Update the expiration date for this registration, and pass in the data from", "# this form.", "reg", ".", "expirationDate", "=", "expiry", "reg", ".", "firstName", "=", "form", ".", "cleaned_data", ".", "pop", "(", "'firstName'", ")", "reg", ".", "lastName", "=", "form", ".", "cleaned_data", ".", "pop", "(", "'lastName'", ")", "reg", ".", "email", "=", "form", ".", "cleaned_data", ".", "pop", "(", "'email'", ")", "reg", ".", "phone", "=", "form", ".", "cleaned_data", ".", "pop", "(", "'phone'", ",", "None", ")", "reg", ".", "student", "=", "form", ".", "cleaned_data", ".", "pop", "(", "'student'", ",", "False", ")", "reg", ".", "comments", "=", "form", ".", "cleaned_data", ".", "pop", "(", "'comments'", ",", "None", ")", "reg", ".", "howHeardAboutUs", "=", "form", ".", "cleaned_data", ".", "pop", "(", "'howHeardAboutUs'", ",", "None", ")", "# Anything else in the form goes to the TemporaryRegistration data.", "reg", ".", "data", ".", "update", "(", "form", ".", "cleaned_data", ")", "reg", ".", "save", "(", ")", "# This signal (formerly the post_temporary_registration signal) allows", "# vouchers to be applied temporarily, and it can be used for other tasks", "post_student_info", ".", "send", "(", "sender", "=", "StudentInfoView", ",", "registration", "=", "reg", ")", "return", "HttpResponseRedirect", "(", "self", ".", "get_success_url", "(", ")", ")" ]
Even if this form is valid, the handlers for this form may have added messages to the request. In that case, then the page should be handled as if the form were invalid. Otherwise, update the session data with the form data and then move to the next view
[ "Even", "if", "this", "form", "is", "valid", "the", "handlers", "for", "this", "form", "may", "have", "added", "messages", "to", "the", "request", ".", "In", "that", "case", "then", "the", "page", "should", "be", "handled", "as", "if", "the", "form", "were", "invalid", ".", "Otherwise", "update", "the", "session", "data", "with", "the", "form", "data", "and", "then", "move", "to", "the", "next", "view" ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/core/classreg.py#L666-L699
django-danceschool/django-danceschool
danceschool/core/handlers.py
linkUserToMostRecentCustomer
def linkUserToMostRecentCustomer(sender,**kwargs): ''' If a new primary email address has just been confirmed, check if the user associated with that email has an associated customer object yet. If not, then look for the customer with that email address who most recently registered for something and that is not associated with another user. Automatically associate the User with with Customer, and if missing, fill in the user's name information with the Customer's name. This way, when a new or existing customer creates a user account, they are seamlessly linked to their most recent existing registration at the time they verify their email address. ''' email_address = kwargs.get('email_address',None) if not email_address or not email_address.primary or not email_address.verified: return user = email_address.user if not hasattr(user, 'customer'): last_reg = Registration.objects.filter( customer__email=email_address.email, customer__user__isnull=True, dateTime__isnull=False ).order_by('-dateTime').first() if last_reg: customer = last_reg.customer customer.user = user customer.save() if not user.first_name and not user.last_name: user.first_name = customer.first_name user.last_name = customer.last_name user.save()
python
def linkUserToMostRecentCustomer(sender,**kwargs): email_address = kwargs.get('email_address',None) if not email_address or not email_address.primary or not email_address.verified: return user = email_address.user if not hasattr(user, 'customer'): last_reg = Registration.objects.filter( customer__email=email_address.email, customer__user__isnull=True, dateTime__isnull=False ).order_by('-dateTime').first() if last_reg: customer = last_reg.customer customer.user = user customer.save() if not user.first_name and not user.last_name: user.first_name = customer.first_name user.last_name = customer.last_name user.save()
[ "def", "linkUserToMostRecentCustomer", "(", "sender", ",", "*", "*", "kwargs", ")", ":", "email_address", "=", "kwargs", ".", "get", "(", "'email_address'", ",", "None", ")", "if", "not", "email_address", "or", "not", "email_address", ".", "primary", "or", "not", "email_address", ".", "verified", ":", "return", "user", "=", "email_address", ".", "user", "if", "not", "hasattr", "(", "user", ",", "'customer'", ")", ":", "last_reg", "=", "Registration", ".", "objects", ".", "filter", "(", "customer__email", "=", "email_address", ".", "email", ",", "customer__user__isnull", "=", "True", ",", "dateTime__isnull", "=", "False", ")", ".", "order_by", "(", "'-dateTime'", ")", ".", "first", "(", ")", "if", "last_reg", ":", "customer", "=", "last_reg", ".", "customer", "customer", ".", "user", "=", "user", "customer", ".", "save", "(", ")", "if", "not", "user", ".", "first_name", "and", "not", "user", ".", "last_name", ":", "user", ".", "first_name", "=", "customer", ".", "first_name", "user", ".", "last_name", "=", "customer", ".", "last_name", "user", ".", "save", "(", ")" ]
If a new primary email address has just been confirmed, check if the user associated with that email has an associated customer object yet. If not, then look for the customer with that email address who most recently registered for something and that is not associated with another user. Automatically associate the User with with Customer, and if missing, fill in the user's name information with the Customer's name. This way, when a new or existing customer creates a user account, they are seamlessly linked to their most recent existing registration at the time they verify their email address.
[ "If", "a", "new", "primary", "email", "address", "has", "just", "been", "confirmed", "check", "if", "the", "user", "associated", "with", "that", "email", "has", "an", "associated", "customer", "object", "yet", ".", "If", "not", "then", "look", "for", "the", "customer", "with", "that", "email", "address", "who", "most", "recently", "registered", "for", "something", "and", "that", "is", "not", "associated", "with", "another", "user", ".", "Automatically", "associate", "the", "User", "with", "with", "Customer", "and", "if", "missing", "fill", "in", "the", "user", "s", "name", "information", "with", "the", "Customer", "s", "name", ".", "This", "way", "when", "a", "new", "or", "existing", "customer", "creates", "a", "user", "account", "they", "are", "seamlessly", "linked", "to", "their", "most", "recent", "existing", "registration", "at", "the", "time", "they", "verify", "their", "email", "address", "." ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/core/handlers.py#L17-L51
django-danceschool/django-danceschool
danceschool/core/handlers.py
linkCustomerToVerifiedUser
def linkCustomerToVerifiedUser(sender, **kwargs): """ If a Registration is processed in which the associated Customer does not yet have a User, then check to see if the Customer's email address has been verified as belonging to a specific User, and if that User has an associated Customer. If such a User is found, then associated this Customer with that User. This way, if a new User verifies their email account before they have submitted any Registrations, their Customer account is seamlessly linked when they do complete their first Registration. """ registration = kwargs.get('registration', None) if not registration or (hasattr(registration.customer,'user') and registration.customer.user): return logger.debug('Checking for User for Customer with no associated registration.') customer = registration.customer try: verified_email = EmailAddress.objects.get( email=customer.email, verified=True, primary=True, user__customer__isnull=True ) logger.info("Found user %s to associate with customer %s.", verified_email.user.id, customer.id) customer.user = verified_email.user customer.save() if not customer.user.first_name and not customer.user.last_name: customer.user.first_name = customer.first_name customer.user.last_name = customer.last_name customer.user.save() except ObjectDoesNotExist: logger.info("No user found to associate with customer %s.", customer.id) except MultipleObjectsReturned: # This should never happen, as email should be unique in the db table account_emailaddress. # If it does, something's broken in the database or Django. errmsg = "Something's not right with the database: more than one entry found on the database for the email %s. \ This duplicate key value violates unique constraint \"account_emailaddress_email_key\". \ The email field should be unique for each account.\n" logger.exception(errmsg, customer.email)
python
def linkCustomerToVerifiedUser(sender, **kwargs): registration = kwargs.get('registration', None) if not registration or (hasattr(registration.customer,'user') and registration.customer.user): return logger.debug('Checking for User for Customer with no associated registration.') customer = registration.customer try: verified_email = EmailAddress.objects.get( email=customer.email, verified=True, primary=True, user__customer__isnull=True ) logger.info("Found user %s to associate with customer %s.", verified_email.user.id, customer.id) customer.user = verified_email.user customer.save() if not customer.user.first_name and not customer.user.last_name: customer.user.first_name = customer.first_name customer.user.last_name = customer.last_name customer.user.save() except ObjectDoesNotExist: logger.info("No user found to associate with customer %s.", customer.id) except MultipleObjectsReturned: errmsg = "Something's not right with the database: more than one entry found on the database for the email %s. \ This duplicate key value violates unique constraint \"account_emailaddress_email_key\". \ The email field should be unique for each account.\n" logger.exception(errmsg, customer.email)
[ "def", "linkCustomerToVerifiedUser", "(", "sender", ",", "*", "*", "kwargs", ")", ":", "registration", "=", "kwargs", ".", "get", "(", "'registration'", ",", "None", ")", "if", "not", "registration", "or", "(", "hasattr", "(", "registration", ".", "customer", ",", "'user'", ")", "and", "registration", ".", "customer", ".", "user", ")", ":", "return", "logger", ".", "debug", "(", "'Checking for User for Customer with no associated registration.'", ")", "customer", "=", "registration", ".", "customer", "try", ":", "verified_email", "=", "EmailAddress", ".", "objects", ".", "get", "(", "email", "=", "customer", ".", "email", ",", "verified", "=", "True", ",", "primary", "=", "True", ",", "user__customer__isnull", "=", "True", ")", "logger", ".", "info", "(", "\"Found user %s to associate with customer %s.\"", ",", "verified_email", ".", "user", ".", "id", ",", "customer", ".", "id", ")", "customer", ".", "user", "=", "verified_email", ".", "user", "customer", ".", "save", "(", ")", "if", "not", "customer", ".", "user", ".", "first_name", "and", "not", "customer", ".", "user", ".", "last_name", ":", "customer", ".", "user", ".", "first_name", "=", "customer", ".", "first_name", "customer", ".", "user", ".", "last_name", "=", "customer", ".", "last_name", "customer", ".", "user", ".", "save", "(", ")", "except", "ObjectDoesNotExist", ":", "logger", ".", "info", "(", "\"No user found to associate with customer %s.\"", ",", "customer", ".", "id", ")", "except", "MultipleObjectsReturned", ":", "# This should never happen, as email should be unique in the db table account_emailaddress.", "# If it does, something's broken in the database or Django.", "errmsg", "=", "\"Something's not right with the database: more than one entry found on the database for the email %s. \\\n This duplicate key value violates unique constraint \\\"account_emailaddress_email_key\\\". \\\n The email field should be unique for each account.\\n\"", "logger", ".", "exception", "(", "errmsg", ",", "customer", ".", "email", ")" ]
If a Registration is processed in which the associated Customer does not yet have a User, then check to see if the Customer's email address has been verified as belonging to a specific User, and if that User has an associated Customer. If such a User is found, then associated this Customer with that User. This way, if a new User verifies their email account before they have submitted any Registrations, their Customer account is seamlessly linked when they do complete their first Registration.
[ "If", "a", "Registration", "is", "processed", "in", "which", "the", "associated", "Customer", "does", "not", "yet", "have", "a", "User", "then", "check", "to", "see", "if", "the", "Customer", "s", "email", "address", "has", "been", "verified", "as", "belonging", "to", "a", "specific", "User", "and", "if", "that", "User", "has", "an", "associated", "Customer", ".", "If", "such", "a", "User", "is", "found", "then", "associated", "this", "Customer", "with", "that", "User", ".", "This", "way", "if", "a", "new", "User", "verifies", "their", "email", "account", "before", "they", "have", "submitted", "any", "Registrations", "their", "Customer", "account", "is", "seamlessly", "linked", "when", "they", "do", "complete", "their", "first", "Registration", "." ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/core/handlers.py#L55-L99
django-danceschool/django-danceschool
danceschool/core/autocomplete_light_registry.py
StaffMemberAutoComplete.create_object
def create_object(self, text): ''' Allow creation of staff members using a full name string. ''' if self.create_field == 'fullName': firstName = text.split(' ')[0] lastName = ' '.join(text.split(' ')[1:]) return self.get_queryset().create(**{'firstName': firstName, 'lastName': lastName}) else: return super(StaffMemberAutoComplete,self).create_object(text)
python
def create_object(self, text): if self.create_field == 'fullName': firstName = text.split(' ')[0] lastName = ' '.join(text.split(' ')[1:]) return self.get_queryset().create(**{'firstName': firstName, 'lastName': lastName}) else: return super(StaffMemberAutoComplete,self).create_object(text)
[ "def", "create_object", "(", "self", ",", "text", ")", ":", "if", "self", ".", "create_field", "==", "'fullName'", ":", "firstName", "=", "text", ".", "split", "(", "' '", ")", "[", "0", "]", "lastName", "=", "' '", ".", "join", "(", "text", ".", "split", "(", "' '", ")", "[", "1", ":", "]", ")", "return", "self", ".", "get_queryset", "(", ")", ".", "create", "(", "*", "*", "{", "'firstName'", ":", "firstName", ",", "'lastName'", ":", "lastName", "}", ")", "else", ":", "return", "super", "(", "StaffMemberAutoComplete", ",", "self", ")", ".", "create_object", "(", "text", ")" ]
Allow creation of staff members using a full name string.
[ "Allow", "creation", "of", "staff", "members", "using", "a", "full", "name", "string", "." ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/core/autocomplete_light_registry.py#L125-L132
django-danceschool/django-danceschool
danceschool/banlist/handlers.py
checkBanlist
def checkBanlist(sender, **kwargs): ''' Check that this individual is not on the ban list. ''' if not getConstant('registration__enableBanList'): return logger.debug('Signal to check RegistrationContactForm handled by banlist app.') formData = kwargs.get('formData', {}) first = formData.get('firstName') last = formData.get('lastName') email = formData.get('email') request = kwargs.get('request', {}) session = getattr(request, 'session', {}).get(REG_VALIDATION_STR, {}) registrationId = getattr(kwargs.get('registration', None), 'id', None) records = BannedPerson.objects.exclude( disabled=True ).exclude( expirationDate__lte=timezone.now() ).filter( (Q(firstName__iexact=first) & Q(lastName__iexact=last)) | Q(bannedemail__email__iexact=email) ) if not records.exists(): return # Generate an "error code" to reference so that it is easier to lookup # the record on why they were flagged. flagCode = ''.join(random.choice(string.ascii_uppercase) for x in range(8)) ip = get_client_ip(request) respondTo = getConstant('registration__banListContactEmail') or getConstant('contact__businessEmail') for record in records: flagRecord = BanFlaggedRecord.objects.create( flagCode=flagCode, person=record, ipAddress=ip, data={'session': session, 'formData': formData, 'registrationId': registrationId} ) notify = getConstant('registration__banListNotificationEmail') if notify: send_from = getConstant('contact__businessEmail') subject = _('Notice of attempted registration by banned individual') message = _( 'This is an automated notification that the following individual has attempted ' + 'to register for a class series or event:\n\n' + 'Name: %s\n' % record.fullName + 'Email: %s\n' % email + 'Date/Time: %s\n' % flagRecord.dateTime + 'IP Address: %s\n\n' % ip + 'This individual has been prevented from finalizing their registration, and they ' + 'have been asked to notify the school at %s with code %s to proceed.' % (respondTo, flagCode) ) sendEmail(subject, message, send_from, to=[notify]) message = ugettext('There appears to be an issue with this registration. ' 'Please contact %s to proceed with the registration process. ' 'You may reference the error code %s.' % (respondTo, flagCode)) if request.user.has_perm('banlist.ignore_ban'): messages.warning(request, message) else: raise ValidationError(message)
python
def checkBanlist(sender, **kwargs): if not getConstant('registration__enableBanList'): return logger.debug('Signal to check RegistrationContactForm handled by banlist app.') formData = kwargs.get('formData', {}) first = formData.get('firstName') last = formData.get('lastName') email = formData.get('email') request = kwargs.get('request', {}) session = getattr(request, 'session', {}).get(REG_VALIDATION_STR, {}) registrationId = getattr(kwargs.get('registration', None), 'id', None) records = BannedPerson.objects.exclude( disabled=True ).exclude( expirationDate__lte=timezone.now() ).filter( (Q(firstName__iexact=first) & Q(lastName__iexact=last)) | Q(bannedemail__email__iexact=email) ) if not records.exists(): return flagCode = ''.join(random.choice(string.ascii_uppercase) for x in range(8)) ip = get_client_ip(request) respondTo = getConstant('registration__banListContactEmail') or getConstant('contact__businessEmail') for record in records: flagRecord = BanFlaggedRecord.objects.create( flagCode=flagCode, person=record, ipAddress=ip, data={'session': session, 'formData': formData, 'registrationId': registrationId} ) notify = getConstant('registration__banListNotificationEmail') if notify: send_from = getConstant('contact__businessEmail') subject = _('Notice of attempted registration by banned individual') message = _( 'This is an automated notification that the following individual has attempted ' + 'to register for a class series or event:\n\n' + 'Name: %s\n' % record.fullName + 'Email: %s\n' % email + 'Date/Time: %s\n' % flagRecord.dateTime + 'IP Address: %s\n\n' % ip + 'This individual has been prevented from finalizing their registration, and they ' + 'have been asked to notify the school at %s with code %s to proceed.' % (respondTo, flagCode) ) sendEmail(subject, message, send_from, to=[notify]) message = ugettext('There appears to be an issue with this registration. ' 'Please contact %s to proceed with the registration process. ' 'You may reference the error code %s.' % (respondTo, flagCode)) if request.user.has_perm('banlist.ignore_ban'): messages.warning(request, message) else: raise ValidationError(message)
[ "def", "checkBanlist", "(", "sender", ",", "*", "*", "kwargs", ")", ":", "if", "not", "getConstant", "(", "'registration__enableBanList'", ")", ":", "return", "logger", ".", "debug", "(", "'Signal to check RegistrationContactForm handled by banlist app.'", ")", "formData", "=", "kwargs", ".", "get", "(", "'formData'", ",", "{", "}", ")", "first", "=", "formData", ".", "get", "(", "'firstName'", ")", "last", "=", "formData", ".", "get", "(", "'lastName'", ")", "email", "=", "formData", ".", "get", "(", "'email'", ")", "request", "=", "kwargs", ".", "get", "(", "'request'", ",", "{", "}", ")", "session", "=", "getattr", "(", "request", ",", "'session'", ",", "{", "}", ")", ".", "get", "(", "REG_VALIDATION_STR", ",", "{", "}", ")", "registrationId", "=", "getattr", "(", "kwargs", ".", "get", "(", "'registration'", ",", "None", ")", ",", "'id'", ",", "None", ")", "records", "=", "BannedPerson", ".", "objects", ".", "exclude", "(", "disabled", "=", "True", ")", ".", "exclude", "(", "expirationDate__lte", "=", "timezone", ".", "now", "(", ")", ")", ".", "filter", "(", "(", "Q", "(", "firstName__iexact", "=", "first", ")", "&", "Q", "(", "lastName__iexact", "=", "last", ")", ")", "|", "Q", "(", "bannedemail__email__iexact", "=", "email", ")", ")", "if", "not", "records", ".", "exists", "(", ")", ":", "return", "# Generate an \"error code\" to reference so that it is easier to lookup\r", "# the record on why they were flagged.\r", "flagCode", "=", "''", ".", "join", "(", "random", ".", "choice", "(", "string", ".", "ascii_uppercase", ")", "for", "x", "in", "range", "(", "8", ")", ")", "ip", "=", "get_client_ip", "(", "request", ")", "respondTo", "=", "getConstant", "(", "'registration__banListContactEmail'", ")", "or", "getConstant", "(", "'contact__businessEmail'", ")", "for", "record", "in", "records", ":", "flagRecord", "=", "BanFlaggedRecord", ".", "objects", ".", "create", "(", "flagCode", "=", "flagCode", ",", "person", "=", "record", ",", "ipAddress", "=", "ip", ",", "data", "=", "{", "'session'", ":", "session", ",", "'formData'", ":", "formData", ",", "'registrationId'", ":", "registrationId", "}", ")", "notify", "=", "getConstant", "(", "'registration__banListNotificationEmail'", ")", "if", "notify", ":", "send_from", "=", "getConstant", "(", "'contact__businessEmail'", ")", "subject", "=", "_", "(", "'Notice of attempted registration by banned individual'", ")", "message", "=", "_", "(", "'This is an automated notification that the following individual has attempted '", "+", "'to register for a class series or event:\\n\\n'", "+", "'Name: %s\\n'", "%", "record", ".", "fullName", "+", "'Email: %s\\n'", "%", "email", "+", "'Date/Time: %s\\n'", "%", "flagRecord", ".", "dateTime", "+", "'IP Address: %s\\n\\n'", "%", "ip", "+", "'This individual has been prevented from finalizing their registration, and they '", "+", "'have been asked to notify the school at %s with code %s to proceed.'", "%", "(", "respondTo", ",", "flagCode", ")", ")", "sendEmail", "(", "subject", ",", "message", ",", "send_from", ",", "to", "=", "[", "notify", "]", ")", "message", "=", "ugettext", "(", "'There appears to be an issue with this registration. '", "'Please contact %s to proceed with the registration process. '", "'You may reference the error code %s.'", "%", "(", "respondTo", ",", "flagCode", ")", ")", "if", "request", ".", "user", ".", "has_perm", "(", "'banlist.ignore_ban'", ")", ":", "messages", ".", "warning", "(", "request", ",", "message", ")", "else", ":", "raise", "ValidationError", "(", "message", ")" ]
Check that this individual is not on the ban list.
[ "Check", "that", "this", "individual", "is", "not", "on", "the", "ban", "list", "." ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/banlist/handlers.py#L35-L105
django-danceschool/django-danceschool
danceschool/financial/models.py
TransactionParty.clean
def clean(self): ''' Verify that the user and staffMember are not mismatched. Location can only be specified if user and staffMember are not. ''' if self.staffMember and self.staffMember.userAccount and \ self.user and not self.staffMember.userAccount == self.user: raise ValidationError(_('Transaction party user does not match staff member user.')) if self.location and (self.user or self.staffMember): raise ValidationError(_('Transaction party may not be both a Location and a User or StaffMember.'))
python
def clean(self): if self.staffMember and self.staffMember.userAccount and \ self.user and not self.staffMember.userAccount == self.user: raise ValidationError(_('Transaction party user does not match staff member user.')) if self.location and (self.user or self.staffMember): raise ValidationError(_('Transaction party may not be both a Location and a User or StaffMember.'))
[ "def", "clean", "(", "self", ")", ":", "if", "self", ".", "staffMember", "and", "self", ".", "staffMember", ".", "userAccount", "and", "self", ".", "user", "and", "not", "self", ".", "staffMember", ".", "userAccount", "==", "self", ".", "user", ":", "raise", "ValidationError", "(", "_", "(", "'Transaction party user does not match staff member user.'", ")", ")", "if", "self", ".", "location", "and", "(", "self", ".", "user", "or", "self", ".", "staffMember", ")", ":", "raise", "ValidationError", "(", "_", "(", "'Transaction party may not be both a Location and a User or StaffMember.'", ")", ")" ]
Verify that the user and staffMember are not mismatched. Location can only be specified if user and staffMember are not.
[ "Verify", "that", "the", "user", "and", "staffMember", "are", "not", "mismatched", ".", "Location", "can", "only", "be", "specified", "if", "user", "and", "staffMember", "are", "not", "." ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/financial/models.py#L83-L94
django-danceschool/django-danceschool
danceschool/financial/models.py
TransactionParty.save
def save(self, updateBy=None, *args, **kwargs): ''' Verify that the user and staffMember are populated with linked information, and ensure that the name is properly specified. ''' if ( self.staffMember and self.staffMember.userAccount and not self.user ) or ( isinstance(updateBy,StaffMember) and self.staffMember.userAccount ): self.user = self.staffMember.userAccount elif ( self.user and getattr(self.user,'staffmember',None) and not self.staffMember ) or ( isinstance(updateBy,User) and getattr(self.user,'staffmember',None) ): self.staffMember = self.user.staffmember # Don't replace the name if it has been given, but do fill it out if it is blank. if not self.name: if self.user and self.user.get_full_name(): self.name = self.user.get_full_name() elif self.staffMember: self.name = self.staffMember.fullName or self.staffMember.privateEmail elif self.location: self.name = self.location.name super(TransactionParty, self).save(*args, **kwargs)
python
def save(self, updateBy=None, *args, **kwargs): if ( self.staffMember and self.staffMember.userAccount and not self.user ) or ( isinstance(updateBy,StaffMember) and self.staffMember.userAccount ): self.user = self.staffMember.userAccount elif ( self.user and getattr(self.user,'staffmember',None) and not self.staffMember ) or ( isinstance(updateBy,User) and getattr(self.user,'staffmember',None) ): self.staffMember = self.user.staffmember if not self.name: if self.user and self.user.get_full_name(): self.name = self.user.get_full_name() elif self.staffMember: self.name = self.staffMember.fullName or self.staffMember.privateEmail elif self.location: self.name = self.location.name super(TransactionParty, self).save(*args, **kwargs)
[ "def", "save", "(", "self", ",", "updateBy", "=", "None", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "(", "self", ".", "staffMember", "and", "self", ".", "staffMember", ".", "userAccount", "and", "not", "self", ".", "user", ")", "or", "(", "isinstance", "(", "updateBy", ",", "StaffMember", ")", "and", "self", ".", "staffMember", ".", "userAccount", ")", ":", "self", ".", "user", "=", "self", ".", "staffMember", ".", "userAccount", "elif", "(", "self", ".", "user", "and", "getattr", "(", "self", ".", "user", ",", "'staffmember'", ",", "None", ")", "and", "not", "self", ".", "staffMember", ")", "or", "(", "isinstance", "(", "updateBy", ",", "User", ")", "and", "getattr", "(", "self", ".", "user", ",", "'staffmember'", ",", "None", ")", ")", ":", "self", ".", "staffMember", "=", "self", ".", "user", ".", "staffmember", "# Don't replace the name if it has been given, but do fill it out if it is blank.", "if", "not", "self", ".", "name", ":", "if", "self", ".", "user", "and", "self", ".", "user", ".", "get_full_name", "(", ")", ":", "self", ".", "name", "=", "self", ".", "user", ".", "get_full_name", "(", ")", "elif", "self", ".", "staffMember", ":", "self", ".", "name", "=", "self", ".", "staffMember", ".", "fullName", "or", "self", ".", "staffMember", ".", "privateEmail", "elif", "self", ".", "location", ":", "self", ".", "name", "=", "self", ".", "location", ".", "name", "super", "(", "TransactionParty", ",", "self", ")", ".", "save", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
Verify that the user and staffMember are populated with linked information, and ensure that the name is properly specified.
[ "Verify", "that", "the", "user", "and", "staffMember", "are", "populated", "with", "linked", "information", "and", "ensure", "that", "the", "name", "is", "properly", "specified", "." ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/financial/models.py#L96-L124
django-danceschool/django-danceschool
danceschool/financial/models.py
RepeatedExpenseRule.timeAtThreshold
def timeAtThreshold(self,dateTime): ''' A convenience method for checking when a time is on the start/end boundary for this rule. ''' # Anything that's not at a day boundary is for sure not at a threshold. if not ( dateTime.hour == self.dayStarts and dateTime.minute == 0 and dateTime.second == 0 and dateTime.microsecond == 0 ): return False if self.applyRateRule == self.RateRuleChoices.daily: return True elif self.applyRateRule == self.RateRuleChoices.weekly: return (dateTime == self.weekStarts) elif self.applyRateRule == self.RateRuleChoices.monthly: return (dateTime.day == self.monthStarts) # Everything else is nonsensical, so False. return False
python
def timeAtThreshold(self,dateTime): if not ( dateTime.hour == self.dayStarts and dateTime.minute == 0 and dateTime.second == 0 and dateTime.microsecond == 0 ): return False if self.applyRateRule == self.RateRuleChoices.daily: return True elif self.applyRateRule == self.RateRuleChoices.weekly: return (dateTime == self.weekStarts) elif self.applyRateRule == self.RateRuleChoices.monthly: return (dateTime.day == self.monthStarts) return False
[ "def", "timeAtThreshold", "(", "self", ",", "dateTime", ")", ":", "# Anything that's not at a day boundary is for sure not at a threshold.", "if", "not", "(", "dateTime", ".", "hour", "==", "self", ".", "dayStarts", "and", "dateTime", ".", "minute", "==", "0", "and", "dateTime", ".", "second", "==", "0", "and", "dateTime", ".", "microsecond", "==", "0", ")", ":", "return", "False", "if", "self", ".", "applyRateRule", "==", "self", ".", "RateRuleChoices", ".", "daily", ":", "return", "True", "elif", "self", ".", "applyRateRule", "==", "self", ".", "RateRuleChoices", ".", "weekly", ":", "return", "(", "dateTime", "==", "self", ".", "weekStarts", ")", "elif", "self", ".", "applyRateRule", "==", "self", ".", "RateRuleChoices", ".", "monthly", ":", "return", "(", "dateTime", ".", "day", "==", "self", ".", "monthStarts", ")", "# Everything else is nonsensical, so False.", "return", "False" ]
A convenience method for checking when a time is on the start/end boundary for this rule.
[ "A", "convenience", "method", "for", "checking", "when", "a", "time", "is", "on", "the", "start", "/", "end", "boundary", "for", "this", "rule", "." ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/financial/models.py#L258-L279
django-danceschool/django-danceschool
danceschool/financial/models.py
RepeatedExpenseRule.ruleName
def ruleName(self): ''' This should be overridden for child classes ''' return '%s %s' % (self.rentalRate, self.RateRuleChoices.values.get(self.applyRateRule,self.applyRateRule))
python
def ruleName(self): return '%s %s' % (self.rentalRate, self.RateRuleChoices.values.get(self.applyRateRule,self.applyRateRule))
[ "def", "ruleName", "(", "self", ")", ":", "return", "'%s %s'", "%", "(", "self", ".", "rentalRate", ",", "self", ".", "RateRuleChoices", ".", "values", ".", "get", "(", "self", ".", "applyRateRule", ",", "self", ".", "applyRateRule", ")", ")" ]
This should be overridden for child classes
[ "This", "should", "be", "overridden", "for", "child", "classes" ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/financial/models.py#L416-L418
django-danceschool/django-danceschool
danceschool/financial/models.py
RoomRentalInfo.ruleName
def ruleName(self): ''' overrides from parent class ''' return _('%s at %s' % (self.room.name, self.room.location.name))
python
def ruleName(self): return _('%s at %s' % (self.room.name, self.room.location.name))
[ "def", "ruleName", "(", "self", ")", ":", "return", "_", "(", "'%s at %s'", "%", "(", "self", ".", "room", ".", "name", ",", "self", ".", "room", ".", "location", ".", "name", ")", ")" ]
overrides from parent class
[ "overrides", "from", "parent", "class" ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/financial/models.py#L469-L471
django-danceschool/django-danceschool
danceschool/financial/models.py
GenericRepeatedExpense.clean
def clean(self): ''' priorDays is required for Generic Repeated Expenses to avoid infinite loops ''' if not self.priorDays and not self.startDate: raise ValidationError(_( 'Either a start date or an "up to __ days in the past" limit is required ' + 'for repeated expense rules that are not associated with a venue or a staff member.' )) super(GenericRepeatedExpense,self).clean()
python
def clean(self): if not self.priorDays and not self.startDate: raise ValidationError(_( 'Either a start date or an "up to __ days in the past" limit is required ' + 'for repeated expense rules that are not associated with a venue or a staff member.' )) super(GenericRepeatedExpense,self).clean()
[ "def", "clean", "(", "self", ")", ":", "if", "not", "self", ".", "priorDays", "and", "not", "self", ".", "startDate", ":", "raise", "ValidationError", "(", "_", "(", "'Either a start date or an \"up to __ days in the past\" limit is required '", "+", "'for repeated expense rules that are not associated with a venue or a staff member.'", ")", ")", "super", "(", "GenericRepeatedExpense", ",", "self", ")", ".", "clean", "(", ")" ]
priorDays is required for Generic Repeated Expenses to avoid infinite loops
[ "priorDays", "is", "required", "for", "Generic", "Repeated", "Expenses", "to", "avoid", "infinite", "loops" ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/financial/models.py#L585-L592
django-danceschool/django-danceschool
danceschool/financial/models.py
ExpenseItem.save
def save(self, *args, **kwargs): ''' This custom save method ensures that an expense is not attributed to multiple categories. It also ensures that the series and event properties are always associated with any type of expense of that series or event. ''' # Set the approval and payment dates if they have just been approved/paid. if not hasattr(self,'__paid') or not hasattr(self,'__approved'): if self.approved and not self.approvalDate: self.approvalDate = timezone.now() if self.paid and not self.paymentDate: self.paymentDate = timezone.now() else: if self.approved and not self.approvalDate and not self.__approvalDate: self.approvalDate = timezone.now() if self.paid and not self.paymentDate and not self.__paymentDate: self.paymentDate = timezone.now() # Fill out the series and event properties to permit easy calculation of # revenues and expenses by series or by event. if self.expenseRule and not self.payTo: this_loc = getattr(self.expenseRule,'location',None) this_member = getattr(self.expenseRule,'location',None) if this_loc: self.payTo = TransactionParty.objects.get_or_create( location=this_loc, defaults={'name': this_loc.name} )[0] elif this_member: self.payTo = TransactionParty.objects.get_or_create( staffMember=this_member, defaults={ 'name': this_member.fullName, 'user': getattr(this_member,'userAccount',None) } )[0] # Set the accrual date. The method for events ensures that the accrualDate month # is the same as the reported month of the series/event by accruing to the end date of the last # class or occurrence in that month. if not self.accrualDate: if self.event and self.event.month: self.accrualDate = self.event.eventoccurrence_set.order_by('endTime').filter(**{'endTime__month': self.event.month}).last().endTime elif self.submissionDate: self.accrualDate = self.submissionDate else: self.submissionDate = timezone.now() self.accrualDate = self.submissionDate # Set the total for hourly work if self.hours and not self.wageRate and not self.total and not getattr(getattr(self,'payTo',None),'location',None) and self.category: self.wageRate = self.category.defaultRate elif self.hours and not self.wageRate and not self.total and getattr(getattr(self,'payTo',None),'location',None): self.wageRate = self.payTo.location.rentalRate if self.hours and self.wageRate and not self.total: self.total = self.hours * self.wageRate super(ExpenseItem, self).save(*args, **kwargs) self.__approved = self.approved self.__paid = self.paid self.__approvalDate = self.approvalDate self.__paymentDate = self.paymentDate # If a file is attached, ensure that it is not public, and that it is saved in the 'Expense Receipts' folder if self.attachment: try: self.attachment.folder = Folder.objects.get(name=_('Expense Receipts')) except ObjectDoesNotExist: pass self.attachment.is_public = False self.attachment.save()
python
def save(self, *args, **kwargs): if not hasattr(self,'__paid') or not hasattr(self,'__approved'): if self.approved and not self.approvalDate: self.approvalDate = timezone.now() if self.paid and not self.paymentDate: self.paymentDate = timezone.now() else: if self.approved and not self.approvalDate and not self.__approvalDate: self.approvalDate = timezone.now() if self.paid and not self.paymentDate and not self.__paymentDate: self.paymentDate = timezone.now() if self.expenseRule and not self.payTo: this_loc = getattr(self.expenseRule,'location',None) this_member = getattr(self.expenseRule,'location',None) if this_loc: self.payTo = TransactionParty.objects.get_or_create( location=this_loc, defaults={'name': this_loc.name} )[0] elif this_member: self.payTo = TransactionParty.objects.get_or_create( staffMember=this_member, defaults={ 'name': this_member.fullName, 'user': getattr(this_member,'userAccount',None) } )[0] if not self.accrualDate: if self.event and self.event.month: self.accrualDate = self.event.eventoccurrence_set.order_by('endTime').filter(**{'endTime__month': self.event.month}).last().endTime elif self.submissionDate: self.accrualDate = self.submissionDate else: self.submissionDate = timezone.now() self.accrualDate = self.submissionDate if self.hours and not self.wageRate and not self.total and not getattr(getattr(self,'payTo',None),'location',None) and self.category: self.wageRate = self.category.defaultRate elif self.hours and not self.wageRate and not self.total and getattr(getattr(self,'payTo',None),'location',None): self.wageRate = self.payTo.location.rentalRate if self.hours and self.wageRate and not self.total: self.total = self.hours * self.wageRate super(ExpenseItem, self).save(*args, **kwargs) self.__approved = self.approved self.__paid = self.paid self.__approvalDate = self.approvalDate self.__paymentDate = self.paymentDate if self.attachment: try: self.attachment.folder = Folder.objects.get(name=_('Expense Receipts')) except ObjectDoesNotExist: pass self.attachment.is_public = False self.attachment.save()
[ "def", "save", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# Set the approval and payment dates if they have just been approved/paid.", "if", "not", "hasattr", "(", "self", ",", "'__paid'", ")", "or", "not", "hasattr", "(", "self", ",", "'__approved'", ")", ":", "if", "self", ".", "approved", "and", "not", "self", ".", "approvalDate", ":", "self", ".", "approvalDate", "=", "timezone", ".", "now", "(", ")", "if", "self", ".", "paid", "and", "not", "self", ".", "paymentDate", ":", "self", ".", "paymentDate", "=", "timezone", ".", "now", "(", ")", "else", ":", "if", "self", ".", "approved", "and", "not", "self", ".", "approvalDate", "and", "not", "self", ".", "__approvalDate", ":", "self", ".", "approvalDate", "=", "timezone", ".", "now", "(", ")", "if", "self", ".", "paid", "and", "not", "self", ".", "paymentDate", "and", "not", "self", ".", "__paymentDate", ":", "self", ".", "paymentDate", "=", "timezone", ".", "now", "(", ")", "# Fill out the series and event properties to permit easy calculation of", "# revenues and expenses by series or by event.", "if", "self", ".", "expenseRule", "and", "not", "self", ".", "payTo", ":", "this_loc", "=", "getattr", "(", "self", ".", "expenseRule", ",", "'location'", ",", "None", ")", "this_member", "=", "getattr", "(", "self", ".", "expenseRule", ",", "'location'", ",", "None", ")", "if", "this_loc", ":", "self", ".", "payTo", "=", "TransactionParty", ".", "objects", ".", "get_or_create", "(", "location", "=", "this_loc", ",", "defaults", "=", "{", "'name'", ":", "this_loc", ".", "name", "}", ")", "[", "0", "]", "elif", "this_member", ":", "self", ".", "payTo", "=", "TransactionParty", ".", "objects", ".", "get_or_create", "(", "staffMember", "=", "this_member", ",", "defaults", "=", "{", "'name'", ":", "this_member", ".", "fullName", ",", "'user'", ":", "getattr", "(", "this_member", ",", "'userAccount'", ",", "None", ")", "}", ")", "[", "0", "]", "# Set the accrual date. The method for events ensures that the accrualDate month", "# is the same as the reported month of the series/event by accruing to the end date of the last", "# class or occurrence in that month.", "if", "not", "self", ".", "accrualDate", ":", "if", "self", ".", "event", "and", "self", ".", "event", ".", "month", ":", "self", ".", "accrualDate", "=", "self", ".", "event", ".", "eventoccurrence_set", ".", "order_by", "(", "'endTime'", ")", ".", "filter", "(", "*", "*", "{", "'endTime__month'", ":", "self", ".", "event", ".", "month", "}", ")", ".", "last", "(", ")", ".", "endTime", "elif", "self", ".", "submissionDate", ":", "self", ".", "accrualDate", "=", "self", ".", "submissionDate", "else", ":", "self", ".", "submissionDate", "=", "timezone", ".", "now", "(", ")", "self", ".", "accrualDate", "=", "self", ".", "submissionDate", "# Set the total for hourly work", "if", "self", ".", "hours", "and", "not", "self", ".", "wageRate", "and", "not", "self", ".", "total", "and", "not", "getattr", "(", "getattr", "(", "self", ",", "'payTo'", ",", "None", ")", ",", "'location'", ",", "None", ")", "and", "self", ".", "category", ":", "self", ".", "wageRate", "=", "self", ".", "category", ".", "defaultRate", "elif", "self", ".", "hours", "and", "not", "self", ".", "wageRate", "and", "not", "self", ".", "total", "and", "getattr", "(", "getattr", "(", "self", ",", "'payTo'", ",", "None", ")", ",", "'location'", ",", "None", ")", ":", "self", ".", "wageRate", "=", "self", ".", "payTo", ".", "location", ".", "rentalRate", "if", "self", ".", "hours", "and", "self", ".", "wageRate", "and", "not", "self", ".", "total", ":", "self", ".", "total", "=", "self", ".", "hours", "*", "self", ".", "wageRate", "super", "(", "ExpenseItem", ",", "self", ")", ".", "save", "(", "*", "args", ",", "*", "*", "kwargs", ")", "self", ".", "__approved", "=", "self", ".", "approved", "self", ".", "__paid", "=", "self", ".", "paid", "self", ".", "__approvalDate", "=", "self", ".", "approvalDate", "self", ".", "__paymentDate", "=", "self", ".", "paymentDate", "# If a file is attached, ensure that it is not public, and that it is saved in the 'Expense Receipts' folder", "if", "self", ".", "attachment", ":", "try", ":", "self", ".", "attachment", ".", "folder", "=", "Folder", ".", "objects", ".", "get", "(", "name", "=", "_", "(", "'Expense Receipts'", ")", ")", "except", "ObjectDoesNotExist", ":", "pass", "self", ".", "attachment", ".", "is_public", "=", "False", "self", ".", "attachment", ".", "save", "(", ")" ]
This custom save method ensures that an expense is not attributed to multiple categories. It also ensures that the series and event properties are always associated with any type of expense of that series or event.
[ "This", "custom", "save", "method", "ensures", "that", "an", "expense", "is", "not", "attributed", "to", "multiple", "categories", ".", "It", "also", "ensures", "that", "the", "series", "and", "event", "properties", "are", "always", "associated", "with", "any", "type", "of", "expense", "of", "that", "series", "or", "event", "." ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/financial/models.py#L724-L796
django-danceschool/django-danceschool
danceschool/financial/models.py
RevenueItem.relatedItems
def relatedItems(self): ''' If this item is associated with a registration, then return all other items associated with the same registration. ''' if self.registration: return self.registration.revenueitem_set.exclude(pk=self.pk)
python
def relatedItems(self): if self.registration: return self.registration.revenueitem_set.exclude(pk=self.pk)
[ "def", "relatedItems", "(", "self", ")", ":", "if", "self", ".", "registration", ":", "return", "self", ".", "registration", ".", "revenueitem_set", ".", "exclude", "(", "pk", "=", "self", ".", "pk", ")" ]
If this item is associated with a registration, then return all other items associated with the same registration.
[ "If", "this", "item", "is", "associated", "with", "a", "registration", "then", "return", "all", "other", "items", "associated", "with", "the", "same", "registration", "." ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/financial/models.py#L874-L880
django-danceschool/django-danceschool
danceschool/financial/models.py
RevenueItem.save
def save(self, *args, **kwargs): ''' This custom save method ensures that a revenue item is not attributed to multiple categories. It also ensures that the series and event properties are always associated with any type of revenue of that series or event. ''' # Set the received date if the payment was just marked received if not hasattr(self,'__received'): if self.received and not self.receivedDate: self.receivedDate = timezone.now() else: if self.received and not self.receivedDate and not self.__receivedDate: self.receivedDate = timezone.now() # Set the accrual date. The method for series/events ensures that the accrualDate month # is the same as the reported month of the event/series by accruing to the start date of the first # occurrence in that month. if not self.accrualDate: if self.invoiceItem and self.invoiceItem.finalEventRegistration: min_event_time = self.invoiceItem.finalEventRegistration.event.eventoccurrence_set.filter(**{'startTime__month':self.invoiceItem.finalEventRegistration.event.month}).first().startTime self.accrualDate = min_event_time elif self.event: self.accrualDate = self.event.eventoccurrence_set.order_by('startTime').filter(**{'startTime__month': self.event.month}).last().startTime elif self.invoiceItem: self.accrualDate = self.invoiceItem.invoice.creationDate elif self.receivedDate: self.accrualDate = self.receivedDate elif self.submissionDate: self.accrualDate = self.submissionDate else: self.submissionDate = timezone.now() self.accrualDate = self.submissionDate # Now, set the registration property and check that this item is not attributed # to multiple categories. if self.invoiceItem and self.invoiceItem.finalEventRegistration: self.event = self.invoiceItem.finalEventRegistration.event elif self.invoiceItem and self.invoiceItem.temporaryEventRegistration: self.event = self.invoiceItem.temporaryEventRegistration.event # If no grossTotal is reported, use the net total. If no net total is reported, use the grossTotal if self.grossTotal is None and self.total: self.grossTotal = self.total if self.total is None and self.grossTotal: self.total = self.grossTotal super(RevenueItem, self).save(*args, **kwargs) self.__received = self.received self.__receivedDate = self.receivedDate # If a file is attached, ensure that it is not public, and that it is saved in the 'Expense Receipts' folder if self.attachment: try: self.attachment.folder = Folder.objects.get(name=_('Revenue Receipts')) except ObjectDoesNotExist: pass self.attachment.is_public = False self.attachment.save()
python
def save(self, *args, **kwargs): if not hasattr(self,'__received'): if self.received and not self.receivedDate: self.receivedDate = timezone.now() else: if self.received and not self.receivedDate and not self.__receivedDate: self.receivedDate = timezone.now() if not self.accrualDate: if self.invoiceItem and self.invoiceItem.finalEventRegistration: min_event_time = self.invoiceItem.finalEventRegistration.event.eventoccurrence_set.filter(**{'startTime__month':self.invoiceItem.finalEventRegistration.event.month}).first().startTime self.accrualDate = min_event_time elif self.event: self.accrualDate = self.event.eventoccurrence_set.order_by('startTime').filter(**{'startTime__month': self.event.month}).last().startTime elif self.invoiceItem: self.accrualDate = self.invoiceItem.invoice.creationDate elif self.receivedDate: self.accrualDate = self.receivedDate elif self.submissionDate: self.accrualDate = self.submissionDate else: self.submissionDate = timezone.now() self.accrualDate = self.submissionDate if self.invoiceItem and self.invoiceItem.finalEventRegistration: self.event = self.invoiceItem.finalEventRegistration.event elif self.invoiceItem and self.invoiceItem.temporaryEventRegistration: self.event = self.invoiceItem.temporaryEventRegistration.event if self.grossTotal is None and self.total: self.grossTotal = self.total if self.total is None and self.grossTotal: self.total = self.grossTotal super(RevenueItem, self).save(*args, **kwargs) self.__received = self.received self.__receivedDate = self.receivedDate if self.attachment: try: self.attachment.folder = Folder.objects.get(name=_('Revenue Receipts')) except ObjectDoesNotExist: pass self.attachment.is_public = False self.attachment.save()
[ "def", "save", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# Set the received date if the payment was just marked received", "if", "not", "hasattr", "(", "self", ",", "'__received'", ")", ":", "if", "self", ".", "received", "and", "not", "self", ".", "receivedDate", ":", "self", ".", "receivedDate", "=", "timezone", ".", "now", "(", ")", "else", ":", "if", "self", ".", "received", "and", "not", "self", ".", "receivedDate", "and", "not", "self", ".", "__receivedDate", ":", "self", ".", "receivedDate", "=", "timezone", ".", "now", "(", ")", "# Set the accrual date. The method for series/events ensures that the accrualDate month", "# is the same as the reported month of the event/series by accruing to the start date of the first", "# occurrence in that month.", "if", "not", "self", ".", "accrualDate", ":", "if", "self", ".", "invoiceItem", "and", "self", ".", "invoiceItem", ".", "finalEventRegistration", ":", "min_event_time", "=", "self", ".", "invoiceItem", ".", "finalEventRegistration", ".", "event", ".", "eventoccurrence_set", ".", "filter", "(", "*", "*", "{", "'startTime__month'", ":", "self", ".", "invoiceItem", ".", "finalEventRegistration", ".", "event", ".", "month", "}", ")", ".", "first", "(", ")", ".", "startTime", "self", ".", "accrualDate", "=", "min_event_time", "elif", "self", ".", "event", ":", "self", ".", "accrualDate", "=", "self", ".", "event", ".", "eventoccurrence_set", ".", "order_by", "(", "'startTime'", ")", ".", "filter", "(", "*", "*", "{", "'startTime__month'", ":", "self", ".", "event", ".", "month", "}", ")", ".", "last", "(", ")", ".", "startTime", "elif", "self", ".", "invoiceItem", ":", "self", ".", "accrualDate", "=", "self", ".", "invoiceItem", ".", "invoice", ".", "creationDate", "elif", "self", ".", "receivedDate", ":", "self", ".", "accrualDate", "=", "self", ".", "receivedDate", "elif", "self", ".", "submissionDate", ":", "self", ".", "accrualDate", "=", "self", ".", "submissionDate", "else", ":", "self", ".", "submissionDate", "=", "timezone", ".", "now", "(", ")", "self", ".", "accrualDate", "=", "self", ".", "submissionDate", "# Now, set the registration property and check that this item is not attributed", "# to multiple categories.", "if", "self", ".", "invoiceItem", "and", "self", ".", "invoiceItem", ".", "finalEventRegistration", ":", "self", ".", "event", "=", "self", ".", "invoiceItem", ".", "finalEventRegistration", ".", "event", "elif", "self", ".", "invoiceItem", "and", "self", ".", "invoiceItem", ".", "temporaryEventRegistration", ":", "self", ".", "event", "=", "self", ".", "invoiceItem", ".", "temporaryEventRegistration", ".", "event", "# If no grossTotal is reported, use the net total. If no net total is reported, use the grossTotal", "if", "self", ".", "grossTotal", "is", "None", "and", "self", ".", "total", ":", "self", ".", "grossTotal", "=", "self", ".", "total", "if", "self", ".", "total", "is", "None", "and", "self", ".", "grossTotal", ":", "self", ".", "total", "=", "self", ".", "grossTotal", "super", "(", "RevenueItem", ",", "self", ")", ".", "save", "(", "*", "args", ",", "*", "*", "kwargs", ")", "self", ".", "__received", "=", "self", ".", "received", "self", ".", "__receivedDate", "=", "self", ".", "receivedDate", "# If a file is attached, ensure that it is not public, and that it is saved in the 'Expense Receipts' folder", "if", "self", ".", "attachment", ":", "try", ":", "self", ".", "attachment", ".", "folder", "=", "Folder", ".", "objects", ".", "get", "(", "name", "=", "_", "(", "'Revenue Receipts'", ")", ")", "except", "ObjectDoesNotExist", ":", "pass", "self", ".", "attachment", ".", "is_public", "=", "False", "self", ".", "attachment", ".", "save", "(", ")" ]
This custom save method ensures that a revenue item is not attributed to multiple categories. It also ensures that the series and event properties are always associated with any type of revenue of that series or event.
[ "This", "custom", "save", "method", "ensures", "that", "a", "revenue", "item", "is", "not", "attributed", "to", "multiple", "categories", ".", "It", "also", "ensures", "that", "the", "series", "and", "event", "properties", "are", "always", "associated", "with", "any", "type", "of", "revenue", "of", "that", "series", "or", "event", "." ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/financial/models.py#L891-L949
django-danceschool/django-danceschool
danceschool/private_lessons/forms.py
SlotCreationForm.clean
def clean(self): ''' Only allow submission if there are not already slots in the submitted window, and only allow rooms associated with the chosen location. ''' super(SlotCreationForm,self).clean() startDate = self.cleaned_data.get('startDate') endDate = self.cleaned_data.get('endDate') startTime = self.cleaned_data.get('startTime') endTime = self.cleaned_data.get('endTime') instructor = self.cleaned_data.get('instructorId') existingSlots = InstructorAvailabilitySlot.objects.filter( instructor=instructor, startTime__gt=( ensure_localtime(datetime.combine(startDate,startTime)) - timedelta(minutes=getConstant('privateLessons__lessonLengthInterval')) ), startTime__lt=ensure_localtime(datetime.combine(endDate,endTime)), ) if existingSlots.exists(): raise ValidationError(_('Newly created slots cannot overlap existing slots for this instructor.'),code='invalid')
python
def clean(self): super(SlotCreationForm,self).clean() startDate = self.cleaned_data.get('startDate') endDate = self.cleaned_data.get('endDate') startTime = self.cleaned_data.get('startTime') endTime = self.cleaned_data.get('endTime') instructor = self.cleaned_data.get('instructorId') existingSlots = InstructorAvailabilitySlot.objects.filter( instructor=instructor, startTime__gt=( ensure_localtime(datetime.combine(startDate,startTime)) - timedelta(minutes=getConstant('privateLessons__lessonLengthInterval')) ), startTime__lt=ensure_localtime(datetime.combine(endDate,endTime)), ) if existingSlots.exists(): raise ValidationError(_('Newly created slots cannot overlap existing slots for this instructor.'),code='invalid')
[ "def", "clean", "(", "self", ")", ":", "super", "(", "SlotCreationForm", ",", "self", ")", ".", "clean", "(", ")", "startDate", "=", "self", ".", "cleaned_data", ".", "get", "(", "'startDate'", ")", "endDate", "=", "self", ".", "cleaned_data", ".", "get", "(", "'endDate'", ")", "startTime", "=", "self", ".", "cleaned_data", ".", "get", "(", "'startTime'", ")", "endTime", "=", "self", ".", "cleaned_data", ".", "get", "(", "'endTime'", ")", "instructor", "=", "self", ".", "cleaned_data", ".", "get", "(", "'instructorId'", ")", "existingSlots", "=", "InstructorAvailabilitySlot", ".", "objects", ".", "filter", "(", "instructor", "=", "instructor", ",", "startTime__gt", "=", "(", "ensure_localtime", "(", "datetime", ".", "combine", "(", "startDate", ",", "startTime", ")", ")", "-", "timedelta", "(", "minutes", "=", "getConstant", "(", "'privateLessons__lessonLengthInterval'", ")", ")", ")", ",", "startTime__lt", "=", "ensure_localtime", "(", "datetime", ".", "combine", "(", "endDate", ",", "endTime", ")", ")", ",", ")", "if", "existingSlots", ".", "exists", "(", ")", ":", "raise", "ValidationError", "(", "_", "(", "'Newly created slots cannot overlap existing slots for this instructor.'", ")", ",", "code", "=", "'invalid'", ")" ]
Only allow submission if there are not already slots in the submitted window, and only allow rooms associated with the chosen location.
[ "Only", "allow", "submission", "if", "there", "are", "not", "already", "slots", "in", "the", "submitted", "window", "and", "only", "allow", "rooms", "associated", "with", "the", "chosen", "location", "." ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/private_lessons/forms.py#L70-L94
django-danceschool/django-danceschool
danceschool/financial/autocomplete_light_registry.py
get_method_list
def get_method_list(): ''' Include manual methods by default ''' methods = [str(_('Cash')),str(_('Check')),str(_('Bank/Debit Card')),str(_('Other'))] methods += ExpenseItem.objects.order_by().values_list('paymentMethod',flat=True).distinct() methods += RevenueItem.objects.order_by().values_list('paymentMethod',flat=True).distinct() methods_list = list(set(methods)) if None in methods_list: methods_list.remove(None) return methods_list
python
def get_method_list(): methods = [str(_('Cash')),str(_('Check')),str(_('Bank/Debit Card')),str(_('Other'))] methods += ExpenseItem.objects.order_by().values_list('paymentMethod',flat=True).distinct() methods += RevenueItem.objects.order_by().values_list('paymentMethod',flat=True).distinct() methods_list = list(set(methods)) if None in methods_list: methods_list.remove(None) return methods_list
[ "def", "get_method_list", "(", ")", ":", "methods", "=", "[", "str", "(", "_", "(", "'Cash'", ")", ")", ",", "str", "(", "_", "(", "'Check'", ")", ")", ",", "str", "(", "_", "(", "'Bank/Debit Card'", ")", ")", ",", "str", "(", "_", "(", "'Other'", ")", ")", "]", "methods", "+=", "ExpenseItem", ".", "objects", ".", "order_by", "(", ")", ".", "values_list", "(", "'paymentMethod'", ",", "flat", "=", "True", ")", ".", "distinct", "(", ")", "methods", "+=", "RevenueItem", ".", "objects", ".", "order_by", "(", ")", ".", "values_list", "(", "'paymentMethod'", ",", "flat", "=", "True", ")", ".", "distinct", "(", ")", "methods_list", "=", "list", "(", "set", "(", "methods", ")", ")", "if", "None", "in", "methods_list", ":", "methods_list", ".", "remove", "(", "None", ")", "return", "methods_list" ]
Include manual methods by default
[ "Include", "manual", "methods", "by", "default" ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/financial/autocomplete_light_registry.py#L11-L23
django-danceschool/django-danceschool
danceschool/financial/autocomplete_light_registry.py
TransactionPartyAutoComplete.get_create_option
def get_create_option(self, context, q): """Form the correct create_option to append to results.""" create_option = [] display_create_option = False if self.create_field and q: page_obj = context.get('page_obj', None) if page_obj is None or page_obj.number == 1: display_create_option = True if display_create_option and self.has_add_permission(self.request): ''' Generate querysets of Locations, StaffMembers, and Users that match the query string. ''' for s in Location.objects.filter( Q( Q(name__istartswith=q) & Q(transactionparty__isnull=True) ) ): create_option += [{ 'id': 'Location_%s' % s.id, 'text': _('Generate from location "%(location)s"') % {'location': s.name}, 'create_id': True, }] for s in StaffMember.objects.filter( Q( (Q(firstName__istartswith=q) | Q(lastName__istartswith=q)) & Q(transactionparty__isnull=True) ) ): create_option += [{ 'id': 'StaffMember_%s' % s.id, 'text': _('Generate from staff member "%(staff_member)s"') % {'staff_member': s.fullName}, 'create_id': True, }] for s in User.objects.filter( Q( (Q(first_name__istartswith=q) | Q(last_name__istartswith=q)) & Q(staffmember__isnull=True) & Q(transactionparty__isnull=True) ) ): create_option += [{ 'id': 'User_%s' % s.id, 'text': _('Generate from user "%(user)s"') % {'user': s.get_full_name()}, 'create_id': True, }] # Finally, allow creation from a name only. create_option += [{ 'id': q, 'text': _('Create "%(new_value)s"') % {'new_value': q}, 'create_id': True, }] return create_option
python
def get_create_option(self, context, q): create_option = [] display_create_option = False if self.create_field and q: page_obj = context.get('page_obj', None) if page_obj is None or page_obj.number == 1: display_create_option = True if display_create_option and self.has_add_permission(self.request): for s in Location.objects.filter( Q( Q(name__istartswith=q) & Q(transactionparty__isnull=True) ) ): create_option += [{ 'id': 'Location_%s' % s.id, 'text': _('Generate from location "%(location)s"') % {'location': s.name}, 'create_id': True, }] for s in StaffMember.objects.filter( Q( (Q(firstName__istartswith=q) | Q(lastName__istartswith=q)) & Q(transactionparty__isnull=True) ) ): create_option += [{ 'id': 'StaffMember_%s' % s.id, 'text': _('Generate from staff member "%(staff_member)s"') % {'staff_member': s.fullName}, 'create_id': True, }] for s in User.objects.filter( Q( (Q(first_name__istartswith=q) | Q(last_name__istartswith=q)) & Q(staffmember__isnull=True) & Q(transactionparty__isnull=True) ) ): create_option += [{ 'id': 'User_%s' % s.id, 'text': _('Generate from user "%(user)s"') % {'user': s.get_full_name()}, 'create_id': True, }] create_option += [{ 'id': q, 'text': _('Create "%(new_value)s"') % {'new_value': q}, 'create_id': True, }] return create_option
[ "def", "get_create_option", "(", "self", ",", "context", ",", "q", ")", ":", "create_option", "=", "[", "]", "display_create_option", "=", "False", "if", "self", ".", "create_field", "and", "q", ":", "page_obj", "=", "context", ".", "get", "(", "'page_obj'", ",", "None", ")", "if", "page_obj", "is", "None", "or", "page_obj", ".", "number", "==", "1", ":", "display_create_option", "=", "True", "if", "display_create_option", "and", "self", ".", "has_add_permission", "(", "self", ".", "request", ")", ":", "'''\r\n Generate querysets of Locations, StaffMembers, and Users that \r\n match the query string.\r\n '''", "for", "s", "in", "Location", ".", "objects", ".", "filter", "(", "Q", "(", "Q", "(", "name__istartswith", "=", "q", ")", "&", "Q", "(", "transactionparty__isnull", "=", "True", ")", ")", ")", ":", "create_option", "+=", "[", "{", "'id'", ":", "'Location_%s'", "%", "s", ".", "id", ",", "'text'", ":", "_", "(", "'Generate from location \"%(location)s\"'", ")", "%", "{", "'location'", ":", "s", ".", "name", "}", ",", "'create_id'", ":", "True", ",", "}", "]", "for", "s", "in", "StaffMember", ".", "objects", ".", "filter", "(", "Q", "(", "(", "Q", "(", "firstName__istartswith", "=", "q", ")", "|", "Q", "(", "lastName__istartswith", "=", "q", ")", ")", "&", "Q", "(", "transactionparty__isnull", "=", "True", ")", ")", ")", ":", "create_option", "+=", "[", "{", "'id'", ":", "'StaffMember_%s'", "%", "s", ".", "id", ",", "'text'", ":", "_", "(", "'Generate from staff member \"%(staff_member)s\"'", ")", "%", "{", "'staff_member'", ":", "s", ".", "fullName", "}", ",", "'create_id'", ":", "True", ",", "}", "]", "for", "s", "in", "User", ".", "objects", ".", "filter", "(", "Q", "(", "(", "Q", "(", "first_name__istartswith", "=", "q", ")", "|", "Q", "(", "last_name__istartswith", "=", "q", ")", ")", "&", "Q", "(", "staffmember__isnull", "=", "True", ")", "&", "Q", "(", "transactionparty__isnull", "=", "True", ")", ")", ")", ":", "create_option", "+=", "[", "{", "'id'", ":", "'User_%s'", "%", "s", ".", "id", ",", "'text'", ":", "_", "(", "'Generate from user \"%(user)s\"'", ")", "%", "{", "'user'", ":", "s", ".", "get_full_name", "(", ")", "}", ",", "'create_id'", ":", "True", ",", "}", "]", "# Finally, allow creation from a name only.\r", "create_option", "+=", "[", "{", "'id'", ":", "q", ",", "'text'", ":", "_", "(", "'Create \"%(new_value)s\"'", ")", "%", "{", "'new_value'", ":", "q", "}", ",", "'create_id'", ":", "True", ",", "}", "]", "return", "create_option" ]
Form the correct create_option to append to results.
[ "Form", "the", "correct", "create_option", "to", "append", "to", "results", "." ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/financial/autocomplete_light_registry.py#L80-L135
django-danceschool/django-danceschool
danceschool/financial/autocomplete_light_registry.py
TransactionPartyAutoComplete.create_object
def create_object(self, text): ''' Allow creation of transaction parties using a full name string. ''' if self.create_field == 'name': if text.startswith('Location_'): this_id = text[len('Location_'):] this_loc = Location.objects.get(id=this_id) return self.get_queryset().get_or_create( name=this_loc.name,location=this_loc )[0] elif text.startswith('StaffMember_'): this_id = text[len('StaffMember_'):] this_member = StaffMember.objects.get(id=this_id) return self.get_queryset().get_or_create( name=this_member.fullName,staffMember=this_member, defaults={'user': getattr(this_member,'userAccount',None)} )[0] elif text.startswith('User_'): this_id = text[len('User_'):] this_user = User.objects.get(id=this_id) return self.get_queryset().get_or_create( name=this_user.get_full_name(),user=this_user, defaults={'staffMember': getattr(this_user,'staffmember',None)} )[0] else: return self.get_queryset().get_or_create( name=text,staffMember=None,user=None,location=None )[0] else: return super(TransactionPartyAutoComplete,self).create_object(text)
python
def create_object(self, text): if self.create_field == 'name': if text.startswith('Location_'): this_id = text[len('Location_'):] this_loc = Location.objects.get(id=this_id) return self.get_queryset().get_or_create( name=this_loc.name,location=this_loc )[0] elif text.startswith('StaffMember_'): this_id = text[len('StaffMember_'):] this_member = StaffMember.objects.get(id=this_id) return self.get_queryset().get_or_create( name=this_member.fullName,staffMember=this_member, defaults={'user': getattr(this_member,'userAccount',None)} )[0] elif text.startswith('User_'): this_id = text[len('User_'):] this_user = User.objects.get(id=this_id) return self.get_queryset().get_or_create( name=this_user.get_full_name(),user=this_user, defaults={'staffMember': getattr(this_user,'staffmember',None)} )[0] else: return self.get_queryset().get_or_create( name=text,staffMember=None,user=None,location=None )[0] else: return super(TransactionPartyAutoComplete,self).create_object(text)
[ "def", "create_object", "(", "self", ",", "text", ")", ":", "if", "self", ".", "create_field", "==", "'name'", ":", "if", "text", ".", "startswith", "(", "'Location_'", ")", ":", "this_id", "=", "text", "[", "len", "(", "'Location_'", ")", ":", "]", "this_loc", "=", "Location", ".", "objects", ".", "get", "(", "id", "=", "this_id", ")", "return", "self", ".", "get_queryset", "(", ")", ".", "get_or_create", "(", "name", "=", "this_loc", ".", "name", ",", "location", "=", "this_loc", ")", "[", "0", "]", "elif", "text", ".", "startswith", "(", "'StaffMember_'", ")", ":", "this_id", "=", "text", "[", "len", "(", "'StaffMember_'", ")", ":", "]", "this_member", "=", "StaffMember", ".", "objects", ".", "get", "(", "id", "=", "this_id", ")", "return", "self", ".", "get_queryset", "(", ")", ".", "get_or_create", "(", "name", "=", "this_member", ".", "fullName", ",", "staffMember", "=", "this_member", ",", "defaults", "=", "{", "'user'", ":", "getattr", "(", "this_member", ",", "'userAccount'", ",", "None", ")", "}", ")", "[", "0", "]", "elif", "text", ".", "startswith", "(", "'User_'", ")", ":", "this_id", "=", "text", "[", "len", "(", "'User_'", ")", ":", "]", "this_user", "=", "User", ".", "objects", ".", "get", "(", "id", "=", "this_id", ")", "return", "self", ".", "get_queryset", "(", ")", ".", "get_or_create", "(", "name", "=", "this_user", ".", "get_full_name", "(", ")", ",", "user", "=", "this_user", ",", "defaults", "=", "{", "'staffMember'", ":", "getattr", "(", "this_user", ",", "'staffmember'", ",", "None", ")", "}", ")", "[", "0", "]", "else", ":", "return", "self", ".", "get_queryset", "(", ")", ".", "get_or_create", "(", "name", "=", "text", ",", "staffMember", "=", "None", ",", "user", "=", "None", ",", "location", "=", "None", ")", "[", "0", "]", "else", ":", "return", "super", "(", "TransactionPartyAutoComplete", ",", "self", ")", ".", "create_object", "(", "text", ")" ]
Allow creation of transaction parties using a full name string.
[ "Allow", "creation", "of", "transaction", "parties", "using", "a", "full", "name", "string", "." ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/financial/autocomplete_light_registry.py#L137-L166
django-danceschool/django-danceschool
danceschool/core/templatetags/danceschool_tags.py
has_group
def has_group(user, group_name): ''' This allows specification group-based permissions in templates. In most instances, creating model-based permissions and giving them to the desired group is preferable. ''' if user.groups.filter(name=group_name).exists(): return True return False
python
def has_group(user, group_name): if user.groups.filter(name=group_name).exists(): return True return False
[ "def", "has_group", "(", "user", ",", "group_name", ")", ":", "if", "user", ".", "groups", ".", "filter", "(", "name", "=", "group_name", ")", ".", "exists", "(", ")", ":", "return", "True", "return", "False" ]
This allows specification group-based permissions in templates. In most instances, creating model-based permissions and giving them to the desired group is preferable.
[ "This", "allows", "specification", "group", "-", "based", "permissions", "in", "templates", ".", "In", "most", "instances", "creating", "model", "-", "based", "permissions", "and", "giving", "them", "to", "the", "desired", "group", "is", "preferable", "." ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/core/templatetags/danceschool_tags.py#L53-L61
django-danceschool/django-danceschool
danceschool/core/templatetags/danceschool_tags.py
get_item_by_key
def get_item_by_key(passed_list, key, value): ''' This one allows us to get one or more items from a list of dictionaries based on the value of a specified key, where both the key and the value can be variable names. Does not work with None or null string passed values. ''' if value in [None, '']: return if type(passed_list) in [QuerySet, PolymorphicQuerySet]: sub_list = passed_list.filter(**{key: value}) else: sub_list = [x for x in passed_list if x.get(key) == value] if len(sub_list) == 1: return sub_list[0] return sub_list
python
def get_item_by_key(passed_list, key, value): if value in [None, '']: return if type(passed_list) in [QuerySet, PolymorphicQuerySet]: sub_list = passed_list.filter(**{key: value}) else: sub_list = [x for x in passed_list if x.get(key) == value] if len(sub_list) == 1: return sub_list[0] return sub_list
[ "def", "get_item_by_key", "(", "passed_list", ",", "key", ",", "value", ")", ":", "if", "value", "in", "[", "None", ",", "''", "]", ":", "return", "if", "type", "(", "passed_list", ")", "in", "[", "QuerySet", ",", "PolymorphicQuerySet", "]", ":", "sub_list", "=", "passed_list", ".", "filter", "(", "*", "*", "{", "key", ":", "value", "}", ")", "else", ":", "sub_list", "=", "[", "x", "for", "x", "in", "passed_list", "if", "x", ".", "get", "(", "key", ")", "==", "value", "]", "if", "len", "(", "sub_list", ")", "==", "1", ":", "return", "sub_list", "[", "0", "]", "return", "sub_list" ]
This one allows us to get one or more items from a list of dictionaries based on the value of a specified key, where both the key and the value can be variable names. Does not work with None or null string passed values.
[ "This", "one", "allows", "us", "to", "get", "one", "or", "more", "items", "from", "a", "list", "of", "dictionaries", "based", "on", "the", "value", "of", "a", "specified", "key", "where", "both", "the", "key", "and", "the", "value", "can", "be", "variable", "names", ".", "Does", "not", "work", "with", "None", "or", "null", "string", "passed", "values", "." ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/core/templatetags/danceschool_tags.py#L74-L92
django-danceschool/django-danceschool
danceschool/core/templatetags/danceschool_tags.py
get_field_for_object
def get_field_for_object(field_type, field_id, form): ''' This tag allows one to get a specific series or event form field in registration views. ''' field_name = field_type + '_' + str(field_id) return form.__getitem__(field_name)
python
def get_field_for_object(field_type, field_id, form): field_name = field_type + '_' + str(field_id) return form.__getitem__(field_name)
[ "def", "get_field_for_object", "(", "field_type", ",", "field_id", ",", "form", ")", ":", "field_name", "=", "field_type", "+", "'_'", "+", "str", "(", "field_id", ")", "return", "form", ".", "__getitem__", "(", "field_name", ")" ]
This tag allows one to get a specific series or event form field in registration views.
[ "This", "tag", "allows", "one", "to", "get", "a", "specific", "series", "or", "event", "form", "field", "in", "registration", "views", "." ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/core/templatetags/danceschool_tags.py#L96-L102
django-danceschool/django-danceschool
danceschool/core/templatetags/danceschool_tags.py
template_exists
def template_exists(template_name): ''' Determine if a given template exists so that it can be loaded if so, or a default alternative can be used if not. ''' try: template.loader.get_template(template_name) return True except template.TemplateDoesNotExist: return False
python
def template_exists(template_name): try: template.loader.get_template(template_name) return True except template.TemplateDoesNotExist: return False
[ "def", "template_exists", "(", "template_name", ")", ":", "try", ":", "template", ".", "loader", ".", "get_template", "(", "template_name", ")", "return", "True", "except", "template", ".", "TemplateDoesNotExist", ":", "return", "False" ]
Determine if a given template exists so that it can be loaded if so, or a default alternative can be used if not.
[ "Determine", "if", "a", "given", "template", "exists", "so", "that", "it", "can", "be", "loaded", "if", "so", "or", "a", "default", "alternative", "can", "be", "used", "if", "not", "." ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/core/templatetags/danceschool_tags.py#L106-L115
django-danceschool/django-danceschool
danceschool/core/templatetags/danceschool_tags.py
numRegisteredForRole
def numRegisteredForRole(event, role): ''' This tag allows one to access the number of registrations for any dance role. ''' if not isinstance(event, Event) or not isinstance(role, DanceRole): return None return event.numRegisteredForRole(role)
python
def numRegisteredForRole(event, role): if not isinstance(event, Event) or not isinstance(role, DanceRole): return None return event.numRegisteredForRole(role)
[ "def", "numRegisteredForRole", "(", "event", ",", "role", ")", ":", "if", "not", "isinstance", "(", "event", ",", "Event", ")", "or", "not", "isinstance", "(", "role", ",", "DanceRole", ")", ":", "return", "None", "return", "event", ".", "numRegisteredForRole", "(", "role", ")" ]
This tag allows one to access the number of registrations for any dance role.
[ "This", "tag", "allows", "one", "to", "access", "the", "number", "of", "registrations", "for", "any", "dance", "role", "." ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/core/templatetags/danceschool_tags.py#L119-L126
django-danceschool/django-danceschool
danceschool/core/templatetags/danceschool_tags.py
soldOutForRole
def soldOutForRole(event, role): ''' This tag allows one to determine whether any event is sold out for any particular role. ''' if not isinstance(event, Event) or not isinstance(role, DanceRole): return None return event.soldOutForRole(role)
python
def soldOutForRole(event, role): if not isinstance(event, Event) or not isinstance(role, DanceRole): return None return event.soldOutForRole(role)
[ "def", "soldOutForRole", "(", "event", ",", "role", ")", ":", "if", "not", "isinstance", "(", "event", ",", "Event", ")", "or", "not", "isinstance", "(", "role", ",", "DanceRole", ")", ":", "return", "None", "return", "event", ".", "soldOutForRole", "(", "role", ")" ]
This tag allows one to determine whether any event is sold out for any particular role.
[ "This", "tag", "allows", "one", "to", "determine", "whether", "any", "event", "is", "sold", "out", "for", "any", "particular", "role", "." ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/core/templatetags/danceschool_tags.py#L130-L137
django-danceschool/django-danceschool
danceschool/core/templatetags/danceschool_tags.py
numRegisteredForRoleName
def numRegisteredForRoleName(event, roleName): ''' This tag allows one to access the number of registrations for any dance role using only the role's name. ''' if not isinstance(event, Event): return None try: role = DanceRole.objects.get(name=roleName) except ObjectDoesNotExist: return None return event.numRegisteredForRole(role)
python
def numRegisteredForRoleName(event, roleName): if not isinstance(event, Event): return None try: role = DanceRole.objects.get(name=roleName) except ObjectDoesNotExist: return None return event.numRegisteredForRole(role)
[ "def", "numRegisteredForRoleName", "(", "event", ",", "roleName", ")", ":", "if", "not", "isinstance", "(", "event", ",", "Event", ")", ":", "return", "None", "try", ":", "role", "=", "DanceRole", ".", "objects", ".", "get", "(", "name", "=", "roleName", ")", "except", "ObjectDoesNotExist", ":", "return", "None", "return", "event", ".", "numRegisteredForRole", "(", "role", ")" ]
This tag allows one to access the number of registrations for any dance role using only the role's name.
[ "This", "tag", "allows", "one", "to", "access", "the", "number", "of", "registrations", "for", "any", "dance", "role", "using", "only", "the", "role", "s", "name", "." ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/core/templatetags/danceschool_tags.py#L141-L154
django-danceschool/django-danceschool
danceschool/core/templatetags/danceschool_tags.py
getReturnPage
def getReturnPage(context, prior=False): ''' This tag makes it easy to get return links from within a template without requiring custom logic inside the view. Just include {% getReturnPage as returnPage %} and then reference {{ returnPage.url }} and {{ returnPage.title }} as needed. ''' siteHistory = getattr(context.get('request',None),'session',{}).get('SITE_HISTORY',{}) return returnPageHelper(siteHistory,prior=prior)
python
def getReturnPage(context, prior=False): siteHistory = getattr(context.get('request',None),'session',{}).get('SITE_HISTORY',{}) return returnPageHelper(siteHistory,prior=prior)
[ "def", "getReturnPage", "(", "context", ",", "prior", "=", "False", ")", ":", "siteHistory", "=", "getattr", "(", "context", ".", "get", "(", "'request'", ",", "None", ")", ",", "'session'", ",", "{", "}", ")", ".", "get", "(", "'SITE_HISTORY'", ",", "{", "}", ")", "return", "returnPageHelper", "(", "siteHistory", ",", "prior", "=", "prior", ")" ]
This tag makes it easy to get return links from within a template without requiring custom logic inside the view. Just include {% getReturnPage as returnPage %} and then reference {{ returnPage.url }} and {{ returnPage.title }} as needed.
[ "This", "tag", "makes", "it", "easy", "to", "get", "return", "links", "from", "within", "a", "template", "without", "requiring", "custom", "logic", "inside", "the", "view", ".", "Just", "include", "{", "%", "getReturnPage", "as", "returnPage", "%", "}", "and", "then", "reference", "{{", "returnPage", ".", "url", "}}", "and", "{{", "returnPage", ".", "title", "}}", "as", "needed", "." ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/core/templatetags/danceschool_tags.py#L164-L172
django-danceschool/django-danceschool
danceschool/vouchers/models.py
Voucher.create_new_code
def create_new_code(cls,**kwargs): ''' Creates a new Voucher with a unique voucherId ''' prefix = kwargs.pop('prefix','') new = False while not new: # Standard is a ten-letter random string of uppercase letters random_string = ''.join(random.choice(string.ascii_uppercase) for z in range(10)) if not Voucher.objects.filter(voucherId='%s%s' % (prefix, random_string)).exists(): new = True return Voucher.objects.create(voucherId='%s%s' % (prefix, random_string),**kwargs)
python
def create_new_code(cls,**kwargs): prefix = kwargs.pop('prefix','') new = False while not new: random_string = ''.join(random.choice(string.ascii_uppercase) for z in range(10)) if not Voucher.objects.filter(voucherId='%s%s' % (prefix, random_string)).exists(): new = True return Voucher.objects.create(voucherId='%s%s' % (prefix, random_string),**kwargs)
[ "def", "create_new_code", "(", "cls", ",", "*", "*", "kwargs", ")", ":", "prefix", "=", "kwargs", ".", "pop", "(", "'prefix'", ",", "''", ")", "new", "=", "False", "while", "not", "new", ":", "# Standard is a ten-letter random string of uppercase letters", "random_string", "=", "''", ".", "join", "(", "random", ".", "choice", "(", "string", ".", "ascii_uppercase", ")", "for", "z", "in", "range", "(", "10", ")", ")", "if", "not", "Voucher", ".", "objects", ".", "filter", "(", "voucherId", "=", "'%s%s'", "%", "(", "prefix", ",", "random_string", ")", ")", ".", "exists", "(", ")", ":", "new", "=", "True", "return", "Voucher", ".", "objects", ".", "create", "(", "voucherId", "=", "'%s%s'", "%", "(", "prefix", ",", "random_string", ")", ",", "*", "*", "kwargs", ")" ]
Creates a new Voucher with a unique voucherId
[ "Creates", "a", "new", "Voucher", "with", "a", "unique", "voucherId" ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/vouchers/models.py#L66-L79
django-danceschool/django-danceschool
danceschool/guestlist/ajax.py
getGuestList
def getGuestList(request): ''' This function handles the filtering of available eventregistration-related invoice items and is used on the revenue reporting form. ''' if not ( request.method == 'POST' and request.POST.get('guestlist_id') and request.POST.get('event_id') and request.user.is_authenticated and request.user.has_perm('guestlist.view_guestlist') ): return JsonResponse({}) guestList = GuestList.objects.filter(id=request.POST.get('guestlist_id')).first() event = Event.objects.filter(id=request.POST.get('event_id')).first() if not guestList or not event: return JsonResponse({}) return JsonResponse({ 'names': guestList.getListForEvent(event), })
python
def getGuestList(request): if not ( request.method == 'POST' and request.POST.get('guestlist_id') and request.POST.get('event_id') and request.user.is_authenticated and request.user.has_perm('guestlist.view_guestlist') ): return JsonResponse({}) guestList = GuestList.objects.filter(id=request.POST.get('guestlist_id')).first() event = Event.objects.filter(id=request.POST.get('event_id')).first() if not guestList or not event: return JsonResponse({}) return JsonResponse({ 'names': guestList.getListForEvent(event), })
[ "def", "getGuestList", "(", "request", ")", ":", "if", "not", "(", "request", ".", "method", "==", "'POST'", "and", "request", ".", "POST", ".", "get", "(", "'guestlist_id'", ")", "and", "request", ".", "POST", ".", "get", "(", "'event_id'", ")", "and", "request", ".", "user", ".", "is_authenticated", "and", "request", ".", "user", ".", "has_perm", "(", "'guestlist.view_guestlist'", ")", ")", ":", "return", "JsonResponse", "(", "{", "}", ")", "guestList", "=", "GuestList", ".", "objects", ".", "filter", "(", "id", "=", "request", ".", "POST", ".", "get", "(", "'guestlist_id'", ")", ")", ".", "first", "(", ")", "event", "=", "Event", ".", "objects", ".", "filter", "(", "id", "=", "request", ".", "POST", ".", "get", "(", "'event_id'", ")", ")", ".", "first", "(", ")", "if", "not", "guestList", "or", "not", "event", ":", "return", "JsonResponse", "(", "{", "}", ")", "return", "JsonResponse", "(", "{", "'names'", ":", "guestList", ".", "getListForEvent", "(", "event", ")", ",", "}", ")" ]
This function handles the filtering of available eventregistration-related invoice items and is used on the revenue reporting form.
[ "This", "function", "handles", "the", "filtering", "of", "available", "eventregistration", "-", "related", "invoice", "items", "and", "is", "used", "on", "the", "revenue", "reporting", "form", "." ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/guestlist/ajax.py#L8-L30
django-danceschool/django-danceschool
danceschool/payments/payatdoor/cms_plugins.py
PayAtDoorFormPlugin.render
def render(self, context, instance, placeholder): ''' Add the cart-specific context to this form ''' context = super(PayAtDoorFormPlugin, self).render(context, instance, placeholder) context.update({ 'business_name': getConstant('contact__businessName'), 'currencyCode': getConstant('general__currencyCode'), 'form': self.get_form(context, instance, placeholder), }) return context
python
def render(self, context, instance, placeholder): context = super(PayAtDoorFormPlugin, self).render(context, instance, placeholder) context.update({ 'business_name': getConstant('contact__businessName'), 'currencyCode': getConstant('general__currencyCode'), 'form': self.get_form(context, instance, placeholder), }) return context
[ "def", "render", "(", "self", ",", "context", ",", "instance", ",", "placeholder", ")", ":", "context", "=", "super", "(", "PayAtDoorFormPlugin", ",", "self", ")", ".", "render", "(", "context", ",", "instance", ",", "placeholder", ")", "context", ".", "update", "(", "{", "'business_name'", ":", "getConstant", "(", "'contact__businessName'", ")", ",", "'currencyCode'", ":", "getConstant", "(", "'general__currencyCode'", ")", ",", "'form'", ":", "self", ".", "get_form", "(", "context", ",", "instance", ",", "placeholder", ")", ",", "}", ")", "return", "context" ]
Add the cart-specific context to this form
[ "Add", "the", "cart", "-", "specific", "context", "to", "this", "form" ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/payments/payatdoor/cms_plugins.py#L19-L29
django-danceschool/django-danceschool
danceschool/prerequisites/models.py
Requirement.customerMeetsRequirement
def customerMeetsRequirement(self, customer, danceRole=None, registration=None): ''' This method checks whether a given customer meets a given set of requirements. ''' cust_reqs = self.customerrequirement_set.filter(customer=customer,met=True) if customer: cust_priors = customer.eventregistration_set.filter(event__series__isnull=False) else: cust_priors = EventRegistration.objects.none() # If there's an explicit object stating that this customer meets the requirement, then we're done. if self.roleEnforced and danceRole and cust_reqs.filter(role=danceRole).exists(): return True elif not self.roleEnforced and cust_reqs.exists(): return True elif self.roleEnforced and not danceRole: return False # Go through each item for this requirement and see if the customer meets that item for item in self.requirementitem_set.all(): filter_dict = {} if item.requiredLevel: filter_dict['event__series__classDescription__danceTypeLevel'] = item.requiredLevel if item.requiredClass: filter_dict['event__series__classDescription'] = item.requiredClass if self.roleEnforced: filter_dict['role'] = danceRole current_matches = 0 overlap_matches = 0 nonconcurrent_filter = {'event__endTime__lte': timezone.now()} if registration: if isinstance(registration,Registration): current_matches = registration.eventregistration_set.filter(**filter_dict).count() elif isinstance(registration,TemporaryRegistration): current_matches = registration.temporaryeventregistration_set.filter(**filter_dict).count() nonconcurrent_filter = {'event__endTime__lte': registration.firstSeriesStartTime} overlap_matches = cust_priors.filter(**filter_dict).exclude(**nonconcurrent_filter).filter( event__startTime__lte=registration.lastSeriesEndTime, ).count() priors_matches = cust_priors.filter(**filter_dict).filter(**nonconcurrent_filter).count() # The number of matches depends on the concurrency rule for this item if item.concurrentRule == item.ConcurrencyRule.prohibited: matches = priors_matches elif item.concurrentRule == item.ConcurrencyRule.allowOneOverlapClass: matches = priors_matches + \ cust_priors.filter(**filter_dict).exclude(**nonconcurrent_filter).filter( event__startTime__lte=registration.getTimeOfClassesRemaining(1) ).count() elif item.concurrentRule == item.ConcurrencyRule.allowTwoOverlapClasses: matches = priors_matches + \ cust_priors.filter(**filter_dict).exclude(**nonconcurrent_filter).filter( event__startTime__lte=registration.getTimeOfClassesRemaining(2) ).count() elif item.concurrentRule == item.ConcurrencyRule.allowed: matches = priors_matches + overlap_matches + \ (current_matches if isinstance(registration,TemporaryRegistration) else 0) elif item.concurrentRule == item.ConcurrencyRule.required: matches = overlap_matches + current_matches if matches >= item.quantity: # If this is an 'or' or a 'not' requirement, then we are done if self.booleanRule == self.BooleanChoice.booleanOr: return True if self.booleanRule == self.BooleanChoice.booleanNot: return False else: # If this is an 'and' requirement and we didn't meet, then we are done if self.booleanRule == self.BooleanChoice.booleanAnd: return False # If we got this far, then either all 'and' requirements were met, or all 'or' and 'not' requirements were not met if self.booleanRule == self.BooleanChoice.booleanOr or self.requirementitem_set.count() == 0: return False return True
python
def customerMeetsRequirement(self, customer, danceRole=None, registration=None): cust_reqs = self.customerrequirement_set.filter(customer=customer,met=True) if customer: cust_priors = customer.eventregistration_set.filter(event__series__isnull=False) else: cust_priors = EventRegistration.objects.none() if self.roleEnforced and danceRole and cust_reqs.filter(role=danceRole).exists(): return True elif not self.roleEnforced and cust_reqs.exists(): return True elif self.roleEnforced and not danceRole: return False for item in self.requirementitem_set.all(): filter_dict = {} if item.requiredLevel: filter_dict['event__series__classDescription__danceTypeLevel'] = item.requiredLevel if item.requiredClass: filter_dict['event__series__classDescription'] = item.requiredClass if self.roleEnforced: filter_dict['role'] = danceRole current_matches = 0 overlap_matches = 0 nonconcurrent_filter = {'event__endTime__lte': timezone.now()} if registration: if isinstance(registration,Registration): current_matches = registration.eventregistration_set.filter(**filter_dict).count() elif isinstance(registration,TemporaryRegistration): current_matches = registration.temporaryeventregistration_set.filter(**filter_dict).count() nonconcurrent_filter = {'event__endTime__lte': registration.firstSeriesStartTime} overlap_matches = cust_priors.filter(**filter_dict).exclude(**nonconcurrent_filter).filter( event__startTime__lte=registration.lastSeriesEndTime, ).count() priors_matches = cust_priors.filter(**filter_dict).filter(**nonconcurrent_filter).count() if item.concurrentRule == item.ConcurrencyRule.prohibited: matches = priors_matches elif item.concurrentRule == item.ConcurrencyRule.allowOneOverlapClass: matches = priors_matches + \ cust_priors.filter(**filter_dict).exclude(**nonconcurrent_filter).filter( event__startTime__lte=registration.getTimeOfClassesRemaining(1) ).count() elif item.concurrentRule == item.ConcurrencyRule.allowTwoOverlapClasses: matches = priors_matches + \ cust_priors.filter(**filter_dict).exclude(**nonconcurrent_filter).filter( event__startTime__lte=registration.getTimeOfClassesRemaining(2) ).count() elif item.concurrentRule == item.ConcurrencyRule.allowed: matches = priors_matches + overlap_matches + \ (current_matches if isinstance(registration,TemporaryRegistration) else 0) elif item.concurrentRule == item.ConcurrencyRule.required: matches = overlap_matches + current_matches if matches >= item.quantity: if self.booleanRule == self.BooleanChoice.booleanOr: return True if self.booleanRule == self.BooleanChoice.booleanNot: return False else: if self.booleanRule == self.BooleanChoice.booleanAnd: return False if self.booleanRule == self.BooleanChoice.booleanOr or self.requirementitem_set.count() == 0: return False return True
[ "def", "customerMeetsRequirement", "(", "self", ",", "customer", ",", "danceRole", "=", "None", ",", "registration", "=", "None", ")", ":", "cust_reqs", "=", "self", ".", "customerrequirement_set", ".", "filter", "(", "customer", "=", "customer", ",", "met", "=", "True", ")", "if", "customer", ":", "cust_priors", "=", "customer", ".", "eventregistration_set", ".", "filter", "(", "event__series__isnull", "=", "False", ")", "else", ":", "cust_priors", "=", "EventRegistration", ".", "objects", ".", "none", "(", ")", "# If there's an explicit object stating that this customer meets the requirement, then we're done.", "if", "self", ".", "roleEnforced", "and", "danceRole", "and", "cust_reqs", ".", "filter", "(", "role", "=", "danceRole", ")", ".", "exists", "(", ")", ":", "return", "True", "elif", "not", "self", ".", "roleEnforced", "and", "cust_reqs", ".", "exists", "(", ")", ":", "return", "True", "elif", "self", ".", "roleEnforced", "and", "not", "danceRole", ":", "return", "False", "# Go through each item for this requirement and see if the customer meets that item", "for", "item", "in", "self", ".", "requirementitem_set", ".", "all", "(", ")", ":", "filter_dict", "=", "{", "}", "if", "item", ".", "requiredLevel", ":", "filter_dict", "[", "'event__series__classDescription__danceTypeLevel'", "]", "=", "item", ".", "requiredLevel", "if", "item", ".", "requiredClass", ":", "filter_dict", "[", "'event__series__classDescription'", "]", "=", "item", ".", "requiredClass", "if", "self", ".", "roleEnforced", ":", "filter_dict", "[", "'role'", "]", "=", "danceRole", "current_matches", "=", "0", "overlap_matches", "=", "0", "nonconcurrent_filter", "=", "{", "'event__endTime__lte'", ":", "timezone", ".", "now", "(", ")", "}", "if", "registration", ":", "if", "isinstance", "(", "registration", ",", "Registration", ")", ":", "current_matches", "=", "registration", ".", "eventregistration_set", ".", "filter", "(", "*", "*", "filter_dict", ")", ".", "count", "(", ")", "elif", "isinstance", "(", "registration", ",", "TemporaryRegistration", ")", ":", "current_matches", "=", "registration", ".", "temporaryeventregistration_set", ".", "filter", "(", "*", "*", "filter_dict", ")", ".", "count", "(", ")", "nonconcurrent_filter", "=", "{", "'event__endTime__lte'", ":", "registration", ".", "firstSeriesStartTime", "}", "overlap_matches", "=", "cust_priors", ".", "filter", "(", "*", "*", "filter_dict", ")", ".", "exclude", "(", "*", "*", "nonconcurrent_filter", ")", ".", "filter", "(", "event__startTime__lte", "=", "registration", ".", "lastSeriesEndTime", ",", ")", ".", "count", "(", ")", "priors_matches", "=", "cust_priors", ".", "filter", "(", "*", "*", "filter_dict", ")", ".", "filter", "(", "*", "*", "nonconcurrent_filter", ")", ".", "count", "(", ")", "# The number of matches depends on the concurrency rule for this item", "if", "item", ".", "concurrentRule", "==", "item", ".", "ConcurrencyRule", ".", "prohibited", ":", "matches", "=", "priors_matches", "elif", "item", ".", "concurrentRule", "==", "item", ".", "ConcurrencyRule", ".", "allowOneOverlapClass", ":", "matches", "=", "priors_matches", "+", "cust_priors", ".", "filter", "(", "*", "*", "filter_dict", ")", ".", "exclude", "(", "*", "*", "nonconcurrent_filter", ")", ".", "filter", "(", "event__startTime__lte", "=", "registration", ".", "getTimeOfClassesRemaining", "(", "1", ")", ")", ".", "count", "(", ")", "elif", "item", ".", "concurrentRule", "==", "item", ".", "ConcurrencyRule", ".", "allowTwoOverlapClasses", ":", "matches", "=", "priors_matches", "+", "cust_priors", ".", "filter", "(", "*", "*", "filter_dict", ")", ".", "exclude", "(", "*", "*", "nonconcurrent_filter", ")", ".", "filter", "(", "event__startTime__lte", "=", "registration", ".", "getTimeOfClassesRemaining", "(", "2", ")", ")", ".", "count", "(", ")", "elif", "item", ".", "concurrentRule", "==", "item", ".", "ConcurrencyRule", ".", "allowed", ":", "matches", "=", "priors_matches", "+", "overlap_matches", "+", "(", "current_matches", "if", "isinstance", "(", "registration", ",", "TemporaryRegistration", ")", "else", "0", ")", "elif", "item", ".", "concurrentRule", "==", "item", ".", "ConcurrencyRule", ".", "required", ":", "matches", "=", "overlap_matches", "+", "current_matches", "if", "matches", ">=", "item", ".", "quantity", ":", "# If this is an 'or' or a 'not' requirement, then we are done", "if", "self", ".", "booleanRule", "==", "self", ".", "BooleanChoice", ".", "booleanOr", ":", "return", "True", "if", "self", ".", "booleanRule", "==", "self", ".", "BooleanChoice", ".", "booleanNot", ":", "return", "False", "else", ":", "# If this is an 'and' requirement and we didn't meet, then we are done", "if", "self", ".", "booleanRule", "==", "self", ".", "BooleanChoice", ".", "booleanAnd", ":", "return", "False", "# If we got this far, then either all 'and' requirements were met, or all 'or' and 'not' requirements were not met", "if", "self", ".", "booleanRule", "==", "self", ".", "BooleanChoice", ".", "booleanOr", "or", "self", ".", "requirementitem_set", ".", "count", "(", ")", "==", "0", ":", "return", "False", "return", "True" ]
This method checks whether a given customer meets a given set of requirements.
[ "This", "method", "checks", "whether", "a", "given", "customer", "meets", "a", "given", "set", "of", "requirements", "." ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/prerequisites/models.py#L49-L129
django-danceschool/django-danceschool
danceschool/financial/handlers.py
updateTransactionParty
def updateTransactionParty(sender,instance,**kwargs): ''' If a User, StaffMember, or Location is updated, and there exists an associated TransactionParty, then the name and other attributes of that party should be updated to reflect the new information. ''' if 'loaddata' in sys.argv or ('raw' in kwargs and kwargs['raw']): return logger.debug('TransactionParty signal fired for %s %s.' % (instance.__class__.__name__, instance.id)) party = getattr(instance,'transactionparty',None) if party: party.save(updateBy=instance)
python
def updateTransactionParty(sender,instance,**kwargs): if 'loaddata' in sys.argv or ('raw' in kwargs and kwargs['raw']): return logger.debug('TransactionParty signal fired for %s %s.' % (instance.__class__.__name__, instance.id)) party = getattr(instance,'transactionparty',None) if party: party.save(updateBy=instance)
[ "def", "updateTransactionParty", "(", "sender", ",", "instance", ",", "*", "*", "kwargs", ")", ":", "if", "'loaddata'", "in", "sys", ".", "argv", "or", "(", "'raw'", "in", "kwargs", "and", "kwargs", "[", "'raw'", "]", ")", ":", "return", "logger", ".", "debug", "(", "'TransactionParty signal fired for %s %s.'", "%", "(", "instance", ".", "__class__", ".", "__name__", ",", "instance", ".", "id", ")", ")", "party", "=", "getattr", "(", "instance", ",", "'transactionparty'", ",", "None", ")", "if", "party", ":", "party", ".", "save", "(", "updateBy", "=", "instance", ")" ]
If a User, StaffMember, or Location is updated, and there exists an associated TransactionParty, then the name and other attributes of that party should be updated to reflect the new information.
[ "If", "a", "User", "StaffMember", "or", "Location", "is", "updated", "and", "there", "exists", "an", "associated", "TransactionParty", "then", "the", "name", "and", "other", "attributes", "of", "that", "party", "should", "be", "updated", "to", "reflect", "the", "new", "information", "." ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/financial/handlers.py#L151-L165
django-danceschool/django-danceschool
danceschool/payments/square/tasks.py
updateSquareFees
def updateSquareFees(paymentRecord): ''' The Square Checkout API does not calculate fees immediately, so this task is called to be asynchronously run 1 minute after the initial transaction, so that any Invoice or ExpenseItem associated with this transaction also remains accurate. ''' fees = paymentRecord.netFees invoice = paymentRecord.invoice invoice.fees = fees invoice.save() invoice.allocateFees() return fees
python
def updateSquareFees(paymentRecord): fees = paymentRecord.netFees invoice = paymentRecord.invoice invoice.fees = fees invoice.save() invoice.allocateFees() return fees
[ "def", "updateSquareFees", "(", "paymentRecord", ")", ":", "fees", "=", "paymentRecord", ".", "netFees", "invoice", "=", "paymentRecord", ".", "invoice", "invoice", ".", "fees", "=", "fees", "invoice", ".", "save", "(", ")", "invoice", ".", "allocateFees", "(", ")", "return", "fees" ]
The Square Checkout API does not calculate fees immediately, so this task is called to be asynchronously run 1 minute after the initial transaction, so that any Invoice or ExpenseItem associated with this transaction also remains accurate.
[ "The", "Square", "Checkout", "API", "does", "not", "calculate", "fees", "immediately", "so", "this", "task", "is", "called", "to", "be", "asynchronously", "run", "1", "minute", "after", "the", "initial", "transaction", "so", "that", "any", "Invoice", "or", "ExpenseItem", "associated", "with", "this", "transaction", "also", "remains", "accurate", "." ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/payments/square/tasks.py#L5-L17
django-danceschool/django-danceschool
danceschool/stats/stats.py
getClassTypeMonthlyData
def getClassTypeMonthlyData(year=None, series=None, typeLimit=None): ''' To break out by class type and month simultaneously, get data for each series and aggregate by class type. ''' # If no year specified, report current year to date. if not year: year = timezone.now().year role_list = DanceRole.objects.distinct() # Report data on all students registered unless otherwise specified if series not in ['registrations','studenthours'] and series not in [x.pluralName for x in role_list]: series = 'registrations' when_all = { 'eventregistration__dropIn': False, 'eventregistration__cancelled': False, } annotations = {'registrations': Sum(Case(When(Q(**when_all),then=1),output_field=FloatField()))} for this_role in role_list: annotations[this_role.pluralName] = Sum(Case(When(Q(Q(**when_all) & Q(eventregistration__role=this_role)),then=1),output_field=FloatField())) series_counts = Series.objects.filter(year=year).annotate(**annotations).annotate(studenthours=F('duration') * F('registrations')).select_related('classDescription__danceTypeLevel__danceType','classDescription__danceTypeLevel') # If no limit specified on number of types, then do not aggregate dance types. # Otherwise, report the typeLimit most common types individually, and report all # others as other. This gets tuples of names and counts dance_type_counts = [(dance_type,count) for dance_type,count in Counter([x.classDescription.danceTypeLevel for x in series_counts]).items()] dance_type_counts.sort(key=lambda k: k[1],reverse=True) if typeLimit: dance_types = [x[0] for x in dance_type_counts[:typeLimit]] else: dance_types = [x[0] for x in dance_type_counts] results = [] # Month by month, calculate the result data for month in range(1,13): this_month_result = { 'month': month, 'month_name': month_name[month], } for dance_type in dance_types: this_month_result[dance_type.__str__()] = \ series_counts.filter(classDescription__danceTypeLevel=dance_type,month=month).aggregate(Sum(series))['%s__sum' % series] if typeLimit: this_month_result['Other'] = \ series_counts.filter(month=month).exclude(classDescription__danceTypeLevel__in=dance_types).aggregate(Sum(series))['%s__sum' % series] results.append(this_month_result) # Now get totals totals_result = { 'month': 'Totals', 'month_name': 'totals', } for dance_type in dance_types: totals_result[dance_type.__str__()] = \ series_counts.filter(classDescription__danceTypeLevel=dance_type).aggregate(Sum(series))['%s__sum' % series] if typeLimit: totals_result['Other'] = \ series_counts.exclude(classDescription__danceTypeLevel__in=dance_types).aggregate(Sum(series))['%s__sum' % series] results.append(totals_result) return results
python
def getClassTypeMonthlyData(year=None, series=None, typeLimit=None): if not year: year = timezone.now().year role_list = DanceRole.objects.distinct() if series not in ['registrations','studenthours'] and series not in [x.pluralName for x in role_list]: series = 'registrations' when_all = { 'eventregistration__dropIn': False, 'eventregistration__cancelled': False, } annotations = {'registrations': Sum(Case(When(Q(**when_all),then=1),output_field=FloatField()))} for this_role in role_list: annotations[this_role.pluralName] = Sum(Case(When(Q(Q(**when_all) & Q(eventregistration__role=this_role)),then=1),output_field=FloatField())) series_counts = Series.objects.filter(year=year).annotate(**annotations).annotate(studenthours=F('duration') * F('registrations')).select_related('classDescription__danceTypeLevel__danceType','classDescription__danceTypeLevel') dance_type_counts = [(dance_type,count) for dance_type,count in Counter([x.classDescription.danceTypeLevel for x in series_counts]).items()] dance_type_counts.sort(key=lambda k: k[1],reverse=True) if typeLimit: dance_types = [x[0] for x in dance_type_counts[:typeLimit]] else: dance_types = [x[0] for x in dance_type_counts] results = [] for month in range(1,13): this_month_result = { 'month': month, 'month_name': month_name[month], } for dance_type in dance_types: this_month_result[dance_type.__str__()] = \ series_counts.filter(classDescription__danceTypeLevel=dance_type,month=month).aggregate(Sum(series))['%s__sum' % series] if typeLimit: this_month_result['Other'] = \ series_counts.filter(month=month).exclude(classDescription__danceTypeLevel__in=dance_types).aggregate(Sum(series))['%s__sum' % series] results.append(this_month_result) totals_result = { 'month': 'Totals', 'month_name': 'totals', } for dance_type in dance_types: totals_result[dance_type.__str__()] = \ series_counts.filter(classDescription__danceTypeLevel=dance_type).aggregate(Sum(series))['%s__sum' % series] if typeLimit: totals_result['Other'] = \ series_counts.exclude(classDescription__danceTypeLevel__in=dance_types).aggregate(Sum(series))['%s__sum' % series] results.append(totals_result) return results
[ "def", "getClassTypeMonthlyData", "(", "year", "=", "None", ",", "series", "=", "None", ",", "typeLimit", "=", "None", ")", ":", "# If no year specified, report current year to date.", "if", "not", "year", ":", "year", "=", "timezone", ".", "now", "(", ")", ".", "year", "role_list", "=", "DanceRole", ".", "objects", ".", "distinct", "(", ")", "# Report data on all students registered unless otherwise specified", "if", "series", "not", "in", "[", "'registrations'", ",", "'studenthours'", "]", "and", "series", "not", "in", "[", "x", ".", "pluralName", "for", "x", "in", "role_list", "]", ":", "series", "=", "'registrations'", "when_all", "=", "{", "'eventregistration__dropIn'", ":", "False", ",", "'eventregistration__cancelled'", ":", "False", ",", "}", "annotations", "=", "{", "'registrations'", ":", "Sum", "(", "Case", "(", "When", "(", "Q", "(", "*", "*", "when_all", ")", ",", "then", "=", "1", ")", ",", "output_field", "=", "FloatField", "(", ")", ")", ")", "}", "for", "this_role", "in", "role_list", ":", "annotations", "[", "this_role", ".", "pluralName", "]", "=", "Sum", "(", "Case", "(", "When", "(", "Q", "(", "Q", "(", "*", "*", "when_all", ")", "&", "Q", "(", "eventregistration__role", "=", "this_role", ")", ")", ",", "then", "=", "1", ")", ",", "output_field", "=", "FloatField", "(", ")", ")", ")", "series_counts", "=", "Series", ".", "objects", ".", "filter", "(", "year", "=", "year", ")", ".", "annotate", "(", "*", "*", "annotations", ")", ".", "annotate", "(", "studenthours", "=", "F", "(", "'duration'", ")", "*", "F", "(", "'registrations'", ")", ")", ".", "select_related", "(", "'classDescription__danceTypeLevel__danceType'", ",", "'classDescription__danceTypeLevel'", ")", "# If no limit specified on number of types, then do not aggregate dance types.", "# Otherwise, report the typeLimit most common types individually, and report all", "# others as other. This gets tuples of names and counts", "dance_type_counts", "=", "[", "(", "dance_type", ",", "count", ")", "for", "dance_type", ",", "count", "in", "Counter", "(", "[", "x", ".", "classDescription", ".", "danceTypeLevel", "for", "x", "in", "series_counts", "]", ")", ".", "items", "(", ")", "]", "dance_type_counts", ".", "sort", "(", "key", "=", "lambda", "k", ":", "k", "[", "1", "]", ",", "reverse", "=", "True", ")", "if", "typeLimit", ":", "dance_types", "=", "[", "x", "[", "0", "]", "for", "x", "in", "dance_type_counts", "[", ":", "typeLimit", "]", "]", "else", ":", "dance_types", "=", "[", "x", "[", "0", "]", "for", "x", "in", "dance_type_counts", "]", "results", "=", "[", "]", "# Month by month, calculate the result data", "for", "month", "in", "range", "(", "1", ",", "13", ")", ":", "this_month_result", "=", "{", "'month'", ":", "month", ",", "'month_name'", ":", "month_name", "[", "month", "]", ",", "}", "for", "dance_type", "in", "dance_types", ":", "this_month_result", "[", "dance_type", ".", "__str__", "(", ")", "]", "=", "series_counts", ".", "filter", "(", "classDescription__danceTypeLevel", "=", "dance_type", ",", "month", "=", "month", ")", ".", "aggregate", "(", "Sum", "(", "series", ")", ")", "[", "'%s__sum'", "%", "series", "]", "if", "typeLimit", ":", "this_month_result", "[", "'Other'", "]", "=", "series_counts", ".", "filter", "(", "month", "=", "month", ")", ".", "exclude", "(", "classDescription__danceTypeLevel__in", "=", "dance_types", ")", ".", "aggregate", "(", "Sum", "(", "series", ")", ")", "[", "'%s__sum'", "%", "series", "]", "results", ".", "append", "(", "this_month_result", ")", "# Now get totals", "totals_result", "=", "{", "'month'", ":", "'Totals'", ",", "'month_name'", ":", "'totals'", ",", "}", "for", "dance_type", "in", "dance_types", ":", "totals_result", "[", "dance_type", ".", "__str__", "(", ")", "]", "=", "series_counts", ".", "filter", "(", "classDescription__danceTypeLevel", "=", "dance_type", ")", ".", "aggregate", "(", "Sum", "(", "series", ")", ")", "[", "'%s__sum'", "%", "series", "]", "if", "typeLimit", ":", "totals_result", "[", "'Other'", "]", "=", "series_counts", ".", "exclude", "(", "classDescription__danceTypeLevel__in", "=", "dance_types", ")", ".", "aggregate", "(", "Sum", "(", "series", ")", ")", "[", "'%s__sum'", "%", "series", "]", "results", ".", "append", "(", "totals_result", ")", "return", "results" ]
To break out by class type and month simultaneously, get data for each series and aggregate by class type.
[ "To", "break", "out", "by", "class", "type", "and", "month", "simultaneously", "get", "data", "for", "each", "series", "and", "aggregate", "by", "class", "type", "." ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/stats/stats.py#L138-L211
django-danceschool/django-danceschool
danceschool/stats/stats.py
getMonthlyPerformance
def getMonthlyPerformance(): ''' This function does the work of compiling monthly performance data that can either be rendered as CSV or as JSON ''' when_all = { 'eventregistration__dropIn': False, 'eventregistration__cancelled': False, } # Get objects at the Series level so that we can calculate StudentHours series_counts = list(Series.objects.annotate( eventregistrations=Sum(Case(When(Q(**when_all),then=1),output_field=IntegerField())),) .values('year','month','eventregistrations','duration')) for series in series_counts: series['studenthours'] = (series.get('eventregistrations') or 0) * (series.get('duration') or 0) all_years = set([x['year'] for x in series_counts]) dataseries_list = ['EventRegistrations', 'Registrations','Hours','StudentHours','AvgStudents'] yearTotals = {} # Initialize dictionaries for dataseries in dataseries_list: yearTotals[dataseries] = {'MonthlyAverage': {}} for year in all_years: yearTotals[dataseries][year] = {} # Fill in by year and month for a cleaner looping process for year in all_years: # Monthly Totals for month in range(1,13): # Total EventRegistrations per month is retrieved by the query above. yearTotals['EventRegistrations'][year][month] = sum([x['eventregistrations'] or 0 for x in series_counts if x['month'] == month and x['year'] == year]) # Total Registrations per month and hours per month require a separate query for each month yearTotals['Registrations'][year][month] = len(Registration.objects.filter(eventregistration__dropIn=False, eventregistration__cancelled=False,eventregistration__event__year=year,eventregistration__event__month=month).distinct()) yearTotals['Hours'][year][month] = sum([x['duration'] or 0 for x in series_counts if x['month'] == month and x['year'] == year]) yearTotals['StudentHours'][year][month] = sum([x['studenthours'] or 0 for x in series_counts if x['month'] == month and x['year'] == year]) if yearTotals['Hours'][year][month] > 0: yearTotals['AvgStudents'][year][month] = yearTotals['StudentHours'][year][month] / float(yearTotals['Hours'][year][month]) else: yearTotals['AvgStudents'][year][month] = 0 # Annual Totals for sub_series in ['EventRegistrations','Registrations','Hours','StudentHours']: yearTotals[sub_series][year]['Total'] = sum([x for x in yearTotals[sub_series][year].values()]) # Annual (Monthly) Averages month_count = len([x for k,x in yearTotals['Hours'][year].items() if k in range(1,13) and x > 0]) if month_count > 0: for sub_series in ['EventRegistrations','Registrations','Hours','StudentHours']: yearTotals[sub_series][year]['Average'] = yearTotals[sub_series][year]['Total'] / float(month_count) yearTotals['AvgStudents'][year]['Average'] = yearTotals['StudentHours'][year]['Total'] / float(yearTotals['Hours'][year]['Total']) # Monthly Averages for month in range(1,13): yearly_hours_data = [x[month] for k,x in yearTotals['Hours'].items() if k in all_years and x[month] > 0] yearly_studenthours_data = [x[month] for k,x in yearTotals['StudentHours'].items() if k in all_years and x[month] > 0] yearly_eventregistrations_data = [x[month] for k,x in yearTotals['EventRegistrations'].items() if k in all_years and yearTotals['Hours'][k][month] > 0] yearly_registrations_data = [x[month] for k,x in yearTotals['Registrations'].items() if k in all_years and yearTotals['Hours'][k][month] > 0] year_count = len(yearly_hours_data) if year_count > 0: yearTotals['EventRegistrations']['MonthlyAverage'][month] = sum([x for x in yearly_eventregistrations_data]) / year_count yearTotals['Registrations']['MonthlyAverage'][month] = sum([x for x in yearly_registrations_data]) / year_count yearTotals['Hours']['MonthlyAverage'][month] = sum([x for x in yearly_hours_data]) / year_count yearTotals['StudentHours']['MonthlyAverage'][month] = sum([x for x in yearly_studenthours_data]) / year_count yearTotals['AvgStudents']['MonthlyAverage'][month] = yearTotals['StudentHours']['MonthlyAverage'][month] / float(yearTotals['Hours']['MonthlyAverage'][month]) return yearTotals
python
def getMonthlyPerformance(): when_all = { 'eventregistration__dropIn': False, 'eventregistration__cancelled': False, } series_counts = list(Series.objects.annotate( eventregistrations=Sum(Case(When(Q(**when_all),then=1),output_field=IntegerField())),) .values('year','month','eventregistrations','duration')) for series in series_counts: series['studenthours'] = (series.get('eventregistrations') or 0) * (series.get('duration') or 0) all_years = set([x['year'] for x in series_counts]) dataseries_list = ['EventRegistrations', 'Registrations','Hours','StudentHours','AvgStudents'] yearTotals = {} for dataseries in dataseries_list: yearTotals[dataseries] = {'MonthlyAverage': {}} for year in all_years: yearTotals[dataseries][year] = {} for year in all_years: for month in range(1,13): yearTotals['EventRegistrations'][year][month] = sum([x['eventregistrations'] or 0 for x in series_counts if x['month'] == month and x['year'] == year]) yearTotals['Registrations'][year][month] = len(Registration.objects.filter(eventregistration__dropIn=False, eventregistration__cancelled=False,eventregistration__event__year=year,eventregistration__event__month=month).distinct()) yearTotals['Hours'][year][month] = sum([x['duration'] or 0 for x in series_counts if x['month'] == month and x['year'] == year]) yearTotals['StudentHours'][year][month] = sum([x['studenthours'] or 0 for x in series_counts if x['month'] == month and x['year'] == year]) if yearTotals['Hours'][year][month] > 0: yearTotals['AvgStudents'][year][month] = yearTotals['StudentHours'][year][month] / float(yearTotals['Hours'][year][month]) else: yearTotals['AvgStudents'][year][month] = 0 for sub_series in ['EventRegistrations','Registrations','Hours','StudentHours']: yearTotals[sub_series][year]['Total'] = sum([x for x in yearTotals[sub_series][year].values()]) month_count = len([x for k,x in yearTotals['Hours'][year].items() if k in range(1,13) and x > 0]) if month_count > 0: for sub_series in ['EventRegistrations','Registrations','Hours','StudentHours']: yearTotals[sub_series][year]['Average'] = yearTotals[sub_series][year]['Total'] / float(month_count) yearTotals['AvgStudents'][year]['Average'] = yearTotals['StudentHours'][year]['Total'] / float(yearTotals['Hours'][year]['Total']) for month in range(1,13): yearly_hours_data = [x[month] for k,x in yearTotals['Hours'].items() if k in all_years and x[month] > 0] yearly_studenthours_data = [x[month] for k,x in yearTotals['StudentHours'].items() if k in all_years and x[month] > 0] yearly_eventregistrations_data = [x[month] for k,x in yearTotals['EventRegistrations'].items() if k in all_years and yearTotals['Hours'][k][month] > 0] yearly_registrations_data = [x[month] for k,x in yearTotals['Registrations'].items() if k in all_years and yearTotals['Hours'][k][month] > 0] year_count = len(yearly_hours_data) if year_count > 0: yearTotals['EventRegistrations']['MonthlyAverage'][month] = sum([x for x in yearly_eventregistrations_data]) / year_count yearTotals['Registrations']['MonthlyAverage'][month] = sum([x for x in yearly_registrations_data]) / year_count yearTotals['Hours']['MonthlyAverage'][month] = sum([x for x in yearly_hours_data]) / year_count yearTotals['StudentHours']['MonthlyAverage'][month] = sum([x for x in yearly_studenthours_data]) / year_count yearTotals['AvgStudents']['MonthlyAverage'][month] = yearTotals['StudentHours']['MonthlyAverage'][month] / float(yearTotals['Hours']['MonthlyAverage'][month]) return yearTotals
[ "def", "getMonthlyPerformance", "(", ")", ":", "when_all", "=", "{", "'eventregistration__dropIn'", ":", "False", ",", "'eventregistration__cancelled'", ":", "False", ",", "}", "# Get objects at the Series level so that we can calculate StudentHours", "series_counts", "=", "list", "(", "Series", ".", "objects", ".", "annotate", "(", "eventregistrations", "=", "Sum", "(", "Case", "(", "When", "(", "Q", "(", "*", "*", "when_all", ")", ",", "then", "=", "1", ")", ",", "output_field", "=", "IntegerField", "(", ")", ")", ")", ",", ")", ".", "values", "(", "'year'", ",", "'month'", ",", "'eventregistrations'", ",", "'duration'", ")", ")", "for", "series", "in", "series_counts", ":", "series", "[", "'studenthours'", "]", "=", "(", "series", ".", "get", "(", "'eventregistrations'", ")", "or", "0", ")", "*", "(", "series", ".", "get", "(", "'duration'", ")", "or", "0", ")", "all_years", "=", "set", "(", "[", "x", "[", "'year'", "]", "for", "x", "in", "series_counts", "]", ")", "dataseries_list", "=", "[", "'EventRegistrations'", ",", "'Registrations'", ",", "'Hours'", ",", "'StudentHours'", ",", "'AvgStudents'", "]", "yearTotals", "=", "{", "}", "# Initialize dictionaries", "for", "dataseries", "in", "dataseries_list", ":", "yearTotals", "[", "dataseries", "]", "=", "{", "'MonthlyAverage'", ":", "{", "}", "}", "for", "year", "in", "all_years", ":", "yearTotals", "[", "dataseries", "]", "[", "year", "]", "=", "{", "}", "# Fill in by year and month for a cleaner looping process", "for", "year", "in", "all_years", ":", "# Monthly Totals", "for", "month", "in", "range", "(", "1", ",", "13", ")", ":", "# Total EventRegistrations per month is retrieved by the query above.", "yearTotals", "[", "'EventRegistrations'", "]", "[", "year", "]", "[", "month", "]", "=", "sum", "(", "[", "x", "[", "'eventregistrations'", "]", "or", "0", "for", "x", "in", "series_counts", "if", "x", "[", "'month'", "]", "==", "month", "and", "x", "[", "'year'", "]", "==", "year", "]", ")", "# Total Registrations per month and hours per month require a separate query for each month", "yearTotals", "[", "'Registrations'", "]", "[", "year", "]", "[", "month", "]", "=", "len", "(", "Registration", ".", "objects", ".", "filter", "(", "eventregistration__dropIn", "=", "False", ",", "eventregistration__cancelled", "=", "False", ",", "eventregistration__event__year", "=", "year", ",", "eventregistration__event__month", "=", "month", ")", ".", "distinct", "(", ")", ")", "yearTotals", "[", "'Hours'", "]", "[", "year", "]", "[", "month", "]", "=", "sum", "(", "[", "x", "[", "'duration'", "]", "or", "0", "for", "x", "in", "series_counts", "if", "x", "[", "'month'", "]", "==", "month", "and", "x", "[", "'year'", "]", "==", "year", "]", ")", "yearTotals", "[", "'StudentHours'", "]", "[", "year", "]", "[", "month", "]", "=", "sum", "(", "[", "x", "[", "'studenthours'", "]", "or", "0", "for", "x", "in", "series_counts", "if", "x", "[", "'month'", "]", "==", "month", "and", "x", "[", "'year'", "]", "==", "year", "]", ")", "if", "yearTotals", "[", "'Hours'", "]", "[", "year", "]", "[", "month", "]", ">", "0", ":", "yearTotals", "[", "'AvgStudents'", "]", "[", "year", "]", "[", "month", "]", "=", "yearTotals", "[", "'StudentHours'", "]", "[", "year", "]", "[", "month", "]", "/", "float", "(", "yearTotals", "[", "'Hours'", "]", "[", "year", "]", "[", "month", "]", ")", "else", ":", "yearTotals", "[", "'AvgStudents'", "]", "[", "year", "]", "[", "month", "]", "=", "0", "# Annual Totals", "for", "sub_series", "in", "[", "'EventRegistrations'", ",", "'Registrations'", ",", "'Hours'", ",", "'StudentHours'", "]", ":", "yearTotals", "[", "sub_series", "]", "[", "year", "]", "[", "'Total'", "]", "=", "sum", "(", "[", "x", "for", "x", "in", "yearTotals", "[", "sub_series", "]", "[", "year", "]", ".", "values", "(", ")", "]", ")", "# Annual (Monthly) Averages", "month_count", "=", "len", "(", "[", "x", "for", "k", ",", "x", "in", "yearTotals", "[", "'Hours'", "]", "[", "year", "]", ".", "items", "(", ")", "if", "k", "in", "range", "(", "1", ",", "13", ")", "and", "x", ">", "0", "]", ")", "if", "month_count", ">", "0", ":", "for", "sub_series", "in", "[", "'EventRegistrations'", ",", "'Registrations'", ",", "'Hours'", ",", "'StudentHours'", "]", ":", "yearTotals", "[", "sub_series", "]", "[", "year", "]", "[", "'Average'", "]", "=", "yearTotals", "[", "sub_series", "]", "[", "year", "]", "[", "'Total'", "]", "/", "float", "(", "month_count", ")", "yearTotals", "[", "'AvgStudents'", "]", "[", "year", "]", "[", "'Average'", "]", "=", "yearTotals", "[", "'StudentHours'", "]", "[", "year", "]", "[", "'Total'", "]", "/", "float", "(", "yearTotals", "[", "'Hours'", "]", "[", "year", "]", "[", "'Total'", "]", ")", "# Monthly Averages", "for", "month", "in", "range", "(", "1", ",", "13", ")", ":", "yearly_hours_data", "=", "[", "x", "[", "month", "]", "for", "k", ",", "x", "in", "yearTotals", "[", "'Hours'", "]", ".", "items", "(", ")", "if", "k", "in", "all_years", "and", "x", "[", "month", "]", ">", "0", "]", "yearly_studenthours_data", "=", "[", "x", "[", "month", "]", "for", "k", ",", "x", "in", "yearTotals", "[", "'StudentHours'", "]", ".", "items", "(", ")", "if", "k", "in", "all_years", "and", "x", "[", "month", "]", ">", "0", "]", "yearly_eventregistrations_data", "=", "[", "x", "[", "month", "]", "for", "k", ",", "x", "in", "yearTotals", "[", "'EventRegistrations'", "]", ".", "items", "(", ")", "if", "k", "in", "all_years", "and", "yearTotals", "[", "'Hours'", "]", "[", "k", "]", "[", "month", "]", ">", "0", "]", "yearly_registrations_data", "=", "[", "x", "[", "month", "]", "for", "k", ",", "x", "in", "yearTotals", "[", "'Registrations'", "]", ".", "items", "(", ")", "if", "k", "in", "all_years", "and", "yearTotals", "[", "'Hours'", "]", "[", "k", "]", "[", "month", "]", ">", "0", "]", "year_count", "=", "len", "(", "yearly_hours_data", ")", "if", "year_count", ">", "0", ":", "yearTotals", "[", "'EventRegistrations'", "]", "[", "'MonthlyAverage'", "]", "[", "month", "]", "=", "sum", "(", "[", "x", "for", "x", "in", "yearly_eventregistrations_data", "]", ")", "/", "year_count", "yearTotals", "[", "'Registrations'", "]", "[", "'MonthlyAverage'", "]", "[", "month", "]", "=", "sum", "(", "[", "x", "for", "x", "in", "yearly_registrations_data", "]", ")", "/", "year_count", "yearTotals", "[", "'Hours'", "]", "[", "'MonthlyAverage'", "]", "[", "month", "]", "=", "sum", "(", "[", "x", "for", "x", "in", "yearly_hours_data", "]", ")", "/", "year_count", "yearTotals", "[", "'StudentHours'", "]", "[", "'MonthlyAverage'", "]", "[", "month", "]", "=", "sum", "(", "[", "x", "for", "x", "in", "yearly_studenthours_data", "]", ")", "/", "year_count", "yearTotals", "[", "'AvgStudents'", "]", "[", "'MonthlyAverage'", "]", "[", "month", "]", "=", "yearTotals", "[", "'StudentHours'", "]", "[", "'MonthlyAverage'", "]", "[", "month", "]", "/", "float", "(", "yearTotals", "[", "'Hours'", "]", "[", "'MonthlyAverage'", "]", "[", "month", "]", ")", "return", "yearTotals" ]
This function does the work of compiling monthly performance data that can either be rendered as CSV or as JSON
[ "This", "function", "does", "the", "work", "of", "compiling", "monthly", "performance", "data", "that", "can", "either", "be", "rendered", "as", "CSV", "or", "as", "JSON" ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/stats/stats.py#L376-L451
django-danceschool/django-danceschool
danceschool/stats/stats.py
getRegistrationReferralCounts
def getRegistrationReferralCounts(startDate,endDate): ''' When a user accesses the class registration page through a referral URL, the marketing_id gets saved in the extra JSON data associated with that registration. This just returns counts associated with how often given referral terms appear in a specified time window (i.e. how many people signed up by clicking through a referral button). ''' timeFilters = {} if startDate: timeFilters['dateTime__gte'] = startDate if endDate: timeFilters['dateTime__lt'] = endDate regs = Registration.objects.filter(**timeFilters) counter = Counter([x.data.get('marketing_id',None) for x in regs if isinstance(x.data,dict)] + [None for x in regs if not isinstance(x.data,dict)]) results = [{'code': k or _('None'), 'count': v} for k,v in counter.items()] return results
python
def getRegistrationReferralCounts(startDate,endDate): timeFilters = {} if startDate: timeFilters['dateTime__gte'] = startDate if endDate: timeFilters['dateTime__lt'] = endDate regs = Registration.objects.filter(**timeFilters) counter = Counter([x.data.get('marketing_id',None) for x in regs if isinstance(x.data,dict)] + [None for x in regs if not isinstance(x.data,dict)]) results = [{'code': k or _('None'), 'count': v} for k,v in counter.items()] return results
[ "def", "getRegistrationReferralCounts", "(", "startDate", ",", "endDate", ")", ":", "timeFilters", "=", "{", "}", "if", "startDate", ":", "timeFilters", "[", "'dateTime__gte'", "]", "=", "startDate", "if", "endDate", ":", "timeFilters", "[", "'dateTime__lt'", "]", "=", "endDate", "regs", "=", "Registration", ".", "objects", ".", "filter", "(", "*", "*", "timeFilters", ")", "counter", "=", "Counter", "(", "[", "x", ".", "data", ".", "get", "(", "'marketing_id'", ",", "None", ")", "for", "x", "in", "regs", "if", "isinstance", "(", "x", ".", "data", ",", "dict", ")", "]", "+", "[", "None", "for", "x", "in", "regs", "if", "not", "isinstance", "(", "x", ".", "data", ",", "dict", ")", "]", ")", "results", "=", "[", "{", "'code'", ":", "k", "or", "_", "(", "'None'", ")", ",", "'count'", ":", "v", "}", "for", "k", ",", "v", "in", "counter", ".", "items", "(", ")", "]", "return", "results" ]
When a user accesses the class registration page through a referral URL, the marketing_id gets saved in the extra JSON data associated with that registration. This just returns counts associated with how often given referral terms appear in a specified time window (i.e. how many people signed up by clicking through a referral button).
[ "When", "a", "user", "accesses", "the", "class", "registration", "page", "through", "a", "referral", "URL", "the", "marketing_id", "gets", "saved", "in", "the", "extra", "JSON", "data", "associated", "with", "that", "registration", ".", "This", "just", "returns", "counts", "associated", "with", "how", "often", "given", "referral", "terms", "appear", "in", "a", "specified", "time", "window", "(", "i", ".", "e", ".", "how", "many", "people", "signed", "up", "by", "clicking", "through", "a", "referral", "button", ")", "." ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/stats/stats.py#L618-L638
django-danceschool/django-danceschool
danceschool/private_lessons/views.py
AddAvailabilitySlotView.form_valid
def form_valid(self, form): ''' Create slots and return success message. ''' startDate = form.cleaned_data['startDate'] endDate = form.cleaned_data['endDate'] startTime = form.cleaned_data['startTime'] endTime = form.cleaned_data['endTime'] instructor = form.cleaned_data['instructorId'] interval_minutes = getConstant('privateLessons__lessonLengthInterval') this_date = startDate while this_date <= endDate: this_time = startTime while this_time < endTime: InstructorAvailabilitySlot.objects.create( instructor=instructor, startTime=ensure_localtime(datetime.combine(this_date, this_time)), duration=interval_minutes, location=form.cleaned_data.get('location'), room=form.cleaned_data.get('room'), pricingTier=form.cleaned_data.get('pricingTier'), ) this_time = (ensure_localtime(datetime.combine(this_date, this_time)) + timedelta(minutes=interval_minutes)).time() this_date += timedelta(days=1) return JsonResponse({'valid': True})
python
def form_valid(self, form): startDate = form.cleaned_data['startDate'] endDate = form.cleaned_data['endDate'] startTime = form.cleaned_data['startTime'] endTime = form.cleaned_data['endTime'] instructor = form.cleaned_data['instructorId'] interval_minutes = getConstant('privateLessons__lessonLengthInterval') this_date = startDate while this_date <= endDate: this_time = startTime while this_time < endTime: InstructorAvailabilitySlot.objects.create( instructor=instructor, startTime=ensure_localtime(datetime.combine(this_date, this_time)), duration=interval_minutes, location=form.cleaned_data.get('location'), room=form.cleaned_data.get('room'), pricingTier=form.cleaned_data.get('pricingTier'), ) this_time = (ensure_localtime(datetime.combine(this_date, this_time)) + timedelta(minutes=interval_minutes)).time() this_date += timedelta(days=1) return JsonResponse({'valid': True})
[ "def", "form_valid", "(", "self", ",", "form", ")", ":", "startDate", "=", "form", ".", "cleaned_data", "[", "'startDate'", "]", "endDate", "=", "form", ".", "cleaned_data", "[", "'endDate'", "]", "startTime", "=", "form", ".", "cleaned_data", "[", "'startTime'", "]", "endTime", "=", "form", ".", "cleaned_data", "[", "'endTime'", "]", "instructor", "=", "form", ".", "cleaned_data", "[", "'instructorId'", "]", "interval_minutes", "=", "getConstant", "(", "'privateLessons__lessonLengthInterval'", ")", "this_date", "=", "startDate", "while", "this_date", "<=", "endDate", ":", "this_time", "=", "startTime", "while", "this_time", "<", "endTime", ":", "InstructorAvailabilitySlot", ".", "objects", ".", "create", "(", "instructor", "=", "instructor", ",", "startTime", "=", "ensure_localtime", "(", "datetime", ".", "combine", "(", "this_date", ",", "this_time", ")", ")", ",", "duration", "=", "interval_minutes", ",", "location", "=", "form", ".", "cleaned_data", ".", "get", "(", "'location'", ")", ",", "room", "=", "form", ".", "cleaned_data", ".", "get", "(", "'room'", ")", ",", "pricingTier", "=", "form", ".", "cleaned_data", ".", "get", "(", "'pricingTier'", ")", ",", ")", "this_time", "=", "(", "ensure_localtime", "(", "datetime", ".", "combine", "(", "this_date", ",", "this_time", ")", ")", "+", "timedelta", "(", "minutes", "=", "interval_minutes", ")", ")", ".", "time", "(", ")", "this_date", "+=", "timedelta", "(", "days", "=", "1", ")", "return", "JsonResponse", "(", "{", "'valid'", ":", "True", "}", ")" ]
Create slots and return success message.
[ "Create", "slots", "and", "return", "success", "message", "." ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/private_lessons/views.py#L61-L88
django-danceschool/django-danceschool
danceschool/private_lessons/views.py
UpdateAvailabilitySlotView.form_valid
def form_valid(self, form): ''' Modify or delete the availability slot as requested and return success message. ''' slotIds = form.cleaned_data['slotIds'] deleteSlot = form.cleaned_data.get('deleteSlot', False) these_slots = InstructorAvailabilitySlot.objects.filter(id__in=slotIds) if deleteSlot: these_slots.delete() else: for this_slot in these_slots: this_slot.location = form.cleaned_data['updateLocation'] this_slot.room = form.cleaned_data['updateRoom'] this_slot.status = form.cleaned_data['updateStatus'] this_slot.pricingTier = form.cleaned_data.get('updatePricing') this_slot.save() return JsonResponse({'valid': True})
python
def form_valid(self, form): slotIds = form.cleaned_data['slotIds'] deleteSlot = form.cleaned_data.get('deleteSlot', False) these_slots = InstructorAvailabilitySlot.objects.filter(id__in=slotIds) if deleteSlot: these_slots.delete() else: for this_slot in these_slots: this_slot.location = form.cleaned_data['updateLocation'] this_slot.room = form.cleaned_data['updateRoom'] this_slot.status = form.cleaned_data['updateStatus'] this_slot.pricingTier = form.cleaned_data.get('updatePricing') this_slot.save() return JsonResponse({'valid': True})
[ "def", "form_valid", "(", "self", ",", "form", ")", ":", "slotIds", "=", "form", ".", "cleaned_data", "[", "'slotIds'", "]", "deleteSlot", "=", "form", ".", "cleaned_data", ".", "get", "(", "'deleteSlot'", ",", "False", ")", "these_slots", "=", "InstructorAvailabilitySlot", ".", "objects", ".", "filter", "(", "id__in", "=", "slotIds", ")", "if", "deleteSlot", ":", "these_slots", ".", "delete", "(", ")", "else", ":", "for", "this_slot", "in", "these_slots", ":", "this_slot", ".", "location", "=", "form", ".", "cleaned_data", "[", "'updateLocation'", "]", "this_slot", ".", "room", "=", "form", ".", "cleaned_data", "[", "'updateRoom'", "]", "this_slot", ".", "status", "=", "form", ".", "cleaned_data", "[", "'updateStatus'", "]", "this_slot", ".", "pricingTier", "=", "form", ".", "cleaned_data", ".", "get", "(", "'updatePricing'", ")", "this_slot", ".", "save", "(", ")", "return", "JsonResponse", "(", "{", "'valid'", ":", "True", "}", ")" ]
Modify or delete the availability slot as requested and return success message.
[ "Modify", "or", "delete", "the", "availability", "slot", "as", "requested", "and", "return", "success", "message", "." ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/private_lessons/views.py#L101-L120
django-danceschool/django-danceschool
danceschool/private_lessons/views.py
BookPrivateLessonView.get_form_kwargs
def get_form_kwargs(self, **kwargs): ''' Pass the current user to the form to render the payAtDoor field if applicable. ''' kwargs = super(BookPrivateLessonView, self).get_form_kwargs(**kwargs) kwargs['user'] = self.request.user if hasattr(self.request,'user') else None return kwargs
python
def get_form_kwargs(self, **kwargs): kwargs = super(BookPrivateLessonView, self).get_form_kwargs(**kwargs) kwargs['user'] = self.request.user if hasattr(self.request,'user') else None return kwargs
[ "def", "get_form_kwargs", "(", "self", ",", "*", "*", "kwargs", ")", ":", "kwargs", "=", "super", "(", "BookPrivateLessonView", ",", "self", ")", ".", "get_form_kwargs", "(", "*", "*", "kwargs", ")", "kwargs", "[", "'user'", "]", "=", "self", ".", "request", ".", "user", "if", "hasattr", "(", "self", ".", "request", ",", "'user'", ")", "else", "None", "return", "kwargs" ]
Pass the current user to the form to render the payAtDoor field if applicable.
[ "Pass", "the", "current", "user", "to", "the", "form", "to", "render", "the", "payAtDoor", "field", "if", "applicable", "." ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/private_lessons/views.py#L137-L143
django-danceschool/django-danceschool
danceschool/private_lessons/views.py
PrivateLessonStudentInfoView.dispatch
def dispatch(self,request,*args,**kwargs): ''' Handle the session data passed by the prior view. ''' lessonSession = request.session.get(PRIVATELESSON_VALIDATION_STR,{}) try: self.lesson = PrivateLessonEvent.objects.get(id=lessonSession.get('lesson')) except (ValueError, ObjectDoesNotExist): messages.error(request,_('Invalid lesson identifier passed to sign-up form.')) return HttpResponseRedirect(reverse('bookPrivateLesson')) expiry = parse_datetime(lessonSession.get('expiry',''),) if not expiry or expiry < timezone.now(): messages.info(request,_('Your registration session has expired. Please try again.')) return HttpResponseRedirect(reverse('bookPrivateLesson')) self.payAtDoor = lessonSession.get('payAtDoor',False) return super(PrivateLessonStudentInfoView,self).dispatch(request,*args,**kwargs)
python
def dispatch(self,request,*args,**kwargs): lessonSession = request.session.get(PRIVATELESSON_VALIDATION_STR,{}) try: self.lesson = PrivateLessonEvent.objects.get(id=lessonSession.get('lesson')) except (ValueError, ObjectDoesNotExist): messages.error(request,_('Invalid lesson identifier passed to sign-up form.')) return HttpResponseRedirect(reverse('bookPrivateLesson')) expiry = parse_datetime(lessonSession.get('expiry',''),) if not expiry or expiry < timezone.now(): messages.info(request,_('Your registration session has expired. Please try again.')) return HttpResponseRedirect(reverse('bookPrivateLesson')) self.payAtDoor = lessonSession.get('payAtDoor',False) return super(PrivateLessonStudentInfoView,self).dispatch(request,*args,**kwargs)
[ "def", "dispatch", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "lessonSession", "=", "request", ".", "session", ".", "get", "(", "PRIVATELESSON_VALIDATION_STR", ",", "{", "}", ")", "try", ":", "self", ".", "lesson", "=", "PrivateLessonEvent", ".", "objects", ".", "get", "(", "id", "=", "lessonSession", ".", "get", "(", "'lesson'", ")", ")", "except", "(", "ValueError", ",", "ObjectDoesNotExist", ")", ":", "messages", ".", "error", "(", "request", ",", "_", "(", "'Invalid lesson identifier passed to sign-up form.'", ")", ")", "return", "HttpResponseRedirect", "(", "reverse", "(", "'bookPrivateLesson'", ")", ")", "expiry", "=", "parse_datetime", "(", "lessonSession", ".", "get", "(", "'expiry'", ",", "''", ")", ",", ")", "if", "not", "expiry", "or", "expiry", "<", "timezone", ".", "now", "(", ")", ":", "messages", ".", "info", "(", "request", ",", "_", "(", "'Your registration session has expired. Please try again.'", ")", ")", "return", "HttpResponseRedirect", "(", "reverse", "(", "'bookPrivateLesson'", ")", ")", "self", ".", "payAtDoor", "=", "lessonSession", ".", "get", "(", "'payAtDoor'", ",", "False", ")", "return", "super", "(", "PrivateLessonStudentInfoView", ",", "self", ")", ".", "dispatch", "(", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
Handle the session data passed by the prior view.
[ "Handle", "the", "session", "data", "passed", "by", "the", "prior", "view", "." ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/private_lessons/views.py#L308-L327
django-danceschool/django-danceschool
danceschool/private_lessons/views.py
PrivateLessonStudentInfoView.get_form_kwargs
def get_form_kwargs(self, **kwargs): ''' Pass along the request data to the form ''' kwargs = super(PrivateLessonStudentInfoView, self).get_form_kwargs(**kwargs) kwargs['request'] = self.request kwargs['payAtDoor'] = self.payAtDoor return kwargs
python
def get_form_kwargs(self, **kwargs): kwargs = super(PrivateLessonStudentInfoView, self).get_form_kwargs(**kwargs) kwargs['request'] = self.request kwargs['payAtDoor'] = self.payAtDoor return kwargs
[ "def", "get_form_kwargs", "(", "self", ",", "*", "*", "kwargs", ")", ":", "kwargs", "=", "super", "(", "PrivateLessonStudentInfoView", ",", "self", ")", ".", "get_form_kwargs", "(", "*", "*", "kwargs", ")", "kwargs", "[", "'request'", "]", "=", "self", ".", "request", "kwargs", "[", "'payAtDoor'", "]", "=", "self", ".", "payAtDoor", "return", "kwargs" ]
Pass along the request data to the form
[ "Pass", "along", "the", "request", "data", "to", "the", "form" ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/private_lessons/views.py#L337-L342
django-danceschool/django-danceschool
danceschool/financial/ajax.py
updateEventRegistrations
def updateEventRegistrations(request): ''' This function handles the filtering of available eventregistration-related invoice items and is used on the revenue reporting form. ''' if not (request.method == 'POST' and request.POST.get('event')): return JsonResponse({}) invoiceItems = InvoiceItem.objects.filter(**{'finalEventRegistration__event__id': request.POST.get('event')}) outRegs = {} for option in invoiceItems: outRegs[str(option.id)] = option.__str__() return JsonResponse({ 'id_invoiceItem': outRegs, })
python
def updateEventRegistrations(request): if not (request.method == 'POST' and request.POST.get('event')): return JsonResponse({}) invoiceItems = InvoiceItem.objects.filter(**{'finalEventRegistration__event__id': request.POST.get('event')}) outRegs = {} for option in invoiceItems: outRegs[str(option.id)] = option.__str__() return JsonResponse({ 'id_invoiceItem': outRegs, })
[ "def", "updateEventRegistrations", "(", "request", ")", ":", "if", "not", "(", "request", ".", "method", "==", "'POST'", "and", "request", ".", "POST", ".", "get", "(", "'event'", ")", ")", ":", "return", "JsonResponse", "(", "{", "}", ")", "invoiceItems", "=", "InvoiceItem", ".", "objects", ".", "filter", "(", "*", "*", "{", "'finalEventRegistration__event__id'", ":", "request", ".", "POST", ".", "get", "(", "'event'", ")", "}", ")", "outRegs", "=", "{", "}", "for", "option", "in", "invoiceItems", ":", "outRegs", "[", "str", "(", "option", ".", "id", ")", "]", "=", "option", ".", "__str__", "(", ")", "return", "JsonResponse", "(", "{", "'id_invoiceItem'", ":", "outRegs", ",", "}", ")" ]
This function handles the filtering of available eventregistration-related invoice items and is used on the revenue reporting form.
[ "This", "function", "handles", "the", "filtering", "of", "available", "eventregistration", "-", "related", "invoice", "items", "and", "is", "used", "on", "the", "revenue", "reporting", "form", "." ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/financial/ajax.py#L5-L21
django-danceschool/django-danceschool
danceschool/guestlist/views.py
GuestListView.get_object
def get_object(self, queryset=None): ''' Get the guest list from the URL ''' return get_object_or_404( GuestList.objects.filter(id=self.kwargs.get('guestlist_id')))
python
def get_object(self, queryset=None): return get_object_or_404( GuestList.objects.filter(id=self.kwargs.get('guestlist_id')))
[ "def", "get_object", "(", "self", ",", "queryset", "=", "None", ")", ":", "return", "get_object_or_404", "(", "GuestList", ".", "objects", ".", "filter", "(", "id", "=", "self", ".", "kwargs", ".", "get", "(", "'guestlist_id'", ")", ")", ")" ]
Get the guest list from the URL
[ "Get", "the", "guest", "list", "from", "the", "URL" ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/guestlist/views.py#L18-L21
django-danceschool/django-danceschool
danceschool/guestlist/views.py
GuestListView.get_context_data
def get_context_data(self,**kwargs): ''' Add the list of names for the given guest list ''' event = Event.objects.filter(id=self.kwargs.get('event_id')).first() if self.kwargs.get('event_id') and not self.object.appliesToEvent(event): raise Http404(_('Invalid event.')) # Use the most current event if nothing has been specified. if not event: event = self.object.currentEvent context = { 'guestList': self.object, 'event': event, 'names': self.object.getListForEvent(event), } context.update(kwargs) return super(GuestListView,self).get_context_data(**context)
python
def get_context_data(self,**kwargs): event = Event.objects.filter(id=self.kwargs.get('event_id')).first() if self.kwargs.get('event_id') and not self.object.appliesToEvent(event): raise Http404(_('Invalid event.')) if not event: event = self.object.currentEvent context = { 'guestList': self.object, 'event': event, 'names': self.object.getListForEvent(event), } context.update(kwargs) return super(GuestListView,self).get_context_data(**context)
[ "def", "get_context_data", "(", "self", ",", "*", "*", "kwargs", ")", ":", "event", "=", "Event", ".", "objects", ".", "filter", "(", "id", "=", "self", ".", "kwargs", ".", "get", "(", "'event_id'", ")", ")", ".", "first", "(", ")", "if", "self", ".", "kwargs", ".", "get", "(", "'event_id'", ")", "and", "not", "self", ".", "object", ".", "appliesToEvent", "(", "event", ")", ":", "raise", "Http404", "(", "_", "(", "'Invalid event.'", ")", ")", "# Use the most current event if nothing has been specified.\r", "if", "not", "event", ":", "event", "=", "self", ".", "object", ".", "currentEvent", "context", "=", "{", "'guestList'", ":", "self", ".", "object", ",", "'event'", ":", "event", ",", "'names'", ":", "self", ".", "object", ".", "getListForEvent", "(", "event", ")", ",", "}", "context", ".", "update", "(", "kwargs", ")", "return", "super", "(", "GuestListView", ",", "self", ")", ".", "get_context_data", "(", "*", "*", "context", ")" ]
Add the list of names for the given guest list
[ "Add", "the", "list", "of", "names", "for", "the", "given", "guest", "list" ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/guestlist/views.py#L23-L39
django-danceschool/django-danceschool
danceschool/private_lessons/models.py
PrivateLessonEvent.getBasePrice
def getBasePrice(self,**kwargs): ''' This method overrides the method of the base Event class by checking the pricingTier associated with this PrivateLessonEvent and getting the appropriate price for it. ''' if not self.pricingTier: return None return self.pricingTier.getBasePrice(**kwargs) * max(self.numSlots,1)
python
def getBasePrice(self,**kwargs): if not self.pricingTier: return None return self.pricingTier.getBasePrice(**kwargs) * max(self.numSlots,1)
[ "def", "getBasePrice", "(", "self", ",", "*", "*", "kwargs", ")", ":", "if", "not", "self", ".", "pricingTier", ":", "return", "None", "return", "self", ".", "pricingTier", ".", "getBasePrice", "(", "*", "*", "kwargs", ")", "*", "max", "(", "self", ".", "numSlots", ",", "1", ")" ]
This method overrides the method of the base Event class by checking the pricingTier associated with this PrivateLessonEvent and getting the appropriate price for it.
[ "This", "method", "overrides", "the", "method", "of", "the", "base", "Event", "class", "by", "checking", "the", "pricingTier", "associated", "with", "this", "PrivateLessonEvent", "and", "getting", "the", "appropriate", "price", "for", "it", "." ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/private_lessons/models.py#L48-L56
django-danceschool/django-danceschool
danceschool/private_lessons/models.py
PrivateLessonEvent.customers
def customers(self): ''' List both any individuals signed up via the registration and payment system, and any individuals signed up without payment. ''' return Customer.objects.filter( Q(privatelessoncustomer__lesson=self) | Q(registration__eventregistration__event=self) ).distinct()
python
def customers(self): return Customer.objects.filter( Q(privatelessoncustomer__lesson=self) | Q(registration__eventregistration__event=self) ).distinct()
[ "def", "customers", "(", "self", ")", ":", "return", "Customer", ".", "objects", ".", "filter", "(", "Q", "(", "privatelessoncustomer__lesson", "=", "self", ")", "|", "Q", "(", "registration__eventregistration__event", "=", "self", ")", ")", ".", "distinct", "(", ")" ]
List both any individuals signed up via the registration and payment system, and any individuals signed up without payment.
[ "List", "both", "any", "individuals", "signed", "up", "via", "the", "registration", "and", "payment", "system", "and", "any", "individuals", "signed", "up", "without", "payment", "." ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/private_lessons/models.py#L122-L130
django-danceschool/django-danceschool
danceschool/private_lessons/models.py
PrivateLessonEvent.save
def save(self, *args, **kwargs): ''' Set registration status to hidden if it is not specified otherwise ''' if not self.status: self.status == Event.RegStatus.hidden super(PrivateLessonEvent,self).save(*args,**kwargs)
python
def save(self, *args, **kwargs): if not self.status: self.status == Event.RegStatus.hidden super(PrivateLessonEvent,self).save(*args,**kwargs)
[ "def", "save", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "not", "self", ".", "status", ":", "self", ".", "status", "==", "Event", ".", "RegStatus", ".", "hidden", "super", "(", "PrivateLessonEvent", ",", "self", ")", ".", "save", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
Set registration status to hidden if it is not specified otherwise
[ "Set", "registration", "status", "to", "hidden", "if", "it", "is", "not", "specified", "otherwise" ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/private_lessons/models.py#L172-L176
django-danceschool/django-danceschool
danceschool/private_lessons/models.py
InstructorAvailabilitySlot.availableDurations
def availableDurations(self): ''' A lesson can always be booked for the length of a single slot, but this method checks if multiple slots are available. This method requires that slots are non-overlapping, which needs to be enforced on slot save. ''' potential_slots = InstructorAvailabilitySlot.objects.filter( instructor=self.instructor, location=self.location, room=self.room, pricingTier=self.pricingTier, startTime__gte=self.startTime, startTime__lte=self.startTime + timedelta(minutes=getConstant('privateLessons__maximumLessonLength')), ).exclude(id=self.id).order_by('startTime') duration_list = [self.duration,] last_start = self.startTime last_duration = self.duration max_duration = self.duration for slot in potential_slots: if max_duration + slot.duration > getConstant('privateLessons__maximumLessonLength'): break if ( slot.startTime == last_start + timedelta(minutes=last_duration) and slot.isAvailable ): duration_list.append(max_duration + slot.duration) last_start = slot.startTime last_duration = slot.duration max_duration += slot.duration return duration_list
python
def availableDurations(self): potential_slots = InstructorAvailabilitySlot.objects.filter( instructor=self.instructor, location=self.location, room=self.room, pricingTier=self.pricingTier, startTime__gte=self.startTime, startTime__lte=self.startTime + timedelta(minutes=getConstant('privateLessons__maximumLessonLength')), ).exclude(id=self.id).order_by('startTime') duration_list = [self.duration,] last_start = self.startTime last_duration = self.duration max_duration = self.duration for slot in potential_slots: if max_duration + slot.duration > getConstant('privateLessons__maximumLessonLength'): break if ( slot.startTime == last_start + timedelta(minutes=last_duration) and slot.isAvailable ): duration_list.append(max_duration + slot.duration) last_start = slot.startTime last_duration = slot.duration max_duration += slot.duration return duration_list
[ "def", "availableDurations", "(", "self", ")", ":", "potential_slots", "=", "InstructorAvailabilitySlot", ".", "objects", ".", "filter", "(", "instructor", "=", "self", ".", "instructor", ",", "location", "=", "self", ".", "location", ",", "room", "=", "self", ".", "room", ",", "pricingTier", "=", "self", ".", "pricingTier", ",", "startTime__gte", "=", "self", ".", "startTime", ",", "startTime__lte", "=", "self", ".", "startTime", "+", "timedelta", "(", "minutes", "=", "getConstant", "(", "'privateLessons__maximumLessonLength'", ")", ")", ",", ")", ".", "exclude", "(", "id", "=", "self", ".", "id", ")", ".", "order_by", "(", "'startTime'", ")", "duration_list", "=", "[", "self", ".", "duration", ",", "]", "last_start", "=", "self", ".", "startTime", "last_duration", "=", "self", ".", "duration", "max_duration", "=", "self", ".", "duration", "for", "slot", "in", "potential_slots", ":", "if", "max_duration", "+", "slot", ".", "duration", ">", "getConstant", "(", "'privateLessons__maximumLessonLength'", ")", ":", "break", "if", "(", "slot", ".", "startTime", "==", "last_start", "+", "timedelta", "(", "minutes", "=", "last_duration", ")", "and", "slot", ".", "isAvailable", ")", ":", "duration_list", ".", "append", "(", "max_duration", "+", "slot", ".", "duration", ")", "last_start", "=", "slot", ".", "startTime", "last_duration", "=", "slot", ".", "duration", "max_duration", "+=", "slot", ".", "duration", "return", "duration_list" ]
A lesson can always be booked for the length of a single slot, but this method checks if multiple slots are available. This method requires that slots are non-overlapping, which needs to be enforced on slot save.
[ "A", "lesson", "can", "always", "be", "booked", "for", "the", "length", "of", "a", "single", "slot", "but", "this", "method", "checks", "if", "multiple", "slots", "are", "available", ".", "This", "method", "requires", "that", "slots", "are", "non", "-", "overlapping", "which", "needs", "to", "be", "enforced", "on", "slot", "save", "." ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/private_lessons/models.py#L252-L284
django-danceschool/django-danceschool
danceschool/private_lessons/models.py
InstructorAvailabilitySlot.availableRoles
def availableRoles(self): ''' Some instructors only offer private lessons for certain roles, so we should only allow booking for the roles that have been selected for the instructor. ''' if not hasattr(self.instructor,'instructorprivatelessondetails'): return [] return [ [x.id,x.name] for x in self.instructor.instructorprivatelessondetails.roles.all() ]
python
def availableRoles(self): if not hasattr(self.instructor,'instructorprivatelessondetails'): return [] return [ [x.id,x.name] for x in self.instructor.instructorprivatelessondetails.roles.all() ]
[ "def", "availableRoles", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ".", "instructor", ",", "'instructorprivatelessondetails'", ")", ":", "return", "[", "]", "return", "[", "[", "x", ".", "id", ",", "x", ".", "name", "]", "for", "x", "in", "self", ".", "instructor", ".", "instructorprivatelessondetails", ".", "roles", ".", "all", "(", ")", "]" ]
Some instructors only offer private lessons for certain roles, so we should only allow booking for the roles that have been selected for the instructor.
[ "Some", "instructors", "only", "offer", "private", "lessons", "for", "certain", "roles", "so", "we", "should", "only", "allow", "booking", "for", "the", "roles", "that", "have", "been", "selected", "for", "the", "instructor", "." ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/private_lessons/models.py#L287-L297
django-danceschool/django-danceschool
danceschool/private_lessons/models.py
InstructorAvailabilitySlot.checkIfAvailable
def checkIfAvailable(self, dateTime=timezone.now()): ''' Available slots are available, but also tentative slots that have been held as tentative past their expiration date ''' return ( self.startTime >= dateTime + timedelta(days=getConstant('privateLessons__closeBookingDays')) and self.startTime <= dateTime + timedelta(days=getConstant('privateLessons__openBookingDays')) and not self.eventRegistration and ( self.status == self.SlotStatus.available or ( self.status == self.SlotStatus.tentative and getattr(getattr(self.temporaryEventRegistration,'registration',None),'expirationDate',timezone.now()) <= timezone.now() ) ) )
python
def checkIfAvailable(self, dateTime=timezone.now()): return ( self.startTime >= dateTime + timedelta(days=getConstant('privateLessons__closeBookingDays')) and self.startTime <= dateTime + timedelta(days=getConstant('privateLessons__openBookingDays')) and not self.eventRegistration and ( self.status == self.SlotStatus.available or ( self.status == self.SlotStatus.tentative and getattr(getattr(self.temporaryEventRegistration,'registration',None),'expirationDate',timezone.now()) <= timezone.now() ) ) )
[ "def", "checkIfAvailable", "(", "self", ",", "dateTime", "=", "timezone", ".", "now", "(", ")", ")", ":", "return", "(", "self", ".", "startTime", ">=", "dateTime", "+", "timedelta", "(", "days", "=", "getConstant", "(", "'privateLessons__closeBookingDays'", ")", ")", "and", "self", ".", "startTime", "<=", "dateTime", "+", "timedelta", "(", "days", "=", "getConstant", "(", "'privateLessons__openBookingDays'", ")", ")", "and", "not", "self", ".", "eventRegistration", "and", "(", "self", ".", "status", "==", "self", ".", "SlotStatus", ".", "available", "or", "(", "self", ".", "status", "==", "self", ".", "SlotStatus", ".", "tentative", "and", "getattr", "(", "getattr", "(", "self", ".", "temporaryEventRegistration", ",", "'registration'", ",", "None", ")", ",", "'expirationDate'", ",", "timezone", ".", "now", "(", ")", ")", "<=", "timezone", ".", "now", "(", ")", ")", ")", ")" ]
Available slots are available, but also tentative slots that have been held as tentative past their expiration date
[ "Available", "slots", "are", "available", "but", "also", "tentative", "slots", "that", "have", "been", "held", "as", "tentative", "past", "their", "expiration", "date" ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/private_lessons/models.py#L299-L313
django-danceschool/django-danceschool
danceschool/stats/cms_plugins.py
StatsGraphPlugin.render
def render(self, context, instance, placeholder): ''' Allows this plugin to use templates designed for a list of locations. ''' context = super(StatsGraphPlugin,self).render(context,instance,placeholder) # Javascript makes it difficult to calculate date/time differences, so instead # pass the most useful ones to the template context in a dictionary. These are used # to show stats over different time ranges. limitMonthDates = {} for m in range(0,25): limitMonthDates[m] = (timezone.now() - relativedelta(months=m)).strftime('%Y-%m-%d') # The same for graphs that allow one to choose different years. recentYears = [timezone.now().year + x for x in range(-5,1)] series_by_year = Series.objects.order_by('year') if series_by_year.count() > 0: first_year = series_by_year.first().year allYears = [x for x in range(first_year,timezone.now().year + 1)] else: allYears = [] context.update({ 'limitMonthDates': limitMonthDates, 'recentYears': recentYears, 'allYears': allYears, }) return context
python
def render(self, context, instance, placeholder): context = super(StatsGraphPlugin,self).render(context,instance,placeholder) limitMonthDates = {} for m in range(0,25): limitMonthDates[m] = (timezone.now() - relativedelta(months=m)).strftime('%Y-%m-%d') recentYears = [timezone.now().year + x for x in range(-5,1)] series_by_year = Series.objects.order_by('year') if series_by_year.count() > 0: first_year = series_by_year.first().year allYears = [x for x in range(first_year,timezone.now().year + 1)] else: allYears = [] context.update({ 'limitMonthDates': limitMonthDates, 'recentYears': recentYears, 'allYears': allYears, }) return context
[ "def", "render", "(", "self", ",", "context", ",", "instance", ",", "placeholder", ")", ":", "context", "=", "super", "(", "StatsGraphPlugin", ",", "self", ")", ".", "render", "(", "context", ",", "instance", ",", "placeholder", ")", "# Javascript makes it difficult to calculate date/time differences, so instead\r", "# pass the most useful ones to the template context in a dictionary. These are used\r", "# to show stats over different time ranges.\r", "limitMonthDates", "=", "{", "}", "for", "m", "in", "range", "(", "0", ",", "25", ")", ":", "limitMonthDates", "[", "m", "]", "=", "(", "timezone", ".", "now", "(", ")", "-", "relativedelta", "(", "months", "=", "m", ")", ")", ".", "strftime", "(", "'%Y-%m-%d'", ")", "# The same for graphs that allow one to choose different years.\r", "recentYears", "=", "[", "timezone", ".", "now", "(", ")", ".", "year", "+", "x", "for", "x", "in", "range", "(", "-", "5", ",", "1", ")", "]", "series_by_year", "=", "Series", ".", "objects", ".", "order_by", "(", "'year'", ")", "if", "series_by_year", ".", "count", "(", ")", ">", "0", ":", "first_year", "=", "series_by_year", ".", "first", "(", ")", ".", "year", "allYears", "=", "[", "x", "for", "x", "in", "range", "(", "first_year", ",", "timezone", ".", "now", "(", ")", ".", "year", "+", "1", ")", "]", "else", ":", "allYears", "=", "[", "]", "context", ".", "update", "(", "{", "'limitMonthDates'", ":", "limitMonthDates", ",", "'recentYears'", ":", "recentYears", ",", "'allYears'", ":", "allYears", ",", "}", ")", "return", "context" ]
Allows this plugin to use templates designed for a list of locations.
[ "Allows", "this", "plugin", "to", "use", "templates", "designed", "for", "a", "list", "of", "locations", "." ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/stats/cms_plugins.py#L23-L50
django-danceschool/django-danceschool
danceschool/private_events/feeds.py
json_event_feed
def json_event_feed(request,location_id=None,room_id=None): ''' The Jquery fullcalendar app requires a JSON news feed, so this function creates the feed from upcoming PrivateEvent objects ''' if not getConstant('calendar__privateCalendarFeedEnabled') or not request.user.is_staff: return JsonResponse({}) this_user = request.user startDate = request.GET.get('start','') endDate = request.GET.get('end','') timeZone = request.GET.get('timezone',getattr(settings,'TIME_ZONE','UTC')) time_filter_dict_events = {} if startDate: time_filter_dict_events['startTime__gte'] = ensure_timezone(datetime.strptime(startDate,'%Y-%m-%d')) if endDate: time_filter_dict_events['endTime__lte'] = ensure_timezone(datetime.strptime(endDate,'%Y-%m-%d')) + timedelta(days=1) instructor_groups = list(this_user.groups.all().values_list('id',flat=True)) filters = Q(event__privateevent__isnull=False) & ( Q(event__privateevent__displayToGroup__in=instructor_groups) | Q(event__privateevent__displayToUsers=this_user) | (Q(event__privateevent__displayToGroup__isnull=True) & Q(event__privateevent__displayToUsers__isnull=True)) ) if location_id: filters = filters & Q(event__location__id=location_id) if room_id: filters = filters & Q(event__room_id=room_id) occurrences = EventOccurrence.objects.filter(filters).filter(**time_filter_dict_events).order_by('-startTime') eventlist = [EventFeedItem(x,timeZone=timeZone).__dict__ for x in occurrences] return JsonResponse(eventlist,safe=False)
python
def json_event_feed(request,location_id=None,room_id=None): if not getConstant('calendar__privateCalendarFeedEnabled') or not request.user.is_staff: return JsonResponse({}) this_user = request.user startDate = request.GET.get('start','') endDate = request.GET.get('end','') timeZone = request.GET.get('timezone',getattr(settings,'TIME_ZONE','UTC')) time_filter_dict_events = {} if startDate: time_filter_dict_events['startTime__gte'] = ensure_timezone(datetime.strptime(startDate,'%Y-%m-%d')) if endDate: time_filter_dict_events['endTime__lte'] = ensure_timezone(datetime.strptime(endDate,'%Y-%m-%d')) + timedelta(days=1) instructor_groups = list(this_user.groups.all().values_list('id',flat=True)) filters = Q(event__privateevent__isnull=False) & ( Q(event__privateevent__displayToGroup__in=instructor_groups) | Q(event__privateevent__displayToUsers=this_user) | (Q(event__privateevent__displayToGroup__isnull=True) & Q(event__privateevent__displayToUsers__isnull=True)) ) if location_id: filters = filters & Q(event__location__id=location_id) if room_id: filters = filters & Q(event__room_id=room_id) occurrences = EventOccurrence.objects.filter(filters).filter(**time_filter_dict_events).order_by('-startTime') eventlist = [EventFeedItem(x,timeZone=timeZone).__dict__ for x in occurrences] return JsonResponse(eventlist,safe=False)
[ "def", "json_event_feed", "(", "request", ",", "location_id", "=", "None", ",", "room_id", "=", "None", ")", ":", "if", "not", "getConstant", "(", "'calendar__privateCalendarFeedEnabled'", ")", "or", "not", "request", ".", "user", ".", "is_staff", ":", "return", "JsonResponse", "(", "{", "}", ")", "this_user", "=", "request", ".", "user", "startDate", "=", "request", ".", "GET", ".", "get", "(", "'start'", ",", "''", ")", "endDate", "=", "request", ".", "GET", ".", "get", "(", "'end'", ",", "''", ")", "timeZone", "=", "request", ".", "GET", ".", "get", "(", "'timezone'", ",", "getattr", "(", "settings", ",", "'TIME_ZONE'", ",", "'UTC'", ")", ")", "time_filter_dict_events", "=", "{", "}", "if", "startDate", ":", "time_filter_dict_events", "[", "'startTime__gte'", "]", "=", "ensure_timezone", "(", "datetime", ".", "strptime", "(", "startDate", ",", "'%Y-%m-%d'", ")", ")", "if", "endDate", ":", "time_filter_dict_events", "[", "'endTime__lte'", "]", "=", "ensure_timezone", "(", "datetime", ".", "strptime", "(", "endDate", ",", "'%Y-%m-%d'", ")", ")", "+", "timedelta", "(", "days", "=", "1", ")", "instructor_groups", "=", "list", "(", "this_user", ".", "groups", ".", "all", "(", ")", ".", "values_list", "(", "'id'", ",", "flat", "=", "True", ")", ")", "filters", "=", "Q", "(", "event__privateevent__isnull", "=", "False", ")", "&", "(", "Q", "(", "event__privateevent__displayToGroup__in", "=", "instructor_groups", ")", "|", "Q", "(", "event__privateevent__displayToUsers", "=", "this_user", ")", "|", "(", "Q", "(", "event__privateevent__displayToGroup__isnull", "=", "True", ")", "&", "Q", "(", "event__privateevent__displayToUsers__isnull", "=", "True", ")", ")", ")", "if", "location_id", ":", "filters", "=", "filters", "&", "Q", "(", "event__location__id", "=", "location_id", ")", "if", "room_id", ":", "filters", "=", "filters", "&", "Q", "(", "event__room_id", "=", "room_id", ")", "occurrences", "=", "EventOccurrence", ".", "objects", ".", "filter", "(", "filters", ")", ".", "filter", "(", "*", "*", "time_filter_dict_events", ")", ".", "order_by", "(", "'-startTime'", ")", "eventlist", "=", "[", "EventFeedItem", "(", "x", ",", "timeZone", "=", "timeZone", ")", ".", "__dict__", "for", "x", "in", "occurrences", "]", "return", "JsonResponse", "(", "eventlist", ",", "safe", "=", "False", ")" ]
The Jquery fullcalendar app requires a JSON news feed, so this function creates the feed from upcoming PrivateEvent objects
[ "The", "Jquery", "fullcalendar", "app", "requires", "a", "JSON", "news", "feed", "so", "this", "function", "creates", "the", "feed", "from", "upcoming", "PrivateEvent", "objects" ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/private_events/feeds.py#L122-L159
django-danceschool/django-danceschool
danceschool/core/cms_plugins.py
LocationListPlugin.render
def render(self, context, instance, placeholder): ''' Allows this plugin to use templates designed for a list of locations. ''' context = super(LocationListPlugin,self).render(context,instance,placeholder) context['location_list'] = Location.objects.filter(status=Location.StatusChoices.active) return context
python
def render(self, context, instance, placeholder): context = super(LocationListPlugin,self).render(context,instance,placeholder) context['location_list'] = Location.objects.filter(status=Location.StatusChoices.active) return context
[ "def", "render", "(", "self", ",", "context", ",", "instance", ",", "placeholder", ")", ":", "context", "=", "super", "(", "LocationListPlugin", ",", "self", ")", ".", "render", "(", "context", ",", "instance", ",", "placeholder", ")", "context", "[", "'location_list'", "]", "=", "Location", ".", "objects", ".", "filter", "(", "status", "=", "Location", ".", "StatusChoices", ".", "active", ")", "return", "context" ]
Allows this plugin to use templates designed for a list of locations.
[ "Allows", "this", "plugin", "to", "use", "templates", "designed", "for", "a", "list", "of", "locations", "." ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/core/cms_plugins.py#L71-L75
django-danceschool/django-danceschool
danceschool/core/cms_plugins.py
LocationPlugin.render
def render(self, context, instance, placeholder): ''' Allows this plugin to use templates designed for a list of locations. ''' context = super(LocationPlugin,self).render(context,instance,placeholder) context['location_list'] = [instance.location,] return context
python
def render(self, context, instance, placeholder): context = super(LocationPlugin,self).render(context,instance,placeholder) context['location_list'] = [instance.location,] return context
[ "def", "render", "(", "self", ",", "context", ",", "instance", ",", "placeholder", ")", ":", "context", "=", "super", "(", "LocationPlugin", ",", "self", ")", ".", "render", "(", "context", ",", "instance", ",", "placeholder", ")", "context", "[", "'location_list'", "]", "=", "[", "instance", ".", "location", ",", "]", "return", "context" ]
Allows this plugin to use templates designed for a list of locations.
[ "Allows", "this", "plugin", "to", "use", "templates", "designed", "for", "a", "list", "of", "locations", "." ]
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/core/cms_plugins.py#L85-L89