예제 #1
0
 def test_form_field_formatting(self):
     iban_form_field = IBANFormField()
     self.assertEqual(iban_form_field.prepare_value('NL02ABNA0123456789'),
                      'NL02 ABNA 0123 4567 89')
     self.assertEqual(
         iban_form_field.prepare_value('NL02 ABNA 0123 4567 89'),
         'NL02 ABNA 0123 4567 89')
     self.assertIsNone(iban_form_field.prepare_value(None))
예제 #2
0
    class NewRefundForm(forms.Form):
        payer = forms.CharField(label=_('Account holder'), )
        iban = IBANFormField(label=_('IBAN'), )
        bic = BICFormField(
            label=_('BIC (optional)'),
            required=False,
        )

        def __init__(self, *args, **kwargs):
            super().__init__(*args, **kwargs)
            for n, f in self.fields.items():
                f.required = False
                f.widget.is_required = False

        def clean_payer(self):
            val = self.cleaned_data.get('payer')
            if not val:
                raise ValidationError(_("This field is required."))
            return val

        def clean_iban(self):
            val = self.cleaned_data.get('iban')
            if not val:
                raise ValidationError(_("This field is required."))
            return val
예제 #3
0
class OrderForm(forms.ModelForm):
    """
    Order form details
    """
    account_iban = IBANFormField(label='Konta numurs (IBAN)')
    swift = BICFormField(label='Bankas SWIFT kods')

    class Meta(object):
        model = models.Order
        fields = (
            'quantity',
            'name',
            'phone',
            'email',
            'legal_address',
            'shipment_address',
            'bank',
            'swift',
            'account_iban',
        )
        widgets = {
            'quantity': forms.TextInput(attrs={'class': 'col-5'}),
            'phone': forms.TextInput(attrs={'class': 'col-5'}),
            'email': forms.EmailInput(attrs={'class': 'col-5'}),
            'bank': forms.TextInput(attrs={'class': 'col-5'}),
            'swift': forms.TextInput(attrs={'class': 'col-5'}),
            'legal_address': forms.Textarea(attrs={
                'cols': 80,
                'rows': 2
            }),
            'shipment_address': forms.Textarea(attrs={
                'cols': 80,
                'rows': 2
            }),
        }
예제 #4
0
class UserEditForm(forms.ModelForm):
    iban = IBANFormField()
    first_name = forms.CharField(required=True)
    last_name = forms.CharField(required=True)

    class Meta:
        model = BankAccountUser
        fields = ['username', 'first_name', 'last_name', 'iban']
예제 #5
0
 def settings_form_fields(self):
     d = OrderedDict([
         ('ack',
          forms.BooleanField(
              label=
              _('I have understood that I need to regularly create SEPA XML export files and transfer '
                'them to my bank in order to have my bank collect the customer payments.'
                ),
              required=True,
          )),
         ('creditor_name',
          forms.CharField(
              label=_('Creditor name'),
              max_length=70,
          )),
         ('creditor_iban', IBANFormField(label=_('Creditor IBAN'), )),
         ('creditor_bic', BICFormField(label=_('Creditor BIC'), )),
         ('creditor_id',
          forms.CharField(
              label=_('Creditor ID'),
              validators=[
                  RegexValidator(
                      regex=
                      (r"^[a-zA-Z]{2,2}[0-9]{2,2}([A-Za-z0-9]|[\+|\?|/|\-|:|\(|\)|\.|,|']){3,3}"
                       r"([A-Za-z0-9]|[\+|\?|/|\-|:|\(|\)|\.|,|']){1,28}$"),
                      message=_('This must be a valid SEPA creditor ID.'),
                  )
              ],
              max_length=28)),
         ('reference_prefix',
          forms.CharField(
              label=_('Mandate reference prefix'),
              validators=[
                  RegexValidator(
                      regex=r"^[a-zA-Z0-9',.:+\-/\(\)?]+$",
                      message=
                      _("This may only contain letters, numbers, and the following special "
                        "characters: ' , . : + - / ( ) ?")),
              ],
              required=False,
              help_text=
              _('We will use this string and append the event slug and the order code to build a '
                'unique SEPA mandate reference.'),
              max_length=35 - settings.ENTROPY['order_code'] - 2 -
              len(self.event.slug))),
         ('prenotification_days',
          forms.IntegerField(
              label=_('Pre-notification time'),
              help_text=
              _('Number of days between the placement of the order and the due date of the direct '
                'debit. Depending on your legislation and your bank rules, you might be required to '
                'hand in a debit at least 5 days before the due date at your bank and you might even '
                'be required to inform the customer at least 14 days beforehand. We recommend '
                'configuring at least 7 days.'),
              min_value=1)),
     ] + list(super().settings_form_fields.items()))
     d.move_to_end('_enabled', last=False)
     return d
