-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathcnpj.go
125 lines (104 loc) · 2.55 KB
/
cnpj.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
package brazil
import (
"math/rand"
"regexp"
"strconv"
"time"
)
// CNPJ struct
type cnpj struct {
number cnpjNumber
valid bool
}
func (c cnpj) Number(mask bool) string {
if c.valid && mask {
return string(c.number[:2]) +
"." +
string(c.number[2:5]) +
"." +
string(c.number[5:8]) +
"/" +
string(c.number[8:12]) +
"-" +
string(c.number[12:])
}
return string(c.number)
}
func ParseCNPJ(number string) (cnpj, error) {
number = regexp.MustCompile(`[^0-9]`).ReplaceAllString(number, "")
if len(number) != 14 {
return cnpj{}, ErrIncorrectLenghtCNPJNumber
}
cnpjNumber := cnpjNumber(number)
if !cnpjNumber.hasValidFirstDigit() {
return cnpj{}, ErrInvalidCNPJFirstDigit
}
if !cnpjNumber.hasValidSecondDigit() {
return cnpj{}, ErrInvalidCNPJSecondDigit
}
return cnpj{
number: cnpjNumber,
valid: true,
}, nil
}
func RandomCNPJNumber(mask bool) string {
var multipliers = []int{6, 5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2}
source := rand.NewSource(time.Now().UnixNano())
r := rand.New(source)
cnpjNumber := int(r.Int63n(899999999999) + 100000000000)
cnpjString := strconv.Itoa(cnpjNumber)
// Calculate first digit
sum := 0
for i := 0; i < 12; i++ {
number, _ := strconv.Atoi(string(cnpjString[i]))
sum += number * multipliers[i+1]
}
firstDigit := 0
if sum%11 >= 2 {
firstDigit = 11 - sum%11
}
// Calculate second digit
sum = 0
for i := 0; i < 12; i++ {
number, _ := strconv.Atoi(string(cnpjString[i]))
sum += number * multipliers[i]
}
sum += firstDigit * multipliers[12]
secondDigit := 0
if sum%11 >= 2 {
secondDigit = 11 - sum%11
}
if mask {
return cnpjString[:2] + "." + cnpjString[2:5] + "." + cnpjString[5:8] + "/" + cnpjString[8:12] + "-" + strconv.Itoa(firstDigit) + strconv.Itoa(secondDigit)
}
return cnpjString + strconv.Itoa(firstDigit) + strconv.Itoa(secondDigit)
}
type cnpjNumber string
func (c cnpjNumber) hasValidFirstDigit() bool {
var (
multipliers = []int{5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2}
sum int
)
for i := 0; i < 12; i++ {
cnpjDigit, _ := strconv.Atoi(string(c[i]))
sum += cnpjDigit * multipliers[i]
}
if sum%11 < 2 {
return string(c[12]) == strconv.Itoa(0)
}
return string(c[12]) == strconv.Itoa(11-sum%11)
}
func (c cnpjNumber) hasValidSecondDigit() bool {
var (
multipliers = []int{6, 5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2}
sum int
)
for i := 0; i < 13; i++ {
cnpjDigit, _ := strconv.Atoi(string(c[i]))
sum += cnpjDigit * multipliers[i]
}
if sum%11 < 2 {
return string(c[13]) == strconv.Itoa(0)
}
return string(c[13]) == strconv.Itoa(11-sum%11)
}