GenFakeUPC考虑校验规则

This commit is contained in:
gazebo
2019-12-13 18:39:54 +08:00
parent f7418d2581
commit b428c0236e
2 changed files with 31 additions and 4 deletions

View File

@@ -409,8 +409,29 @@ func SplitSkuName(skuName string) (prefix, name, comment, specUnit, unit string,
return prefix, name, comment, specUnit, unit, specQuality return prefix, name, comment, specUnit, unit, specQuality
} }
// https://my.oschina.net/hyller/blog/700414
func CalUpcCheckSum(upc12 int64) (checkSum int) {
var sum [2]int
for i := 0; i < 12; i++ {
base := int64(math.Pow10(i))
sum[i%2] += int((upc12 / base) % 10)
}
sum[0] *= 3
return (10 - (sum[0]+sum[1])%10)
}
func IsUpcValid(upc string) bool {
if len(upc) != 13 {
return false
}
upcInt := utils.Str2Int64WithDefault(upc, 0)
checkSum := CalUpcCheckSum(upcInt / 10)
return int(utils.Str2Int64(upc[12:])) == checkSum
}
func GenFakeUPC(skuID int) string { func GenFakeUPC(skuID int) string {
return fmt.Sprintf("%013d", int64(skuID)+6666000000000) id := int64(skuID) + 666600000000
return fmt.Sprintf("%012d%d", id, CalUpcCheckSum(id))
} }
func MakeValidationMapFromSlice(validValues []string, flag int) map[string]int { func MakeValidationMapFromSlice(validValues []string, flag int) map[string]int {

View File

@@ -288,11 +288,11 @@ func TestGetOneEmailFromStr(t *testing.T) {
func TestGenFakeUPC(t *testing.T) { func TestGenFakeUPC(t *testing.T) {
for _, v := range [][]string{ for _, v := range [][]string{
[]string{ []string{
"6666000000123", "6666000298034",
"123", "29803",
}, },
[]string{ []string{
"6666007654321", "6666076543212",
"7654321", "7654321",
}, },
} { } {
@@ -300,4 +300,10 @@ func TestGenFakeUPC(t *testing.T) {
t.Errorf("%s failed, result:%s, expect:%s", v[1], str, v[0]) t.Errorf("%s failed, result:%s, expect:%s", v[1], str, v[0])
} }
} }
if !IsUpcValid("6666076543212") {
t.Fatal("wrong1")
}
if IsUpcValid("6666076543210") {
t.Fatal("wrong2")
}
} }