diff --git a/CHANGELOG.md b/CHANGELOG.md index da7eb34..8ab82f9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,16 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## World's TIN +### Added + +- Utilitário `tin_anguilla` [#506](https://github.com/brazilian-utils/brutils-python/pull/506) +- Utilitário `tin_australia` [#512](https://github.com/brazilian-utils/brutils-python/pull/512) +- Utilitário `tin_united_states_of_america` [#517](https://github.com/brazilian-utils/brutils-python/pull/517) +- Utilitário `tin_venezuela` [#520](https://github.com/brazilian-utils/brutils-python/pull/520) +- Utilitário `tin_angola` [#523](https://github.com/brazilian-utils/brutils-python/pull/523) + + ## [Unreleased] ### Added diff --git a/README.md b/README.md index 42a41b0..bab9852 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@

🇧🇷 Brazilian Utils

-

Utils library for Brazilian-specific businesses.

+

Biblioteca de utilitários para empresas específicas do Brasil.

[![codecov](https://codecov.io/gh/brazilian-utils/brutils-python/branch/main/graph/badge.svg?token=5KNECS8JYF)](https://codecov.io/gh/brazilian-utils/brutils-python) [![Downloads per Month](https://shields.io/pypi/dm/brutils)](https://pypistats.org/packages/brutils) @@ -41,1219 +41,181 @@ False # Utilitários -- [CPF](#cpf) - - [is\_valid\_cpf](#is_valid_cpf) - - [format\_cpf](#format_cpf) - - [remove\_symbols\_cpf](#remove_symbols_cpf) - - [generate\_cpf](#generate_cpf) -- [CNPJ](#cnpj) - - [is\_valid\_cnpj](#is_valid_cnpj) - - [format\_cnpj](#format_cnpj) - - [remove\_symbols\_cnpj](#remove_symbols_cnpj) - - [generate\_cnpj](#generate_cnpj) -- [CEP](#cep) - - [is\_valid\_cep](#is_valid_cep) - - [format\_cep](#format_cep) - - [remove\_symbols\_cep](#remove_symbols_cep) - - [generate\_cep](#generate_cep) - - [get\_address\_from\_cep](#get_address_from_cep) - - [get\_cep\_information\_from\_address](#get_cep_information_from_address) -- [Telefone](#telefone) - - [is\_valid\_phone](#is_valid_phone) - - [format\_phone](#format_phone) - - [remove\_symbols\_phone](#remove_symbols_phone) - - [remove\_international\_dialing\_code](#remove_international_dialing_code) - - [generate\_phone](#generate_phone) -- [Email](#email) - - [is\_valid\_email](#is_valid_email) -- [Data](#date) - - [convert\_date\_to_text](#convert_date_to_text) -- [Placa de Carro](#placa-de-carro) - - [is\_valid\_license\_plate](#is_valid_license_plate) - - [format\_license\_plate](#format_license_plate) - - [remove\_symbols\_license\_plate](#remove_symbols_license_plate) - - [generate\_license\_plate](#generate_license_plate) - - [convert\_license\_plate\_to\_mercosul](#convert_license_plate_to_mercosul) - - [get\_format\_license\_plate](#get_format_license_plate) -- [PIS](#pis) - - [is\_valid\_pis](#is_valid_pis) - - [format\_pis](#format_pis) - - [remove\_symbols\_pis](#remove_symbols_pis) - - [generate\_pis](#generate_pis) -- [Processo Jurídico](#processo-jurídico) -- [is\_valid\_legal\_process](#is_valid_legal_process) - - [format\_legal\_process](#format_legal_process) - - [remove\_symbols\_legal\_process](#remove_symbols_legal_process) - - [generate\_legal\_process](#generate_legal_process) -- [Titulo Eleitoral](#titulo-eleitoral) - - [is\_valid\_voter\_id](#is_valid_voter_id) - - [format\_voter\_id](#format_voter_id) - - [generate\_voter\_id](#generate_voter_id) -- [IBGE](#ibge) - - [get_code_by_municipality_name](#get_code_by_municipality_name) - - [convert_code_to_uf](#convert_code_to_uf) - - [get\_municipality\_by\_code](#get_municipality_by_code) -- [Feriados](#feriados) - - [is_holiday](#is_holiday) -- [Monetário](#monetário) - - [format\_currency](#format_currency) - -## CPF - -### is_valid_cpf - -Retorna se os dígitos de verificação do CPF fornecido -correspondem ao seu número base. Esta função não verifica a existência do CPF; -ela apenas valida o formato da string. -Argumentos: - -- cpf (str): O CPF a ser validado, uma string de 11 dígitos - -Retorna: - -- bool: Verdadeiro se os dígitos de verificação corresponderem ao número base, - Falso caso contrário. - -Exemplo: - -```python ->>> from brutils import is_valid_cpf ->>> is_valid_cpf("82178537464") -True ->>> is_valid_cpf('00011122233') -False -``` - -### format_cpf - -Formata um CPF (Cadastro de Pessoa Física brasileiro) para exibição visual. -Esta função recebe uma string de CPF contendo apenas números como entrada e -adiciona símbolos de formatação padrão para exibição. - -Argumentos: - -- cpf (str): Uma string de CPF contendo apenas números. - -Retorna: - -- str: O CPF formatado com símbolos visuais se for válido, - None se não for válido. - -Exemplo: - -```python ->>> from brutils import format_cpf ->>> format_cpf('82178537464') -'821.785.374-64' ->>> format_cpf("55550207753") -'555.502.077-53' -``` - -### remove_symbols_cpf - -Remove símbolos específicos de uma string de CPF (Cadastro de Pessoa Física -brasileiro). Esta função recebe como entrada uma string de CPF e remove todas as -ocorrências dos caracteres '.', '-' dela. - -Argumentos: - -- cpf (str): A string de CPF contendo os símbolos a serem removidos. - -Retorna: - -- str: Uma nova string com os símbolos especificados removidos. - -Exemplo: - -```python ->>> from brutils import remove_symbols_cpf ->>> remove_symbols_cpf('000.111.222-33') -'00011122233' -``` - -### generate_cpf - -Gerar uma string de dígitos de CPF válida aleatória. - -Retorna: - -- str: Um CPF válido gerado aleatoriamente. - -Exemplo: - -```python ->>> from brutils import generate_cpf ->>> generate_cpf() -'17433964657' ->>> generate_cpf() -"10895948109" -``` - -## CNPJ - -### is_valid_cnpj - -Verifica se os dígitos de verificação do CNPJ (Cadastro Nacional da Pessoa -Jurídica) fornecido correspondem ao seu número base. A entrada deve ser uma -string de dígitos com o comprimento apropriado. Esta função não verifica a -existência do CNPJ; ela só valida o formato da string. - -Argumentos: - -- cnpj (str): O CNPJ a ser validado. - -Retorna: - -- bool: True se os dígitos de verificação corresponderem ao número base, - False caso contrário. - -Exemplo: - -```python ->>> from brutils import is_valid_cnpj ->>> is_valid_cnpj('03560714000142') -True ->>> is_valid_cnpj('00111222000133') -False -``` - -### format_cnpj - -Formata uma string de CNPJ (Cadastro Nacional da Pessoa Jurídica) para exibição -visual. -Esta função recebe uma string de CNPJ como entrada, valida seu formato e a -formata com símbolos visuais padrão para fins de exibição. - -Argumentos: - -- cnpj (str): A string de CNPJ a ser formatada para exibição. - -Retorna: - -- str: O CNPJ formatado com símbolos visuais se for válido, None se não for válido. - -Exemplo: - -```python ->>> from brutils import format_cnpj ->>> format_cnpj("03560714000142") -'03.560.714/0001-42' ->>> format_cnpj("98765432100100") -None -``` - -### remove_symbols_cnpj - -Remove símbolos específicos de uma string de CNPJ (Cadastro Nacional da Pessoa -Jurídica). -Esta função recebe uma string de CNPJ como entrada e remove todas as -ocorrências dos caracteres '.', '/' e '-' dela. - -Argumentos: - -- cnpj (str): A string de CNPJ que contém os símbolos a serem removidos. - -Retorna: - -- str: Uma nova string com os símbolos especificados removidos. - -Exemplo: - -```python ->>> from brutils import remove_symbols_cnpj ->>> remove_symbols_cnpj('00.111.222/0001-00') -'00111222000100' -``` - -### generate_cnpj - -Gera uma string de dígitos CNPJ válida aleatória. Um número de filial -opcional pode ser fornecido; o padrão é 1. - -Argumentos: - -- branch (int): Um número de filial opcional a ser incluído no CNPJ. - -Retorna: - -- str: Um CNPJ válido gerado aleatoriamente. - -Exemplo: - -```python ->>> from brutils import generate_cnpj ->>> generate_cnpj() -'34665388000161' ->>> generate_cnpj(1234) -"01745284123455" -``` - -## CEP - -### is_valid_cep - -Verifica se um CEP (Código de Endereçamento Postal) brasileiro é válido. -Para que um CEP seja considerado válido, a entrada deve ser uma string contendo -exatamente 8 dígitos. Esta função não verifica se o CEP é um CEP real, pois -valida apenas o formato da string. - -Argumentos: - -- cep (str): A string contendo o CEP a ser verificado. - -Retorno: - -- bool: True se o CEP for válido (8 dígitos), False caso contrário. - -Exemplo: - -```python ->>> from brutils import is_valid_cep ->>> is_valid_cep('01310200') -True ->>> is_valid_cep("12345") -False ->>> is_valid_cep("abcdefgh") -False -``` - -### format_cep - -Formata um CEP (Código de Endereçamento Postal) brasileiro em um formato padrão. -Esta função recebe um CEP como entrada e, se for um CEP válido com 8 dígitos, -o formata no padrão "12345-678". - -Argumentos: - -- cep (str): O CEP (Código de Endereçamento Postal) de entrada a ser - formatado. - -Retorna: - -- str: O CEP formatado no formato "12345-678" se for válido, None se não for - válido. - -Example: - -```python ->>> from brutils import format_cep ->>> format_cep('01310200') -'01310-200' ->>> format_cep("12345678") -"12345-678" ->>> format_cep("12345") -None -``` - -### remove_symbols_cep - -Remove símbolos específicos de um CEP (Código de Endereçamento Postal) -fornecido. Esta função recebe um CEP como entrada e remove todas as ocorrências -dos caracteres '.' e '-' dele. - -Argumentos: - -- cep (str): O CEP (Código de Endereçamento Postal) de entrada que contém os - símbolos a serem removidos. - -Retorna: - -- str: Uma nova string com os símbolos especificados removidos. - -Exemplo: - -```python ->>> from brutils import remove_symbols_cep ->>> remove_symbols_cep('01310-200') -'01310200' ->>> remove_symbols_cep("123-45.678.9") -"123456789" ->>> remove_symbols_cep("abc.xyz") -"abcxyz" -``` - -### generate_cep - -Gera um número de CEP (Código de Endereçamento Postal) aleatório de 8 dígitos -como uma string. - -Retorna: +- [TIN Australia](#tin_australia) + - [remove\_symbols](#remove_symbols) + - [is\_valid\_tfn](#is_valid_tfn) + - [is\_valid\_abn](#is_valid_abn) + - [format\_tfn](#format_tfn) + - [format\_abn](#format_abn) + - [generate\_tfn](#generate_tfn) + - [generate\_abn](#generate_abn) + - [example\_usage](#example_usage) -- str: Um número de 8 dígitos gerado aleatoriamente. - -Exemplo: - -```python ->>> from brutils import generate_cep ->>> generate_cep() -'77520503' ->>> generate_cep() -'29641407' -``` - -### get_address_from_cep - -Busca as informações de endereço a partir de um CEP (Código de Endereçamento Postal) utilizando a API da ViaCEP. - -Argumentos: - -- cep (str): O CEP a ser utilizado na busca. -- raise_exceptions (bool, opcional): Se deve gerar exceções quando o CEP for inválido ou não for encontrado. O padrão é False. - -Retorna: - -- Address | None: Um objeto Address (TypedDict) contendo as informações de endereço se o CEP for encontrado, caso contrário, None. - -Exemplo: - -```python ->>> from brutils import get_address_from_cep ->>> get_address_from_cep("12345678") -{ - "cep": "12345-678", - "logradouro": "Rua Example", - "complemento": "", - "bairro": "Example", - "localidade": "Example", - "uf": "EX", - "ibge": "1234567", - "gia": "1234", - "ddd": "12", - "siafi": "1234" -} -``` - -### get_cep_information_from_address - -Busca o CEP e outras informações a partir de um endereço utilizando a API da ViaCEP. - -Argumentos: - -- federal_unit (str): Abreviação de duas letras do estado brasileiro. -- city (str): Nome da cidade. -- street (str): Nome (ou substring) da rua. -- raise_exceptions (bool, opcional): Se deve gerar exceções quando o endereço é inválido ou não foi encontrado. O padrão é False. - -Retorna: - -- list[Address] | None: Uma lista de objetos Address (TypedDict) contendo as informações de endereço se o endereço for encontrado, None caso contrário. - -Exemplo: - -```python ->>> from brutils import get_cep_information_from_address ->>> get_cep_information_from_address("EX", "Example", "Rua Example") -[ - { - "cep": "12345-678", - "logradouro": "Rua Example", - "complemento": "", - "bairro": "Example", - "localidade": "Example", - "uf": "EX", - "ibge": "1234567", - "gia": "1234", - "ddd": "12", - "siafi": "1234" - } -] -``` - -## Telefone - -### is_valid_phone - -Retorna se um número de telefone brasileiro é válido conforme o formato da string. -Não verifica se o número realmente existe. -``` - -is_valid_phone(phone_number, type) - -``` - -Argumentos: - -- phone_number (str): - - o número de telefone a ser validado - - apenas dígitos, sem símbolos - - sem o código do país - - deve incluir o número de DDD com dois dígitos - - exemplo: '+55 48 9999 9999' deve ser utilizado como '4899999999' - - obrigatório - -- type (str): - - 'mobile' para validar apenas números de celular - - 'landline' para validar apenas números de telefone fixo - - caso não especificado, valida para um para o outro. - - opcional - -Retorna: - -- bool: True se o número é válido, False caso contrário. - -Exemplo: - -```python ->>> from brutils import is_valid_phone ->>> is_valid_phone('11994029275') -True ->>> is_valid_phone('11994029275', 'mobile') -True ->>> is_valid_phone('1938814933', 'landline') -True -``` - -### format_phone - -Formata um número de telefone para exibição visual. Esta função recebe uma string representando um número de telefone contendo apenas números como entrada e adiciona símbolos de formatação padrão para exibição. - -Argumentos: - -- phone (str): Uma string representando um número de telefone. - -Retorna: - -- str: O número de telefone formatado para exibição ou None se não for válido. - -Exemplo: - -```python ->>> from brutils import format_phone ->>> format_phone("11994029275") -'(11)99402-9275' ->>> format_phone("1635014415") -'(16)3501-4415' ->>> format_phone("333333") -None -``` - -### remove_symbols_phone - -Remove símbolos do número de telefone. Esta função recebe um número de telefone como entrada e remove todos os símbolos, como parênteses '()', traços '-' e espaços ' '. - -Argumentos: - -- phone (str): O número de telefone de entrada que contém os símbolos a serem removidos. - -Retorna: - -- str: Uma nova string com os símbolos especificados removidos. - -Exemplo: - -```python ->>> from brutils import remove_symbols_phone ->>> remove_symbols_phone('(21)2569-6969') -'2125696969' ->>> remove_symbols_phone('11 9999-8888') -'1199998888' ->>> remove_symbols_phone('333333') -'333333' -``` - -### remove_international_dialing_code - -Remove o código internacional (+55) de uma string que contém um número de telefone brasileiro, mantendo outros caracteres especiais. - -Argumentos: - -- phone (str): O número de telefone de entrada que pode conter o código internacional. - -Retorna: - -- str: Uma nova string sem o código internacional, preservando outros caracteres especiais. - -Exemplo: - -```python ->>> from brutils import remove_international_dialing_code ->>> remove_international_dialing_code("5521994029275") -"21994029275" ->>> remove_international_dialing_code("+5521994029275") -"+21994029275" ->>> remove_international_dialing_code("5555994029275") -"55994029275" ->>> remove_international_dialing_code("21994029275") -"21994029275" ->>> remove_international_dialing_code("(+55)21994029275") -"(+)21994029275" -``` +## NIF Austrália -### generate_phone +### remove_symbols -Gera um número de telefone aleatório válido. +Remove espaços, pontos e hifens da sequência de entrada (input) dado pelo usuário. Argumentos: -- type (str): Pode ser "landline" ou "mobile". - Se não for especificado, a função gera um número - aleatório de qualquer tipo. +- tin (str): O TIN (NIF) a ser validado, uma string de 8 a 11 dígitos (números). Retorna: -- str: Um número de telefone válido gerado aleatoriamente. - -Exemplo: - -```python ->>> from brutils import generate_phone ->>> generate_phone() -"5929797740" ->>> generate_phone("mobile") -"1899115895" ->>> generate_phone("landline") -"5535317900" -``` - -## Email - -### is_valid_email - -Verificar se uma string corresponde a um endereço de e-mail válido. - -Argumentos: - -- email (str): A string de entrada a ser verificada. - -Retorna: - -- bool: Verdadeiro se o email for um endereço de e-mail válido, Falso - caso contrário. - -Exemplo: - -```python -from brutils import is_valid_email - ->>> is_valid_email("joao.ninguem@gmail.com") -True ->>> is_valid_email(".joao.ninguem@gmail.com") -False ->>> is_valid_email("joao.ninguem@gmail.") -False ->>> is_valid_email("joao ninguem@gmail.com") -False -``` - -## Data - -## convert_date_to_text - -Converte uma data em sua representação textual. - -Argumentos: - - date (str): Uma string no formato dd/mm/aaaa - -Retorna: - - A represetação textual da data ou None caso a data esteja mal formatada ou a data seja inválida. - -Exemplo: - -````python ->>> from brutils import convert_date_to_text ->>> convert_date_to_text("25/12/2000") -"Vinte e cinco de dezembro de dois mil" ->>> convert_date_to_text("31/02/2000") -None ->>> convert_date_to_text("29/02/2024") -"Vinte e nove de fevereiro de dois mil e vinte e quatro" ->>> convert_date_to_text("1/08/2024") -"Primeiro de agosto de dois mil e vinte e quatro" -```` - - -## Placa de Carro - -### is_valid_license_plate - -Verifica se uma placa de carro é válida. -Esta função não verifica se a placa de carro é uma placa de carro real, -apenas valida o formato da string. - -Argumentos: - -- license_plate (str): Uma string representando uma placa de carro. -- type (str): "old_format" ou "mercosul". - Se não especificado, verifica um ou outro. - -Retorna: - -- bool: True se a placa de carro for válida, False caso contrário. - -Exemplo: - -```python ->>> from brutils import is_valid_license_plate ->>> is_valid_license_plate('ABC1234') -True ->>> is_valid_license_plate('def5678', type="old_format") -True ->>> is_valid_license_plate('ABC4E67') -True ->>> is_valid_license_plate('ABC4E67', type="mercosul") -True ->>> is_valid_license_plate('GHI-4567') -False -``` - -### format_license_plate - -Formata uma placa de carro no padrão correto. -Esta função recebe uma placa de carro em qualquer formato (LLLNNNN ou LLLNLNN) e retorna uma versão formatada. - -Argumentos: - -- license_plate (str): Uma string representando uma placa de carro. - -Retorna: - -- str: A string da placa de carro formatada ou - 'None' se a entrada for inválida. - -Exemplo: - -```python ->>> from brutils import format_license_plate ->>> format_license_plate("ABC1234") -"ABC-1234" -# formato antigo (contém traço) ->>> format_license_plate("abc1234") -"ABC-1234" -# formato antigo (contém traço) ->>> format_license_plate("ABC1D23") -"ABC1D23" -# formato mercosul ->>> format_license_plate("abc1d23") -"ABC1D23" -# formato mercosul ->>> format_license_plate("ABCD123") -None -``` - -### remove_symbols_license_plate - -Remove o símbolo de hífen (-) de uma string de placa de carro. - -Argumentos: - -- license_plate_number (str): Uma string de placa de carro contendo símbolos a serem removidos. - -Retorna: - -- str: A string da placa de carro com os símbolos especificados removidos. - -Exemplo: - -```python -from brutils import remove_symbols_license_plate ->>> remove_symbols_license_plate("ABC-123") -"ABC123" ->>> remove_symbols_license_plate("abc123") -"abc123" ->>> remove_symbols_license_plate("ABCD123") -"ABCD123" ->>> remove_symbols_license_plate("@abc#-#123@") -"@abc##123@" -``` - -### generate_license_plate - -Gera uma placa de carro válida no formato especificado. Caso nenhum formato seja fornecido, ele retornará uma placa de carro no formato Mercosul. - -Argumentos: - -- format (str): O formato desejado para a placa de carro. 'LLLNNNN' para o formato antigo ou 'LLLNLNN' para o formato Mercosul. O padrão é 'LLLNLNN'. - -Retorna: - -- str: Um número de placa de carro gerado aleatoriamente ou - None se o formato for inválido. - -Exemplo: - -```python -from brutils import generate_license_plate ->>> generate_license_plate() -"ABC1D23" ->>> generate_license_plate(format="LLLNLNN") -"ABC4D56" ->>> generate_license_plate(format="LLLNNNN") -"ABC123" ->>> generate_license_plate(format="invalid") -None -``` - -### convert_license_plate_to_mercosul - -Converte uma placa de carro no formato antigo (LLLNNNN) para o formato Mercosul (LLLNLNN). - -Argumentos: - -- license_plate(str): Uma string com o tamanho adequado que representa a placa no formato antigo. - -Retorna: - -- str: A placa Mercosul convertida (LLLNLNN) ou None se a entrada for inválida. - -Exemplo: - -```python ->>> from brutils import convert_license_plate_to_mercosul ->>> convert_license_plate_to_mercosul("ABC123") -"ABC1C34" ->>> convert_license_plate_to_mercosul("abc123") -"ABC1C34" ->>> convert_license_plate_to_mercosul("ABC1D23") -None -``` - -### get_format_license_plate - -Retorna o formato de uma placa de carro. 'LLLNNNN' para o formato antigo e -'LLLNLNN' para o formato Mercosul. - -Argumentos: - -- license_plate (str): Uma string de placa de carro sem símbolos. - -Retorna: - -- str: O formato da placa de carro (LLLNNNN, LLLNLNN) ou - 'None' se o formato for inválido. - -Exemplo: - -```python -from brutils import get_format_license_plate ->>> get_format_license_plate("ABC123") -"LLLNNNN" ->>> get_format_license_plate("abc123") -"LLLNNNN" ->>> get_format_license_plate("ABC1D23") -"LLLNLNN" ->>> get_format_license_plate("abc1d23") -"LLLNLNN" ->>> get_format_license_plate("ABCD123") -None -``` - -## PIS - -### is_valid_pis - -Verifica se o número PIS/PASEP é valido. Apenas números, formatados como string. Não verifica se o PIS/PASEP realmente existe. - -Referências: - -- . - -Argumentos: - -- pis (str): Número PIS como uma string com o comprimento apropriado. - -Retorna: - -- bool: True se o PIS for válido, False caso contrário. - -Exemplo: - -```python -from brutils import is_valid_pis ->>> is_valid_pis("82178537464") -False ->>> is_valid_pis("12082043519") -True -``` +- bool: Verdadeiro se os dígitos de verificação corresponderem ao número base, + Falso caso contrário. -### format_pis +### is_valid_tfn -Formata uma string de PIS (Programa de Integração Social) válida com símbolos e adiciona símbolos de formatação padrão para exibição. +Australian Tax File Number (TFN). Valida o TIN da pessoa física (cidadão / indivíduo) para garantir que esteja dentro das especificações do país passadas como parâmetros! Argumentos: -- pis (str): Uma string válida de PIS contendo apenas números. +- tin (str): Uma string com 8 ou 9 dígitos (1 dígito de verificação). Retorna: -- str: Uma string de PIS formatada com símbolos visuais padrão ou None se a entrada for inválida. +- str: Se o input passado pelo usuário conter qualquer coisa diferente do argumento acima, retorna uma mensagem de "inválido", como erro. Exemplo: ```python -from brutils import format_pis ->>> format_pis("17033259504") -'170.33259.50-4' ->>> format_pis("12013128292") -'120.13128.29-2' +>>> from tin_Australia import is_valid_tfn +>>> is_valid_tfn("123 456 789") => 'Valid Australia TIN' +>>> is_valid_tfn("1230 456 789") => 'Invalid Australia TIN' ``` -### remove_symbols_pis +### is_valid_abn -Esta função recebe uma string de PIS (Programa de Integração Social) com símbolos de formatação e retorna uma versão limpa sem símbolos. Remove apenas os símbolos "-" e "." , propositalmente não remove outros símbolos. +Australian Business Number (ABN) - Valida o TIN da pessoa jurírica (empresa) para garantir que esteja dentro das especificações do país passadas como parâmetros! Argumentos: -- pis (str): Uma string de PIS que pode conter símbolos de formatação. - -Retorna: - -- str: Uma string de PIS limpa, sem símbolos de formatação. - -Exemplo: - -```python -from brutils import remove_symbols_pis - ->>> remove_symbols_pis('170.33259.50-4') -'17033259504' ->>> remove_symbols_pis("123.456.789-09") -'12345678909' ->>> remove_symbols_pis('/._') -'/_' -``` - -### generate_pis - -Gera uma string de dígitos contendo um número de um PIS brasileiro válido aleatório. +- tin (str): Uma string de 11 dígitos (2 dígitos de verificação). Retorna: -- str: Um número PIS válido gerado aleatoriamente como string. +- str: Se o input passado pelo usuário conter qualquer coisa diferente do argumento acima, retorna uma mensagem de "inválido", como erro. Exemplo: ```python -from brutils import generate_pis ->>> generate_pis() -'61352489741' ->>> generate_pis() -'73453349671' +>>> from tin_Australia import is_valid_abn +>>> is_valid_abn("12 345 678 901") => 'Valid Australia TIN' +>>> is_valid_abn("120 345 678 901") => 'Invalid Australia TIN' ``` -## Processo Jurídico - -## is_valid_legal_process +### format_tfn -Verifica se um ID de processo jurídico é válido, não verifica se o ID de processo jurídico é um ID de processo -jurídico real; ela apenas valida o formato da string. - -Argumentos: - -- legal_process_id (str): Uma string contendo apenas dígitos que representa - o ID do processo jurídico. - -Retorna: +Australian Tax File Number (TFN) - Formata um TIN para exibição. -- bool: True se o ID do processo jurídico for válido, False caso - contrário. - -Examplo: - -```python ->>> from brutils import is_valid_legal_process ->>> is_valid_legal_process('10188748220234018200') -True ->>> is_valid_legal_process('45532346920234025107') -True ->>> is_valid_legal_process('00000000000000000000') -False ->>> is_valid_legal_process('455323423QQWEQWSsasd&*(()') -False ->>> -``` - -### format_legal_process - -Formata um ID de processo jurídico em um formato padrão. - -Argumentos: - -- legal_process_id (str): Uma string de 20 dígitos que representa o ID do - processo jurídico. - -Retorna: - -- str: O ID do processo jurídico formatado ou None se a entrada for inválida. - -Exemplo: - -```python ->>> from brutils import format_legal_process ->>> format_legal_process('23141945820055070079') -'2314194-58.2005.5.07.0079' ->>> format_legal_process('00000000000000000000') -'0000000-00.0000.0.00.0000' ->>> -``` - -### remove_symbols_legal_process - -Remove símbolos específicos de um processo jurídico fornecido. - -Esta função recebe um processo jurídico como entrada e remove todas as -ocorrências dos caracteres '.' e '-' dele. - -Argumentos: +Args: -- legal_process (str): Um processo jurídico contendo símbolos a serem - removidos. +- tin (str): Adiciona os separados corretos conforme os parâmetros do país. Retorna: -- str: A string do processo jurídico com os símbolos especificados removidos. +- str: Um TIN formatado com os separadores no lugar certo! Exemplo: ```python -from brutils import remove_symbols_legal_process ->>> remove_symbols_legal_process("6439067-89.2023.4.04.5902") -"64390678920234045902" ->>> remove_symbols_legal_process("4976023-82.2012.7.00.2263") -"49760238220127002263" ->>> remove_symbols_legal_process("4976023-82.2012.7.00.2263*!*&#") -"49760238220127002263*!*&#" +>>> from tin_Australia import format_tfn +>>> format_tfn("123456789") => ("123 456 789") ``` -### generate_legal_process +### format_abn -Gera um número válido aleatório de ID de processo jurídico. +Australian Business Number (ABN) - Formata um TIN para exibição. -Argumentos: +Args: -- year (int): O ano para o ID do processo jurídico (o padrão é o ano atual). - Não pode ser um ano do passado. -- orgao (int): O órgão (1-9) para o ID do processo jurídico - (o padrão é aleatório). +- tin (str): Adiciona os separados corretos conforme os parâmetros do país. Retorna: -- str: Um ID de processo jurídico gerado aleatoriamente. - None caso algum dos argumento seja inválido. +- str: Um TIN formatado com os separadores no lugar certo! Exemplo: - ```python ->>> from brutils import generate_legal_process ->>> generate_legal_process() -"45676401020238170592" ->>> generate_legal_process(ano=2025) -"32110268020258121130" ->>> generate_legal_process(orgao=5) -"37573041520235090313" ->>> generate_legal_process(ano=2024, orgao=4) -"33158248820244017105" +>>> from tin_Australia import format_abn +>>> format_abn("12345678901") => ("12 345 678 901") ``` -## Titulo Eleitoral - -### is_valid_voter_id -Verifica se um número de Título de Eleitor brasileiro é válido. Não verifica se realmente existe. +### generate_tfn -Referências: +Australian Tax File Number (TFN) - Gera um TIN de Australia válido. -- -- - -Argumentos: +Args: -- voter_id (str): string representando o número do título de eleitor a ser verificado. +- tin (str): Gera um TIN de Australia válido. Retorna: -- bool: True se o número do título de eleitor for válido. False, caso contrário. +- str: Gera um número válido dados os parâmetros corretos. Exemplo: ```python ->>> from brutils import is_valid_voter_id ->>> is_valid_voter_id('123456789011') -False ->>> is_valid_voter_id('427503840213') -True +>>> from tin_Australia import generate_tfn +>>> generate_tfn("123 456 789") => 'Valid Australia TIN' +>>> generate_tfn("1230 456 789") => 'Invalid Australia TIN' ``` -### format_voter_id - -Formata um número de Título de Eleitor para exibição visual. - -Esta função recebe uma string de Título de Eleitor contendo -apenas números como entrada e adiciona os espaços de formatação -padrão para exibição. - -Argumentos: - * voter_id (str): Uma string de Título de Eleitor contendo apenas números. - -Retorna: - * str: O Título de Eleitor formatado com os espaços, se for válido. - Retorna None se não for válido. - -Exemplo: - -```python ->>> from brutils import format_voter_id ->>> format_voter_id("246593980493") -'2465 9398 04 93' ->>> format_voter_id("202715292895") -'2027 1529 28 95' ->>> format_voter_id("739035552205") ->>> -``` -### generate_voter_id +### generate_abn -Gera uma string de dígitos de Título de Eleitor válida aleatória a partir de um estado brasileiro informado. +Australian Business Number (ABN) - Gera um TIN de Australia válido. Args: - * federative_union (str): Unidade Federativa para o título de eleitor que será gerado. O valor padrão "ZZ" é usado para Títulos de Eleitor emitidos para estrangeiros. -Retorna: - * str: Um Título de Eleitor válido gerado aleatoriamente. - -Exemplo: - -```python ->>> from brutils import generate_voter_id ->>> generate_voter_id() -'183475722801' ->>> generate_voter_id(federative_union ="MG") -'950125640248' -``` - -## IBGE - -### convert_code_to_uf -Converte um determinado código do IBGE (string de 2 dígitos) para sua UF (abreviatura estadual) correspondente. - -Args: - * code (str): O código IBGE de 2 dígitos a ser convertido. +- tin (str): Gera um TIN de Australia válido. Retorna: - * str or None: O código UF correspondente ao código IBGE, ou None se o - código IBGE for inválido. - -Exemplo: - -```python ->>> from brutils.ibge.uf import convert_code_to_uf ->>> convert_code_to_uf("12") -'AC' ->>> convert_code_to_uf("33") -'RJ' ->>> convert_code_to_uf("99") ->>> -``` -### get_municipality_by_code - -Retorna o nome do município e a UF para um código do IBGE. - -Args: - * code (str): O código do IBGE para o município. - -Returns: - * tuple: Retorna uma Tupla formatado como ("Município", "UF"). - * None: Retorna None se o código for inválido. - -Example: - -```python ->>> from brutils import get_municipality_by_code ->>> get_municipality_by_code(3550308) -("São Paulo", "SP") -``` - -### get_code_by_municipality_name - -Retorna o código IBGE para um dado nome de município e código de UF. - -Essa função recebe uma string representando o nome de um município e o código da UF, e retorna o código IBGE correspondente (string). A função lida com os nomes ignorando diferenças de maiúsculas, acentos, tratando o caractere "ç" como "c", e ignorando diferenças de maiúsculas para o código da UF. - -Argumentos: - * municipality_name (str): O nome do município. - * uf (str): O código UF do estado. - -Retorna: - * str: O código IBGE do município. Retorna None se o nome não for válido ou não existir. +- str: Gera um número válido dados os parâmetros corretos. Exemplo: ```python ->>> from brutils import get_code_by_municipality_name ->>> get_code_by_municipality_name("São Paulo", "SP") -"3550308" ->>> get_code_by_municipality_name("goiania", "go") -"5208707" ->>> get_code_by_municipality_name("Conceição do Coité", "BA") -"2908408" ->>> get_code_by_municipality_name("conceicao do Coite", "Ba") -"2908408" ->>> get_code_by_municipality_name("Municipio Inexistente", "") -None ->>> get_code_by_municipality_name("Municipio Inexistente", "RS") -None +>>> from tin_Australia import generate_abn +>>> generate_abn("12 345 678 901") => 'Valid Australia TIN' +>>> generate_abn("120 345 678 901") => 'Invalid Australia TIN' ``` -## Feriados -### is_holiday +### example_usage -Verifica se uma determinada data é um feriado nacional ou estadual no Brasil. - -Esta função recebe um objeto `datetime` como a data e uma UF opcional (Unidade Federativa) para especificar feriados estaduais. Retorna `True` se a data for um feriado, `False` se não for, ou `None` se a data ou UF forem inválidas. Nota: a função não abrange feriados municipais. +Gera TIN válido aleatoriamente como exemplo para pessoas físicas e jurídicas, analisa o input do usuário, além de formatá-los. Argumentos: -- `date (datetime)`: A data a ser verificada. -- `uf (str, opcional)`: A abreviação do estado (UF) para verificar feriados estaduais. Se não fornecido, apenas feriados nacionais são considerados. +- str: Um TIN válido gerado aleatoriamente como exemplo para pessoas físicas e jurídicas, input do usuário. Retorna: -- `bool | None`: `True` se a data for um feriado, `False` se não for, ou `None` se a data ou UF forem inválidas. +- str: Um TIN válido gerado aleatoriamente como exemplo para pessoas físicas e jurídicas, input do usuário analisado e formatado com símbolos visuais se for válido, None se não for válido. Exemplo: ```python ->>> from datetime import datetime ->>> from brutils import is_holiday - ->>> is_holiday(datetime(2024, 1, 1)) -True ->>> is_holiday(datetime(2024, 1, 2)) -False ->>> is_holiday(datetime(2024, 3, 2), uf="SP") -False ->>> is_holiday(datetime(2024, 12, 25), uf="RJ") -True -``` - -## Monetário - -### format_currency +>>> from tin_Australia import example_usage +>>> tin_tfn("123456789") => 'Valid Australia TIN tfn' +>>> tin_abn("12345678901") => 'Valid Australia TIN abn' -Formata um número seguindo o padrão monetário brasileiro. O número será formatado -adicionando o símbolo R$ como prefixo, vírgula como separador decimal, e ponto como -agrupador de milhar. +>>> is_valid(tin_tfn) => 'Valid Australia TIN abn' +>>> is_valid(tin_abn) => 'Valid Australia TIN abn' -Argumentos: - * float ou Decimal: Um número com ou sem casas decimais. - -Retorna: - * str ou None: O número formatado seguindo o padrão brasileiro. +>>> is_valid(user_input)("36485987125") => 'Valid input - Australia TIN abn' -Exemplo: - -```python ->>> from brutils.currency import format_currency ->>> format_currency(1259.03) -'R$ 1.259,03' ->>> format_currency(0) -'R$ 0,00' ->>> format_currency("not a number") -None +>>> formatted_input = format_tin(user_input) => ("36 485 987 125") ``` +--- + # Novos Utilitários e Reportar Bugs Caso queira sugerir novas funcionalidades ou reportar bugs, basta criar @@ -1291,4 +253,4 @@ Vamos construir juntos! 🚀🚀

-_Feito por [contrib.rocks](https://contrib.rocks)._ \ No newline at end of file +_Feito por [contrib.rocks](https://contrib.rocks)._ diff --git a/README_EN.md b/README_EN.md index 4f97c00..5820fb3 100644 --- a/README_EN.md +++ b/README_EN.md @@ -41,1221 +41,186 @@ False # Utilities -- [CPF](#cpf) - - [is\_valid\_cpf](#is_valid_cpf) - - [format\_cpf](#format_cpf) - - [remove\_symbols\_cpf](#remove_symbols_cpf) - - [generate\_cpf](#generate_cpf) -- [CNPJ](#cnpj) - - [is\_valid\_cnpj](#is_valid_cnpj) - - [format\_cnpj](#format_cnpj) - - [remove\_symbols\_cnpj](#remove_symbols_cnpj) - - [generate\_cnpj](#generate_cnpj) -- [CEP](#cep) - - [is\_valid\_cep](#is_valid_cep) - - [format\_cep](#format_cep) - - [remove\_symbols\_cep](#remove_symbols_cep) - - [generate\_cep](#generate_cep) - - [get\_address\_from\_cep](#get_address_from_cep) - - [get\_cep\_information\_from\_address](#get_cep_information_from_address) -- [Date](#date) - - [convert\_date\_to_text](#convert_date_to_text) -- [Phone](#phone) - - [is\_valid\_phone](#is_valid_phone) - - [format\_phone](#format_phone) - - [remove\_symbols\_phone](#remove_symbols_phone) - - [remove\_international\_dialing\_code](#remove_international_dialing_code) - - [generate\_phone](#generate_phone) -- [Email](#email) - - [is\_valid\_email](#is_valid_email) -- [License Plate](#license-plate) - - [is\_valid\_license\_plate](#is_valid_license_plate) - - [format\_license\_plate](#format_license_plate) - - [remove\_symbols\_license\_plate](#remove_symbols_license_plate) - - [generate\_license\_plate](#generate_license_plate) - - [convert\_license\_plate\_to\_mercosul](#convert_license_plate_to_mercosul) - - [get\_format\_license\_plate](#get_format_license_plate) -- [PIS](#pis) - - [is\_valid\_pis](#is_valid_pis) - - [format\_pis](#format_pis) - - [remove\_symbols\_pis](#remove_symbols_pis) - - [generate\_pis](#generate_pis) -- [Legal Process](#legal-process) - - [is\_valid\_legal\_process](#is_valid_legal_process) - - [format\_legal\_process](#format_legal_process) - - [remove\_symbols\_legal\_process](#remove_symbols_legal_process) - - [generate\_legal\_process](#generate_legal_process) -- [Voter ID](#voter-id) - - [is_valid_voter_id](#is_valid_voter_id) - - [format_voter_id](#format_voter_id) - - [generate_voter_id](#generate_voter_id) -- [IBGE](#ibge) - - [convert_code_to_uf](#convert_code_to_uf) - - [get\_municipality\_by\_code](#get_municipality_by_code) - - [get_code_by_municipality_name](#get_code_by_municipality_name) -- [Holidays](#holidays) - - [is_holiday](#is_holiday) -- [Monetary](#monetary) - - [format_currency](#format_currency) - -## CPF - -### is_valid_cpf - -Returns whether or not the verifying checksum digits of the given CPF -(Brazilian Individual Taxpayer Number) match its base number. -This function does not verify the existence of the CPF; it only -validates the format of the string. +- [TIN Australia](#tin_australia) + - [remove\_symbols](#remove_symbols) + - [is\_valid\_tfn](#is_valid_tfn) + - [is\_valid\_abn](#is_valid_abn) + - [format\_tfn](#format_tfn) + - [format\_abn](#format_abn) + - [generate\_tfn](#generate_tfn) + - [generate\_abn](#generate_abn) + - [example\_usage](#example_usage) -Args: - -- cpf (str): The CPF to be validated, a 11-digit string - -Returns: - -- bool: True if the checksum digits match the base number, - False otherwise. - -Example: - -```python ->>> from brutils import is_valid_cpf ->>> is_valid_cpf("82178537464") -True ->>> is_valid_cpf('00011122233') -False -``` - -### format_cpf - -Format a CPF (Brazilian Individual Taxpayer Number) for display with visual -aid symbols. This function takes a numbers-only CPF string as input and adds -standard formatting visual aid symbols for display. - -Args: - -- cpf (str): A numbers-only CPF string. - -Returns: - -- str: A formatted CPF string with standard visual aid symbols or - None if the input is invalid. - -Example: - -```python ->>> from brutils import format_cpf ->>> format_cpf('82178537464') -'821.785.374-64' ->>> format_cpf("55550207753") -'555.502.077-53' -``` - -### remove_symbols_cpf -Removes specific symbols from a CPF (Brazilian Individual Taxpayer Number) -string. This function takes a CPF string as input and removes all occurrences of -the '.', '-' characters from it. +## TIN Australia -Args: - -- cpf (str): The CPF string containing symbols to be removed. - -Returns: -- str: A new string with the specified symbols removed. +### remove_symbols -Example: - -```python ->>> from brutils import remove_symbols_cpf ->>> remove_symbols_cpf('000.111.222-33') -'00011122233' -``` - -### generate_cpf - -Generate a random valid CPF (Brazilian Individual Taxpayer Number) digit string. - -Returns: - -- str: A random valid CPF string. - -Example: - -```python ->>> from brutils import generate_cpf ->>> generate_cpf() -'17433964657' ->>> generate_cpf() -"10895948109" -``` - -## CNPJ - -### is_valid_cnpj - -Returns whether or not the verifying checksum digits of the given CNPJ -(Brazilian Company Registration Number) match its base number. -Input should be a digit string of proper length. -This function does not verify the existence of the CNPJ; it only -validates the format of the string. +Remove spaces, dots, and hyphens from the input string. Args: -- cnpj (str): The CNPJ to be validated. +- tin (str): The TIN to be validated, a string of 8 to 11 digits (numbers). Returns: - bool: True if the checksum digits match the base number, False otherwise. -Example: - -```python ->>> from brutils import is_valid_cnpj ->>> is_valid_cnpj('03560714000142') -True ->>> is_valid_cnpj('00111222000133') -False -``` - -### format_cnpj - -Formats a CNPJ (Brazilian Company Registration Number) string for visual -display. -This function takes a CNPJ string as input, validates its format, and -formats it with standard visual aid symbols for display purposes. - -Args: - -- cnpj (str): The CNPJ string to be formatted for display. - -Returns: - -- str: The formatted CNPJ with visual aid symbols if it's valid, - None if it's not valid. - -Example: - -```python ->>> from brutils import format_cnpj ->>> format_cnpj("03560714000142") -'03.560.714/0001-42' ->>> format_cnpj("98765432100100") -None -``` - -### remove_symbols_cnpj - -Removes specific symbols from a CNPJ (Brazilian Company Registration Number) -string. -This function takes a CNPJ string as input and removes all occurrences of -the '.', '/' and '-' characters from it. - -Args: - -- cnpj (str): The CNPJ string containing symbols to be removed. - -Returns: - -- str: A new string with the specified symbols removed. - -Example: - -```python ->>> from brutils import remove_symbols_cnpj ->>> remove_symbols_cnpj('00.111.222/0001-00') -'00111222000100' -``` - -### generate_cnpj - -Generates a random valid CNPJ (Brazilian Company Registration Number) digit -string. An optional branch number parameter can be given; it defaults to 1. - -Args: - -- branch (int): An optional branch number to be included in the CNPJ. - -Returns: - -- str: A randomly generated valid CNPJ string. - -Example: - -```python ->>> from brutils import generate_cnpj ->>> generate_cnpj() -'34665388000161' ->>> generate_cnpj(1234) -"01745284123455" -``` - -## CEP - -### is_valid_cep - -Checks if a Brazilian CEP (Postal Code) is valid. -To be considered valid, the input must be a string containing exactly 8 digits. -This function does not verify if the CEP is a real postal code; it only -validates the format of the string. - -Args: - -- cep (str): The string containing the CEP to be checked. - -Returns: - -- bool: True if the CEP is valid (8 digits), False otherwise. - -Example: - -```python ->>> from brutils import is_valid_cep ->>> is_valid_cep('01310200') -True ->>> is_valid_cep("12345") -False ->>> is_valid_cep("abcdefgh") -False -``` - -### format_cep - -This function takes a CEP (Postal Code) as input and, if it is a valid -8-digit CEP, formats it into the standard "12345-678" format. - -Args: - -- cep (str): The input CEP (Postal Code) to be formatted. -Returns: - -- str: The formatted CEP in the "12345-678" format if it's valid, - None if it's not valid. - -Example: - -```python ->>> from brutils import format_cep ->>> format_cep('01310200') -'01310-200' ->>> format_cep("12345678") -"12345-678" ->>> format_cep("12345") -None -``` - -### remove_symbols_cep - -This function takes a CEP (Postal Code) as input and removes all occurrences of -the '.' and '-' characters from it. - -Args: - -- cep (str): The input CEP (Postal Code) containing symbols to be removed. - -Returns: - -- str: A new string with the specified symbols removed. - -Example: - -```python ->>> from brutils import remove_symbols_cep ->>> remove_symbols_cep('01310-200') -'01310200' ->>> remove_symbols_cep("123-45.678.9") -"123456789" ->>> remove_symbols_cep("abc.xyz") -"abcxyz" -``` - -### generate_cep - -Generates a random 8-digit CEP (Postal Code) number as a string. - -Returns: - -- str: A randomly generated 8-digit number. - -Example: - -```python ->>> from brutils import generate_cep ->>> generate_cep() -'77520503' -``` - -### get_address_from_cep - -Fetches address information from a given CEP (Postal Code) using the ViaCEP API. - -Args: - -- cep (str): The CEP (Postal Code) to be used in the search. -- raise_exceptions (bool, optional): Whether to raise exceptions when the CEP is invalid or not found. Defaults to False. - -Returns: - -- Address | None: An Address object (TypedDict) containing the address information if the CEP is found, None otherwise. - -Example: - -```python ->>> from brutils import get_address_from_cep ->>> get_address_from_cep("12345678") -{ - "cep": "12345-678", - "logradouro": "Rua Example", - "complemento": "", - "bairro": "Example", - "localidade": "Example", - "uf": "EX", - "ibge": "1234567", - "gia": "1234", - "ddd": "12", - "siafi": "1234" -} -``` - -### get_cep_information_from_address +### is_valid_tfn -Fetches CEP (Postal Code) options from a given address using the ViaCEP API. +Australian Tax File Number (TFN) - Validates the TIN of the tfn (citizen/tfn) to ensure that it is within the country specifications passed as parameters! Args: -- federal_unit (str): The two-letter abbreviation of the Brazilian state. -- city (str): The name of the city. -- street (str): The name (or substring) of the street. -- raise_exceptions (bool, optional): Whether to raise exceptions when the address is invalid or not found. Defaults to False. +- tin (str): A string with 8 or 9 digits (1 check digit). Returns: -- list[Address] | None: A list of Address objects (TypedDict) containing the address information if the address is found, None otherwise. +- str: If the input passed by the user contains anything other than the above argument, return an "invalid" error message. Example: ```python ->>> from brutils import get_cep_information_from_address ->>> get_cep_information_from_address("EX", "Example", "Rua Example") -[ - { - "cep": "12345-678", - "logradouro": "Rua Example", - "complemento": "", - "bairro": "Example", - "localidade": "Example", - "uf": "EX", - "ibge": "1234567", - "gia": "1234", - "ddd": "12", - "siafi": "1234" - } -] +>>> from tin_Australia import is_valid_tfn +>>> is_valid_tfn("123 456 789") => 'Valid Australia TIN' +>>> is_valid_tfn("1230 456 789") => 'Invalid Australia TIN' ``` -## Date -### convert_date_to_text -Convert a brazilian date (dd/mm/yyyy) format in their portuguese textual representation. - -Args: - - date (str): A date in a string format dd/mm/yyyy. - -Return: - - (str) | None: A portuguese textual representation of the date or None case a date is invalid. - - -Example: - -````python ->>> from brutils import convert_date_to_text ->>> convert_date_to_text("25/12/2000") -"Vinte e cinco de dezembro de dois mil" ->>> convert_date_to_text("31/02/2000") -None ->>> convert_date_to_text("29/02/2024") -"Vinte e nove de fevereiro de dois mil e vinte e quatro" ->>> convert_date_to_text("1/08/2024") -"Primeiro de agosto de dois mil e vinte e quatro" -```` - -## Phone - -### is_valid_phone - -Return whether a Brazilian phone number is valid. -It does not verify if the number actually exists. - -``` -is_valid_phone(phone_number, type) -``` - -Args: +### is_valid_abn -- phone_number: - - the phone number to be validated - - digits only, no symbols - - without the country code - - should include the area code (DDD) with two digits - - example: '+55 48 9999 9999' should be used as '4899999999' - - mandatory +Australian Business Number (ABN) - Validates the TIN of the legal entity (abn) to ensure that it is within the specifications of the country passed as parameters! -- type: - - 'mobile' to validate only mobile numbers - - 'landline' to validate only landline phone numbers - - if not specified, it validates for either. - - optional - -Returns: - -- bool: True if the phone number is valid. False otherwise. - -Example: - -```python ->>> from brutils import is_valid_phone ->>> is_valid_phone('11994029275') -True ->>> is_valid_mobile_phone('11994029275', 'mobile') -True ->>> is_valid_landline_phone('1938814933', 'landline') -True -``` - -### format_phone - -Format a phone number for visual display. This function takes a string representing a phone number containing only numbers as input and adds standard formatting symbols for display. - -Args: - -- phone (str): A string representing a phone number. - -Returns: - -- str: The formatted phone number for display or None if it is not valid. - -Example: - -```python ->>> from brutils import format_phone ->>> format_phone("11994029275") -'(11)99402-9275' ->>> format_phone("1635014415") -'(16)3501-4415' ->>> format_phone("333333") -None -``` - -### remove_symbols_phone - -Remove symbols from the phone number. This function takes a phone number as input and removes all symbols, such as parentheses '()', dashes '-', and spaces ' '. - -Args: - -- phone (str): The input phone number containing the symbols to be removed. - -Returns: - -- str: A new string with the specified symbols removed. - -Example: - -```python ->>> from brutils import remove_symbols_phone ->>> remove_symbols_phone('(21)2569-6969') -'2125696969' ->>> remove_symbols_phone('11 9999-8888') -'1199998888' ->>> remove_symbols_phone('333333') -'333333' -``` - -### remove_international_dialing_code - -Remove the international code (+55) from a string containing a Brazilian phone number, preserving other special characters. - -Args: - -- phone (str): The input phone number that may contain the international code. - -Returns: - -- str: A new string without the international code, preserving other special characters. - -Example: - -```python ->>> from brutils import remove_international_dialing_code ->>> remove_international_dialing_code("5521994029275") -"21994029275" ->>> remove_international_dialing_code("+5521994029275") -"+21994029275" ->>> remove_international_dialing_code("5555994029275") -"55994029275" ->>> remove_international_dialing_code("21994029275") -"21994029275" ->>> remove_international_dialing_code("(+55)21994029275") -"(+)21994029275" -``` - -### generate_phone - -Generates a valid random phone number. - -Args: - -- type (str): It can be "landline" or "mobile". - If not specified, the function generates - a random number of any type. - -Returns: - -- str: A randomly generated valid phone number. - -Example: - -```python ->>> from brutils import generate_phone ->>> generate_phone() -"5929797740" ->>> generate_phone("mobile") -"1899115895" ->>> generate_phone("landline") -"5535317900" -``` - -## Email - -### is_valid_email - -Check if a string corresponds to a valid email address. - -Args: - -- email (str): The input string to be checked. - -Returns: - -- bool: True if email is a valid email address, False otherwise. - -Example: - -```python -from brutils import is_valid_email - ->>> is_valid_email("joao.ninguem@gmail.com") -True ->>> is_valid_email(".joao.ninguem@gmail.com") -False ->>> is_valid_email("joao.ninguem@gmail.") -False ->>> is_valid_email("joao ninguem@gmail.com") -False -``` - -## License Plate - -### is_valid_license_plate - -Check if a license plate is valid. -This function does not verify if the license plate is a real license plate; -it only validates the format of the string. - -Args: - -- license_plate (str): A license plate string. -- type (str): "old_format" or "mercosul". - If not specified, checks for one or another. - -Returns: - -- bool: True if the license plate is valid, False otherwise. - -Example: - -```python ->>> from brutils import is_valid_license_plate ->>> is_valid_license_plate('ABC1234') -True ->>> is_valid_license_plate('def5678', type="old_format") -True ->>> is_valid_license_plate('ABC4E67') -True ->>> is_valid_license_plate('ABC4E67', type="mercosul") -True ->>> is_valid_license_plate('GHI-4567') -False -``` - -### format_license_plate - -Formats a license plate into the correct pattern. -This function receives a license plate in any pattern (LLLNNNN or LLLNLNN) -and returns a formatted version. - -Args: - -- license_plate (str): A license plate string. - -Returns: - -- str: The formatted license plate string or - 'None' if the input is invalid. - -Example: - -```python ->>> from brutils import format_license_plate ->>> format_license_plate("ABC1234") -"ABC-1234" -# old format (contains a dash) ->>> format_license_plate("abc1234") -"ABC-1234" -# old format (contains a dash) ->>> format_license_plate("ABC1D23") -"ABC1D23" -# mercosul format ->>> format_license_plate("abc1d23") -"ABC1D23" -# mercosul format ->>> format_license_plate("ABCD123") -None -``` - -### remove_symbols_license_plate - -Removes the dash (-) symbol from a license plate string. - -Args: - -- license_plate_number (str): A license plate number containing symbols to - be removed. - -Returns: - -- str: The license plate number with the specified symbols removed. - -Example: - -```python -from brutils import remove_symbols_license_plate ->>> remove_symbols_license_plate("ABC-123") -"ABC123" ->>> remove_symbols_license_plate("abc123") -"abc123" ->>> remove_symbols_license_plate("ABCD123") -"ABCD123" ->>> remove_symbols_license_plate("@abc#-#123@") -"@abc##123@" -``` - -### generate_license_plate - -Generate a valid license plate in the given format. In case no format is -provided, it will return a license plate in the Mercosul format. - -Args: +Arguments: -- format (str): The desired format for the license plate. - 'LLLNNNN' for the old pattern or 'LLLNLNN' for the - Mercosul one. Default is 'LLLNLNN' +- tin (str): A string with 11 digits (2 check digit). Returns: -- str: A randomly generated license plate number or - 'None' if the format is invalid. +- str: If the input passed by the user contains anything other than the argument above, returns an "invalid" error message. Example: ```python -from brutils import generate_license_plate ->>> generate_license_plate() -"ABC1D23" ->>> generate_license_plate(format="LLLNLNN") -"ABC4D56" ->>> generate_license_plate(format="LLLNNNN") -"ABC123" ->>> generate_license_plate(format="invalid") -None +>>> from tin_Australia import is_valid_abn +>>> is_valid_abn("12 345 678 901") => 'Valid Australia TIN' +>>> is_valid_abn("120 345 678 901") => 'Invalid Australia TIN' ``` -### convert_license_plate_to_mercosul - -Converts an old pattern license plate (LLLNNNN) to a Mercosul format -(LLLNLNN). -Args: +### format_tfn -- license_plate (str): A string of proper length representing the - old pattern license plate. - -Returns: - -- str: The converted Mercosul license plate (LLLNLNN) or - 'None' if the input is invalid. - -Example: - -```python ->>> from brutils import convert_license_plate_to_mercosul ->>> convert_license_plate_to_mercosul("ABC123") -"ABC1C34" ->>> convert_license_plate_to_mercosul("abc123") -"ABC1C34" ->>> convert_license_plate_to_mercosul("ABC1D23") -None -``` - -### get_format_license_plate - -Return the format of a license plate. 'LLLNNNN' for the old pattern and -'LLLNLNN' for the Mercosul one. +Australian Tax File Number (TFN) - Formats an TIN for display. Args: -- license_plate (str): A license plate string without symbols. +- tin(str): Adds the correct separators as per the country parameters. Returns: -- str: The format of the license plate (LLLNNNN, LLLNLNN) or - 'None' if the format is invalid. +- str: A formatted TIN with the separators in the right place! Example: ```python -from brutils import get_format_license_plate ->>> get_format_license_plate("ABC123") -"LLLNNNN" ->>> get_format_license_plate("abc123") -"LLLNNNN" ->>> get_format_license_plate("ABC1D23") -"LLLNLNN" ->>> get_format_license_plate("abc1d23") -"LLLNLNN" ->>> get_format_license_plate("ABCD123") -None +>>> from tin_Australia import format_tfn +>>> format_tfn("123456789") => ("123 456 789") ``` -## PIS - -### is_valid_pis -Verifies if the PIS/PASEP number is valid. Only numbers, formatted as a string. It does not check if the PIS/PASEP actually exists. +### format_abn -References: - -- . +Australian Business Number (ABN) - Formats an TIN for display. Args: -- pis (str): PIS number as a string with the proper length. +- tin(str): Adds the correct separators as per the country parameters. Returns: -- bool: True if the PIS is valid, False otherwise. +- str: A formatted TIN with the separators in the right place! Example: ```python -from brutils import is_valid_pis ->>> is_valid_pis("82178537464") -False ->>> is_valid_pis("12082043519") -True +>>> from tin_Australia import format_abn +>>> format_abn("12345678901") => ("12 345 678 901") ``` -### format_pis -Formats a valid PIS (Programa de Integração Social) string with symbols and adds standard formatting symbols for display. - -Args: - -- pis (str): A valid string of PIS containing only numbers. - -Returns: +### generate_tfn -- str: A formatted PIS string with standard visual aid symbols or None if the input is invalid. - -Example: - -```python -from brutils import format_pis ->>> format_pis("17033259504") -'170.33259.50-4' ->>> format_pis("12013128292") -'120.13128.29-2' -``` - -### remove_symbols_pis - -This function takes a string of PIS (Programa de Integração Social) with formatting symbols and returns a clean version without certain symbols. It intentionally removes only the symbols "-" and ".", leaving other symbols untouched. +Australian Tax File Number (TFN) - Generates a valid TIN. Args: -- pis (str): A string of PIS that may contain formatting symbols. - -Returns: - -- str: A clean string of PIS without formatting symbols. - -Example: - -```python -from brutils import remove_symbols_pis ->>> remove_symbols_pis('170.33259.50-4') -'17033259504' ->>> remove_symbols_pis("123.456.789-09") -'12345678909' ->>> remove_symbols_pis('/._') -'/_' -``` - -### generate_pis - -Generates a string of digits containing a random valid Brazilian PIS number. +- tin (str): Generates a valid TIN. Returns: -- str: A randomly generated valid PIS number as a string. +- str: Generates a valid number given the correct parameters. Example: ```python -from brutils import generate_pis ->>> generate_pis() -'61352489741' ->>> generate_pis() -'73453349671' +>>> from tin_Australia import generate_tfn +>>> generate_tfn("123 456 789") => 'Valid Australia TIN' +>>> generate_tfn("1230 456 789") => 'Invalid Australia TIN' ``` -## Legal Process - -## is_valid_legal_process -Check if a legal process ID is valid. +### generate_abn -This function does not verify if the legal process ID is a real legal -process ID; it only validates the format of the string. +Australian Business Number (ABN) - Generates a valid TIN. Args: -- legal_process_id (str): A digit-only string representing the legal - process ID. +- tin (str): Generates a valid TIN. Returns: -- bool: True if the legal process ID is valid, False otherwise. +- str: Generates a valid number given the correct parameters. Example: ```python ->>> from brutils import is_valid_legal_process ->>> is_valid_legal_process('10188748220234018200') -True ->>> is_valid_legal_process('45532346920234025107') -True ->>> is_valid_legal_process('00000000000000000000') -False ->>> is_valid_legal_process('455323423QQWEQWSsasd&*(()') -False ->>> +>>> from tin_Australia import generate_abn +>>> generate_abn("12 345 678 901") => 'Valid Australia TIN' +>>> generate_abn("120 345 678 901") => 'Invalid Australia TIN' ``` -### format_legal_process - -Format a legal process ID into a standard format. -Args: - -- legal_process_id (str): A 20-digits string representing the legal - process ID. - -Returns: +### example_usage -- str: The formatted legal process ID or None if the input is invalid. - -Example: - -```python ->>> from brutils import format_legal_process ->>> format_legal_process('23141945820055070079') -'2314194-58.2005.5.07.0079' ->>> format_legal_process('00000000000000000000') -'0000000-00.0000.0.00.0000' ->>> format_legal_process("123") -None -``` - -### remove_symbols_legal_process - -Removes specific symbols from a given legal process. - -This function takes a legal process as input and removes all occurrences -of the '.' and '-' characters from it. - -Args: - -- legal_process (str): A legal process containing symbols to be removed. - -Returns: - -- str: The legal process string with the specified symbols removed. - -Example: - -```python -from brutils import remove_symbols_legal_process ->>> remove_symbols_legal_process("6439067-89.2023.4.04.5902") -"64390678920234045902" ->>> remove_symbols_legal_process("4976023-82.2012.7.00.2263") -"49760238220127002263" ->>> remove_symbols_legal_process("4976023-82.2012.7.00.2263*!*&#") -"49760238220127002263*!*&#" -``` - -### generate_legal_process - -Generate a random legal process ID number. - -Args: - -- year (int): The year for the legal process ID (default is the current - year). - The year should not be in the past -- orgao (int): The organization code (1-9) for the legal process ID - (default is random). - -Returns: - -- str: A randomly generated legal process ID. - None if one of the arguments is invalid. - -Example: - -```python ->>> from brutils import generate_legal_process ->>> generate_legal_process() -"45676401020238170592" ->>> generate_legal_process(year=2025) -"32110268020258121130" ->>> generate_legal_process(orgao=5) -"37573041520235090313" ->>> generate_legal_process(year=2024, orgao=4) -"33158248820244017105" -``` - -## Voter ID - -### is_valid_voter_id - -Check if a Brazilian voter id number is valid. -It does not verify if the voter id actually exists. - -References: - -- , -- - -Args: - -- voter_id(str): string representing the voter id to be verified. - -Returns: - -- bool: True if the voter id is valid. False otherwise. - -Example: - -```python ->>> from brutils import is_valid_voter_id ->>> is_valid_voter_id('123456789011') -False ->>> is_valid_voter_id('427503840213') -True -``` - -### format_voter_id - -Formats a voter ID number for visual display. - -This function takes a voter ID string containing only numbers as input -and adds the standard formatting spaces for display. +Generates random valid TIN as an example for tfns and legal entities, analyzes user input, and formats them. Arguments: - * voter_id (str): A voter ID string containing only numbers. - -Returns: - * str: The formatted voter ID with spaces if valid. - Returns None if not valid. - -Example: - -```python ->>> from brutils import format_voter_id ->>> format_voter_id("246593980493") -'2465 9398 04 93' ->>> format_voter_id("202715292895") -'2027 1529 28 95' ->>> format_voter_id("739035552205") ->>> -``` - -### generate_voter_id -Generate a valid random Voter ID string of digits from an informed Brazilian federation union. - -Args: - * federative_union(str): federative union for the voter id that will be generated. The default value "ZZ" is used for voter IDs issued to foreigners. +- str: A valid randomly generated TIN as an example for tfns and companies, user input. Returns: - * str: A randomly generated valid voter ID. - -Example: - -```python ->>> from brutils import generate_voter_id ->>> generate_voter_id() -'183475722801' ->>> generate_voter_id(federative_union ="MG") -'950125640248' -``` -## IBGE - -### convert_code_to_uf -Converts a given IBGE code (2-digit string) to its corresponding UF (state abbreviation). - -Args: - * code (str): The 2-digit IBGE code to be converted. - -Retorna: - * str or None: The UF code corresponding to the IBGE code, or None if the - IBGE code is invalid. - -Exemplo: - -```python ->>> from brutils.ibge.uf import convert_code_to_uf ->>> convert_code_to_uf("12") -'AC' ->>> convert_code_to_uf("33") -'RJ' ->>> convert_code_to_uf("99") ->>> -``` -### get_municipality_by_code - -Returns the municipality name and UF for a given IBGE code. - -Args: - * code (str): The IBGE code of the municipality. - -Returns: - * tuple: Returns a tuple formatted as ("Município", "UF"). - * None: Returns None if the code is not valid. +- str: A valid randomly generated TIN as an example for tfns and companies, user input parsed and formatted with visual symbols if valid, None if not. Example: ```python ->>> from brutils import get_municipality_by_code ->>> get_municipality_by_code(3550308) -("São Paulo", "SP") -``` - -### get_code_by_municipality_name +>>> from tin_Australia import example_usage +>>> tin_tfn("123456789") => 'Valid Australia TIN tfn' +>>> tin_abn("12345678901") => 'Valid Australia TIN abn' -Returns the IBGE code for a given municipality name and uf code. +>>> is_valid(tin_tfn) => 'Valid Australia TIN abn' +>>> is_valid(tin_abn) => 'Valid Australia TIN abn' -This function takes a string representing a municipality's name -and uf's code and returns the corresponding IBGE code (string). The function -will handle names by ignoring differences in case, accents, and -treating the character ç as c and ignoring case differences for the uf code. +>>> is_valid(user_input)("36485987125") => 'Valid input - Australia TIN abn' -Args: - * municipality_name (str): The name of the municipality. - * uf (str): The uf code of the state. - -Returns: - * str: The IBGE code of the municipality. Returns None if the name is not valid or does not exist. - -Example: - -```python ->>> from brutils import get_code_by_municipality_name ->>> get_code_by_municipality_name("São Paulo", "SP") -"3550308" ->>> get_code_by_municipality_name("goiania", "go") -"5208707" ->>> get_code_by_municipality_name("Conceição do Coité", "BA") -"2908408" ->>> get_code_by_municipality_name("conceicao do Coite", "Ba") -"2908408" ->>> get_code_by_municipality_name("Municipio Inexistente", "") -None ->>> get_code_by_municipality_name("Municipio Inexistente", "RS") -None +>>> formatted_input = format_tin(user_input) => ("36 485 987 125") ``` -## Holidays - -### is_holiday - -Checks if a given date is a national or state holiday in Brazil. - -This function takes a `datetime` object as the date and an optional state abbreviation (UF) to specify state holidays. It returns `True` if the date is a holiday, `False` if it’s not, or `None` if the date or UF are invalid. Note that the function does not cover municipal holidays. - -Args: - -- `date (datetime)`: The date to be checked. -- `uf (str, optional)`: The state abbreviation (UF) to check for state holidays. If not provided, only national holidays are considered. - -Returns: - -- `bool | None`: `True` if the date is a holiday, `False` if it’s not, or `None` if the date or UF are invalid. - -Example: - -```python ->>> from datetime import datetime ->>> from brutils import is_holiday ->>> is_holiday(datetime(2024, 1, 1)) -True ->>> is_holiday(datetime(2024, 1, 2)) -False ->>> is_holiday(datetime(2024, 3, 2), uf="SP") -False ->>> is_holiday(datetime(2024, 12, 25), uf="RJ") -True -``` - -## Monetary - -### format_currency - -Formats a number following the Brazilian monetary standard. The number will be -formatted by adding the R$ symbol as a prefix, a comma as a decimal separator, and a -period as a thousands grouper. - -Args: - * float or Decimal: A number with or without decimal places. - -Returns: - * str or None: The number formatted following the Brazilian standard. - -Example: - -```python ->>> from brutils.currency import format_currency ->>> format_currency(1259.03) -'R$ 1.259,03' ->>> format_currency(0) -'R$ 0,00' ->>> format_currency("not a number") -None -``` +--- # Feature Request and Bug Report @@ -1294,4 +259,4 @@ Let's build it together 🚀🚀

-_Made with [contrib.rocks](https://contrib.rocks)._ \ No newline at end of file +_Made with [contrib.rocks](https://contrib.rocks)._ diff --git a/brutils/worlds_tin/tin_australia.py b/brutils/worlds_tin/tin_australia.py new file mode 100644 index 0000000..fe4f800 --- /dev/null +++ b/brutils/worlds_tin/tin_australia.py @@ -0,0 +1,159 @@ +from random import randint + + +# REMOVE SYMBOLS +def remove_symbols(dirty_tin): # type: (str) -> str + """ + Removes spaces, dots, dashes, and other symbols from a string. + """ + return "".join(filter(str.isdigit, dirty_tin)) + + +# VALIDATION FUNCTIONS +def is_valid_tfn(tfn): # type: (str) -> str + """ + Validates an Australian Tax File Number (TFN). + + A TFN must be 8 or 9 digits and pass a weighted checksum validation. + + Args: + tfn (str): TFN to validate. + + Returns: + str: 'Valid TFN' if valid, otherwise 'Invalid TFN'. + """ + tfn = remove_symbols(tfn) + + # TFN must be 8 or 9 digits + if len(tfn) not in [8, 9] or not tfn.isdigit(): + return "Invalid TFN: Must be 8 or 9 numeric digits." + + # Weighted checksum validation + weights = [1, 4, 3, 7, 5, 8, 6, 9, 10][: len(tfn)] + checksum = sum(int(digit) * weight for digit, weight in zip(tfn, weights)) + if checksum % 11 == 0: + return "Valid TFN" + return "Invalid TFN: Failed checksum validation." + + +def is_valid_abn(abn): # type: (str) -> str + """ + Validates an Australian Business Number (ABN). + + An ABN must be 11 digits and pass a modulo 89 checksum validation. + + Args: + abn (str): ABN to validate. + + Returns: + str: 'Valid ABN' if valid, otherwise 'Invalid ABN'. + """ + abn = remove_symbols(abn) + + # ABN must be 11 digits + if len(abn) != 11 or not abn.isdigit(): + return "Invalid ABN: Must be exactly 11 numeric digits." + + # Adjust the first digit and calculate checksum + adjusted_digits = [int(abn[0]) - 1] + [int(d) for d in abn[1:]] + weights = [10, 1, 3, 5, 7, 9, 11, 13, 15, 17, 19] + checksum = sum(d * w for d, w in zip(adjusted_digits, weights)) + if checksum % 89 == 0: + return "Valid ABN" + return "Invalid ABN: Failed checksum validation." + + +# FORMAT FUNCTIONS +def format_tfn(tfn): # type: (str) -> str + """ + Formats a TFN as XXX XXX XXX or XX XXX XXX. + + Args: + tfn (str): TFN to format. + + Returns: + str: Formatted TFN or None if invalid. + """ + tfn = remove_symbols(tfn) + if is_valid_tfn(tfn) == "Valid TFN": + if len(tfn) == 9: + return f"{tfn[:3]} {tfn[3:6]} {tfn[6:]}" + if len(tfn) == 8: + return f"{tfn[:2]} {tfn[2:5]} {tfn[5:]}" + return None + + +def format_abn(abn): # type: (str) -> str + """ + Formats an ABN as XX XXX XXX XXX. + + Args: + abn (str): ABN to format. + + Returns: + str: Formatted ABN or None if invalid. + """ + abn = remove_symbols(abn) + if is_valid_abn(abn) == "Valid ABN": + return f"{abn[:2]} {abn[2:5]} {abn[5:8]} {abn[8:]}" + return None + + +# GENERATE FUNCTIONS +def generate_tfn(): # type: () -> str + """ + Generates a valid Australian Tax File Number (TFN). + + Returns: + str: A valid TFN. + """ + while True: + tfn = f"{randint(10**7, 10**9 - 1)}" + if is_valid_tfn(tfn) == "Valid TFN": + return tfn + + +def generate_abn(): # type: () -> str + """ + Generates a valid Australian Business Number (ABN). + + Returns: + str: A valid ABN. + """ + while True: + identifier = f"{randint(10**7, 10**9 - 1)}" + for prefix in range(10, 100): + abn = f"{prefix}{identifier}" + if is_valid_abn(abn) == "Valid ABN": + return abn + + +# USAGE EXAMPLES +def example_usage(): + # Generate examples + generated_tfn = generate_tfn() + print( + f"Generated TFN: {generated_tfn} - Valid? {is_valid_tfn(generated_tfn)}" + ) + print(f"Formatted TFN: {format_tfn(generated_tfn)}") + + generated_abn = generate_abn() + print( + f"Generated ABN: {generated_abn} - Valid? {is_valid_abn(generated_abn)}" + ) + print(f"Formatted ABN: {format_abn(generated_abn)}") + + # User input + user_input = input("Enter a TFN or ABN (with or without symbols): ") + if len(remove_symbols(user_input)) in [8, 9]: + print(is_valid_tfn(user_input)) + print(f"Formatted TFN: {format_tfn(user_input)}") + elif len(remove_symbols(user_input)) == 11: + print(is_valid_abn(user_input)) + print(f"Formatted ABN: {format_abn(user_input)}") + else: + print("Invalid input. Please enter a valid TFN or ABN.") + + +# Run example +example_usage() diff --git a/tests/worlds_tin/test_australia_tin.py b/tests/worlds_tin/test_australia_tin.py new file mode 100644 index 0000000..6ad4493 --- /dev/null +++ b/tests/worlds_tin/test_australia_tin.py @@ -0,0 +1,55 @@ +from unittest import TestCase, main +from unittest.mock import patch + +from tin_australia import ( + remove_symbols, + is_valid_tfn, + is_valid_abn, + format_tfn, + format_abn, + generate_tfn, + generate_abn, +) + + +class TestTFNABN(TestCase): + def test_remove_symbols(self): + self.assertEqual(remove_symbols("123456789"), "123456789") + self.assertEqual(remove_symbols("12-34.56 789"), "123456789") + self.assertEqual(remove_symbols("...---..."), "") + + def test_is_valid_tfn(self): + self.assertEqual(is_valid_tfn("123456782"), "Valid TFN") + self.assertEqual(is_valid_tfn("12345678"), "Invalid TFN: Failed checksum validation.") + self.assertEqual(is_valid_tfn("A23456789"), "Invalid TFN: Must be 8 or 9 numeric digits.") + + def test_is_valid_abn(self): + self.assertEqual(is_valid_abn("51824753556"), "Valid ABN") + self.assertEqual(is_valid_abn("12345678901"), "Invalid ABN: Failed checksum validation.") + self.assertEqual(is_valid_abn("A2345678901"), "Invalid ABN: Must be exactly 11 numeric digits.") + + def test_generate_tfn(self): + for _ in range(100): + tfn = generate_tfn() + self.assertEqual(is_valid_tfn(tfn), "Valid TFN") + + def test_generate_abn(self): + for _ in range(100): + abn = generate_abn() + self.assertEqual(is_valid_abn(abn), "Valid ABN") + + @patch("tin_australia.is_valid_tfn") + def test_format_tfn(self, mock_is_valid_tfn): + mock_is_valid_tfn.return_value = "Valid TFN" + self.assertEqual(format_tfn("123456782"), "12 345 6782") + self.assertIsNone(format_tfn("123")) + + @patch("tin_australia.is_valid_abn") + def test_format_abn(self, mock_is_valid_abn): + mock_is_valid_abn.return_value = "Valid ABN" + self.assertEqual(format_abn("51824753556"), "51 824 753 556") + self.assertIsNone(format_abn("123")) + + +if __name__ == "__main__": + main() \ No newline at end of file