Module: BrazilianUtils::CNPJUtils

Defined in:
lib/brazilian-utils/cnpj-utils.rb

Constant Summary collapse

V2_CHARSET =

Characters usable in the alphanumeric CNPJ's base (positions 0-11).

'0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'.freeze
V2_WEIGHTS_DV1 =
[5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2].freeze
V2_WEIGHTS_DV2 =
[6, 5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2].freeze

Class Method Summary collapse

Class Method Details

.display(cnpj) ⇒ String?

Note:

This method should not be used in new code and is only provided for backward compatibility. Use format_cnpj instead.

Formats a CNPJ string for visual display (legacy method).

Will format an adequately formatted numbers-only CNPJ string, adding in standard formatting visual aid symbols for display.

Examples:

display("12345678901234")   #=> "12.345.678/9012-34"
display("98765432100100")   #=> "98.765.432/1001-00"

Parameters:

  • cnpj (String) —

    The CNPJ string to be formatted for display.

Returns:

  • (String, nil) —

    The formatted CNPJ with visual aid symbols if it's valid, nil if it's not valid.



54
55
56
57
58
59
60
61
62
63
64
# File 'lib/brazilian-utils/cnpj-utils.rb', line 54

def self.display(cnpj)
  return nil unless cnpj.to_s.match?(/^\d{14}$/)
  return nil if cnpj.chars.uniq.length == 1

  format('%s.%s.%s/%s-%s',
         cnpj[0..1],
         cnpj[2..4],
         cnpj[5..7],
         cnpj[8..11],
         cnpj[12..13])
end

.format_cnpj(cnpj) ⇒ String?

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.

Examples:

format_cnpj("03560714000142")   #=> "03.560.714/0001-42"
format_cnpj("98765432100100")   #=> nil

Parameters:

  • cnpj (String) —

    The CNPJ string to be formatted for display.

Returns:

  • (String, nil) —

    The formatted CNPJ with visual aid symbols if it's valid, nil if it's not valid.



78
79
80
81
82
83
84
85
86
87
# File 'lib/brazilian-utils/cnpj-utils.rb', line 78

def self.format_cnpj(cnpj)
  return nil unless valid?(cnpj)

  format('%s.%s.%s/%s-%s',
         cnpj[0..1],
         cnpj[2..4],
         cnpj[5..7],
         cnpj[8..11],
         cnpj[12..13])
end

.generate(branch: nil, version: 1) ⇒ String

Generates a random valid CNPJ digit string.

An optional branch number parameter can be given; it defaults to 1 (v1) or a random branch 1-9999 (v2, when not given).

Examples:

generate()               #=> "30180536000105"
generate(branch: 1234)   #=> "01745284123455"
generate(version: 2)     #=> "12ABC34501DE35"

Parameters:

  • branch (Integer, nil) (defaults to: nil) —

    An optional branch number to be included in the CNPJ.

  • version (Integer) (defaults to: 1) —

    1 (default) generates the classic all-numeric CNPJ; 2 generates the alphanumeric CNPJ.

Returns:

  • (String) —

    A randomly generated valid CNPJ string.



155
156
157
158
159
160
161
162
163
164
# File 'lib/brazilian-utils/cnpj-utils.rb', line 155

def self.generate(branch: nil, version: 1)
  return generate_v2(branch) if version.to_i == 2

  branch_num = branch.nil? ? 1 : branch % 10_000
  branch_num = 1 if branch_num.zero?
  branch_str = branch_num.to_s.rjust(4, '0')
  base = format('%08d', rand(100_000_000)) + branch_str

  base + checksum(base)
end

.parse(value, options = {}) ⇒ String

Removes CNPJ formatting and returns the normalized value, capped to 14 characters.

Examples:

parse("46.843.485/0001-86")  #=> "46843485000186"

Parameters:

  • value (String, Integer) —

    A CNPJ, with or without formatting.

  • options (Hash) (defaults to: {}) —

    :version 1 (default) keeps digits only; 2 keeps letters and digits, upper-cased (the alphanumeric CNPJ format).

