예제 #1
0
def test_magic_methods():
    bic = BIC('GENODEM1GLS')
    assert bic == 'GENODEM1GLS'
    assert bic == BIC('GENODEM1GLS')
    assert bic != BIC('GENODEMMXXX')
    assert bic != 12345
    assert bic < 'GENODEM1GLT'

    assert str(bic) == 'GENODEM1GLS'
    assert repr(bic) == '<BIC=GENODEM1GLS>'
예제 #2
0
def test_magic_methods():
    bic = BIC("GENODEM1GLS")
    assert bic == "GENODEM1GLS"
    assert bic == BIC("GENODEM1GLS")
    assert bic != BIC("GENODEMMXXX")
    assert bic != 12345
    assert bic < "GENODEM1GLT"

    assert str(bic) == "GENODEM1GLS"
    assert hash(bic) == hash("GENODEM1GLS")
    assert repr(bic) == "<BIC=GENODEM1GLS>"
예제 #3
0
    def bic_parsed(self):
        with suppress(ValueError):
            bic = self.bic_autocomplete
            if bic:
                return BIC(bic)

        return None
예제 #4
0
    def sepa_direct_debit_state(self):
        if not self.iban:
            return SepaDirectDebitState.NO_IBAN

        if not self.iban_parsed:
            return SepaDirectDebitState.INVALID_IBAN

        if self.mandate_state == "rescinded":
            return SepaDirectDebitState.RESCINDED

        if self.mandate_state == "bounced":
            return SepaDirectDebitState.BOUNCED

        if self.mandate_state == "inactive":
            return SepaDirectDebitState.INACTIVE

        if not self.bic_autocomplete:
            return SepaDirectDebitState.NO_BIC

        bic = self.bic_parsed
        if not bic:
            return SepaDirectDebitState.INVALID_BIC

        if bic.country_code == "DE" and not bic.exists:
            # PBNKDEFF and PBNKDEFFXXX should be the same
            b_ = BIC(str(bic) + "XXX")
            if not b_.exists:
                return SepaDirectDebitState.INVALID_BIC

        if not self.mandate_reference:
            return SepaDirectDebitState.NO_MANDATE_REFERENCE

        return SepaDirectDebitState.OK
예제 #5
0
def test_bic_properties():
    bic = BIC("GENODEM1GLS")
    assert bic.length == 11
    assert bic.bank_code == "GENO"
    assert bic.country_code == "DE"
    assert bic.location_code == "M1"
    assert bic.branch_code == "GLS"
    assert bic.domestic_bank_codes == ["43060967", "43060988"]
    assert bic.bank_names == [
        "GLS Gemeinschaftsbank",
        "GLS Gemeinschaftsbank (GAA)",
    ]
    assert bic.bank_short_names == [
        "GLS Bank in Bochum (GAA)",
        "GLS Gemeinschaftsbk Bochum",
    ]
    assert bic.country == countries.get(alpha_2="DE")
    with pytest.warns(DeprecationWarning):
        assert bic.bank_name == "GLS Gemeinschaftsbank"
    with pytest.warns(DeprecationWarning):
        assert bic.bank_short_name == "GLS Bank in Bochum (GAA)"
    with pytest.warns(DeprecationWarning):
        assert bic.country_bank_code == "43060967"
    assert bic.exists
    assert bic.type == "passive"
예제 #6
0
 def clean_bic(self):
     input_bic = self.cleaned_data['bic']
     try:
         bic_obj = BIC(input_bic)
     except ValueError:
         raise forms.ValidationError(
             _('The BIC you entered does not seem to be correct!'))
     return bic_obj.compact
예제 #7
0
def test_bic_properties():
    bic = BIC('GENODEM1GLS')
    assert bic.length == 11
    assert bic.bank_code == 'GENO'
    assert bic.branch_code == 'GLS'
    assert bic.country_code == 'DE'
    assert bic.location_code == 'M1'
    assert bic.country_bank_code == '43060967'
    assert bic.exists
    assert bic.type == 'passive'