예제 #6
0
class RegistrationForm(forms.ModelForm):
    password = forms.CharField(widget=forms.PasswordInput)
    iban = IBANFormField()
    first_name = forms.CharField(required=True)
    last_name = forms.CharField(required=True)

    class Meta:
        model = BankAccountUser
        fields = ['username', 'first_name', 'last_name', 'password', 'iban']
예제 #7
0
class SEPATransferForm(PinRequestForm):
    form_name = _("SEPA transfer")
    field_order = ['recipient', 'iban', 'bic', 'amount', 'purpose']

    recipient = forms.CharField(label=_('Recipient'), required=True)
    iban = IBANFormField(label=_("IBAN"), required=True)
    bic = BICFormField(label=_("BIC"), required=True)
    amount = forms.DecimalField(label=_('Amount'), required=True)
    purpose = forms.CharField(label=_('Purpose'), required=True)
예제 #8
0
 def payment_form_fields(self):
     return OrderedDict([
         ('account', forms.CharField(label=_('Account holder'))),
         ('iban', IBANFormField(label=_('IBAN'))),
         ('bic', BICFormField(label=_('BIC'))),
         ('mandate',
          forms.BooleanField(label=_(
              'I hereby grant the SEPA direct debit mandate for this order (see below)'
          ))),
     ])
예제 #9
0
class SepaXMLExportForm(forms.Form):
    account_holder = forms.CharField(label=_("Account holder"))
    iban = IBANFormField(label="IBAN")
    bic = BICFormField(label="BIC")

    def set_initial_from_event(self, event: Event):
        banktransfer = event.get_payment_providers(cached=True)[BankTransfer.identifier]
        self.initial["account_holder"] = banktransfer.settings.get("bank_details_sepa_name")
        self.initial["iban"] = banktransfer.settings.get("bank_details_sepa_iban")
        self.initial["bic"] = banktransfer.settings.get("bank_details_sepa_bic")
예제 #10
0
class CommunityCharityProfileForm(CommunityUserProfileForm):
    iban = IBANFormField(label=_('IBAN number'), required=False)
    bic_code = forms.CharField(
        label=_('BIC code'), validators=[swift_bic_validator], required=False)
    account_holder = forms.CharField(
        max_length=255, required=False, help_text=_('Account holder name'))
    mandate_id = forms.CharField(label=_('mandate ID'), required=False)
    signature_date = forms.DateField(required=False)
    registration_number = forms.CharField(
        max_length=14, help_text=_('VAT Number'), required=False)

    class Meta:
        model = User
        fields = (
            'email',
            'first_name',
            'last_name'
        )

    def __init__(self, *args, **kwargs):
        """
        Overrides base class ``__init__`` method to define the ``User`` related
        fields as 'required'.
        """
        super(CommunityCharityProfileForm, self).__init__(*args, **kwargs)

        self.fields['business_name'].required = True
        self.fields['business_name'].label = _('Charity name')

    def save(self, commit=True):
        user_profile = super(CommunityCharityProfileForm, self).save(commit)

        charity_attrs = {
            'profile': user_profile,
            'iban': self.cleaned_data.get('iban', ''),
            'bic_code': self.cleaned_data.get('bic_code', ''),
            'account_holder': self.cleaned_data.get('account_holder', ''),
            'mandate_id': generate_mandate_id(user_profile.user),
            'signature_date': self.cleaned_data.get('signature_date', '')
        }

        if not self.instance.pk:
            charity_profile = CharityProfile.objects.create(**charity_attrs)
        else:
            charity_profile = self.instance

            # not editable after creation
            charity_attrs.pop('signature_date')

            for key in charity_attrs.keys():
                setattr(charity_profile, key, charity_attrs[key])

            charity_profile.save()

        return charity_profile
