-
Notifications
You must be signed in to change notification settings - Fork 1
/
ups.go
79 lines (64 loc) · 1.62 KB
/
ups.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
package kargo
import (
"regexp"
"strconv"
)
// UPS is a carrier that have package struct
type UPS struct {
*Package
}
// NewUPS initialize a new UPS struct with package value
func NewUPS(p *Package) *UPS {
return &UPS{Package: p}
}
// GetCarrierName Implements the CarrierFactory interface method
// Retuns the name of carrier struct with package value
func (u *UPS) GetCarrierName() string {
return "UPS"
}
// Match Implements the CarrierFactory interface method
// Retuns the name of carrier struct with package value
func (u *UPS) Match() bool {
if m, _ := regexp.MatchString(`^1Z[A-Z0-9]{16}$`, u.Package.TrackingNumber); m == false {
return false
}
u.Package.Carrier = u.GetCarrierName()
return true
}
// GetPackage Implements the CarrierFactory interface method
// Returns the package that carrier holds
func (u *UPS) GetPackage() *Package {
return u.Package
}
// Validate Implements the CarrierFactory interface method
// Checks whether is a package belongs to that carrier
func (u *UPS) Validate() bool {
chars := u.Package.TrackingNumber[2 : len(u.Package.TrackingNumber)-1]
checkDigit, err := strconv.Atoi(u.Package.TrackingNumber[len(u.Package.TrackingNumber)-1:])
if err != nil {
return false
}
var odd, even int = 0, 0
for i, char := range chars {
t := (string(char))
num, err := strconv.Atoi(t)
if err != nil {
num = int(char-3) % 10
}
if i%2 == 0 {
even += num
continue
}
odd += num
}
check := ((odd * 2) + even) % 10
if check != 0 {
check = 10 - check
}
if check != checkDigit {
return false
}
u.Package.Carrier = u.GetCarrierName()
u.Package.IsValid = true
return true
}