예제 #8
0
def generate_random_iban_bic(country: str, bic: str) -> str:
    """
    Generates a random iban for a given country and BIC (note: works only for the countries supported by the Schwifty library)
    """
    bank_codes = BIC(bic).domestic_bank_codes
    if not bank_codes:
        raise Exception(
            'BIC {0} is not supported. Use bank code or regenerate an existing account'
            .format(bic))
    bank_code = randomization.choice(bank_codes)
    return generate_random_iban_bank(country, bank_code)
예제 #9
0
def test_unknown_bic_properties():
    bic = BIC('ABNAJPJTXXX')
    assert bic.length == 11
    assert bic.bank_code == 'ABNA'
    assert bic.country_code == 'JP'
    assert bic.location_code == 'JT'
    assert bic.branch_code == 'XXX'
    assert bic.country_bank_code is None
    assert bic.bank_name is None
    assert bic.bank_short_name is None
    assert not bic.exists
    assert bic.type == 'default'
예제 #10
0
def test_bic_properties():
    bic = BIC('GENODEM1GLS')
    assert bic.length == 11
    assert bic.bank_code == 'GENO'
    assert bic.country_code == 'DE'
    assert bic.location_code == 'M1'
    assert bic.branch_code == 'GLS'
    assert bic.country_bank_code == '43060967'
    assert bic.bank_name == 'GLS Gemeinschaftsbank'
    assert bic.bank_short_name == 'GLS Gemeinschaftsbk Bochum'
    assert bic.exists
    assert bic.type == 'passive'
예제 #11
0
def test_unknown_bic_properties():
    bic = BIC("ABNAJPJTXXX")
    assert bic.length == 11
    assert bic.bank_code == "ABNA"
    assert bic.country_code == "JP"
    assert bic.location_code == "JT"
    assert bic.branch_code == "XXX"
    assert bic.country_bank_code is None
    assert bic.domestic_bank_codes == []
    assert bic.bank_name is None
    assert bic.bank_names == []
    assert bic.bank_short_name is None
    assert bic.bank_short_names == []
    assert not bic.exists
    assert bic.type == "default"
예제 #12
0
    def errors(self):
        api_errors = super(BankInformation, self).errors()
        if api_errors.errors:
            return api_errors
        try:
            IBAN(self.iban)
        except (ValueError, TypeError):
            api_errors.add_error('iban', f"L'IBAN renseigné (\"{self.iban}\") est invalide")

        try:
            BIC(self.bic)
        except (ValueError, TypeError):
            api_errors.add_error('bic', f"Le BIC renseigné (\"{self.bic}\") est invalide")

        return api_errors
예제 #13
0
 def check_bank(self):
     if not self.bank or not self.bank.bic:
         return
     if IBAN and BIC:
         iban = IBAN(self.iban)
         bic = BIC(self.bank.bic)
         if (iban.bic
                 and iban.bic != bic
                 and (
                     iban.country_code != bic.country_code
                     or (iban.bank_code or iban.branch_code)
                     not in bic.domestic_bank_codes)):
             raise AccountValidationError(
                 gettext('bank.msg_invalid_iban_bic',
                     account=self.rec_name,
                     bic=iban.bic))
예제 #14
0
def process():
    with requests.get(URL, stream=True) as fp:
        csvfile = csv.reader(
            [line.decode("cp1250") for line in fp.iter_lines()], delimiter=";")
    registry = []
    for row in csvfile:
        bic = row[2].strip().upper()
        if bic and not BIC(bic, allow_invalid=True).is_valid:
            continue
        registry.append({
            "country_code": "SK",
            "primary": True,
            "bic": bic,
            "bank_code": row[0].strip().zfill(4),
            "name": row[1].strip(),
            "short_name": row[1].strip(),
        })
    return registry