예제 #11
0
class PrepareDDForm(forms.Form):
    debit_date = forms.DateField(
        label=_("Debit date"),
        required=True,
        help_text=
        _("Date on which the debit should become effective. "
          "Warning: There are likely to be contractual limitations concerning this "
          "date between you and your bank. Generally should be 14 days in the "
          "future, on a bank day, not more than 30 days in the future."))
    debit_text = forms.CharField(required=True,
                                 label=_('Memo'),
                                 help_text=_(
                                     'Memo/subject that the member will see '
                                     'on their bank statement.'))

    own_name = forms.CharField(required=True, label=_('Creditor name'))
    own_iban = IBANFormField(required=True, label=_('Creditor IBAN'))
    own_bic = BICFormField(required=True, label=_('Creditor BIC'))
    sepa_format = forms.CharField(required=True,
                                  label=_('SEPA PAIN format'),
                                  initial='pain.001.001.03')
    own_account = forms.CharField(required=False, widget=forms.HiddenInput())

    cor1 = forms.BooleanField(label=_('Issue express debit (COR1)'),
                              required=False,
                              help_text=_(
                                  "An express debit has a reduced lead "
                                  "time of generally 1 business day, "
                                  "but must be explicitly agreed upon "
                                  "when giving the SEPA mandate."))

    exp_bank_types = forms.ChoiceField(required=True,
                                       label=_("Bank types"),
                                       choices=[('ALL', _('All banks')),
                                                ('DE', _('German banks only')),
                                                ('NDE',
                                                 _('Non-German banks only'))])
    exp_member_numbers = forms.CharField(
        required=False,
        label=_("Member numbers"),
        help_text=_(
            "Allows to issue a direct debit for a subset of members only. "
            "Example: 1-9,20-29,42"))

    subject = forms.CharField(required=True)
    text = forms.CharField(widget=forms.Textarea)

    debit_date.widget.attrs.update({'class': 'datepicker'})
예제 #12
0
class AccountForm(forms.ModelForm):
    """
    Class to add an account
    """
    owner = forms.ModelChoiceField(queryset=Client.objects.all(),
                                   widget=forms.HiddenInput())
    iban = IBANFormField(include_countries=IBAN_SEPA_COUNTRIES)

    class Meta:
        model = BankAccount
        fields = ("owner", "iban")
        labels = {
            "owner": "Account owner",
            "iban": "IBAN",
        }

    def __init__(self, *args, **kwargs):
        super(AccountForm, self).__init__(*args, **kwargs)
예제 #13
0
class ConsumerForm(forms.ModelForm, BootstrapForm):

    signup_ref = forms.CharField(required=False,
                                 max_length=150,
                                 widget=forms.HiddenInput())
    cif = ESIdentityCardNumberField(label=_('NIF/CIF'))
    iban_code = IBANFormField(
        label=_('Cuenta bancaria (IBAN)'),
        required=False,
        widget=forms.TextInput(attrs={
            'class': 'iban-code',
            'placeholder': 'ES0000000000000000000000'
        }))

    required_fields = [
        'first_name',
        'last_name',
    ]

    class Meta:
        model = Consumer
        exclude = [
            'group', 'status', 'legal_form', 'member_type', 'cr_member',
            'registration_date', 'cyclos_user'
        ]
        widgets = {
            'address': forms.Textarea(attrs={'rows': 3}),
        }

    def save(self, commit=True):

        instance = forms.ModelForm.save(self, False)
        instance.member_type = MEMBER_CONSUMER

        # Do we need to save all changes now?
        if commit:
            instance.save()

        return instance
예제 #14
0
class BankUserUpdateForm(forms.ModelForm):
    iban = IBANFormField(label=_('IBAN'))

    class Meta:
        model = BankUser
        fields = (
            'first_name',
            'last_name',
            'iban',
        )

    def clean_first_name(self):
        first_name = self.cleaned_data.get('first_name', '')
        return first_name.upper().strip()

    def clean_last_name(self):
        last_name = self.cleaned_data.get('last_name', '')
        return last_name.upper().strip()

    def clean_iban(self):
        iban = self.cleaned_data.get('iban', '')
        return iban.upper().strip()
