ode-alfa 0.1.0.dev0__tar.gz → 0.1.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,17 +1,19 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: ode-alfa
3
- Version: 0.1.0.dev0
4
- Summary: Offline CPF and CNPJ (numeric and alphanumeric) check-digit validation
3
+ Version: 0.1.1
4
+ Summary: Offline validation of Brazilian CPF and CNPJ numbers, including the new alphanumeric CNPJ
5
5
  Author: Yury Cavalcante
6
6
  License-Expression: Apache-2.0
7
7
  Project-URL: Homepage, https://github.com/YUCAVALCANTE/ode-alfa
8
8
  Project-URL: Issues, https://github.com/YUCAVALCANTE/ode-alfa/issues
9
9
  Project-URL: Changelog, https://github.com/YUCAVALCANTE/ode-alfa/blob/main/CHANGELOG.md
10
10
  Project-URL: Toolkit, https://github.com/YUCAVALCANTE/open-data-engineering-toolkit
11
- Keywords: cpf,cnpj,cnpj-alfanumerico,brasil,validation,data-quality
11
+ Keywords: cpf,cnpj,cnpj-alfanumerico,alphanumeric-cnpj,brazil,brasil,receita-federal,validation,data-quality
12
12
  Classifier: Development Status :: 3 - Alpha
13
13
  Classifier: Intended Audience :: Developers
14
14
  Classifier: Intended Audience :: Science/Research
15
+ Classifier: Natural Language :: English
16
+ Classifier: Natural Language :: Portuguese (Brazilian)
15
17
  Classifier: Operating System :: OS Independent
16
18
  Classifier: Programming Language :: Python :: 3
17
19
  Classifier: Programming Language :: Python :: 3 :: Only
@@ -31,18 +33,73 @@ Dynamic: license-file
31
33
 
32
34
  # ode-alfa
33
35
 
