class CorporateMembershipTypeForm(forms.ModelForm): description = forms.CharField(label=_('Description'), max_length=500, required=False, widget=forms.Textarea(attrs={'rows': '3'})) price = PriceField(decimal_places=2, help_text=_("Set 0 for free membership.")) renewal_price = PriceField(decimal_places=2, required=False, help_text=_("Set 0 for free membership.")) above_cap_price = PriceField( decimal_places=2, help_text=_("Price for members who join above cap.")) status_detail = forms.ChoiceField(choices=( ('active', _('Active')), ('inactive', _('Inactive')), ('admin hold', _('Admin Hold')), )) class Meta: model = CorporateMembershipType fields = ( 'name', 'price', 'renewal_price', 'membership_type', 'apply_cap', 'membership_cap', 'allow_above_cap', 'above_cap_price', 'description', 'admin_only', 'number_passes', 'position', 'status_detail', )
class MarkAsPaidForm(forms.ModelForm): amount = PriceField( label=_('Amount'), initial=0.0, min_value=0, ) payment_method = forms.CharField( label=_('payment method'), max_length=20, widget=forms.Select(choices=PAYMENT_METHODS)) submit_dt = SplitDateTimeField( label=_('Submit Date and Time'), initial=datetime.now()) class Meta: model = Payment fields = ( 'amount', 'payment_method', 'submit_dt', ) def save(self, user, invoice, *args, **kwargs): """ Save payment, bind invoice instance. Set payment fields (e.g. name, description) """ instance = super(MarkAsPaidForm, self).save(*args, **kwargs) instance.method = self.cleaned_data['payment_method'] instance.invoice = invoice instance.first_name = invoice.bill_to_first_name instance.last_name = invoice.bill_to_last_name instance.email = invoice.bill_to_email instance.status_detail = 'approved' instance.creator = user instance.creator_username = user.username instance.owner = user instance.owner_username = user.username instance.save() invoice_object = invoice.get_object() if invoice_object: if hasattr(invoice_object, 'get_payment_description'): instance.description = invoice_object.get_payment_description(invoice) if not instance.description: instance.description = 'Invoice {} for {}({})'.format( instance.pk, invoice_object, invoice_object.pk) return instance
class DirectoryPricingForm(forms.ModelForm): status = forms.ChoiceField(initial=1, choices=STATUS_CHOICES, required=False) regular_price = PriceField(max_digits=15, decimal_places=2, initial=0, required=False) premium_price = PriceField(max_digits=15, decimal_places=2, initial=0, required=False) regular_price_member = PriceField(max_digits=15, decimal_places=2, initial=0, required=False) premium_price_member = PriceField(max_digits=15, decimal_places=2, initial=0, required=False) class Meta: model = DirectoryPricing fields = ( 'duration', 'regular_price', 'premium_price', 'regular_price_member', 'premium_price_member', 'show_member_pricing', 'status', ) def __init__(self, *args, **kwargs): user = kwargs.pop('user', None) super(DirectoryPricingForm, self).__init__(*args, **kwargs) if user and user.profile.is_superuser: self.fields['duration'] = forms.ChoiceField( initial=14, choices=ADMIN_DURATION_CHOICES) else: self.fields['duration'] = forms.ChoiceField( initial=14, choices=DURATION_CHOICES)
class CustomMembershipTypeForm(FormControlWidgetMixin, forms.ModelForm): price = PriceField(decimal_places=2, help_text=_("Set 0 for free membership.")) renewal_price = PriceField(decimal_places=2, required=False, help_text=_("Set 0 for free membership.")) class Meta: model = ChapterMembershipType fields = ( 'name', 'price', 'renewal_price', ) def __init__(self, *args, chapter, **kwargs): self.chapter = chapter super(CustomMembershipTypeForm, self).__init__(*args, **kwargs) self.fields['name'].label = _('Membership Type') [self.ctype] = self.chapter.customizedtype_set.filter( membership_type__id=self.instance.id)[:1] or [None] if self.ctype: # override with the value in CustomizedAppField (saved previously, if any) self.initial['price'] = self.ctype.price self.initial['renewal_price'] = self.ctype.renewal_price # set membership type name as readyonly as chapter leaders should not change it readonly_fields = [ 'name', ] for field in readonly_fields: self.fields[field].widget.attrs['readonly'] = True def save(self, commit=True): if not self.ctype: self.ctype = CustomizedType(membership_type=self.instance, chapter=self.chapter) self.ctype.price = self.cleaned_data['price'] self.ctype.renewal_price = self.cleaned_data['renewal_price'] self.ctype.save() return self.ctype
class JobPricingForm(forms.ModelForm): duration = forms.ChoiceField(initial=14, choices=DURATION_CHOICES) status = forms.ChoiceField(initial=1, choices=STATUS_CHOICES, required=False) regular_price = PriceField(max_digits=15, decimal_places=2, initial=0, required=False) premium_price = PriceField(max_digits=15, decimal_places=2, initial=0, required=False) regular_price_member = PriceField(max_digits=15, decimal_places=2, initial=0, required=False) premium_price_member = PriceField(max_digits=15, decimal_places=2, initial=0, required=False) class Meta: model = JobPricing fields = ( 'title', 'duration', 'regular_price', 'premium_price', 'regular_price_member', 'premium_price_member', 'include_tax', 'tax_rate', 'show_member_pricing', 'status', )
class PricingForm(FormControlWidgetMixin, forms.ModelForm): billing_dt_select = BillingCycleField(label=_('When to bill'), widget=BillingDateSelectWidget, help_text=_('It is used to determine the payment due date for each billing cycle')) billing_cycle = BillingCycleField(label=_('How often to bill'), widget=BillingCycleWidget) price = PriceField(max_digits=10, decimal_places=2, required=False, help_text=_('Leaving this field blank allows visitors to set their own price')) class Meta: model = Pricing fields = ('label', 'price', 'taxable', 'tax_rate', 'billing_cycle', 'billing_dt_select', 'has_trial_period', 'trial_period_days', ) fieldsets = [(_('Form Information'), { 'fields': [ 'label', 'price', 'taxable', 'tax_rate', 'billing_cycle', 'billing_dt_select', ], 'legend': '' }), (_('Trial Period'), { 'fields': [ 'has_trial_period', 'trial_period_days',], 'legend': '', }),] def __init__(self, *args, **kwargs): super(PricingForm, self).__init__(*args, **kwargs) # Setup initial values for billing_cycle and billing_dt_select # in order to have empty values for extra forms. if self.instance.pk: self.fields['billing_dt_select'].initial = [self.instance.num_days, self.instance.due_sore] self.fields['billing_cycle'].initial = [self.instance.billing_frequency, self.instance.billing_period] else: self.fields['billing_dt_select'].initial = [0, u'start'] self.fields['billing_cycle'].initial = [1, u'month'] # Add class for recurring payment fields recurring_payment_fields = [ 'taxable', 'tax_rate', 'billing_cycle', 'billing_dt_select', 'has_trial_period', 'trial_period_days' ] for field in recurring_payment_fields: class_attr = self.fields[field].widget.attrs.get('class', None) if class_attr and 'recurring-payment' not in class_attr: class_attr += ' recurring-payment' self.fields[field].widget.attrs.update({'class': class_attr}) def save(self, **kwargs): pricing = super(PricingForm, self).save(**kwargs) if self.cleaned_data.get('billing_dt_select'): dt_select = self.cleaned_data.get('billing_dt_select').split(',') pricing.num_days = dt_select[0] pricing.due_sore = dt_select[1] if self.cleaned_data.get('billing_cycle'): cycle = self.cleaned_data.get('billing_cycle').split(',') pricing.billing_frequency = cycle[0] pricing.billing_period = cycle[1] #pricing.save() return pricing
class DiscountForm(TendenciBaseForm): value = PriceField( label=_('Discount Value'), max_digits=10, decimal_places=2, help_text=_('Enter discount value as a positive number.')) class Meta: model = Discount fields = ( 'discount_code', 'value', 'start_dt', 'end_dt', 'never_expires', 'cap', 'apps', 'allow_anonymous_view', 'user_perms', 'group_perms', 'status_detail', ) fieldsets = [(_('Discount Information'), { 'fields': [ 'discount_code', 'value', 'cap', 'never_expires', 'apps', 'start_dt', 'end_dt', ], 'legend': '' }), (_('Permissions'), { 'fields': [ 'allow_anonymous_view', 'user_perms', 'member_perms', 'group_perms', ], 'classes': ['permissions'], }), (_('Administrator Only'), { 'fields': ['status_detail'], 'classes': ['admin-only'], })] start_dt = forms.SplitDateTimeField(label=_('Start Date/Time'), initial=datetime.now()) end_dt = forms.SplitDateTimeField(label=_('End Date/Time'), initial=END_DT_INITIAL) status_detail = forms.ChoiceField(choices=( ('active', _('Active')), ('inactive', _('Inactive')), ('pending', _('Pending')), )) def __init__(self, *args, **kwargs): super(DiscountForm, self).__init__(*args, **kwargs) if self.user and not self.user.profile.is_superuser: if 'status_detail' in self.fields: self.fields.pop('status_detail') MODELS_WITH_DISCOUNT = ['registrationconfiguration', 'membershipset'] content_types = ContentType.objects.filter( model__in=MODELS_WITH_DISCOUNT) if 'apps' in self.fields: self.fields['apps'].choices = ((c.id, c.app_label) for c in content_types) def clean_discount_code(self): data = self.cleaned_data['discount_code'] try: discount = Discount.objects.get(discount_code=data) except Discount.DoesNotExist: return data if not discount == self.instance: raise forms.ValidationError( _('There a discount for this code already exists.')) return data def clean(self): cleaned_data = self.cleaned_data start_dt = cleaned_data.get("start_dt") end_dt = cleaned_data.get("end_dt") if start_dt > end_dt: errors = self._errors.setdefault("end_dt", ErrorList()) errors.append(_(u"This cannot be earlier than the start date.")) # Always return the full collection of cleaned data. return cleaned_data
class MakePaymentForm(forms.ModelForm): captcha = CaptchaField(label=_('Type the code below')) # TODO: Make check-paid an admin only option payment_amount = PriceField(max_digits=10, decimal_places=2) payment_method = forms.CharField( widget=forms.RadioSelect(choices=(('cc', _('Make Online Payment')), )), initial='cc', ) company = forms.CharField(max_length=50, required=False, widget=forms.TextInput(attrs={'size': '30'})) address = forms.CharField(max_length=100, required=False, widget=forms.TextInput(attrs={'size': '35'})) state = forms.CharField(max_length=50, required=False, widget=forms.TextInput(attrs={'size': '5'})) zip_code = forms.CharField(max_length=20, required=False, widget=forms.TextInput(attrs={'size': '10'})) reference_number = forms.CharField( max_length=20, required=False, widget=forms.TextInput(attrs={'size': '15'})) referral_source = forms.CharField( max_length=200, required=False, widget=forms.TextInput(attrs={'size': '40'})) email = EmailVerificationField( label=_("Email"), help_text=_('A valid e-mail address, please.')) email_receipt = forms.BooleanField(initial=True) country = forms.ChoiceField(label=_('Country'), choices=(('', '-----------'), ) + tuple(COUNTRIES)) class Meta: model = MakePayment fields = ( 'payment_amount', 'payment_method', 'first_name', 'last_name', 'company', 'address', 'address2', 'city', 'state', 'zip_code', 'country', 'phone', 'email', 'email_receipt', 'reference_number', 'referral_source', 'comments', 'captcha', ) def __init__(self, user, *args, **kwargs): super(MakePaymentForm, self).__init__(*args, **kwargs) self.initial['country'] = get_setting('site', 'global', 'defaultcountry') self.fields['reference_number'].label = get_setting( 'module', 'make_payment', 'referencenumberlabel') or _('Reference #') # populate the user fields if user and user.id: if 'captcha' in self.fields: self.fields.pop('captcha') self.fields['first_name'].initial = user.first_name self.fields['last_name'].initial = user.last_name self.fields['email'].initial = user.email try: profile = user.profile if profile: self.fields['company'].initial = profile.company self.fields['address'].initial = profile.address self.fields['address2'].initial = profile.address2 self.fields['city'].initial = profile.city self.fields['state'].initial = profile.state self.fields['zip_code'].initial = profile.zipcode self.fields['country'].initial = profile.country self.fields['phone'].initial = profile.phone except: pass
class RecurringPaymentForm(forms.ModelForm): #status_detail = forms.ChoiceField(choices=(('inactive','Inactive'),('active','Active')), # initial='active') payment_amount = PriceField(decimal_places=2) trial_amount = PriceField(decimal_places=2, required=False) billing_dt_select = BillingCycleField( label=_('When to bill'), widget=BillingDateSelectWidget, help_text= _('It is used to determine the payment due date for each billing cycle' )) billing_cycle = BillingCycleField(label=_('How often to bill'), widget=BillingCycleWidget) class Meta: model = RecurringPayment fields = ( 'user', 'url', 'description', 'payment_amount', 'taxable', 'tax_rate', 'billing_start_dt', 'billing_cycle', 'billing_dt_select', 'has_trial_period', 'trial_period_start_dt', 'trial_period_end_dt', 'trial_amount', 'status', 'status_detail', ) def __init__(self, *args, **kwargs): super(RecurringPaymentForm, self).__init__(*args, **kwargs) # billing_cycle if self.instance.pk: initial_list = [ str(self.instance.billing_frequency), str(self.instance.billing_period) ] else: initial_list = ['1', 'month'] self.fields['billing_cycle'].initial = initial_list # billing_dt_select if self.instance.pk: initial_list = [ str(self.instance.num_days), str(self.instance.due_sore) ] else: initial_list = ['0', 'start'] self.fields['billing_dt_select'].initial = initial_list self.fields['user'].choices = [ (u.id, '%s %s (%s) - %s' % (u.first_name, u.last_name, u.username, u.email)) for u in User.objects.filter( is_active=1).order_by('first_name', 'last_name') ] self.fields['user'].help_text = """If not found in the list, <a href="%s">create a new user</a> before proceeding """ % reverse('profile.add') def clean_billing_cycle(self): value = self.cleaned_data['billing_cycle'] data_list = value.split(',') d = dict(zip(['billing_frequency', 'billing_period'], data_list)) try: d['billing_frequency'] = int(d['billing_frequency']) except: raise forms.ValidationError( _("Billing frequency must be a numeric number.")) return value def clean_billing_dt_select(self): value = self.cleaned_data['billing_dt_select'] data_list = value.split(',') d = dict(zip(['num_days', 'due_sore'], data_list)) try: d['num_days'] = int(d['num_days']) except: raise forms.ValidationError( _("Number day(s) must be a numeric number.")) return value def clean_tax_rate(self): value = self.cleaned_data['tax_rate'] taxable = self.cleaned_data['taxable'] if taxable: if not value: raise forms.ValidationError(_("Please specify a tax rate.")) if value > 1: raise forms.ValidationError( _("Tax rate should be less than 1.")) return value
class ChapterMembershipTypeForm(TendenciBaseForm): type_exp_method = TypeExpMethodField(label=_('Period Type')) description = forms.CharField(label=_('Notes'), max_length=500, required=False, widget=forms.Textarea(attrs={'rows': '3'})) price = PriceField(decimal_places=2, help_text=_("Set 0 for free membership.")) renewal_price = PriceField(decimal_places=2, required=False, help_text=_("Set 0 for free membership.")) status_detail = forms.ChoiceField(choices=(('active', _('Active')), ('inactive', _('Inactive')))) class Meta: model = ChapterMembershipType fields = ( #'app', 'name', 'price', 'description', 'type_exp_method', 'renewal_price', 'allow_renewal', 'renewal', 'never_expires', 'require_approval', 'require_payment_approval', 'admin_only', 'renewal_require_approval', 'renewal_period_start', 'renewal_period_end', 'expiration_grace_period', 'position', 'status', 'status_detail', ) def __init__(self, *args, **kwargs): super(ChapterMembershipTypeForm, self).__init__(*args, **kwargs) self.type_exp_method_fields = type_exp_method_fields initial_list = [] if self.instance.pk: for field in self.type_exp_method_fields: field_value = getattr(self.instance, field) if field == 'fixed_option2_can_rollover' and (not field_value): field_value = '' else: if not field_value: field_value = '' initial_list.append(str(field_value)) self.fields['type_exp_method'].initial = ','.join(initial_list) else: self.fields[ 'type_exp_method'].initial = "rolling,1,years,0,1,0,1,1,0,1,1,,1,1,,1" # a field position dictionary - so we can retrieve data later fields_pos_d = {} for i, field in enumerate(self.type_exp_method_fields): fields_pos_d[field] = (i, type_exp_method_widgets[i]) self.fields['type_exp_method'].widget = TypeExpMethodWidget( attrs={'id': 'type_exp_method'}, fields_pos_d=fields_pos_d) def clean(self): cleaned_data = super(ChapterMembershipTypeForm, self).clean() # Make sure Expiretion Grace Period <= Renewal Period End if 'expiration_grace_period' in self.cleaned_data \ and 'renewal_period_end' in self.cleaned_data: expiration_grace_period = self.cleaned_data[ 'expiration_grace_period'] renewal_period_end = self.cleaned_data['renewal_period_end'] if expiration_grace_period > renewal_period_end: raise forms.ValidationError( _("The Expiration Grace Period should be less than or equal to the Renewal Period End." )) return cleaned_data def clean_expiration_grace_period(self): value = self.cleaned_data['expiration_grace_period'] if value > 100: raise forms.ValidationError( _("This number should be less than 100 (days).")) return value def clean_type_exp_method(self): value = self.cleaned_data['type_exp_method'] # if never expires is checked, no need to check further if self.cleaned_data['never_expires']: return value data_list = value.split(',') d = dict(zip(self.type_exp_method_fields, data_list)) if d['period_type'] == 'rolling': if d['period']: try: d['period'] = int(d['period']) except: raise forms.ValidationError( _("Period must be a numeric number.")) else: raise forms.ValidationError(_("Period is a required field.")) try: d['rolling_option'] = int(d['rolling_option']) except: raise forms.ValidationError( _("Please select a expiration option for join.")) if d['rolling_option'] not in [0, 1]: raise forms.ValidationError( _("Please select a expiration option for join.")) if d['rolling_option'] == 1: try: d['rolling_option1_day'] = int(d['rolling_option1_day']) except: raise forms.ValidationError( _("The day(s) field in option 2 of Expires On must be a numeric number." )) # renew expiration try: d['rolling_renew_option'] = int(d['rolling_renew_option']) except: raise forms.ValidationError( _("Please select a expiration option for renewal.")) if d['rolling_renew_option'] not in [0, 1, 2]: raise forms.ValidationError( _("Please select a expiration option for renewal.")) if d['rolling_renew_option'] == 1: try: d['rolling_renew_option1_day'] = int( d['rolling_renew_option1_day']) except: raise forms.ValidationError( _("The day(s) field in option 2 of Renew Expires On must be a numeric number." )) if d['rolling_renew_option'] == 2: try: d['rolling_renew_option2_day'] = int( d['rolling_renew_option2_day']) except: raise forms.ValidationError( _("The day(s) field in option 3 of Renew Expires On must be a numeric number." )) else: # d['period_type'] == 'fixed' try: d['fixed_option'] = int(d['fixed_option']) except: raise forms.ValidationError( _("Please select an option for fixed period.")) if d['fixed_option'] not in [0, 1]: raise forms.ValidationError( _("Please select an option for fixed period.")) if d['fixed_option'] == 0: try: d['fixed_option1_day'] = int(d['fixed_option1_day']) except: raise forms.ValidationError( _("The day(s) field in the option 1 of Expires On must be a numeric number." )) if d['fixed_option'] == 1: try: d['fixed_option2_day'] = int(d['fixed_option2_day']) except: raise forms.ValidationError( _("The day(s) field in the option 2 of Expires On must be a numeric number." )) if 'fixed_option2_can_rollover' in d: try: d['fixed_option2_rollover_days'] = int( d['fixed_option2_rollover_days']) except: raise forms.ValidationError( _("The grace period day(s) for optoin 2 must be a numeric number." )) return value