예제 #15
0
def validate(bank_information: BankInformation,
             api_errors: ApiErrors) -> ApiErrors:
    if bank_information.status == BankInformationStatus.ACCEPTED:
        if bank_information.iban is None:
            api_errors.add_error("iban", "Cette information est obligatoire")
        else:
            try:
                IBAN(bank_information.iban)
            except (ValueError, TypeError):
                api_errors.add_error(
                    "iban",
                    f'L’IBAN renseigné ("{bank_information.iban}") est invalide'
                )

        if bank_information.bic is None:
            api_errors.add_error("bic", "Cette information est obligatoire")
        else:
            try:
                BIC(bank_information.bic)
            except (ValueError, TypeError):
                api_errors.add_error(
                    "bic",
                    f'Le BIC renseigné ("{bank_information.bic}") est invalide'
                )
    else:
        if bank_information.iban is not None:
            api_errors.add_error(
                "iban",
                f"L’IBAN doit être vide pour le statut {bank_information.status.name}"
            )
        if bank_information.bic is not None:
            api_errors.add_error(
                "bic",
                f"Le BIC doit être vide pour le statut {bank_information.status.name}"
            )

    return api_errors
예제 #16
0
def test_invalid_bic(code, exc):
    with pytest.raises(exc):
        BIC(code)
예제 #17
0
def test_bic():
    bic = BIC('GENODEM1GLS')
    assert bic.formatted == 'GENO DE M1 GLS'
    assert bic.validate()
예제 #18
0
def test_bic():
    bic = BIC("GENODEM1GLS")
    assert bic.formatted == "GENO DE M1 GLS"
    assert bic.validate()
예제 #19
0
def test_bic_type(code, type):
    bic = BIC(code)
    assert bic.type == type
예제 #20
0
 def check_value(self, value):
     try:
         value = BIC(str(value))
         return True
     except ValueError:
         return False
예제 #21
0
 def is_valid_bic(self):
     try:
         BIC(self.bic)
         return True
     except ValueError:
         return False
예제 #22
0
def test_bic_allow_invalid():
    bic = BIC("GENODXM1GLS", allow_invalid=True)
    assert bic
    assert bic.country_code == "DX"
    with pytest.raises(exceptions.InvalidCountryCode):
        bic.validate()
예제 #23
0
def test_bic_no_branch_code():
    bic = BIC("GENODEM1")
    assert bic.branch_code is None
    assert bic.formatted == "GENO DE M1"
예제 #24
0
def test_validate_bics():
    for bic in (bank["bic"] for bank in registry.get("bank") if bank["bic"]):
        BIC(bic, allow_invalid=False)