예제 #15
0
파일: payment.py 프로젝트: skorth/pretix
 def form_fields():
     return OrderedDict([
         ('ack',
          forms.BooleanField(
              label=
              _('I have understood that people will pay the ticket price directly to my bank account and '
                'pretix cannot automatically know what payments arrived. Therefore, I will either mark '
                'payments as complete manually, or regularly import a digital bank statement in order to '
                'give pretix the required information.'),
              required=True,
          )),
         ('bank_details_type',
          forms.ChoiceField(
              label=_('Bank account type'),
              widget=forms.RadioSelect,
              choices=(
                  ('sepa', _('SEPA bank account')
                   ),
                  (
                      'other', _('Other bank account')),
              ),
              initial='sepa')),
         ('bank_details_sepa_name',
          forms.CharField(
              label=_('Name of account holder'),
              widget=forms.TextInput(
                  attrs={
                      'data-display-dependency':
                      '#id_payment_banktransfer_bank_details_type_0',
                      'data-required-if':
                      '#id_payment_banktransfer_bank_details_type_0'
                  }),
              required=False)),
         ('bank_details_sepa_iban',
          IBANFormField(
              label=_('IBAN'),
              required=False,
              widget=forms.TextInput(
                  attrs={
                      'data-display-dependency':
                      '#id_payment_banktransfer_bank_details_type_0',
                      'data-required-if':
                      '#id_payment_banktransfer_bank_details_type_0'
                  }),
          )),
         ('bank_details_sepa_bic',
          BICFormField(
              label=_('BIC'),
              widget=forms.TextInput(
                  attrs={
                      'data-display-dependency':
                      '#id_payment_banktransfer_bank_details_type_0',
                      'data-required-if':
                      '#id_payment_banktransfer_bank_details_type_0'
                  }),
              required=False)),
         ('bank_details_sepa_bank',
          forms.CharField(
              label=_('Name of bank'),
              widget=forms.TextInput(
                  attrs={
                      'data-display-dependency':
                      '#id_payment_banktransfer_bank_details_type_0',
                      'data-required-if':
                      '#id_payment_banktransfer_bank_details_type_0'
                  }),
              required=False)),
         ('bank_details',
          I18nFormField(
              label=_('Bank account details'),
              widget=I18nTextarea,
              help_text=
              _('Include everything else that your customers might need to send you a bank transfer payment. '
                'If you have lots of international customers, they might need your full address and your '
                'bank\'s full address.'),
              widget_kwargs={
                  'attrs': {
                      'rows':
                      '4',
                      'placeholder':
                      _('For SEPA accounts, you can leave this empty. Otherwise, please add everything that '
                        'your customers need to transfer the money, e.g. account numbers, routing numbers, '
                        'addresses, etc.'),
                  }
              },
              required=False)),
         ('public_name',
          I18nFormField(label=_('Payment method name'),
                        widget=I18nTextInput,
                        required=False))
     ])
예제 #16
0
    def settings_form_fields(self):

        d = OrderedDict([
            ('ack',
             forms.BooleanField(
                 label=
                 _('I have understood that I need to regularly create SEPA XML export files and transfer '
                   'them to my bank in order to have my bank collect the customer payments.'
                   ),
                 required=True,
             )),
            ('creditor_name',
             forms.CharField(
                 label=_('Creditor name'),
                 max_length=70,
             )), ('creditor_iban', IBANFormField(label=_('Creditor IBAN'), )),
            ('creditor_bic', BICFormField(label=_('Creditor BIC'), )),
            ('creditor_id',
             forms.CharField(
                 label=_('Creditor ID'),
                 validators=[
                     RegexValidator(
                         regex=
                         (r"^[a-zA-Z]{2,2}[0-9]{2,2}([A-Za-z0-9]|[\+|\?|/|\-|:|\(|\)|\.|,|']){3,3}"
                          r"([A-Za-z0-9]|[\+|\?|/|\-|:|\(|\)|\.|,|']){1,28}$"),
                         message=_('This must be a valid SEPA creditor ID.'),
                     )
                 ],
                 max_length=28)),
            ('reference_prefix',
             forms.CharField(
                 label=_('Mandate reference prefix'),
                 validators=[
                     RegexValidator(
                         regex=r"^[a-zA-Z0-9',.:+\-/\(\)?]+$",
                         message=
                         _("This may only contain letters, numbers, and the following special "
                           "characters: ' , . : + - / ( ) ?")),
                 ],
                 required=False,
                 help_text=
                 _('We will use this string and append the event slug and the order code to build a '
                   'unique SEPA mandate reference.'),
                 max_length=35 - settings.ENTROPY['order_code'] - 2 -
                 len(self.event.slug))),
            ('prenotification_days',
             forms.IntegerField(
                 label=_('Pre-notification time'),
                 help_text=
                 _('Number of days between the placement of the order and the due date of the direct '
                   'debit. Depending on your legislation and your bank rules, you might be required to '
                   'hand in a debit at least 5 days before the due date at your bank and you might even '
                   'be required to inform the customer at least 14 days beforehand. We recommend '
                   'configuring at least 7 days.'),
                 min_value=1)),
            ('iban_blocklist',
             forms.CharField(
                 label=_('IBAN blocklist'),
                 required=False,
                 widget=forms.Textarea,
                 help_text=
                 _('Put one IBAN or IBAN prefix per line. The system will not allow any of these IBANs. Useful e.g. '
                   'if you had lots of failed payments already from a specific person. You can also list country codes'
                   'such as "GB" if you never want to accept IBANs from a specific country.'
                   ))),
            ('earliest_due_date',
             forms.DateField(
                 label=_('Earliest debit due date'),
                 help_text=
                 _('Earliest date the direct debit can be due. '
                   'This date is used as the direct debit due date if the order date plus pre-notification time would result in a due date earlier than this. '
                   'Customers with orders using the earliest due date will receive an email reminding them about the upcoming charge based on the configured pre-notification days.'
                   ),
                 required=False,
                 widget=forms.widgets.DateInput(
                     attrs={'class': 'datepickerfield'}))),
            ('pre_notification_mail_subject',
             I18nFormField(
                 label=_("Pre-notification mail subject"),
                 help_text=
                 _('The subject of the notification email. '
                   'This email is only sent if the earliest debit due date option is used.'
                   ),
                 required=False,
                 widget=I18nTextInput,
                 widget_kwargs={
                     'attrs': {
                         'data-display-dependency':
                         '#id_payment_sepadebit_earliest_due_date'
                     }
                 },
             )),
            ('pre_notification_mail_body',
             I18nFormField(
                 label=_("Pre-notification mail body"),
                 help_text=
                 _('The body of the notification email. '
                   'This email is only sent if the earliest debit due date option is used.'
                   ),
                 required=False,
                 widget=I18nTextarea,
                 widget_kwargs={
                     'attrs': {
                         'data-display-dependency':
                         '#id_payment_sepadebit_earliest_due_date'
                     }
                 },
             ))
        ] + list(super().settings_form_fields.items()))
        d.move_to_end('_enabled', last=False)

        self._set_field_placeholders(d, "pre_notification_mail_subject",
                                     ["event", "order", "sepadebit_payment"],
                                     [])
        self._set_field_placeholders(d, "pre_notification_mail_body",
                                     ["event", "order", "sepadebit_payment"],
                                     [])
        return d
