Search is not available for this dataset
text
stringlengths
75
104k
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)
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...
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')), ...
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: ...
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(...
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 HttpResp...
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 authentic...
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...
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...
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, the...
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 ...
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') ...
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('r...
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 ...
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 t...
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__aut...
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 = ge...
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 pr...
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, ...
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('...
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
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'] sendReminderGrou...
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, TypeErro...
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_t...
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 r...
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,'STR...
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 elem...
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_...
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: ...
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 ...
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): r...
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 ge...
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 = get...
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 '', o...
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 T...
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 mod...
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',or...
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...
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 p...
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({ ...
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 ...
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()} ...
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 = allE...
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 = Tempor...
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"] ...
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 ...
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
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 ne...
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 an...
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...
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': firstNam...
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', {}) ...
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: ...
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 (...
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...
def ruleName(self): ''' This should be overridden for child classes ''' return '%s %s' % (self.rentalRate, self.RateRuleChoices.values.get(self.applyRateRule,self.applyRateRule))
def ruleName(self): ''' overrides from parent class ''' return _('%s at %s' % (self.room.name, self.room.location.name))
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 repeat...
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 approv...
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)
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 r...
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 ...
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...
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 =...
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) ...
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...
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 valu...
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)
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...
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)
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)
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 Obje...
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. ''' ...
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.choic...
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...
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': ...
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_prior...
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 (...
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. ''' fee...
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_...
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...
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 ...
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 = fo...
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__...
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 r...
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...
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
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({}) invoiceItem...
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')))
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.')) ...
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 ...
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__eventregistrati...
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)
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 = In...
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 [] ...
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__closeBook...
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 ...
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: ret...
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...
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