예제 #25
0
    def _populate_by_parsing(self):
        self.return_dict = {}

        if not self.raw:
            return

        m = self.MESSAGE_REGEX.match(self.raw)

        self._boolean = bool(m)

        if not m:
            print ('*'*20)
            print ('Message Not Matching : ',self.raw)
            return None

        self.basic_header = m.group("basic_header")
        self.application_header = m.group("application_header")
        self.user_header = m.group("user_header")
        self.trailer = m.group("trailer")

        self.text = Text(m.group("text") or "")


        try:
            basic_header = self.basic_header[3:14]
            self.basic_bic = BIC(basic_header)
        except:
            pass
        try:
            self.basic_bank_code = self.basic_bic.bank_code
        except:
            self.basic_bank_code=None
        try:
            self.basic_branch_code = self.basic_bic.branch_code
        except:
            self.basic_branch_code=None
        try:
            self.basic_country_code = self.basic_bic.country_code
        except:
            self.basic_country_code=None
        try:
            self.basic_location_code = self.basic_bic.location_code
        except:
            self.basic_location_code = None
        try:
            self.basic_country_bank_code = self.basic_bic.country_bank_code
        except:
            self.basic_country_bank_code = None
        try:
            application_header = self.application_header[4:15]
            self.application_bic = BIC(application_header)
        except:
            pass
        try:
            self.application_bank_code = self.application_bic.bank_code
        except:
            self.application_bank_code=None
        try:
            self.application_branch_code = self.application_bic.branch_code
        except:
            self.application_branch_code=None
        try:
            self.application_country_code = self.application_bic.country_code
        except:
            self.application_country_code=None
        try:
            self.application_location_code = self.application_bic.location_code
        except:
            self.application_location_code = None
        try:
            self.application_country_bank_code = self.application_bic.country_bank_code
        except:
            self.application_country_bank_code = None

        try:
            self.return_dict['basic_bank_code']=self.basic_bank_code
        except:
            pass
        try:
            self.return_dict['basic_branch_code']=self.basic_branch_code
        except:
            pass
        try:
            self.return_dict['basic_country_code']=self.basic_country_code

        except:
            pass
        try:
            self.return_dict['basic_location_code']=self.basic_location_code

        except:
            pass
        try:
            self.return_dict['basic_country_bank_code']=self.basic_country_bank_code

        except:
            pass
        try:
            self.return_dict['application_bank_code']=self.application_bank_code
        except:
            pass
        try:
            self.return_dict['application_branch_code']=self.application_branch_code
        except:
            pass
        try:
            self.return_dict['application_country_code']=self.application_country_code
        except:
            pass
        try:
            self.return_dict['application_location_code']=self.application_location_code
        except:
            pass
        try:
            self.return_dict['application_country_bank_code']=self.application_country_bank_code
        except:
            pass
        try:
            self.return_dict['transaction_reference']=self.text.transaction_reference
        except:
            pass
        try:
            self.return_dict['bank_operation_code']=self.text.bank_operation_code
        except:
            pass
        try:
            self.return_dict['interbank_settled_currency']=self.text.interbank_settled_currency
        except:
            pass
        try:
            self.return_dict['interbank_settled_amount']=self.text.interbank_settled_amount
        except:
            pass
        try:
            self.return_dict['original_ordered_currency']=self.text.original_ordered_currency
        except:
            pass
        try:
            self.return_dict['original_ordered_amount']=self.text.original_ordered_amount
        except:
            pass
        try:
            self.return_dict['ordering_customer']=self.text.ordering_customer
        except:
            pass
        try:
            self.return_dict['ordering_institution']=self.text.ordering_institution
        except:
            pass
        try:
            self.return_dict['sender_correspondent']=self.text.sender_correspondent
        except:
            pass
        try:
            self.return_dict['receiver_correspondent']=self.text.receiver_correspondent
        except:
            pass
        try:
            self.return_dict['intermediary']=self.text.intermediary
        except:
            pass
        try:
            self.return_dict['account_with_institution']=self.text.account_with_institution
        except:
            pass
        try:
            self.return_dict['beneficiary']=self.text.beneficiary
        except:
            pass
        try:
            self.return_dict['remittance_information']=self.text.remittance_information
        except:
            pass
        try:
            self.return_dict['details_of_charges']=self.text.details_of_charges
        except:
            pass
        try:
            self.return_dict['sender_to_receiver_information']=self.text.sender_to_receiver_information
        except:
            pass
        try:
            self.return_dict['regulatory_reporting']=self.text.regulatory_reporting
        except:
            pass
        try:
            self.return_dict['date']=self.text.date
        except:
            pass
        try:
            self.return_dict['application_branch_code']=self.application_branch_code
        except:
            pass
        try:
            self.return_dict['application_country_code']=self.application_country_code
        except:
            pass
        try:
            self.return_dict['application_location_code']=self.application_location_code
        except:
            pass
        try:
            self.return_dict['application_country_bank_code']=self.application_country_bank_code
        except:
            pass
        try:
            self.return_dict['transaction_reference']=self.text.transaction_reference
        except:
            pass
        try:
            self.return_dict['bank_operation_code']=self.text.bank_operation_code
        except:
            pass
        try:
            self.return_dict['interbank_settled_currency']=self.text.interbank_settled_currency
        except:
            pass
        try:
            self.return_dict['interbank_settled_amount']=self.text.interbank_settled_amount
        except:
            pass
        try:
            self.return_dict['original_ordered_currency']=self.text.original_ordered_currency
        except:
            pass
        try:
            self.return_dict['original_ordered_amount']=self.text.original_ordered_amount
        except:
            pass
        try:
            self.return_dict['ordering_customer']=self.text.ordering_customer
        except:
            pass
        try:
            self.return_dict['ordering_institution']=self.text.ordering_institution
        except:
            pass
        try:
            self.return_dict['sender_correspondent']=self.text.sender_correspondent
        except:
            pass
        try:
            self.return_dict['receiver_correspondent']=self.text.receiver_correspondent
        except:
            pass
        try:
            self.return_dict['intermediary']=self.text.intermediary
        except:
            pass
        try:
            self.return_dict['account_with_institution']=self.text.account_with_institution
        except:
            pass
        try:
            self.return_dict['beneficiary']=self.text.beneficiary
        except:
            pass
        try:
            self.return_dict['remittance_information']=self.text.remittance_information
        except:
            pass
        try:
            self.return_dict['details_of_charges']=self.text.details_of_charges
        except:
            pass
        try:
            self.return_dict['sender_to_receiver_information']=self.text.sender_to_receiver_information
        except:
            pass
        try:
            self.return_dict['regulatory_reporting']=self.text.regulatory_reporting
        except:
            pass
        try:
            self.return_dict['date']=self.text.date
        except:
            pass
