rails-br 0.2.0

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.
@@ -0,0 +1,38 @@
1
+ # frozen_string_literal: true
2
+
3
+ module RailsBr
4
+ module Pix
5
+ # CRC-16/CCITT-FALSE usado no campo 63 do BR Code: polinômio `0x1021`,
6
+ # valor inicial `0xFFFF`, sem reflexão e sem XOR final (Manual do BR Code,
7
+ # nota de rodapé 10, e EMV QRCPS-MPM, seção 4.7.3).
8
+ #
9
+ # @example
10
+ # RailsBr::Pix::CRC16.checksum("123456789") # => "29B1"
11
+ module CRC16
12
+ # Polinômio gerador (0x1021).
13
+ POLYNOMIAL = 0x1021
14
+ # Valor inicial do registrador (0xFFFF).
15
+ INITIAL_VALUE = 0xFFFF
16
+ # Máscara de 16 bits.
17
+ MASK = 0xFFFF
18
+ # Bit mais significativo do registrador.
19
+ TOP_BIT = 0x8000
20
+
21
+ # @param data [String] os bytes sobre os quais calcular o CRC
22
+ # @return [String] 4 dígitos hexadecimais maiúsculos, com zeros à esquerda
23
+ def self.checksum(data)
24
+ crc = data.each_byte.reduce(INITIAL_VALUE) { |acc, byte| process_byte(acc, byte) }
25
+ format("%04X", crc)
26
+ end
27
+
28
+ def self.process_byte(crc, byte)
29
+ crc ^= byte << 8
30
+ 8.times do
31
+ crc = crc.anybits?(TOP_BIT) ? ((crc << 1) ^ POLYNOMIAL) & MASK : (crc << 1) & MASK
32
+ end
33
+ crc
34
+ end
35
+ private_class_method :process_byte
36
+ end
37
+ end
38
+ end
@@ -0,0 +1,108 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "../document"
4
+ require_relative "../cpf"
5
+ require_relative "../cnpj"
6
+
7
+ module RailsBr
8
+ module Pix
9
+ # Chave Pix: detecta o tipo e valida o formato.
10
+ #
11
+ # As regras seguem os manuais do Banco Central: Manual Operacional do DICT
12
+ # (v8.5, seção 1), especificação da API do DICT (v2.13.0, tabela de chaves)
13
+ # e Manual de Padrões para Iniciação do Pix (v2.10.0, seção 2.5.1).
14
+ #
15
+ # A validação é **estrita**, como o DICT: a chave não é normalizada. CPF e
16
+ # CNPJ vão sem máscara; o e-mail e a chave aleatória, em minúsculas; o
17
+ # telefone no formato internacional E.164 (`+5561912345678`). Espaços nas
18
+ # pontas tornam a chave inválida.
19
+ #
20
+ # | Tipo | Formato |
21
+ # |----------|----------------------------------------------------------|
22
+ # | `:cpf` | 11 dígitos, com dígitos verificadores corretos |
23
+ # | `:cnpj` | 14 caracteres (numérico ou alfanumérico), DV correto |
24
+ # | `:phone` | `+` e 2 a 15 dígitos, o primeiro de 1 a 9 (E.164) |
25
+ # | `:email` | até 77 caracteres, minúsculo, regex da API do DICT |
26
+ # | `:evp` | UUID com hífens, em minúsculas (chave aleatória) |
27
+ #
28
+ # O `+55` não é exigido pela especificação, que adota E.164 de forma geral.
29
+ #
30
+ # @example
31
+ # key = RailsBr::Pix::Key.new("+5561912345678")
32
+ # key.valid? # => true
33
+ # key.type # => :phone
34
+ # RailsBr::Pix::Key.new("111.444.777-35").valid? # => false (use só dígitos)
35
+ class Key < Document
36
+ # Tipos de chave Pix, na ordem em que são testados.
37
+ TYPES = %i[cpf cnpj phone email evp].freeze
38
+ # Tamanho máximo de uma chave Pix.
39
+ MAX_LENGTH = 77
40
+
41
+ # CPF como chave: 11 dígitos, sem máscara.
42
+ CPF_FORMAT = /\A\d{11}\z/.freeze
43
+ # CNPJ como chave: 14 caracteres, numérico ou alfanumérico, sem máscara.
44
+ CNPJ_FORMAT = /\A[0-9A-Z]{12}\d{2}\z/.freeze
45
+ # Telefone no formato internacional E.164.
46
+ PHONE_FORMAT = /\A\+[1-9]\d{1,14}\z/.freeze
47
+ # Chave aleatória: UUID com hífens, em minúsculas.
48
+ EVP_FORMAT = /\A[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\z/.freeze
49
+ # Expressão regular da API do DICT para e-mail (somente minúsculas).
50
+ EMAIL_FORMAT = %r{
51
+ \A[a-z0-9.!\#$'*+/=?^_`{|}~-]+
52
+ @[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?
53
+ (?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*\z
54
+ }x.freeze
55
+
56
+ # @param value [#to_s, nil]
57
+ # @return [Symbol, nil] o tipo da chave, ou `nil` se for inválida
58
+ def self.type_of(value)
59
+ new(value).type
60
+ end
61
+
62
+ # @param value [#to_s, nil]
63
+ # @return [String] a mensagem de {.parse!}
64
+ def self.invalid_message(value)
65
+ "Chave Pix inválida: #{value.inspect}"
66
+ end
67
+
68
+ # @return [Symbol, nil] um de {TYPES}, ou `nil` se a chave for inválida
69
+ def type
70
+ return if value.empty? || value.length > MAX_LENGTH
71
+
72
+ TYPES.find { |candidate| send(:"#{candidate}?") }
73
+ end
74
+
75
+ # @return [Boolean]
76
+ def valid?
77
+ !type.nil?
78
+ end
79
+
80
+ private
81
+
82
+ # A chave é validada exatamente como recebida.
83
+ def normalize(string)
84
+ string
85
+ end
86
+
87
+ def cpf?
88
+ value.match?(CPF_FORMAT) && CPF.valid?(value)
89
+ end
90
+
91
+ def cnpj?
92
+ value.match?(CNPJ_FORMAT) && CNPJ.valid?(value)
93
+ end
94
+
95
+ def phone?
96
+ value.match?(PHONE_FORMAT)
97
+ end
98
+
99
+ def email?
100
+ value.match?(EMAIL_FORMAT)
101
+ end
102
+
103
+ def evp?
104
+ value.match?(EVP_FORMAT)
105
+ end
106
+ end
107
+ end
108
+ end
@@ -0,0 +1,51 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "../error"
4
+
5
+ module RailsBr
6
+ module Pix
7
+ # Leitura de objetos TLV (ID, tamanho, valor) do padrão EMV QRCPS-MPM,
8
+ # usado pelo BR Code. Cada objeto tem 2 dígitos de ID, 2 dígitos de tamanho
9
+ # (em caracteres) e o valor.
10
+ #
11
+ # @example
12
+ # RailsBr::Pix::TLV.parse("000201010211")
13
+ # # => [["00", "01"], ["01", "11"]]
14
+ module TLV
15
+ # Tamanho do cabeçalho de cada objeto (2 dígitos de ID e 2 de tamanho).
16
+ HEADER_LENGTH = 4
17
+ # Dois dígitos, usado no ID e no tamanho.
18
+ DIGITS = /\A\d{2}\z/.freeze
19
+
20
+ # @param string [String]
21
+ # @return [Array<Array(String, String)>] os pares `[id, valor]`, em ordem
22
+ # @raise [InvalidValueError] se a sequência estiver truncada ou malformada
23
+ def self.parse(string)
24
+ pairs = []
25
+ position = 0
26
+
27
+ while position < string.length
28
+ id, value = read_object(string, position)
29
+ pairs << [id, value]
30
+ position += HEADER_LENGTH + value.length
31
+ end
32
+
33
+ pairs
34
+ end
35
+
36
+ def self.read_object(string, position)
37
+ id = string[position, 2]
38
+ size = string[position + 2, 2]
39
+ unless id.match?(DIGITS) && size.match?(DIGITS)
40
+ raise InvalidValueError, "objeto TLV malformado na posição #{position}"
41
+ end
42
+
43
+ value = string[position + HEADER_LENGTH, size.to_i]
44
+ raise InvalidValueError, "objeto #{id} truncado na posição #{position}" if value.length < size.to_i
45
+
46
+ [id, value]
47
+ end
48
+ private_class_method :read_object
49
+ end
50
+ end
51
+ end
@@ -0,0 +1,11 @@
1
+ # frozen_string_literal: true
2
+
3
+ module RailsBr
4
+ # Helpers do Pix (Banco Central do Brasil).
5
+ module Pix
6
+ autoload :Key, "rails_br/pix/key"
7
+ autoload :CRC16, "rails_br/pix/crc16"
8
+ autoload :TLV, "rails_br/pix/tlv"
9
+ autoload :BRCode, "rails_br/pix/br_code"
10
+ end
11
+ end
@@ -0,0 +1,20 @@
1
+ # frozen_string_literal: true
2
+
3
+ module RailsBr
4
+ # Integração com o Rails. Só é carregada quando o Rails já está presente.
5
+ class Railtie < ::Rails::Railtie
6
+ initializer "rails_br.i18n" do
7
+ RailsBr::Locale.install!
8
+ end
9
+
10
+ # Os validadores só são registrados se o ActiveModel estiver disponível.
11
+ initializer "rails_br.validators" do
12
+ require "rails_br/validators" if defined?(ActiveModel)
13
+ end
14
+
15
+ # Registra os tipos `:br_currency` e `:br_date`.
16
+ initializer "rails_br.types" do
17
+ require "rails_br/types" if defined?(ActiveModel)
18
+ end
19
+ end
20
+ end
@@ -0,0 +1,17 @@
1
+ # frozen_string_literal: true
2
+
3
+ module RailsBr
4
+ # Checagem comum dos leitores de texto ({Currency} e {DateFormat}).
5
+ #
6
+ # @api private
7
+ module TextInput
8
+ # Só `String` em codificação compatível com ASCII e com bytes válidos pode
9
+ # ser lida: aplicar uma expressão regular a outros valores levanta erro.
10
+ #
11
+ # @param value [Object]
12
+ # @return [Boolean]
13
+ def self.readable?(value)
14
+ value.is_a?(String) && value.encoding.ascii_compatible? && value.valid_encoding?
15
+ end
16
+ end
17
+ end
@@ -0,0 +1,48 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "active_model"
4
+ require "bigdecimal"
5
+ require_relative "../currency"
6
+
7
+ module RailsBr
8
+ module Types
9
+ # Tipo de atributo que lê valores em reais (`"R$ 1.234,56"`) como
10
+ # `BigDecimal`. Texto inválido e `Float` viram `nil`; use o validador
11
+ # `br_currency: true` para acusar o erro.
12
+ #
13
+ # @example
14
+ # attribute :price, :br_currency
15
+ class BrCurrency < ActiveModel::Type::Value
16
+ # @return [Symbol] `:decimal`, como o tipo decimal do Rails
17
+ def type
18
+ :decimal
19
+ end
20
+
21
+ # Converte o valor lido do banco de dados.
22
+ #
23
+ # @param value [Object, nil]
24
+ # @return [BigDecimal, nil]
25
+ def deserialize(value)
26
+ BigDecimal(value.to_s) unless value.nil?
27
+ end
28
+
29
+ # Converte o valor a gravar ou a usar em consultas.
30
+ #
31
+ # @param value [Object, nil]
32
+ # @return [BigDecimal, nil]
33
+ def serialize(value)
34
+ cast(value)
35
+ end
36
+
37
+ private
38
+
39
+ def cast_value(value)
40
+ case value
41
+ when String then Currency.parse(value)
42
+ when BigDecimal then value
43
+ when Integer then BigDecimal(value)
44
+ end
45
+ end
46
+ end
47
+ end
48
+ end
@@ -0,0 +1,50 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "active_model"
4
+ require "date"
5
+ require_relative "../date_format"
6
+
7
+ module RailsBr
8
+ module Types
9
+ # Tipo de atributo que lê datas `dd/mm/aaaa` como `Date`. Texto inválido e
10
+ # `Time` viram `nil`; use o validador `br_date: true` para acusar o erro.
11
+ #
12
+ # O texto digitado é sempre lido no padrão brasileiro, inclusive em
13
+ # consultas. Valores vindos do banco de dados são lidos no formato do banco.
14
+ #
15
+ # @example
16
+ # attribute :born_on, :br_date
17
+ class BrDate < ActiveModel::Type::Value
18
+ # @return [Symbol] `:date`, como o tipo de data do Rails
19
+ def type
20
+ :date
21
+ end
22
+
23
+ # Converte o valor lido do banco de dados.
24
+ #
25
+ # @param value [Object, nil]
26
+ # @return [Date, nil]
27
+ def deserialize(value)
28
+ ActiveModel::Type::Date.new.deserialize(value)
29
+ end
30
+
31
+ # Converte o valor a gravar ou a usar em consultas.
32
+ #
33
+ # @param value [Object, nil]
34
+ # @return [Date, nil]
35
+ def serialize(value)
36
+ cast(value)
37
+ end
38
+
39
+ private
40
+
41
+ def cast_value(value)
42
+ case value
43
+ when String then DateFormat.parse(value)
44
+ when DateTime then value.to_date
45
+ when Date then value
46
+ end
47
+ end
48
+ end
49
+ end
50
+ end
@@ -0,0 +1,24 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "active_model"
4
+ require_relative "../rails_br"
5
+ require_relative "types/br_currency"
6
+ require_relative "types/br_date"
7
+
8
+ module RailsBr
9
+ # Tipos de atributo do ActiveModel e do ActiveRecord.
10
+ #
11
+ # `require "rails_br/types"` registra `:br_currency` e `:br_date`. No Rails, o
12
+ # Railtie faz isso automaticamente.
13
+ module Types
14
+ # Nomes com que os tipos são registrados.
15
+ REGISTRY = { br_currency: BrCurrency, br_date: BrDate }.freeze
16
+
17
+ REGISTRY.each { |name, type| ActiveModel::Type.register(name, type) }
18
+
19
+ # O ActiveRecord tem um registro próprio; o hook roda quando ele é carregado.
20
+ ActiveSupport.on_load(:active_record) do
21
+ RailsBr::Types::REGISTRY.each { |name, type| ActiveRecord::Type.register(name, type) }
22
+ end
23
+ end
24
+ end
@@ -0,0 +1,28 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ActiveModel
4
+ module Validations
5
+ # Valida um valor em reais, em atributos `:br_currency` ou de texto. Valores
6
+ # em branco são ignorados; combine com `presence: true` para exigi-los.
7
+ #
8
+ # @example
9
+ # attribute :price, :br_currency
10
+ # validates :price, br_currency: true
11
+ class BrCurrencyValidator < RailsBr::TypedValueValidator
12
+ private
13
+
14
+ def error_key
15
+ :invalid_br_currency
16
+ end
17
+
18
+ def acceptable?(value)
19
+ case value
20
+ when String then !RailsBr::Currency.parse(value).nil?
21
+ when Integer then true
22
+ when BigDecimal then value.finite? && value.round(2) == value
23
+ else false
24
+ end
25
+ end
26
+ end
27
+ end
28
+ end
@@ -0,0 +1,26 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ActiveModel
4
+ module Validations
5
+ # Valida uma data `dd/mm/aaaa`, em atributos `:br_date` ou de texto. Valores
6
+ # em branco são ignorados; combine com `presence: true` para exigi-los.
7
+ #
8
+ # @example
9
+ # attribute :born_on, :br_date
10
+ # validates :born_on, br_date: true
11
+ class BrDateValidator < RailsBr::TypedValueValidator
12
+ private
13
+
14
+ def error_key
15
+ :invalid_br_date
16
+ end
17
+
18
+ def acceptable?(value)
19
+ case value
20
+ when String then !RailsBr::DateFormat.parse(value).nil?
21
+ else value.is_a?(Date)
22
+ end
23
+ end
24
+ end
25
+ end
26
+ end
@@ -0,0 +1,24 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ActiveModel
4
+ module Validations
5
+ # Valida um CNPJ, numérico ou alfanumérico. Valores em branco são
6
+ # ignorados; combine com `presence: true` para torná-lo obrigatório.
7
+ #
8
+ # @example
9
+ # validates :cnpj, cnpj: true
10
+ # validates :cnpj, cnpj: { message: "inválido" }
11
+ class CnpjValidator < EachValidator
12
+ # @param record [ActiveModel::Validations] o objeto validado
13
+ # @param attribute [Symbol] o atributo
14
+ # @param value [Object] o valor do atributo
15
+ # @return [void]
16
+ def validate_each(record, attribute, value)
17
+ return if value.blank?
18
+ return if RailsBr::CNPJ.valid?(value)
19
+
20
+ record.errors.add(attribute, :invalid_cnpj, **options, value: value)
21
+ end
22
+ end
23
+ end
24
+ end
@@ -0,0 +1,27 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Extensões do ActiveModel fornecidas pela gem rails-br.
4
+ module ActiveModel
5
+ # Validadores: `cpf`, `cnpj` e `pix_key`.
6
+ module Validations
7
+ # Valida um CPF. Valores em branco são ignorados; combine com
8
+ # `presence: true` para torná-lo obrigatório.
9
+ #
10
+ # @example
11
+ # validates :cpf, cpf: true
12
+ # validates :cpf, cpf: { message: "inválido" }
13
+ # validates :cpf, cpf: true, allow_nil: true
14
+ class CpfValidator < EachValidator
15
+ # @param record [ActiveModel::Validations] o objeto validado
16
+ # @param attribute [Symbol] o atributo
17
+ # @param value [Object] o valor do atributo
18
+ # @return [void]
19
+ def validate_each(record, attribute, value)
20
+ return if value.blank?
21
+ return if RailsBr::CPF.valid?(value)
22
+
23
+ record.errors.add(attribute, :invalid_cpf, **options, value: value)
24
+ end
25
+ end
26
+ end
27
+ end
@@ -0,0 +1,24 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ActiveModel
4
+ module Validations
5
+ # Valida uma chave Pix (CPF, CNPJ, telefone, e-mail ou chave aleatória).
6
+ # A validação é estrita: veja {RailsBr::Pix::Key}. Valores em branco são
7
+ # ignorados; combine com `presence: true` para torná-la obrigatória.
8
+ #
9
+ # @example
10
+ # validates :pix_key, pix_key: true
11
+ class PixKeyValidator < EachValidator
12
+ # @param record [ActiveModel::Validations] o objeto validado
13
+ # @param attribute [Symbol] o atributo
14
+ # @param value [Object] o valor do atributo
15
+ # @return [void]
16
+ def validate_each(record, attribute, value)
17
+ return if value.blank?
18
+ return if RailsBr::Pix::Key.valid?(value)
19
+
20
+ record.errors.add(attribute, :invalid_pix_key, **options, value: value)
21
+ end
22
+ end
23
+ end
24
+ end
@@ -0,0 +1,49 @@
1
+ # frozen_string_literal: true
2
+
3
+ module RailsBr
4
+ # Base dos validadores de atributos que convertem texto (`br_currency` e
5
+ # `br_date`). Quando a conversão falha, o atributo fica `nil`; por isso o
6
+ # validador examina também o valor digitado, antes da conversão.
7
+ #
8
+ # As opções `allow_nil` e `allow_blank` não escondem texto inválido: valores
9
+ # realmente em branco já são ignorados.
10
+ #
11
+ # @api private
12
+ class TypedValueValidator < ActiveModel::EachValidator
13
+ # @param record [ActiveModel::Validations] o objeto validado
14
+ # @return [void]
15
+ def validate(record)
16
+ attributes.each do |attribute|
17
+ validate_each(record, attribute, record.read_attribute_for_validation(attribute))
18
+ end
19
+ end
20
+
21
+ # @param record [ActiveModel::Validations] o objeto validado
22
+ # @param attribute [Symbol] o atributo
23
+ # @param value [Object] o valor já convertido
24
+ # @return [void]
25
+ def validate_each(record, attribute, value)
26
+ candidate = value.nil? ? raw_value(record, attribute) : value
27
+ return if candidate.blank? || acceptable?(candidate)
28
+
29
+ record.errors.add(attribute, error_key, **options, value: candidate)
30
+ end
31
+
32
+ private
33
+
34
+ # O ActiveRecord (e o ActiveModel mais novo) expõe `*_before_type_cast`. No
35
+ # ActiveModel::Attributes de versões antigas, o valor fica no AttributeSet.
36
+ def raw_value(record, attribute)
37
+ method = "#{attribute}_before_type_cast"
38
+ return record.public_send(method) if record.respond_to?(method)
39
+
40
+ attribute_set_value(record.instance_variable_get(:@attributes), attribute.to_s)
41
+ end
42
+
43
+ def attribute_set_value(set, name)
44
+ return unless defined?(ActiveModel::AttributeSet) && set.is_a?(ActiveModel::AttributeSet)
45
+
46
+ set[name].value_before_type_cast if set.key?(name)
47
+ end
48
+ end
49
+ end
@@ -0,0 +1,14 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "active_model"
4
+ require_relative "../rails_br"
5
+ require_relative "locale"
6
+
7
+ RailsBr::Locale.install!
8
+
9
+ require_relative "validators/cpf_validator"
10
+ require_relative "validators/cnpj_validator"
11
+ require_relative "validators/pix_key_validator"
12
+ require_relative "validators/typed_value_validator"
13
+ require_relative "validators/br_currency_validator"
14
+ require_relative "validators/br_date_validator"
@@ -0,0 +1,6 @@
1
+ # frozen_string_literal: true
2
+
3
+ module RailsBr
4
+ # Versão da gem, seguindo o SemVer.
5
+ VERSION = "0.2.0"
6
+ end
data/lib/rails_br.rb ADDED
@@ -0,0 +1,22 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "rails_br/version"
4
+ require_relative "rails_br/error"
5
+
6
+ # Helpers brasileiros para Ruby e Rails.
7
+ #
8
+ # O núcleo é Ruby puro e não altera classes nativas (sem monkey patching).
9
+ # Cada módulo é carregado sob demanda: `RailsBr::CPF` só é lido do disco no
10
+ # primeiro uso, ou explicitamente com `require "rails_br/cpf"`.
11
+ module RailsBr
12
+ autoload :Document, "rails_br/document"
13
+ autoload :CPF, "rails_br/cpf"
14
+ autoload :CNPJ, "rails_br/cnpj"
15
+ autoload :Pix, "rails_br/pix"
16
+ autoload :Currency, "rails_br/currency"
17
+ autoload :DateFormat, "rails_br/date_format"
18
+ autoload :TextInput, "rails_br/text_input"
19
+ autoload :Locale, "rails_br/locale"
20
+ end
21
+
22
+ require_relative "rails_br/railtie" if defined?(Rails::Railtie)