Returns:

  • (String) —

    The parsed value.



301
302
303
304
305
306
307
308
309
310
311
312
313
# File 'lib/brazilian-utils/cnpj-utils.rb', line 301

def self.parse(value, options = {})
  return '' unless value.is_a?(String) || value.is_a?(Integer)

  version = (options[:version] || options['version'] || 1).to_i

  cleaned = if version == 2
              value.to_s.gsub(/[^a-zA-Z0-9]/, '').upcase
            else
              value.to_s.gsub(/\D/, '')
            end

  cleaned[0, 14]
end

.remove_symbols(dirty) ⇒ String

Removes specific symbols from a CNPJ string.

This function is an alias for the sieve function, offering a more descriptive name.

Examples:

remove_symbols("12.345/6789-01")   #=> "12345678901"
remove_symbols("98/76.543-2101")   #=> "98765432101"

Parameters:

  • dirty (String) —

    The dirty string containing symbols to be removed.

Returns:

  • (String) —

    A new string with the specified symbols removed.



35
36
37
# File 'lib/brazilian-utils/cnpj-utils.rb', line 35

def self.remove_symbols(dirty)
  sieve(dirty)
end

.sieve(dirty) ⇒ String

Note:

This method should not be used in new code and is only provided for backward compatibility. Use remove_symbols instead.

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.

Examples:

sieve("12.345/6789-01")     #=> "12345678901"
sieve("98/76.543-2101")     #=> "98765432101"

Parameters:

  • dirty (String) —

    The CNPJ string containing symbols to be removed.

Returns:

  • (String) —

    A new string with the specified symbols removed.



20
21
22
# File 'lib/brazilian-utils/cnpj-utils.rb', line 20

def self.sieve(dirty)
  dirty.to_s.delete('./-')
end

.valid?(cnpj, version: 1) ⇒ Boolean

Returns whether or not the verifying checksum digits of the given CNPJ match its base number.

This function does not verify the existence of the CNPJ; it only validates the format of the string.

Examples:

valid?("03560714000142")           #=> true
valid?("00111222000133")           #=> false
valid?("12ABC34501DE35", version: 2)

Parameters:

  • cnpj (String) —

    The CNPJ to be validated, a 14-digit string (v1, numeric) or a 14-character alphanumeric string (v2, when version: 2 is given).

  • version (Integer) (defaults to: 1) —

    1 (default) validates the classic all-numeric CNPJ; 2 validates the alphanumeric CNPJ introduced by IN RFB 2.119.

Returns:

  • (Boolean) —

    true if the checksum digits match the base number, false otherwise.



134
135
136
137
138
# File 'lib/brazilian-utils/cnpj-utils.rb', line 134

def self.valid?(cnpj, version: 1)
  return false unless cnpj.is_a?(String)

  version.to_i == 2 ? valid_v2?(cnpj) : validate(cnpj)
end

.validate(cnpj) ⇒ Boolean

Note:

This method should not be used in new code and is only provided for backward compatibility. Use valid? instead.

Validates a CNPJ by comparing its verifying checksum digits to its base number.

This function checks the validity of a CNPJ by comparing its verifying checksum digits to its base number. The input should be a string of digits with the appropriate length.

Examples:

validate("03560714000142")   #=> true
validate("00111222000133")   #=> false

Parameters:

  • cnpj (String) —

    The CNPJ to be validated.

Returns:

  • (Boolean) —

    true if the checksum digits match the base number, false otherwise.



107
108
109
110
111
112
113
114
# File 'lib/brazilian-utils/cnpj-utils.rb', line 107

def self.validate(cnpj)
  return false unless cnpj.to_s.match?(/^\d{14}$/)
  return false if cnpj.chars.uniq.length == 1

  (0..1).all? do |i|
    hashdigit(cnpj, i + 13) == cnpj[12 + i].to_i
  end
end