From 5b31c05c539671298c8c967a34d09f5573764e97 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Paulo=20Sima=CC=83o?= Date: Wed, 29 Sep 2021 22:04:43 -0300 Subject: [PATCH] cnpj on the way --- cnpj/lib.go | 65 ++++++++++++++++++++++++++++++++++++++++++++++++ cnpj/lib_test.go | 20 +++++++++++++++ 2 files changed, 85 insertions(+) create mode 100644 cnpj/lib.go create mode 100644 cnpj/lib_test.go diff --git a/cnpj/lib.go b/cnpj/lib.go new file mode 100644 index 0000000..0339b94 --- /dev/null +++ b/cnpj/lib.go @@ -0,0 +1,65 @@ +package cnpj + +import ( + "strconv" + "unicode" +) + +//Gets a string and formats is as CPF +func Format(s string) string { + raw := Strip(s) + ret := raw[0:2] + "." + raw[2:5] + "." + raw[5:8] + "/" + raw[8:12] + "-" + raw[12:14] + return ret + +} + +//Removes all non-digit symbols +func Strip(s string) string { + ret := "" + for _, v := range s { + if unicode.IsDigit(v) { + ret = ret + string(v) + } + } + return ret +} + +//Checks if verification digit are respected +func Check(s string) bool { + raw := Strip(s) + nums := make([]int, 0) + for _, v := range raw { + i, _ := strconv.Atoi(string(v)) + nums = append(nums, i) + } + + d1 := 0 + mul := 5 + for _, v := range nums[0 : len(nums)-2] { + d1 = d1 + (v * mul) + mul-- + if mul == 2 { + mul = 9 + } + } + mod1 := 11 - ((d1) % 11) + if mod1 > 10 { + mod1 = 0 + } + + d2 := 0 + mul = 6 + for _, v := range nums[0 : len(nums)-2] { + d2 = d2 + (v * mul) + mul-- + if mul == 2 { + mul = 9 + } + } + d2 = d2 + (mod1 * mul) + mod2 := 11 - ((d2) % 11) + if mod2 > 10 { + mod2 = 0 + } + return mod1 == nums[len(nums)-2] && mod2 == nums[len(nums)-1] +} diff --git a/cnpj/lib_test.go b/cnpj/lib_test.go new file mode 100644 index 0000000..41992b2 --- /dev/null +++ b/cnpj/lib_test.go @@ -0,0 +1,20 @@ +package cnpj + +import ( + "log" + "testing" +) + +func TestFormat(t *testing.T) { + log.Printf(Format("03794020685")) +} + +func TestCheck(t *testing.T) { + for _, v := range []string{ + "60.119.200/0001-90", + } { + ret := Check(v) + log.Printf("%s=>%v", v, ret) + } + +}