예제 #17
0
class CommunityInstitutionProfileForm(CommunityUserProfileForm):
    iban = IBANFormField(label=_('IBAN number'), required=False)
    bic_code = forms.CharField(
        label=_('BIC code'), validators=[swift_bic_validator], required=False)
    account_holder = forms.CharField(
        max_length=255, required=False, help_text=_('Account holder name'))
    mandate_id = forms.CharField(label=_('mandate ID'), required=False)
    signature_date = forms.DateField(required=False)
    registration_number = forms.CharField(
        max_length=14, help_text=_('VAT Number'), required=False)
    vat_number = forms.CharField(max_length=14, help_text=_('VAT Number'),
                                 required=False)

    class Meta:
        model = User
        fields = (
            'email',
            'first_name',
            'last_name'
        )

    def __init__(self, *args, **kwargs):
        """
        Overrides base class ``__init__`` method to define the ``User`` related
        fields as 'required'.
        """
        super(CommunityInstitutionProfileForm, self).__init__(*args, **kwargs)

        self.fields['business_name'].required = True
        self.fields['business_name'].label = _('Institution name')

    def clean_vat_number(self):
        data = self.cleaned_data.get('vat_number', '')
        if data:
            vat_number_re = re.compile(VAT_NUMBER_REGEX)
            if not vat_number_re.match(data):
                error_msg = _("Please enter a valid VAT Number")
                raise forms.ValidationError(error_msg)

        return data

    def save(self, commit=True):
        user_profile = super(
            CommunityInstitutionProfileForm, self).save(commit)

        institution_attrs = {
            'profile': user_profile,
            'iban': self.cleaned_data.get('iban', ''),
            'bic_code': self.cleaned_data.get('bic_code', ''),
            'account_holder': self.cleaned_data.get('account_holder', ''),
            'mandate_id': generate_mandate_id(user_profile.user),
            'signature_date': self.cleaned_data.get('signature_date', ''),
            'vat_number': self.cleaned_data.get('vat_number', '')
        }

        if not self.instance.pk:
            institution_profile = InstitutionProfile.objects.create(
                **institution_attrs)
        else:
            institution_profile = self.instance

            # not editable after creation
            institution_attrs.pop('signature_date')

            for key in institution_attrs.keys():
                setattr(institution_profile, key, institution_attrs[key])

            institution_profile.save()

        return institution_profile