예제 #26
0
def test_bic_allow_invalid():
    bic = BIC('GENODXM1GLS', allow_invalid=True)
    assert bic
    assert bic.country_code == 'DX'
    with pytest.raises(ValueError):
        bic.validate()
예제 #27
0
def test_country_bank_code():
    assert BIC('ABNAJPJTXXX').country_bank_code is None
    assert BIC('GENODEM1GLS').country_bank_code == '43060967'
예제 #28
0
    def approve_payout(self, request, pk=None):
        project = Project.objects.get(pk=pk)
        project_url = reverse('admin:projects_project_change', args=(project.id,))

        # Check IBAN & BIC
        account = project.account_number
        if len(account) < 3:
            self.message_user(request, 'Invalid Bank Account: {}'.format(account), level='ERROR')
            return HttpResponseRedirect(project_url)

        if len(account) and account[0].isalpha():
            # Looks like an IBAN (starts with letter), let's check
            try:
                iban = IBAN(account)
            except ValueError as e:
                self.message_user(request, 'Invalid IBAN: {}'.format(e), level='ERROR')
                return HttpResponseRedirect(project_url)
            project.account_number = iban.compact
            try:
                bic = BIC(project.account_details)
            except ValueError as e:
                self.message_user(request, 'Invalid BIC: {}'.format(e), level='ERROR')
                return HttpResponseRedirect(project_url)
            project.account_details = bic.compact
            project.save()

        if not request.user.has_perm('projects.approve_payout'):
            self.message_user(request, 'Missing permission: projects.approve_payout', level='ERROR')
        elif project.payout_status != 'needs_approval':
            self.message_user(request, 'The payout does not have the status "needs approval"', level='ERROR')
        else:
            adapter = DoradoPayoutAdapter(project)
            try:
                adapter.trigger_payout()
            except PayoutValidationError as e:
                errors = e.message['errors']
                if type(errors) == unicode:
                    self.message_user(
                        request,
                        'Account details: {}.'.format(errors),
                        level=messages.ERROR
                    )
                else:
                    for field, errors in errors.items():
                        for error in errors:
                            self.message_user(
                                request,
                                'Account details: {}, {}.'.format(field, error.lower()),
                                level=messages.ERROR
                            )
            except (PayoutCreationError, ImproperlyConfigured) as e:
                logger.warning(
                    'Error approving payout: {}'.format(e),
                    exc_info=1
                )

                self.message_user(
                    request,
                    'Failed to approve payout: {}'.format(e),
                    level=messages.ERROR
                )

        return HttpResponseRedirect(project_url)