36
+ [![PyPI](https://img.shields.io/pypi/v/ode-alfa)](https://pypi.org/project/ode-alfa/)
34
37
  [![CI](https://github.com/YUCAVALCANTE/ode-alfa/actions/workflows/ci.yml/badge.svg)](https://github.com/YUCAVALCANTE/ode-alfa/actions/workflows/ci.yml)
35
38
  ![Python](https://img.shields.io/badge/python-3.11%E2%80%933.14-3776AB?logo=python&logoColor=white)
36
- ![Licença](https://img.shields.io/badge/licen%C3%A7a-Apache--2.0-blue)
37
- ![Status](https://img.shields.io/badge/status-em%20desenvolvimento-orange)
39
+ ![License](https://img.shields.io/badge/license-Apache--2.0-blue)
38
40
 
39
- **Validação matemática offline de CPF e CNPJ, inclusive o CNPJ alfanumérico.**
40
- Primeiro pacote do [Open Data Engineering Toolkit](https://github.com/YUCAVALCANTE/open-data-engineering-toolkit).
41
+ **Offline validation of Brazilian CPF and CNPJ numbers, including the new alphanumeric CNPJ.**
42
+ **Validação offline de CPF e CNPJ brasileiros, inclusive o novo CNPJ alfanumérico.**
41
43
 
42
- > **Status:** em desenvolvimento (ciclo de 07/12 a 20/12/2026). Ainda não publicado no PyPI;
43
- > instale a partir do código. A API pode mudar até a v0.1.0.
44
+ [English](#english) · [Português](#português)
44
45
 
45
- ## Por que existe
46
+ First package of the [Open Data Engineering Toolkit](https://github.com/YUCAVALCANTE/open-data-engineering-toolkit).
47
+
48
+ ```bash
49
+ pip install ode-alfa
50
+ ```
51
+
52
+ ## English
53
+
54
+ **CPF** (individual taxpayer ID) and **CNPJ** (company ID) are Brazil's federal tax identifiers.
55
+ Since July 2026 the Brazilian Federal Revenue Service (Receita Federal) issues CNPJs with letters
56
+ (e.g. `00.000.000/E08G-12`). Code that strips non-digits or stores the CNPJ as an integer now
57
+ destroys data silently. `ode-alfa` always treats CPF and CNPJ as **text**, computes and checks the
58
+ official modulo-11 check digits, and tells you *why* a value was rejected.
59
+
60
+ - Pure Python, no dependencies, no network access, fully typed.
61
+ - Does not fix identifiers, restore lost leading zeros, or say who a number belongs to.
62
+ - A correct check digit does **not** prove the CPF/CNPJ exists or is active.
63
+ - Verified step by step against the official Receita Federal example (`12.ABC.345/01DE-35`).
64
+
65
+ ### Usage
66
+
67
+ ```python
68
+ from ode_alfa import cpf, cnpj
69
+
70
+ cpf.is_valid("123.456.789-09") # True
71
+ cnpj.is_valid("00.000.000/E08G-12") # True (alphanumeric)
72
+ cnpj.calculate_dv("00000000E08G") # "12"
73
+ cnpj.format("00000000E08G12") # "00.000.000/E08G-12"
74
+
75
+ r = cnpj.validate("00.000.000/E08G-13")
76
+ r.valid, r.reason, r.expected_dv # (False, "DV_MISMATCH", "12")
77
+ ```
78
+
79
+ `validate` never raises on bad input. `reason` is one of `OK`, `MISSING`, `EXPECTED_ASCII_TEXT`,
80
+ `INVALID_FORMAT`, `REPEATED_SEQUENCE` or `DV_MISMATCH`. The full identifier is available in
81
+ `r.normalized` but is kept out of `repr`, so logging a result does not leak a CPF.
82
+
83
+ ### Command line
84
+
85
+ ```bash
86
+ ode-alfa validate cnpj 00.000.000/E08G-12 # OK (exit code 0)
87
+ cat ids.txt | ode-alfa validate cpf - # one per line; never echoes the identifier
88
+ ```
89
+
90
+ Exit codes: 0 valid, 1 invalid, 2 input error.
91
+
92
+ ### Known limitation
93
+
94
+ With alphanumeric CNPJs, modulo 11 cannot detect swapping a character for another whose value
95
+ differs by a multiple of 11 (e.g. `6`↔`A`, `A`↔`L`). This is a property of the official rule.
96
+
97
+ See also the [comparison with validate-docbr](https://github.com/YUCAVALCANTE/ode-alfa/blob/main/docs/comparacao-validate-docbr.md) and the
98
+ [privacy review](https://github.com/YUCAVALCANTE/ode-alfa/blob/main/docs/privacidade.md) (in Portuguese).
99
+
100
+ ## Português
101
+
102
+ ### Por que existe
46
103
 
47
104
  Desde julho de 2026 o CNPJ pode ter letras (a Receita Federal anunciou a primeira inscrição
48
105
  alfanumérica, `00.000.000/E08G-12`, em 31/07/2026). Códigos que removem tudo que não é dígito ou
@@ -57,16 +114,13 @@ por que um valor foi rejeitado.
57
114
  difere em múltiplo de 11 (por exemplo `6`↔`A`, `7`↔`B`, `8`↔`C`, `9`↔`D`, `A`↔`L`). É uma
58
115
  propriedade da regra oficial, não do pacote; o teste `test_troca_de_um_caractere` a documenta.
59
116
 
60
- ## Instalação
117
+ ### Instalação
61
118
 
62
119
  ```bash
63
- # depois da publicação
64
120
  pip install ode-alfa
65
- # hoje, a partir do código
66
- pip install git+https://github.com/YUCAVALCANTE/ode-alfa
67
121
  ```
68
122
 
69
- ## Uso
123
+ ### Uso
70
124
 
71
125
  ```python
72
126
  from ode_alfa import cpf, cnpj
@@ -96,7 +150,7 @@ r.valid, r.reason, r.expected_dv # (False, "DV_MISMATCH", "12")
96
150
 
97
151
  `calculate_dv`, `normalize` e `format` lançam `ValueError` para entrada inválida.
98
152
 
99
- ## Linha de comando
153
+ ### Linha de comando
100
154
 
101
155
  ```bash
102
156
  ode-alfa validate cnpj 00.000.000/E08G-12 # OK (código de saída 0)
@@ -106,8 +160,9 @@ cat cpfs.txt | ode-alfa validate cpf - # um por linha, sem expor CPF no h
106
160
  ```
107
161
 
108
162
  A CLI imprime só o motivo, nunca o identificador. Saída: 0 válido, 1 inválido, 2 erro de entrada.
163
+ Detalhes em [docs/privacidade.md](https://github.com/YUCAVALCANTE/ode-alfa/blob/main/docs/privacidade.md).
109
164
 
110
- ## Como o DV é calculado
165
+ ### Como o DV é calculado
111
166
 
112
167
  Módulo 11: `S = Σ valor × peso`, `r = S mod 11`, DV = 0 se `r < 2`, senão `11 − r`. No CNPJ,
113
168
  `valor = código ASCII − 48` (0–9 mantêm o valor; A–Z valem 17–42). O DV1 entra na base antes do
@@ -119,15 +174,20 @@ cálculo do DV2.
119
174
  | CNPJ DV1 | 5 4 3 2 9 8 7 6 5 4 3 2 |
120
175
  | CNPJ DV2 | 6 5 4 3 2 9 8 7 6 5 4 3 2 |
121
176
 
122
- ## Roadmap
177
+ O exemplo oficial da Receita Federal (`12.ABC.345/01DE-35`, somas 459 e 424) é verificado passo a
178
+ passo em [`tests/test_conformidade_rfb.py`](https://github.com/YUCAVALCANTE/ode-alfa/blob/main/tests/test_conformidade_rfb.py).
123
179
 
124
- - **v0.1** (gate 20/12/2026): núcleo, CLI, comparação de conformidade com o `validate-docbr`, publicação.
125
- - **v0.2:** adaptadores de lote CSV/Parquet e métricas.
126
- - **v0.3:** scanner de código (casts numéricos e regex destrutivas) e auditoria de colisões.
180
+ ### Comparação com o validate-docbr
127
181
 
128
- Privacidade: não use CPF real em issues, testes ou exemplos. Ver [SECURITY.md](SECURITY.md).
182
+ Os dois concordam em todos os dígitos verificadores, inclusive no CNPJ alfanumérico, e têm
183
+ desempenho parecido. O `ode-alfa` se diferencia pelo contrato de entrada (motivo estruturado,
184
+ máscara estrita, recusa de `int`) e pela CLI que não expõe o identificador. Casos, números e
185
+ conclusão em [docs/comparacao-validate-docbr.md](https://github.com/YUCAVALCANTE/ode-alfa/blob/main/docs/comparacao-validate-docbr.md).
129
186
 
130
- ---
187
+ ### Roadmap
188
+
189
+ - **v0.1** (05/12/2026): núcleo, CLI, conformidade com o exemplo oficial da Receita, comparação com o `validate-docbr`, revisão de privacidade, publicação.
190
+ - **v0.2:** adaptadores de lote CSV/Parquet, relatório de motivos e benchmark com o cadastro público da Receita.
191
+ - **v0.3:** scanner de código (casts numéricos e regex destrutivas) e auditoria de colisões.
131
192
 
132
- *English:* offline check-digit validation for Brazilian CPF and CNPJ, including the alphanumeric
133
- CNPJ introduced in 2026. Pure Python, no dependencies, typed, never treats identifiers as integers.
193
+ Privacidade: não use CPF real em issues, testes ou exemplos. Ver [SECURITY.md](https://github.com/YUCAVALCANTE/ode-alfa/blob/main/SECURITY.md).
@@ -0,0 +1,160 @@
1
+ # ode-alfa
2
+
3
+ [![PyPI](https://img.shields.io/pypi/v/ode-alfa)](https://pypi.org/project/ode-alfa/)
4
+ [![CI](https://github.com/YUCAVALCANTE/ode-alfa/actions/workflows/ci.yml/badge.svg)](https://github.com/YUCAVALCANTE/ode-alfa/actions/workflows/ci.yml)
5
+ ![Python](https://img.shields.io/badge/python-3.11%E2%80%933.14-3776AB?logo=python&logoColor=white)
6
+ ![License](https://img.shields.io/badge/license-Apache--2.0-blue)
7
+
8
+ **Offline validation of Brazilian CPF and CNPJ numbers, including the new alphanumeric CNPJ.**
9
+ **Validação offline de CPF e CNPJ brasileiros, inclusive o novo CNPJ alfanumérico.**
10
+
11
+ [English](#english) · [Português](#português)
12
+
13
+ First package of the [Open Data Engineering Toolkit](https://github.com/YUCAVALCANTE/open-data-engineering-toolkit).
14
+
15
+ ```bash
16
+ pip install ode-alfa
17
+ ```
18
+
19
+ ## English
20
+
21
+ **CPF** (individual taxpayer ID) and **CNPJ** (company ID) are Brazil's federal tax identifiers.
22
+ Since July 2026 the Brazilian Federal Revenue Service (Receita Federal) issues CNPJs with letters
23
+ (e.g. `00.000.000/E08G-12`). Code that strips non-digits or stores the CNPJ as an integer now
24
+ destroys data silently. `ode-alfa` always treats CPF and CNPJ as **text**, computes and checks the
25
+ official modulo-11 check digits, and tells you *why* a value was rejected.
26
+
27
+ - Pure Python, no dependencies, no network access, fully typed.
28
+ - Does not fix identifiers, restore lost leading zeros, or say who a number belongs to.
29
+ - A correct check digit does **not** prove the CPF/CNPJ exists or is active.
30
+ - Verified step by step against the official Receita Federal example (`12.ABC.345/01DE-35`).
31
+
32
+ ### Usage
33
+
34
+ ```python
35
+ from ode_alfa import cpf, cnpj
36
+
37
+ cpf.is_valid("123.456.789-09") # True
38
+ cnpj.is_valid("00.000.000/E08G-12") # True (alphanumeric)
39
+ cnpj.calculate_dv("00000000E08G") # "12"
40
+ cnpj.format("00000000E08G12") # "00.000.000/E08G-12"
41
+
42
+ r = cnpj.validate("00.000.000/E08G-13")
43
+ r.valid, r.reason, r.expected_dv # (False, "DV_MISMATCH", "12")
44
+ ```
45
+
46
+ `validate` never raises on bad input. `reason` is one of `OK`, `MISSING`, `EXPECTED_ASCII_TEXT`,
47
+ `INVALID_FORMAT`, `REPEATED_SEQUENCE` or `DV_MISMATCH`. The full identifier is available in
48
+ `r.normalized` but is kept out of `repr`, so logging a result does not leak a CPF.
49
+
50
+ ### Command line
51
+
52
+ ```bash
53
+ ode-alfa validate cnpj 00.000.000/E08G-12 # OK (exit code 0)
54
+ cat ids.txt | ode-alfa validate cpf - # one per line; never echoes the identifier
55
+ ```
56
+
57
+ Exit codes: 0 valid, 1 invalid, 2 input error.
58
+
59
+ ### Known limitation
60
+
61
+ With alphanumeric CNPJs, modulo 11 cannot detect swapping a character for another whose value
62
+ differs by a multiple of 11 (e.g. `6`↔`A`, `A`↔`L`). This is a property of the official rule.
63
+
64
+ See also the [comparison with validate-docbr](https://github.com/YUCAVALCANTE/ode-alfa/blob/main/docs/comparacao-validate-docbr.md) and the
65
+ [privacy review](https://github.com/YUCAVALCANTE/ode-alfa/blob/main/docs/privacidade.md) (in Portuguese).
66
+
67
+ ## Português
68
+
69
+ ### Por que existe
70
+
71
+ Desde julho de 2026 o CNPJ pode ter letras (a Receita Federal anunciou a primeira inscrição
72
+ alfanumérica, `00.000.000/E08G-12`, em 31/07/2026). Códigos que removem tudo que não é dígito ou
73
+ guardam o CNPJ como número inteiro passam a destruir dados sem erro. O `ode-alfa` trata CPF e CNPJ
74
+ sempre como **texto**, calcula e confere os dígitos verificadores pelo módulo 11 oficial e explica
75
+ por que um valor foi rejeitado.
76
+
77
+ - Sem dependências e sem acesso à rede: a validação é só matemática.
78
+ - Não corrige identificadores, não reconstrói zeros perdidos e não diz a quem um número pertence.
79
+ - Um DV correto **não** prova que o CPF/CNPJ existe ou está ativo.
80
+ - No CNPJ alfanumérico, o módulo 11 não detecta a troca de um caractere por outro cujo valor
81
+ difere em múltiplo de 11 (por exemplo `6`↔`A`, `7`↔`B`, `8`↔`C`, `9`↔`D`, `A`↔`L`). É uma
82
+ propriedade da regra oficial, não do pacote; o teste `test_troca_de_um_caractere` a documenta.
83
+
84
+ ### Instalação
85
+
86
+ ```bash
87
+ pip install ode-alfa
88
+ ```
89
+
90
+ ### Uso
91
+
92
+ ```python
93
+ from ode_alfa import cpf, cnpj
94
+
95
+ cpf.calculate_dv("123456789") # "09"
96
+ cpf.is_valid("123.456.789-09") # True
97
+
98
+ cnpj.calculate_dv("00000000E08G") # "12"
99
+ cnpj.is_valid("00.000.000/E08G-12") # True
100
+ cnpj.format("00000000E08G12") # "00.000.000/E08G-12"
101
+ cnpj.normalize("00.000.000/e08g-12") # "00000000E08G12"
102
+
103
+ r = cnpj.validate("00.000.000/E08G-13")
104
+ r.valid, r.reason, r.expected_dv # (False, "DV_MISMATCH", "12")
105
+ ```
106
+
107
+ `validate` nunca lança exceção para entrada ruim; o motivo vem em `reason`:
108
+
109
+ | `reason` | Significado |
110
+ |---|---|
111
+ | `OK` | Formato e dígitos corretos |
112
+ | `MISSING` | `None` |
113
+ | `EXPECTED_ASCII_TEXT` | Não é texto, ou tem caracteres fora do ASCII (ex.: dígitos de largura total) |
114
+ | `INVALID_FORMAT` | Nem o formato cru nem a máscara oficial exata |
115
+ | `REPEATED_SEQUENCE` | Todos os caracteres iguais (ex.: `111.111.111-11`) |
116
+ | `DV_MISMATCH` | Dígitos verificadores não conferem; `expected_dv` traz os corretos |
117
+
118
+ `calculate_dv`, `normalize` e `format` lançam `ValueError` para entrada inválida.
119
+
120
+ ### Linha de comando
121
+
122
+ ```bash
123
+ ode-alfa validate cnpj 00.000.000/E08G-12 # OK (código de saída 0)
124
+ ode-alfa dv cnpj 00000000E08G # 12
125
+ ode-alfa format cpf 12345678909 # 123.456.789-09
126
+ cat cpfs.txt | ode-alfa validate cpf - # um por linha, sem expor CPF no histórico
127
+ ```
128
+
129
+ A CLI imprime só o motivo, nunca o identificador. Saída: 0 válido, 1 inválido, 2 erro de entrada.
130
+ Detalhes em [docs/privacidade.md](https://github.com/YUCAVALCANTE/ode-alfa/blob/main/docs/privacidade.md).
131
+
132
+ ### Como o DV é calculado
133
+
134
+ Módulo 11: `S = Σ valor × peso`, `r = S mod 11`, DV = 0 se `r < 2`, senão `11 − r`. No CNPJ,
135
+ `valor = código ASCII − 48` (0–9 mantêm o valor; A–Z valem 17–42). O DV1 entra na base antes do
136
+ cálculo do DV2.
137
+
138
+ | | Pesos |
139
+ |---|---|
140
+ | CPF DV1 / DV2 | 10…2 / 11…2 |
141
+ | CNPJ DV1 | 5 4 3 2 9 8 7 6 5 4 3 2 |
142
+ | CNPJ DV2 | 6 5 4 3 2 9 8 7 6 5 4 3 2 |
143
+
144
+ O exemplo oficial da Receita Federal (`12.ABC.345/01DE-35`, somas 459 e 424) é verificado passo a
145
+ passo em [`tests/test_conformidade_rfb.py`](https://github.com/YUCAVALCANTE/ode-alfa/blob/main/tests/test_conformidade_rfb.py).
146
+
147
+ ### Comparação com o validate-docbr
148
+
149
+ Os dois concordam em todos os dígitos verificadores, inclusive no CNPJ alfanumérico, e têm
150
+ desempenho parecido. O `ode-alfa` se diferencia pelo contrato de entrada (motivo estruturado,
151
+ máscara estrita, recusa de `int`) e pela CLI que não expõe o identificador. Casos, números e
152
+ conclusão em [docs/comparacao-validate-docbr.md](https://github.com/YUCAVALCANTE/ode-alfa/blob/main/docs/comparacao-validate-docbr.md).
153
+
154
+ ### Roadmap
155
+
156
+ - **v0.1** (05/12/2026): núcleo, CLI, conformidade com o exemplo oficial da Receita, comparação com o `validate-docbr`, revisão de privacidade, publicação.
157
+ - **v0.2:** adaptadores de lote CSV/Parquet, relatório de motivos e benchmark com o cadastro público da Receita.
158
+ - **v0.3:** scanner de código (casts numéricos e regex destrutivas) e auditoria de colisões.
159
+
160
+ Privacidade: não use CPF real em issues, testes ou exemplos. Ver [SECURITY.md](https://github.com/YUCAVALCANTE/ode-alfa/blob/main/SECURITY.md).
@@ -5,17 +5,19 @@ build-backend = "setuptools.build_meta"
5
5
  [project]
6
6
  name = "ode-alfa"
7
7
  dynamic = ["version"]
8
- description = "Offline CPF and CNPJ (numeric and alphanumeric) check-digit validation"
8
+ description = "Offline validation of Brazilian CPF and CNPJ numbers, including the new alphanumeric CNPJ"
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.11"
11
11
  license = "Apache-2.0"
12
12
  license-files = ["LICENSE"]
13
13
  authors = [{ name = "Yury Cavalcante" }]
14
- keywords = ["cpf", "cnpj", "cnpj-alfanumerico", "brasil", "validation", "data-quality"]
14
+ keywords = ["cpf", "cnpj", "cnpj-alfanumerico", "alphanumeric-cnpj", "brazil", "brasil", "receita-federal", "validation", "data-quality"]
15
15
  classifiers = [
16
16
  "Development Status :: 3 - Alpha",
17
17
  "Intended Audience :: Developers",
18
18
  "Intended Audience :: Science/Research",
19
+ "Natural Language :: English",
20
+ "Natural Language :: Portuguese (Brazilian)",
19
21
  "Operating System :: OS Independent",
20
22
  "Programming Language :: Python :: 3",
21
23
  "Programming Language :: Python :: 3 :: Only",
@@ -3,5 +3,5 @@
3
3
  from . import cnpj, cpf
4
4
  from ._core import Validation
5
5
 
6
- __version__ = "0.1.0.dev0"
6
+ __version__ = "0.1.1"
7
7
  __all__ = ["Validation", "__version__", "cnpj", "cpf"]
@@ -8,7 +8,7 @@ from __future__ import annotations
8
8
 
9
9
  import re
10
10
  from collections.abc import Sequence
11
- from dataclasses import dataclass
11
+ from dataclasses import dataclass, field
12
12
  from typing import Literal
13
13
 
14
14
  Kind = Literal["cpf", "cnpj"]
@@ -38,11 +38,12 @@ _WEIGHTS: dict[Kind, tuple[Sequence[int], Sequence[int]]] = {
38
38
  class Validation:
39
39
  """Structured result of a validation.
40
40
 
41
- ``normalized`` holds the full identifier: do not write it to logs or reports when it is a CPF.
41
+ ``normalized`` holds the full identifier. It is left out of ``repr``/``str`` so that logging a
42
+ result does not leak a CPF; read the attribute explicitly when you need it.
42
43
  """
43
44
 
44
45
  valid: bool
45
- normalized: str | None
46
+ normalized: str | None = field(repr=False)
46
47
  reason: Reason
47
48
  expected_dv: str | None = None
48
49
 
@@ -1,17 +1,19 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: ode-alfa
3
- Version: 0.1.0.dev0
4
- Summary: Offline CPF and CNPJ (numeric and alphanumeric) check-digit validation
3
+ Version: 0.1.1
4
+ Summary: Offline validation of Brazilian CPF and CNPJ numbers, including the new alphanumeric CNPJ
5
5
  Author: Yury Cavalcante
6
6
  License-Expression: Apache-2.0
7
7
  Project-URL: Homepage, https://github.com/YUCAVALCANTE/ode-alfa
8
8
  Project-URL: Issues, https://github.com/YUCAVALCANTE/ode-alfa/issues
9
9
  Project-URL: Changelog, https://github.com/YUCAVALCANTE/ode-alfa/blob/main/CHANGELOG.md
10
10
  Project-URL: Toolkit, https://github.com/YUCAVALCANTE/open-data-engineering-toolkit
11
- Keywords: cpf,cnpj,cnpj-alfanumerico,brasil,validation,data-quality
11
+ Keywords: cpf,cnpj,cnpj-alfanumerico,alphanumeric-cnpj,brazil,brasil,receita-federal,validation,data-quality
12
12
  Classifier: Development Status :: 3 - Alpha
13
13
  Classifier: Intended Audience :: Developers
14
14
  Classifier: Intended Audience :: Science/Research
15
+ Classifier: Natural Language :: English
16
+ Classifier: Natural Language :: Portuguese (Brazilian)
15
17
  Classifier: Operating System :: OS Independent
16
18
  Classifier: Programming Language :: Python :: 3
17
19
  Classifier: Programming Language :: Python :: 3 :: Only
@@ -31,18 +33,73 @@ Dynamic: license-file
31
33
 
32
34
  # ode-alfa
33
35
 
36
+ [![PyPI](https://img.shields.io/pypi/v/ode-alfa)](https://pypi.org/project/ode-alfa/)
34
37
  [![CI](https://github.com/YUCAVALCANTE/ode-alfa/actions/workflows/ci.yml/badge.svg)](https://github.com/YUCAVALCANTE/ode-alfa/actions/workflows/ci.yml)
35
38
  ![Python](https://img.shields.io/badge/python-3.11%E2%80%933.14-3776AB?logo=python&logoColor=white)
36
- ![Licença](https://img.shields.io/badge/licen%C3%A7a-Apache--2.0-blue)
37
- ![Status](https://img.shields.io/badge/status-em%20desenvolvimento-orange)
39
+ ![License](https://img.shields.io/badge/license-Apache--2.0-blue)
38
40
 
39
- **Validação matemática offline de CPF e CNPJ, inclusive o CNPJ alfanumérico.**
40
- Primeiro pacote do [Open Data Engineering Toolkit](https://github.com/YUCAVALCANTE/open-data-engineering-toolkit).
41
+ **Offline validation of Brazilian CPF and CNPJ numbers, including the new alphanumeric CNPJ.**
42
+ **Validação offline de CPF e CNPJ brasileiros, inclusive o novo CNPJ alfanumérico.**
41
43
 
42
- > **Status:** em desenvolvimento (ciclo de 07/12 a 20/12/2026). Ainda não publicado no PyPI;
43
- > instale a partir do código. A API pode mudar até a v0.1.0.
44
+ [English](#english) · [Português](#português)
44
45
 
45
- ## Por que existe
46
+ First package of the [Open Data Engineering Toolkit](https://github.com/YUCAVALCANTE/open-data-engineering-toolkit).
47
+
48
+ ```bash
49
+ pip install ode-alfa
50
+ ```
51
+
52
+ ## English
53
+
54
+ **CPF** (individual taxpayer ID) and **CNPJ** (company ID) are Brazil's federal tax identifiers.
55
+ Since July 2026 the Brazilian Federal Revenue Service (Receita Federal) issues CNPJs with letters
56
+ (e.g. `00.000.000/E08G-12`). Code that strips non-digits or stores the CNPJ as an integer now
57
+ destroys data silently. `ode-alfa` always treats CPF and CNPJ as **text**, computes and checks the
58
+ official modulo-11 check digits, and tells you *why* a value was rejected.
59
+
60
+ - Pure Python, no dependencies, no network access, fully typed.
61
+ - Does not fix identifiers, restore lost leading zeros, or say who a number belongs to.
62
+ - A correct check digit does **not** prove the CPF/CNPJ exists or is active.
63
+ - Verified step by step against the official Receita Federal example (`12.ABC.345/01DE-35`).
64
+
65
+ ### Usage
66
+
67
+ ```python
68
+ from ode_alfa import cpf, cnpj
69
+
70
+ cpf.is_valid("123.456.789-09") # True
71
+ cnpj.is_valid("00.000.000/E08G-12") # True (alphanumeric)
72
+ cnpj.calculate_dv("00000000E08G") # "12"
73
+ cnpj.format("00000000E08G12") # "00.000.000/E08G-12"
74
+
75
+ r = cnpj.validate("00.000.000/E08G-13")
76
+ r.valid, r.reason, r.expected_dv # (False, "DV_MISMATCH", "12")
77
+ ```
78
+
79
+ `validate` never raises on bad input. `reason` is one of `OK`, `MISSING`, `EXPECTED_ASCII_TEXT`,
80
+ `INVALID_FORMAT`, `REPEATED_SEQUENCE` or `DV_MISMATCH`. The full identifier is available in
81
+ `r.normalized` but is kept out of `repr`, so logging a result does not leak a CPF.
82
+
83
+ ### Command line
84
+
85
+ ```bash
86
+ ode-alfa validate cnpj 00.000.000/E08G-12 # OK (exit code 0)
87
+ cat ids.txt | ode-alfa validate cpf - # one per line; never echoes the identifier
88
+ ```
89
+
90
+ Exit codes: 0 valid, 1 invalid, 2 input error.
91
+
92
+ ### Known limitation
93
+
94
+ With alphanumeric CNPJs, modulo 11 cannot detect swapping a character for another whose value
95
+ differs by a multiple of 11 (e.g. `6`↔`A`, `A`↔`L`). This is a property of the official rule.
96
+
97
+ See also the [comparison with validate-docbr](https://github.com/YUCAVALCANTE/ode-alfa/blob/main/docs/comparacao-validate-docbr.md) and the
98
+ [privacy review](https://github.com/YUCAVALCANTE/ode-alfa/blob/main/docs/privacidade.md) (in Portuguese).
99
+
100
+ ## Português
101
+
102
+ ### Por que existe
46
103
 
47
104
  Desde julho de 2026 o CNPJ pode ter letras (a Receita Federal anunciou a primeira inscrição
48
105
  alfanumérica, `00.000.000/E08G-12`, em 31/07/2026). Códigos que removem tudo que não é dígito ou
@@ -57,16 +114,13 @@ por que um valor foi rejeitado.
57
114
  difere em múltiplo de 11 (por exemplo `6`↔`A`, `7`↔`B`, `8`↔`C`, `9`↔`D`, `A`↔`L`). É uma
58
115
  propriedade da regra oficial, não do pacote; o teste `test_troca_de_um_caractere` a documenta.
59
116
 
60
- ## Instalação
117
+ ### Instalação
61
118
 
62
119
  ```bash
63
- # depois da publicação
64
120
  pip install ode-alfa
65
- # hoje, a partir do código
66
- pip install git+https://github.com/YUCAVALCANTE/ode-alfa
67
121
  ```
68
122
 
69
- ## Uso
123
+ ### Uso
70
124
 
71
125
  ```python
72
126
  from ode_alfa import cpf, cnpj
@@ -96,7 +150,7 @@ r.valid, r.reason, r.expected_dv # (False, "DV_MISMATCH", "12")
96
150
 
97
151
  `calculate_dv`, `normalize` e `format` lançam `ValueError` para entrada inválida.
98
152
 
99
- ## Linha de comando
153
+ ### Linha de comando
100
154
 
101
155
  ```bash
102
156
  ode-alfa validate cnpj 00.000.000/E08G-12 # OK (código de saída 0)
@@ -106,8 +160,9 @@ cat cpfs.txt | ode-alfa validate cpf - # um por linha, sem expor CPF no h
106
160
  ```
107
161
 
108
162
  A CLI imprime só o motivo, nunca o identificador. Saída: 0 válido, 1 inválido, 2 erro de entrada.
163
+ Detalhes em [docs/privacidade.md](https://github.com/YUCAVALCANTE/ode-alfa/blob/main/docs/privacidade.md).
109
164
 
110
- ## Como o DV é calculado
165
+ ### Como o DV é calculado
111
166
 
112
167
  Módulo 11: `S = Σ valor × peso`, `r = S mod 11`, DV = 0 se `r < 2`, senão `11 − r`. No CNPJ,
113
168
  `valor = código ASCII − 48` (0–9 mantêm o valor; A–Z valem 17–42). O DV1 entra na base antes do
@@ -119,15 +174,20 @@ cálculo do DV2.
119
174
  | CNPJ DV1 | 5 4 3 2 9 8 7 6 5 4 3 2 |
120
175
  | CNPJ DV2 | 6 5 4 3 2 9 8 7 6 5 4 3 2 |
121
176
 
122
- ## Roadmap
177
+ O exemplo oficial da Receita Federal (`12.ABC.345/01DE-35`, somas 459 e 424) é verificado passo a
178
+ passo em [`tests/test_conformidade_rfb.py`](https://github.com/YUCAVALCANTE/ode-alfa/blob/main/tests/test_conformidade_rfb.py).
123
179
 
124
- - **v0.1** (gate 20/12/2026): núcleo, CLI, comparação de conformidade com o `validate-docbr`, publicação.
125
- - **v0.2:** adaptadores de lote CSV/Parquet e métricas.
126
- - **v0.3:** scanner de código (casts numéricos e regex destrutivas) e auditoria de colisões.
180
+ ### Comparação com o validate-docbr
127
181
 
128
- Privacidade: não use CPF real em issues, testes ou exemplos. Ver [SECURITY.md](SECURITY.md).
182
+ Os dois concordam em todos os dígitos verificadores, inclusive no CNPJ alfanumérico, e têm
183
+ desempenho parecido. O `ode-alfa` se diferencia pelo contrato de entrada (motivo estruturado,
184
+ máscara estrita, recusa de `int`) e pela CLI que não expõe o identificador. Casos, números e
185
+ conclusão em [docs/comparacao-validate-docbr.md](https://github.com/YUCAVALCANTE/ode-alfa/blob/main/docs/comparacao-validate-docbr.md).
129
186
 
130
- ---
187
+ ### Roadmap
188
+
189
+ - **v0.1** (05/12/2026): núcleo, CLI, conformidade com o exemplo oficial da Receita, comparação com o `validate-docbr`, revisão de privacidade, publicação.
190
+ - **v0.2:** adaptadores de lote CSV/Parquet, relatório de motivos e benchmark com o cadastro público da Receita.
191
+ - **v0.3:** scanner de código (casts numéricos e regex destrutivas) e auditoria de colisões.
131
192
 
132
- *English:* offline check-digit validation for Brazilian CPF and CNPJ, including the alphanumeric
133
- CNPJ introduced in 2026. Pure Python, no dependencies, typed, never treats identifiers as integers.
193
+ Privacidade: não use CPF real em issues, testes ou exemplos. Ver [SECURITY.md](https://github.com/YUCAVALCANTE/ode-alfa/blob/main/SECURITY.md).
@@ -14,4 +14,5 @@ src/ode_alfa.egg-info/dependency_links.txt
14
14
  src/ode_alfa.egg-info/entry_points.txt
15
15
  src/ode_alfa.egg-info/requires.txt
16
16
  src/ode_alfa.egg-info/top_level.txt
17
- tests/test_alfa.py
17
+ tests/test_alfa.py
18
+ tests/test_conformidade_rfb.py
@@ -147,3 +147,10 @@ def test_cli(capsys: pytest.CaptureFixture[str], monkeypatch: pytest.MonkeyPatch
147
147
  monkeypatch.setattr("sys.stdin", io.StringIO("123.456.789-09\n111.111.111-11\n"))
148
148
  assert main(["validate", "cpf", "-"]) == 1
149
149
  assert capsys.readouterr().out.split() == ["OK", "REPEATED_SEQUENCE"]
150
+
151
+
152
+ def test_repr_nao_expoe_identificador() -> None:
153
+ r = cpf.validate("123.456.789-09")
154
+ assert r.normalized == "12345678909"
155
+ assert "12345678909" not in repr(r)
156
+ assert "12345678909" not in str(r)
@@ -0,0 +1,51 @@
1
+ """Conformidade com o exemplo oficial da Receita Federal (issue #6).
2
+
3
+ Fonte: Receita Federal, "CNPJ Alfanumérico — Perguntas e Respostas", seção "Exemplo de Cálculo
4
+ de Dígito Verificador de um CNPJ alfanumérico"
5
+ (https://www.gov.br/receitafederal/pt-br/centrais-de-conteudo/publicacoes/perguntas-e-respostas/cnpj/cnpj-alfanumerico.pdf),
6
+ e Serpro, "Cálculo dos dígitos verificadores de CNPJ alfanumérico"
7
+ (https://serpro.gov.br/menu/noticias/videos/calculodvcnpjalfanaumerico.pdf). Consultados em
8
+ 05/12/2026. Os valores intermediários abaixo são os publicados nos dois documentos.
9
+ """
10
+
11
+ from ode_alfa import cnpj
12
+ from ode_alfa._core import _WEIGHTS
13
+
14
+ BASE = "12ABC34501DE"
15
+ VALORES = [1, 2, 17, 18, 19, 3, 4, 5, 0, 1, 20, 21] # ASCII - 48
16
+ PESOS_1 = [5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2]
17
+ PRODUTOS_1 = [5, 8, 51, 36, 171, 24, 28, 30, 0, 4, 60, 42]
18
+ SOMA_1, RESTO_1, DV_1 = 459, 8, "3"
19
+ PESOS_2 = [6, 5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2]
20
+ SOMA_2, RESTO_2, DV_2 = 424, 6, "5"
21
+
22
+
23
+ def test_valores_ascii_menos_48() -> None:
24
+ assert [ord(c) - 48 for c in BASE] == VALORES
25
+
26
+
27
+ def test_pesos_oficiais() -> None:
28
+ w1, w2 = _WEIGHTS["cnpj"]
29
+ assert list(w1) == PESOS_1
30
+ assert list(w2) == PESOS_2
31
+
32
+
33
+ def test_primeiro_dv_passo_a_passo() -> None:
34
+ produtos = [v * p for v, p in zip(VALORES, PESOS_1, strict=True)]
35
+ assert produtos == PRODUTOS_1
36
+ assert sum(produtos) == SOMA_1
37
+ assert SOMA_1 % 11 == RESTO_1
38
+ assert str(11 - RESTO_1) == DV_1
39
+
40
+
41
+ def test_segundo_dv_passo_a_passo() -> None:
42
+ valores = [*VALORES, int(DV_1)]
43
+ assert sum(v * p for v, p in zip(valores, PESOS_2, strict=True)) == SOMA_2
44
+ assert SOMA_2 % 11 == RESTO_2
45
+ assert str(11 - RESTO_2) == DV_2
46
+
47
+
48
+ def test_resultado_oficial() -> None:
49
+ assert cnpj.calculate_dv(BASE) == DV_1 + DV_2
50
+ assert cnpj.is_valid("12.ABC.345/01DE-35")
51
+ assert cnpj.format("12ABC34501DE35") == "12.ABC.345/01DE-35"
@@ -1,102 +0,0 @@
1
- # ode-alfa
2
-
3
- [![CI](https://github.com/YUCAVALCANTE/ode-alfa/actions/workflows/ci.yml/badge.svg)](https://github.com/YUCAVALCANTE/ode-alfa/actions/workflows/ci.yml)
4
- ![Python](https://img.shields.io/badge/python-3.11%E2%80%933.14-3776AB?logo=python&logoColor=white)
5
- ![Licença](https://img.shields.io/badge/licen%C3%A7a-Apache--2.0-blue)
6
- ![Status](https://img.shields.io/badge/status-em%20desenvolvimento-orange)
7
-
8
- **Validação matemática offline de CPF e CNPJ, inclusive o CNPJ alfanumérico.**
9
- Primeiro pacote do [Open Data Engineering Toolkit](https://github.com/YUCAVALCANTE/open-data-engineering-toolkit).
10
-
11
- > **Status:** em desenvolvimento (ciclo de 07/12 a 20/12/2026). Ainda não publicado no PyPI;
12
- > instale a partir do código. A API pode mudar até a v0.1.0.
13
-
14
- ## Por que existe
15
-
16
- Desde julho de 2026 o CNPJ pode ter letras (a Receita Federal anunciou a primeira inscrição
17
- alfanumérica, `00.000.000/E08G-12`, em 31/07/2026). Códigos que removem tudo que não é dígito ou
18
- guardam o CNPJ como número inteiro passam a destruir dados sem erro. O `ode-alfa` trata CPF e CNPJ
19
- sempre como **texto**, calcula e confere os dígitos verificadores pelo módulo 11 oficial e explica
20
- por que um valor foi rejeitado.
21
-
22
- - Sem dependências e sem acesso à rede: a validação é só matemática.
23
- - Não corrige identificadores, não reconstrói zeros perdidos e não diz a quem um número pertence.
24
- - Um DV correto **não** prova que o CPF/CNPJ existe ou está ativo.
25
- - No CNPJ alfanumérico, o módulo 11 não detecta a troca de um caractere por outro cujo valor
26
- difere em múltiplo de 11 (por exemplo `6`↔`A`, `7`↔`B`, `8`↔`C`, `9`↔`D`, `A`↔`L`). É uma
27
- propriedade da regra oficial, não do pacote; o teste `test_troca_de_um_caractere` a documenta.
28
-
29
- ## Instalação
30
-
31
- ```bash
32
- # depois da publicação
33
- pip install ode-alfa
34
- # hoje, a partir do código
35
- pip install git+https://github.com/YUCAVALCANTE/ode-alfa
36
- ```
37
-
38
- ## Uso
39
-
40
- ```python
41
- from ode_alfa import cpf, cnpj
42
-
43
- cpf.calculate_dv("123456789") # "09"
44
- cpf.is_valid("123.456.789-09") # True
45
-
46
- cnpj.calculate_dv("00000000E08G") # "12"
47
- cnpj.is_valid("00.000.000/E08G-12") # True
48
- cnpj.format("00000000E08G12") # "00.000.000/E08G-12"
49
- cnpj.normalize("00.000.000/e08g-12") # "00000000E08G12"
50
-
51
- r = cnpj.validate("00.000.000/E08G-13")
52
- r.valid, r.reason, r.expected_dv # (False, "DV_MISMATCH", "12")
53
- ```
54
-
55
- `validate` nunca lança exceção para entrada ruim; o motivo vem em `reason`:
56
-
57
- | `reason` | Significado |
58
- |---|---|
59
- | `OK` | Formato e dígitos corretos |
60
- | `MISSING` | `None` |
61
- | `EXPECTED_ASCII_TEXT` | Não é texto, ou tem caracteres fora do ASCII (ex.: dígitos de largura total) |
62
- | `INVALID_FORMAT` | Nem o formato cru nem a máscara oficial exata |
63
- | `REPEATED_SEQUENCE` | Todos os caracteres iguais (ex.: `111.111.111-11`) |
64
- | `DV_MISMATCH` | Dígitos verificadores não conferem; `expected_dv` traz os corretos |
65
-
66
- `calculate_dv`, `normalize` e `format` lançam `ValueError` para entrada inválida.
67
-
68
- ## Linha de comando
69
-
70
- ```bash
71
- ode-alfa validate cnpj 00.000.000/E08G-12 # OK (código de saída 0)
72
- ode-alfa dv cnpj 00000000E08G # 12
73
- ode-alfa format cpf 12345678909 # 123.456.789-09
74
- cat cpfs.txt | ode-alfa validate cpf - # um por linha, sem expor CPF no histórico
75
- ```
76
-
77
- A CLI imprime só o motivo, nunca o identificador. Saída: 0 válido, 1 inválido, 2 erro de entrada.
78
-
79
- ## Como o DV é calculado
80
-
81
- Módulo 11: `S = Σ valor × peso`, `r = S mod 11`, DV = 0 se `r < 2`, senão `11 − r`. No CNPJ,
82
- `valor = código ASCII − 48` (0–9 mantêm o valor; A–Z valem 17–42). O DV1 entra na base antes do
83
- cálculo do DV2.
84
-
85
- | | Pesos |
86
- |---|---|
87
- | CPF DV1 / DV2 | 10…2 / 11…2 |
88
- | CNPJ DV1 | 5 4 3 2 9 8 7 6 5 4 3 2 |
89
- | CNPJ DV2 | 6 5 4 3 2 9 8 7 6 5 4 3 2 |
90
-
91
- ## Roadmap
92
-
93
- - **v0.1** (gate 20/12/2026): núcleo, CLI, comparação de conformidade com o `validate-docbr`, publicação.
94
- - **v0.2:** adaptadores de lote CSV/Parquet e métricas.
95
- - **v0.3:** scanner de código (casts numéricos e regex destrutivas) e auditoria de colisões.
96
-
97
- Privacidade: não use CPF real em issues, testes ou exemplos. Ver [SECURITY.md](SECURITY.md).
98
-
99
- ---
100
-
101
- *English:* offline check-digit validation for Brazilian CPF and CNPJ, including the alphanumeric
102
- CNPJ introduced in 2026. Pure Python, no dependencies, typed, never treats identifiers as integers.
File without changes
File without changes