예제 #18
0
class LastschriftPaymentForm(BasePaymentForm):
    owner_name = forms.CharField(
        label=_('Account owner'),
        required=True,
        widget=forms.TextInput(attrs={
            'class': 'form-control',
            'placeholder': _('Account owner'),
        }))
    iban = IBANFormField(
        label=_('Your IBAN'),
        required=True,
        include_countries=IBAN_SEPA_COUNTRIES,
        widget=forms.TextInput(
            attrs={
                'class':
                'form-control',
                'pattern': (
                    # 36 len includes possible spaces
                    r"^[A-Z]{2}\d{2}[ ]*[ A-Za-z\d]{11,36}"),
                'placeholder':
                _('e.g. DE12...'),
                'title':
                _('The IBAN starts with two letters and then two numbers. '
                  'SEPA countries only.')
            }))
    terms = forms.BooleanField(
        required=True,
        label='Lastschrift einziehen',
        help_text=(
            "Ich ermächtige (A) Open Knowledge Foundation Deutschland e.V., "
            "Zahlungen von meinem Konto mittels Lastschrift einzuziehen. "
            "Zugleich (B) weise ich mein Kreditinstitut an, die von "
            "Open Knowledge Foundation auf mein Konto gezogenen Lastschriften "
            "einzulösen. Hinweis: Ich kann innerhalb von acht Wochen, "
            "beginnend mit dem Belastungsdatum, die Erstattung des belasteten "
            "Betrages verlangen. Es gelten dabei die mit meinem "
            "Kreditinstitut vereinbarten Bedingungen."),
        error_messages={
            'required':
            _('Sie müssen den Bedingungen der Lastschrift zustimmen.')
        },
    )

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['owner_name'].initial = self.payment.order.get_full_name()
        try:
            self.fields['iban'].initial = self.payment.attrs.iban
            self.fields['owner_name'].initial = self.payment.attrs.owner
        except (KeyError, AttributeError):
            pass

    def save(self):
        self.payment.attrs.iban = self.cleaned_data['iban']
        self.payment.attrs.owner = self.cleaned_data['owner_name']
        order = self.payment.order
        if order.is_recurring:
            subscription = order.subscription
            customer = subscription.customer
            iban_data = json.dumps({
                'owner': self.cleaned_data['owner_name'],
                'iban': self.cleaned_data['iban']
            })
            customer.custom_data = iban_data
            customer.save()
        return self.finalize_payment()

    def finalize_payment(self):
        self.payment.transaction_id = str(uuid.uuid4())
        self.payment.change_status(PaymentStatus.PENDING)  # Calls .save()
예제 #19
0
 def test_default_form(self):
     iban_model_field = IBANField()
     self.assertEqual(type(iban_model_field.formfield()),
                      type(IBANFormField()))
예제 #20
0
 def test_form_field_formatting(self):
     iban_form_field = IBANFormField()
     self.assertEqual(iban_form_field.prepare_value('NL02ABNA0123456789'), 'NL02 ABNA 0123 4567 89')
     self.assertEqual(iban_form_field.prepare_value('NL02 ABNA 0123 4567 89'), 'NL02 ABNA 0123 4567 89')
     self.assertIsNone(iban_form_field.prepare_value(None))
예제 #21
0
class ProviderForm(forms.ModelForm, BootstrapForm):

    categories = forms.ModelMultipleChoiceField(
        queryset=Category.objects.filter(), required=False)
    signup_ref = forms.CharField(required=False,
                                 max_length=150,
                                 widget=forms.HiddenInput())
    cif = ESIdentityCardNumberField(label=_('NIF/CIF'))
    iban_code = IBANFormField(
        label=_('Cuenta bancaria (IBAN)'),
        required=False,
        widget=forms.TextInput(attrs={
            'class': 'iban-code',
            'placeholder': 'ES0000000000000000000000'
        }))

    required_fields = [
        'name',
        'business_name',
    ]

    class Meta:
        model = Provider
        exclude = [
            'group', 'status', 'member_type', 'cr_member', 'registration_date',
            'cyclos_user'
        ]

        widgets = {
            'contact_person': forms.TextInput(),
            'address': forms.Textarea(attrs={'rows': 3}),
            'public_address': forms.Textarea(attrs={'rows': 3}),
            'short_description': forms.Textarea(attrs={'rows': 3}),
            'latitude': forms.NumberInput(attrs={'readonly': False}),
            'longitude': forms.NumberInput(attrs={'readonly': False}),
            'networking': forms.Textarea(attrs={'rows': 4}),
            'num_workers_male_partners': forms.NumberInput(attrs={'min': 0}),
            'num_workers_female_partners': forms.NumberInput(attrs={'min': 0}),
            'num_workers_male_non_partners':
            forms.NumberInput(attrs={'min': 0}),
            'num_workers_female_non_partners':
            forms.NumberInput(attrs={'min': 0}),
        }

    # Overriding __init__ here allows us to provide initial data for permissions
    def __init__(self, *args, **kwargs):
        # Only in case we build the form from an instance
        # (otherwise, 'toppings' list should be empty)
        if kwargs.get('instance'):
            initial = kwargs.setdefault('initial', {})
            # The widget for a ModelMultipleChoiceField expects
            # a list of primary key for the selected data.
            initial['categories'] = [
                t.pk for t in kwargs['instance'].categories.all()
            ]

        forms.ModelForm.__init__(self, *args, **kwargs)

    def save(self, commit=True):

        is_new = self.instance.pk is None
        instance = forms.ModelForm.save(self, False)
        instance.member_type = MEMBER_PROV

        if not instance.public_address or instance.public_address == '':
            instance.public_address = instance.address

        # Prepare a 'save_m2m' method for the form,
        old_save_m2m = self.save_m2m

        def save_m2m():
            old_save_m2m()
            # This is where we actually link the permissions to the group
            instance.categories.clear()
            instance.categories.add(*self.cleaned_data['categories'])

        self.save_m2m = save_m2m

        # Do we need to save all changes now?
        if commit:
            instance.save()
            self.save_m2m()

        return instance