예제 #29
0
파일: record836.py 프로젝트: Minege/dta
    def validate(self) -> None:  # pylint: disable=too-complex, too-many-branches
        """Validate the field's value of the record."""
        super().validate()
        if self.header.processing_date != '000000':
            self.header.add_error(
                'processing_date',
                "NOT PERMITTED: header processing date must be '000000'.")

        if self.header.recipient_clearing.strip():
            self.header.add_error(
                'recipient_clearing',
                "NOT ALLOWED: beneficiary's bank clearing number must be blank."
            )

        if self.header.transaction_type != '836':
            self.header.add_error('transaction_type',
                                  "INVALID: Transaction type must be TA 836.")

        if self.header.payment_type not in ('0', '1'):
            self.header.add_error(
                'payment_type', "INVALID: Payment type must be 0 or 1 TA 836.")

        if not remove_whitespace(self.reference):
            self.add_error(
                'reference',
                "MISSING TRANSACTION NUMBER: Reference may not be blank.")

        try:
            client_iban = IBAN(self.client_account, allow_invalid=False)
        except ValueError:  # Will throw ValueError if it is not a valid IBAN
            self.add_error(
                'client_account',
                "IBAN INVALID: Client account must be a valid with a 21 digit Swiss IBAN (CH resp. LI) ."
            )
        else:
            if not is_swiss_iban(client_iban):
                self.add_error(
                    'client_account',
                    "IBAN INVALID: Client account must be a valid with a 21 digit Swiss IBAN (CH resp. LI) ."
                )

        # Bank clearing is at pos 5-9 in IBAN
        if self.client_account[4:9].lstrip(
                '0') != self.header.client_clearing.strip():
            self.add_error(
                'client_account',
                "IID IN IBAN NOT IDENTICAL WITH BC-NO: IID in IBAN (pos. 5 to 9) must concur with the "
                "ordering party's BC no.")

        now = datetime.now()
        ten_days_ago = now - timedelta(days=10)
        sixty_days_ahead = now + timedelta(days=60)
        try:
            value_date = datetime.strptime(self.value_date, Date.DATE_FORMAT)
        except ValueError:
            self.add_error('value_date', "INVALID: Must contain a valid date.")
        else:
            if value_date < ten_days_ago:
                self.add_error(
                    'value_date',
                    "EXPIRED: value date may not be elapsed more than 10 calendar days."
                )
            elif value_date > sixty_days_ahead:
                self.add_error(
                    'value_date',
                    "TOO FAR AHEAD: value date may not exceed the reading in date + 60 days."
                )

        decimal_places = len(self.amount.strip().split(',', maxsplit=1)[1])
        if self.currency == 'CHF' and decimal_places > 2:
            self.add_error(
                'currency',
                "MORE THAN 2 DECIMAL PLACES: Amount may not contain more than 2 decimal places."
            )
        elif self.currency != 'CHF' and decimal_places > 3:
            self.add_error(
                'currency',
                " MORE THAN 3 DECIMAL PLACES: Amount may not contain more than 3 decimal places (foreign currencies)."
            )

        if not any(self.client_address):
            self.add_error(
                'client_address',
                "INCOMPLETE: Ordering party address, at least one line must exist."
            )
        if self.bank_address_type == IdentificationBankAddress.SWIFT_ADDRESS:
            try:
                BIC(self.bank_address1).validate()
            except ValueError:
                self.add_error(
                    'bank_address_type',
                    f"INCORRECT FIELD IDENTIFICATION: bank address type {IdentificationBankAddress.SWIFT_ADDRESS} "
                    f"may only be used if an 8 or 11 character BIC address (SWIFT) exists."
                )
        # No specification on how to validate a bank's address if the `bank_address_type` is not SWIFT.

        if all(not line1.strip() or not line2.strip()
               for line1, line2 in combinations(self.client_address, 2)):
            self.add_error(
                'client_address',
                "INCOMPLETE: At least two address lines must exist.")

        if any('/C/' in address for address in self.client_address):
            self.add_error('client_address',
                           "INVALID: /C/ may not be present for TA 836.")
예제 #30
0
def test_invalid_bic(code):
    with pytest.raises(ValueError):
        BIC(code)