-
Notifications
You must be signed in to change notification settings - Fork 129
[2.4.0 stack 5/7] New utils: Pix, NF-e, CNS, certidão, CEI/CNO/CAEPF, IBAN, banks, tables, words, business days #511
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
Open
Changes from all commits
Commits
Show all changes
22 commits
Select commit
Hold shift + click to select a range
8ddffc7
feat(nfe-key): add formatNfeKey, isValidNfeKey and parseNfeKey
hyanmandian 402c4fb
feat(pix): add generatePixPayload, isValidPixPayload, isValidPixKey, …
hyanmandian fa2c794
feat(municipality): add getMunicipalities and getMunicipalityByCode (…
hyanmandian 96f3a10
feat(states): add getStateByIbgeCode, getStateCodeByName, getStateNam…
hyanmandian de09e55
feat(area-code): add getAreaCodeInfo and getAreaCodesByState
hyanmandian 92ff255
feat(number-to-words): add convertNumberToWords
hyanmandian c5fbdb5
feat(currency-to-words): add convertCurrencyToWords
hyanmandian b2fdba7
feat(date-to-words): add convertDateToWords
hyanmandian af86b51
feat(cns): add isValidCns and formatCns
hyanmandian b7eb21c
feat(certidao): add formatCertidao, isValidCertidao and parseCertidao
hyanmandian 660a4fc
feat(cei-cno-caepf): add isValidCei, formatCei, isValidCno, formatCno…
hyanmandian 1a5b6b3
feat(registro-profissional): add isValidRegistroProfissional
hyanmandian 43960d2
feat(credit-card): add isValidCreditCard
hyanmandian 34df3bc
feat(iban): add formatIban, isValidIban and parseIban
hyanmandian 4e161cb
feat(vin): add isValidVin
hyanmandian 4924b86
feat(cbo): add getCbo and isValidCbo
hyanmandian 5e3b679
feat(cnae): add formatCnae, getCnae and isValidCnae
hyanmandian 1d10864
feat(ncm): add formatNcm and isValidNcm
hyanmandian bc03e52
feat(cfop): add getCfop and isValidCfop
hyanmandian 45ede38
feat(cst): add isValidCst and isValidCsosn
hyanmandian cc9b6e4
feat(business-days): add isBusinessDay, addBusinessDays and differenc…
hyanmandian 3db81d2
feat(legal-nature): add getLegalNature
hyanmandian File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,67 @@ | ||
| #!/usr/bin/env node | ||
|
|
||
| import { writeFile } from "node:fs/promises"; | ||
| import { dirname, resolve } from "node:path"; | ||
| import { fileURLToPath } from "node:url"; | ||
|
|
||
| import { fetchWithRetry } from "../src/_internals/fetch-with-retry/fetch-with-retry.ts"; | ||
|
|
||
| const scriptsDir = dirname(fileURLToPath(import.meta.url)); | ||
|
|
||
| type CboEntry = { | ||
| cbo: string; | ||
| descricao: string; | ||
| }; | ||
|
|
||
| const main = async () => { | ||
| const response = await fetchWithRetry( | ||
| "https://raw.githubusercontent.com/lucaashoff/lista-cbo-json/main/cbos.json", | ||
| ); | ||
|
|
||
| if (!response.ok) { | ||
| throw new Error(`CBO mirror request failed with status ${response.status}`); | ||
| } | ||
|
|
||
| const json: CboEntry[] = await response.json(); | ||
|
|
||
| const data: Record<string, string> = {}; | ||
|
|
||
| for (const entry of json) { | ||
| const code = /^\d{5}$/.test(entry.cbo) ? `0${entry.cbo}` : entry.cbo; | ||
|
|
||
| if (!/^\d{6}$/.test(code)) continue; | ||
|
|
||
| data[code] = entry.descricao; | ||
| } | ||
|
|
||
| const sorted: Record<string, string> = {}; | ||
| for (const code of Object.keys(data).sort()) { | ||
| sorted[code] = data[code]; | ||
| } | ||
|
|
||
| await writeFile( | ||
| resolve(scriptsDir, "..", "./src/_internals/constants/cbo.ts"), | ||
| `/** | ||
| * CBO 2002 (Classificação Brasileira de Ocupações) titles, indexed by the raw 6 digit code. | ||
| * | ||
| * The MTE download at mtecbo.gov.br requires a browser session and cannot be fetched | ||
| * programmatically, so this table is generated from a public community mirror of the | ||
| * official table. Codes that are not purely numeric with 6 digits in the source (a small | ||
| * number of law enforcement and military ranks and a few sub-occupation codes suffixed | ||
| * with a letter) are normalized by left padding a 5 digit numeric code with a zero, or | ||
| * dropped when a letter is present, since \`Cbo.code\` only accepts 6 digits. | ||
| * | ||
| * Generated by \`node ./scripts/cbo.ts\`. Do not edit by hand. | ||
| * | ||
| * @see https://raw.githubusercontent.com/lucaashoff/lista-cbo-json/main/cbos.json | ||
| * @see http://www.mtecbo.gov.br/cbosite/pages/downloads.jsf | ||
| */ | ||
| export const CBO_TITLES: Record<string, string> = ${JSON.stringify(sorted)}; | ||
| `, | ||
| ); | ||
| }; | ||
|
|
||
| await main().catch((error) => { | ||
| console.error(error instanceof Error ? error.message : error); | ||
| process.exit(1); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,62 @@ | ||
| #!/usr/bin/env node | ||
|
|
||
| import { writeFile } from "node:fs/promises"; | ||
| import { dirname, resolve } from "node:path"; | ||
| import { fileURLToPath } from "node:url"; | ||
|
|
||
| import { fetchWithRetry } from "../src/_internals/fetch-with-retry/fetch-with-retry.ts"; | ||
|
|
||
| const scriptsDir = dirname(fileURLToPath(import.meta.url)); | ||
|
|
||
| const main = async () => { | ||
| const response = await fetchWithRetry( | ||
| "https://raw.githubusercontent.com/jansenfelipe/cfop/master/cfop.csv", | ||
| ); | ||
|
|
||
| if (!response.ok) { | ||
| throw new Error(`CFOP mirror request failed with status ${response.status}`); | ||
| } | ||
|
|
||
| const csv = await response.text(); | ||
|
|
||
| const data: Record<string, string> = {}; | ||
|
|
||
| for (const line of csv.split("\n")) { | ||
| const match = line.match(/^(\d{4});"(.*)"\s*$/); | ||
|
|
||
| if (!match) continue; | ||
|
|
||
| const [, code, description] = match; | ||
|
|
||
| if (code.endsWith("00")) continue; | ||
|
|
||
| data[code] = description.trim(); | ||
| } | ||
|
|
||
| const sorted: Record<string, string> = {}; | ||
| for (const code of Object.keys(data).sort()) { | ||
| sorted[code] = data[code]; | ||
| } | ||
|
|
||
| await writeFile( | ||
| resolve(scriptsDir, "..", "./src/_internals/constants/cfop.ts"), | ||
| `/** | ||
| * CFOP (Código Fiscal de Operações e Prestações) table, indexed by the 4 digit code. | ||
| * | ||
| * Group and subgroup headers (codes ending in "00", e.g. "1000", "1100") are section | ||
| * titles from the official nomenclature rather than operable codes, so they are excluded. | ||
| * | ||
| * Generated by \`node ./scripts/cfop.ts\`. Do not edit by hand. | ||
| * | ||
| * @see https://raw.githubusercontent.com/jansenfelipe/cfop/master/cfop.csv | ||
| * @see https://www.confaz.fazenda.gov.br/legislacao/ajustes/2001/AJ_007_01 | ||
| */ | ||
| export const CFOP_TABLE: Record<string, string> = ${JSON.stringify(sorted)}; | ||
| `, | ||
| ); | ||
| }; | ||
|
|
||
| await main().catch((error) => { | ||
| console.error(error instanceof Error ? error.message : error); | ||
| process.exit(1); | ||
| }); | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,54 @@ | ||
| #!/usr/bin/env node | ||
|
|
||
| import { writeFile } from "node:fs/promises"; | ||
| import { dirname, resolve } from "node:path"; | ||
| import { fileURLToPath } from "node:url"; | ||
|
|
||
| import { fetchWithRetry } from "../src/_internals/fetch-with-retry/fetch-with-retry.ts"; | ||
|
|
||
| const scriptsDir = dirname(fileURLToPath(import.meta.url)); | ||
|
|
||
| type CnaeSubclass = { | ||
| id: string; | ||
| descricao: string; | ||
| }; | ||
|
|
||
| const main = async () => { | ||
| const response = await fetchWithRetry("https://servicodados.ibge.gov.br/api/v2/cnae/subclasses"); | ||
|
|
||
| if (!response.ok) { | ||
| throw new Error(`IBGE CNAE request failed with status ${response.status}`); | ||
| } | ||
|
|
||
| const json: CnaeSubclass[] = await response.json(); | ||
|
|
||
| const entries = json | ||
| .filter((subclass) => /^\d{7}$/.test(subclass.id)) | ||
| .sort((subclassA, subclassB) => (subclassA.id > subclassB.id ? 1 : -1)) | ||
| .map((subclass) => [subclass.id, subclass.descricao] as const); | ||
|
|
||
| const data: Record<string, string> = {}; | ||
| for (const [id, descricao] of entries) { | ||
| data[id] = descricao; | ||
| } | ||
|
|
||
| await writeFile( | ||
| resolve(scriptsDir, "..", "./src/_internals/constants/cnae.ts"), | ||
| `/** | ||
| * CNAE 2.3 (Classificação Nacional de Atividades Econômicas) subclasses, indexed by the | ||
| * raw 7 digit code, mapping to the official subclass description. | ||
| * | ||
| * Generated by \`node ./scripts/cnae.ts\`. Do not edit by hand. | ||
| * | ||
| * @see https://servicodados.ibge.gov.br/api/v2/cnae/subclasses | ||
| * @see https://concla.ibge.gov.br/classificacoes/por-tema/atividades-economicas/classificacao-nacional-de-atividades-economicas | ||
| */ | ||
| export const CNAE_SUBCLASSES: Record<string, string> = ${JSON.stringify(data)}; | ||
| `, | ||
| ); | ||
| }; | ||
|
|
||
| await main().catch((error) => { | ||
| console.error(error instanceof Error ? error.message : error); | ||
| process.exit(1); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,56 @@ | ||
| #!/usr/bin/env node | ||
|
|
||
| import { writeFile } from "node:fs/promises"; | ||
| import { dirname, resolve } from "node:path"; | ||
| import { fileURLToPath } from "node:url"; | ||
|
|
||
| import { fetchWithRetry } from "../src/_internals/fetch-with-retry/fetch-with-retry.ts"; | ||
|
|
||
| const scriptsDir = dirname(fileURLToPath(import.meta.url)); | ||
|
|
||
| type NcmEntry = { | ||
| Codigo: string; | ||
| Data_Fim: string; | ||
| }; | ||
|
|
||
| type NcmResponse = { | ||
| Nomenclaturas: NcmEntry[]; | ||
| }; | ||
|
|
||
| const main = async () => { | ||
| const response = await fetchWithRetry( | ||
| "https://portalunico.siscomex.gov.br/classif/api/publico/nomenclatura/download/json?perfil=PUBLICO", | ||
| ); | ||
|
|
||
| if (!response.ok) { | ||
| throw new Error(`Siscomex NCM request failed with status ${response.status}`); | ||
| } | ||
|
|
||
| const json: NcmResponse = await response.json(); | ||
|
|
||
| const codes = json.Nomenclaturas.filter( | ||
| (entry) => entry.Data_Fim === "31/12/9999" && /^[\d.]{10}$/.test(entry.Codigo), | ||
| ) | ||
| .map((entry) => entry.Codigo.replace(/\D/g, "")) | ||
| .filter((code) => code.length === 8); | ||
|
|
||
| const uniqueSortedCodes = Array.from(new Set(codes)).sort(); | ||
|
|
||
| await writeFile( | ||
| resolve(scriptsDir, "..", "./src/is-valid-ncm/constants.ts"), | ||
| `/** | ||
| * Currently valid NCM (Nomenclatura Comum do Mercosul) 8 digit codes, sorted ascending. | ||
| * | ||
| * Generated by \`node ./scripts/ncm.ts\`. Do not edit by hand. | ||
| * | ||
| * @see https://portalunico.siscomex.gov.br/classif/api/publico/nomenclatura/download/json | ||
| */ | ||
| export const NCM_CODES: readonly string[] = ${JSON.stringify(uniqueSortedCodes)}; | ||
| `, | ||
| ); | ||
| }; | ||
|
|
||
| await main().catch((error) => { | ||
| console.error(error instanceof Error ? error.message : error); | ||
| process.exit(1); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,27 @@ | ||
| import type { WordsCase } from "../number-to-words/number-to-words"; | ||
|
|
||
| /** | ||
| * Applies a `WordsCase` to a "por extenso" string already written out in lowercase. | ||
| * | ||
| * `"sentence"` capitalizes only the first letter; `"upper"` uppercases the whole string with | ||
| * `toLocaleUpperCase("pt-BR")`, which keeps accents intact ("três" -> "TRÊS"). Any value other | ||
| * than `"sentence"` or `"upper"` (including `"lower"`, `undefined` or an invalid value) returns | ||
| * `text` unchanged, since it is already written in lowercase. | ||
| * | ||
| * @param {string} text - The lowercase "por extenso" string to transform. | ||
| * @param {WordsCase} [wordsCase] - The case to apply. Defaults to `"lower"` (no change). | ||
| * @returns {string} `text` with the requested case applied. | ||
| * | ||
| * @example | ||
| * ```typescript | ||
| * applyWordsCase("três reais"); // "três reais" | ||
| * applyWordsCase("três reais", "sentence"); // "Três reais" | ||
| * applyWordsCase("três reais", "upper"); // "TRÊS REAIS" | ||
| * ``` | ||
| */ | ||
| export const applyWordsCase = (text: string, wordsCase?: WordsCase): string => { | ||
| if (wordsCase === "upper") return text.toLocaleUpperCase("pt-BR"); | ||
| if (wordsCase === "sentence") return text.charAt(0).toLocaleUpperCase("pt-BR") + text.slice(1); | ||
|
|
||
| return text; | ||
| }; |
24 changes: 24 additions & 0 deletions
24
src/_internals/calculate-cei-check-digit/calculate-cei-check-digit.test.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,24 @@ | ||
| import { describe, expect, test } from "../test/runtime"; | ||
| import { calculateCeiCheckDigit } from "./calculate-cei-check-digit"; | ||
|
|
||
| describe("calculateCeiCheckDigit", () => { | ||
| test("should return 5 for the base of 11.583.00249/85 (yiibr/yii2-br-validator CeiValidatorTest)", () => { | ||
| expect(calculateCeiCheckDigit("11583002498")).toBe(5); | ||
| }); | ||
|
|
||
| test("should return 7 for the base of 27.729.71181/87 (yiibr/yii2-br-validator CeiValidatorTest)", () => { | ||
| expect(calculateCeiCheckDigit("27729711818")).toBe(7); | ||
| }); | ||
|
|
||
| test("should return 6 for the base of 24.985.96743/86 (marcos-cruz/Documento CeiTest)", () => { | ||
| expect(calculateCeiCheckDigit("24985967438")).toBe(6); | ||
| }); | ||
|
|
||
| test("should return 0 when the folded sum ends in 0 (CNO 401800097960 of the Receita Federal CNO dataset)", () => { | ||
| expect(calculateCeiCheckDigit("40180009796")).toBe(0); | ||
| }); | ||
|
|
||
| test("should return 0 for a base of only zeros", () => { | ||
| expect(calculateCeiCheckDigit("00000000000")).toBe(0); | ||
| }); | ||
| }); |
35 changes: 35 additions & 0 deletions
35
src/_internals/calculate-cei-check-digit/calculate-cei-check-digit.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,35 @@ | ||
| import { CEI_WEIGHTS } from "../constants/cei"; | ||
| import { generateChecksum } from "../generate-checksum/generate-checksum"; | ||
|
|
||
| /** | ||
| * Calculates the check digit of a CEI (Cadastro Específico do INSS) base, the same digit the | ||
| * CNO (Cadastro Nacional de Obras) kept when it replaced the CEI numbering. | ||
| * | ||
| * The 11 base digits are weighted by 7, 4, 1, 8, 5, 2, 1, 6, 3, 7 and 4 from left to right. | ||
| * The tens part and the units part of that sum are added together and the check digit is the | ||
| * complement of the units digit of the result to 10, with 10 mapped back to 0. | ||
| * | ||
| * @param {string} base - The 11 digits that precede the check digit. | ||
| * @returns {number} The check digit, 0 to 9. | ||
| * | ||
| * @example | ||
| * ```typescript | ||
| * calculateCeiCheckDigit("11583002498"); // 5 | ||
| * calculateCeiCheckDigit("40180009796"); // 0 | ||
| * ``` | ||
| * | ||
| * @see Official: https://www.gov.br/receitafederal/pt-br/assuntos/orientacao-tributaria/cadastros/cno | ||
| * @see Official: Cadastro Nacional de Obras (CNO), dados abertos da Receita Federal: the | ||
| * 38432 works registered in Minas Gerais confirm the rule, and their check digits of 0 are | ||
| * what shows that a computed 10 maps back to 0, which neither reference implementation does. | ||
| * @see Based on: https://github.com/yiibr/yii2-br-validator/blob/master/src/CeiValidator.php | ||
| * PHP reference implementation of the CEI check digit. | ||
| * @see Based on: https://github.com/marcos-cruz/Documento/blob/master/src/Bigai.Documentos.Brasil/Cei/Cei.cs | ||
| * Second, independent reference implementation agreeing with the first. | ||
| */ | ||
| export const calculateCeiCheckDigit = (base: string): number => { | ||
| const sum = generateChecksum({ base, weight: CEI_WEIGHTS }); | ||
| const folded = Math.floor(sum / 10) + (sum % 10); | ||
|
|
||
| return (10 - (folded % 10)) % 10; | ||
| }; |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🎯 Functional Correctness | 🟠 Major | 🏗️ Heavy lift
Use a validated CFOP source before generating the table.
The generated table is already corrupt. For example, the description for
1305contains the1306entry, and1306is absent as a key. The same pattern affects1414and6913. As a result,getCfopreturnsnullfor valid codes or returns incorrect descriptions.Replace this mirror with an authoritative, parseable source. Add regression cases for the affected codes before regenerating
src/_internals/constants/cfop.ts.🤖 Prompt for AI Agents