예제 #22
0
 def test_form_field_formatting(self):
     iban_form_field = IBANFormField()
     self.assertEqual(iban_form_field.prepare_value("NL02ABNA0123456789"), "NL02 ABNA 0123 4567 89")
     self.assertEqual(iban_form_field.prepare_value("NL02 ABNA 0123 4567 89"), "NL02 ABNA 0123 4567 89")
     self.assertIsNone(iban_form_field.prepare_value(None))
     self.assertEqual(iban_form_field.to_python(None), "")
예제 #23
0
파일: fields.py 프로젝트: einarfelix/xl
"""

from django.db import models

from localflavor.generic import models as iban_fields
from localflavor.generic.forms import IBANFormField

from lino.api import dd

from lino.utils.jsgen import js_code
import six

from lino.core.elems import CharFieldElement
#from lino.modlib.extjs.ext_renderer import ExtRenderer

IBAN_FORMFIELD = IBANFormField()


class UppercaseTextFieldElement(CharFieldElement):
    """A CharFieldElement which accepts only upper-case characters.
    """
    value_template = "new Lino.UppercaseTextField(%s)"


class IBANFieldElement(UppercaseTextFieldElement):
    def get_column_options(self, **kw):
        """
        Return a string to be used as `Ext.grid.Column.renderer
        <http://docs.sencha.com/extjs/3.4.0/#!/api/Ext.grid.Column-cfg-renderer>`.
        """
        kw = super(UppercaseTextFieldElement, self).get_column_options(**kw)
예제 #24
0
class AddIbanForm(forms.Form):
    user = selected_user
    iban = IBANFormField(include_countries=IBAN_SEPA_COUNTRIES)
예제 #25
0
 def form_fields():
     return OrderedDict([
         ('bank_details_type', forms.ChoiceField(
             label=_('Bank account type'),
             widget=forms.RadioSelect,
             choices=(
                 ('sepa', _('SEPA bank account')),
                 ('other', _('Other bank account')),
             ),
             initial='sepa'
         )),
         ('bank_details_sepa_name', forms.CharField(
             label=_('Name of account holder'),
             widget=forms.TextInput(
                 attrs={
                     'data-display-dependency': '#id_payment_banktransfer_bank_details_type_0',
                     'data-required-if': '#id_payment_banktransfer_bank_details_type_0'
                 }
             ),
             required=False
         )),
         ('bank_details_sepa_iban', IBANFormField(
             label=_('IBAN'),
             required=False,
             widget=forms.TextInput(
                 attrs={
                     'data-display-dependency': '#id_payment_banktransfer_bank_details_type_0',
                     'data-required-if': '#id_payment_banktransfer_bank_details_type_0'
                 }
             ),
         )),
         ('bank_details_sepa_bic', BICFormField(
             label=_('BIC'),
             widget=forms.TextInput(
                 attrs={
                     'data-display-dependency': '#id_payment_banktransfer_bank_details_type_0',
                     'data-required-if': '#id_payment_banktransfer_bank_details_type_0'
                 }
             ),
             required=False
         )),
         ('bank_details_sepa_bank', forms.CharField(
             label=_('Name of bank'),
             widget=forms.TextInput(
                 attrs={
                     'data-display-dependency': '#id_payment_banktransfer_bank_details_type_0',
                     'data-required-if': '#id_payment_banktransfer_bank_details_type_0'
                 }
             ),
             required=False
         )),
         ('bank_details', I18nFormField(
             label=_('Bank account details'),
             widget=I18nTextarea,
             help_text=_(
                 'Include everything else that your customers might need to send you a bank transfer payment. '
                 'If you have lots of international customers, they might need your full address and your '
                 'bank\'s full address.'),
             widget_kwargs={'attrs': {
                 'rows': '4',
                 'placeholder': _(
                     'For SEPA accounts, you can leave this empty. Otherwise, please add everything that '
                     'your customers need to transfer the money, e.g. account numbers, routing numbers, '
                     'addresses, etc.'
                 ),
             }},
             required=False
         )),
         ('public_name', I18nFormField(
             label=_('Payment method name'),
             widget=I18nTextInput,
             required=False
         ))
     ])
예제 #26
0
 def form_fields():
     return OrderedDict([
         ('ack',
          forms.BooleanField(
              label=
              _('I have understood that people will pay the ticket price directly to my bank account and '
                'pretix cannot automatically know what payments arrived. Therefore, I will either mark '
                'payments as complete manually, or regularly import a digital bank statement in order to '
                'give pretix the required information.'),
              required=True,
          )),
         ('bank_details_type',
          forms.ChoiceField(label=_('Bank account type'),
                            widget=forms.RadioSelect,
                            choices=(
                                ('sepa', _('SEPA bank account')),
                                ('other', _('Other bank account')),
                            ),
                            initial='sepa')),
         ('bank_details_sepa_name',
          forms.CharField(
              label=_('Name of account holder'),
              widget=forms.TextInput(
                  attrs={
                      'data-display-dependency':
                      '#id_payment_banktransfer_bank_details_type_0',
                      'data-required-if':
                      '#id_payment_banktransfer_bank_details_type_0'
                  }),
              required=False)),
         ('bank_details_sepa_iban',
          IBANFormField(
              label=_('IBAN'),
              required=False,
              widget=forms.TextInput(
                  attrs={
                      'data-display-dependency':
                      '#id_payment_banktransfer_bank_details_type_0',
                      'data-required-if':
                      '#id_payment_banktransfer_bank_details_type_0'
                  }),
          )),
         ('bank_details_sepa_bic',
          BICFormField(
              label=_('BIC'),
              widget=forms.TextInput(
                  attrs={
                      'data-display-dependency':
                      '#id_payment_banktransfer_bank_details_type_0',
                      'data-required-if':
                      '#id_payment_banktransfer_bank_details_type_0'
                  }),
              required=False)),
         ('bank_details_sepa_bank',
          forms.CharField(
              label=_('Name of bank'),
              widget=forms.TextInput(
                  attrs={
                      'data-display-dependency':
                      '#id_payment_banktransfer_bank_details_type_0',
                      'data-required-if':
                      '#id_payment_banktransfer_bank_details_type_0'
                  }),
              required=False)),
         ('bank_details',
          I18nFormField(
              label=_('Bank account details'),
              widget=I18nTextarea,
              help_text=
              _('Include everything else that your customers might need to send you a bank transfer payment. '
                'If you have lots of international customers, they might need your full address and your '
                'bank\'s full address.'),
              widget_kwargs={
                  'attrs': {
                      'rows':
                      '4',
                      'placeholder':
                      _('For SEPA accounts, you can leave this empty. Otherwise, please add everything that '
                        'your customers need to transfer the money, e.g. account numbers, routing numbers, '
                        'addresses, etc.'),
                  }
              },
              required=False)),
         ('invoice_immediately',
          forms.BooleanField(
              label=
              _('Create an invoice for orders using bank transfer immediately if the event is otherwise '
                'configured to create invoices after payment is completed.'
                ),
              required=False,
          )),
         ('public_name',
          I18nFormField(label=_('Payment method name'),
                        widget=I18nTextInput,
                        required=False)),
         ('omit_hyphen',
          forms.BooleanField(
              label=_('Do not include hyphens in the payment reference.'),
              help_text=_('This is required in some countries.'),
              required=False)),
         ('include_invoice_number',
          forms.BooleanField(
              label=_('Include invoice number in the payment reference.'),
              required=False)),
         ('prefix',
          forms.CharField(
              label=_('Prefix for the payment reference'),
              required=False,
          )),
         ('pending_description',
          I18nFormField(
              label=_('Additional text to show on pending orders'),
              help_text=_(
                  'This text will be shown on the order confirmation page for pending orders in addition to '
                  'the standard text.'),
              widget=I18nTextarea,
              required=False,
          )),
         ('refund_iban_blocklist',
          forms.CharField(
              label=_('IBAN blocklist for refunds'),
              required=False,
              widget=forms.Textarea,
              help_text=
              _('Put one IBAN or IBAN prefix per line. The system will not attempt to send refunds to any '
                'of these IBANs. Useful e.g. if you receive a lot of "forwarded payments" by a third-party payment '
                'provider. You can also list country codes such as "GB" if you never want to send refunds to '
                'IBANs from a specific country.'))),
     ])
예제 #27
0
class UserForm(ModelForm):
    iban = IBANFormField()

    class Meta:
        model = User
        fields = ['first_name', 'last_name', 'iban']