diff --git a/go.mod b/go.mod new file mode 100644 index 000000000..1beab2ae2 --- /dev/null +++ b/go.mod @@ -0,0 +1,33 @@ +module challenge2016 + +go 1.23.5 + +require ( + github.com/bytedance/sonic v1.12.9 // indirect + github.com/bytedance/sonic/loader v0.2.3 // indirect + github.com/cloudwego/base64x v0.1.5 // indirect + github.com/cloudwego/iasm v0.2.0 // indirect + github.com/gabriel-vasile/mimetype v1.4.8 // indirect + github.com/gin-contrib/sse v1.0.0 // indirect + github.com/gin-gonic/gin v1.10.0 // indirect + github.com/go-playground/locales v0.14.1 // indirect + github.com/go-playground/universal-translator v0.18.1 // indirect + github.com/go-playground/validator/v10 v10.25.0 // indirect + github.com/goccy/go-json v0.10.5 // indirect + github.com/json-iterator/go v1.1.12 // indirect + github.com/klauspost/cpuid/v2 v2.2.9 // indirect + github.com/leodido/go-urn v1.4.0 // indirect + github.com/mattn/go-isatty v0.0.20 // indirect + github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect + github.com/modern-go/reflect2 v1.0.2 // indirect + github.com/pelletier/go-toml/v2 v2.2.3 // indirect + github.com/twitchyliquid64/golang-asm v0.15.1 // indirect + github.com/ugorji/go/codec v1.2.12 // indirect + golang.org/x/arch v0.14.0 // indirect + golang.org/x/crypto v0.34.0 // indirect + golang.org/x/net v0.35.0 // indirect + golang.org/x/sys v0.30.0 // indirect + golang.org/x/text v0.22.0 // indirect + google.golang.org/protobuf v1.36.5 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) diff --git a/go.sum b/go.sum new file mode 100644 index 000000000..e0ec2c056 --- /dev/null +++ b/go.sum @@ -0,0 +1,78 @@ +github.com/bytedance/sonic v1.12.9 h1:Od1BvK55NnewtGaJsTDeAOSnLVO2BTSLOe0+ooKokmQ= +github.com/bytedance/sonic v1.12.9/go.mod h1:uVvFidNmlt9+wa31S1urfwwthTWteBgG0hWuoKAXTx8= +github.com/bytedance/sonic/loader v0.1.1/go.mod h1:ncP89zfokxS5LZrJxl5z0UJcsk4M4yY2JpfqGeCtNLU= +github.com/bytedance/sonic/loader v0.2.3 h1:yctD0Q3v2NOGfSWPLPvG2ggA2kV6TS6s4wioyEqssH0= +github.com/bytedance/sonic/loader v0.2.3/go.mod h1:N8A3vUdtUebEY2/VQC0MyhYeKUFosQU6FxH2JmUe6VI= +github.com/cloudwego/base64x v0.1.5 h1:XPciSp1xaq2VCSt6lF0phncD4koWyULpl5bUxbfCyP4= +github.com/cloudwego/base64x v0.1.5/go.mod h1:0zlkT4Wn5C6NdauXdJRhSKRlJvmclQ1hhJgA0rcu/8w= +github.com/cloudwego/iasm v0.2.0 h1:1KNIy1I1H9hNNFEEH3DVnI4UujN+1zjpuk6gwHLTssg= +github.com/cloudwego/iasm v0.2.0/go.mod h1:8rXZaNYT2n95jn+zTI1sDr+IgcD2GVs0nlbbQPiEFhY= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/gabriel-vasile/mimetype v1.4.8 h1:FfZ3gj38NjllZIeJAmMhr+qKL8Wu+nOoI3GqacKw1NM= +github.com/gabriel-vasile/mimetype v1.4.8/go.mod h1:ByKUIKGjh1ODkGM1asKUbQZOLGrPjydw3hYPU2YU9t8= +github.com/gin-contrib/sse v1.0.0 h1:y3bT1mUWUxDpW4JLQg/HnTqV4rozuW4tC9eFKTxYI9E= +github.com/gin-contrib/sse v1.0.0/go.mod h1:zNuFdwarAygJBht0NTKiSi3jRf6RbqeILZ9Sp6Slhe0= +github.com/gin-gonic/gin v1.10.0 h1:nTuyha1TYqgedzytsKYqna+DfLos46nTv2ygFy86HFU= +github.com/gin-gonic/gin v1.10.0/go.mod h1:4PMNQiOhvDRa013RKVbsiNwoyezlm2rm0uX/T7kzp5Y= +github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA= +github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY= +github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY= +github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY= +github.com/go-playground/validator/v10 v10.25.0 h1:5Dh7cjvzR7BRZadnsVOzPhWsrwUr0nmsZJxEAnFLNO8= +github.com/go-playground/validator/v10 v10.25.0/go.mod h1:GGzBIJMuE98Ic/kJsBXbz1x/7cByt++cQ+YOuDM5wus= +github.com/goccy/go-json v0.10.5 h1:Fq85nIqj+gXn/S5ahsiTlK3TmC85qgirsdTP/+DeaC4= +github.com/goccy/go-json v0.10.5/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M= +github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= +github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= +github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= +github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg= +github.com/klauspost/cpuid/v2 v2.2.9 h1:66ze0taIn2H33fBvCkXuv9BmCwDfafmiIVpKV9kKGuY= +github.com/klauspost/cpuid/v2 v2.2.9/go.mod h1:rqkxqrZ1EhYM9G+hXH7YdowN5R5RGN6NK4QwQ3WMXF8= +github.com/knz/go-libedit v1.10.1/go.mod h1:MZTVkCWyz0oBc7JOWP3wNAzd002ZbM/5hgShxwh4x8M= +github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ= +github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI= +github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= +github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= +github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= +github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M= +github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= +github.com/pelletier/go-toml/v2 v2.2.3 h1:YmeHyLY8mFWbdkNWwpr+qIL2bEqT0o95WSdkNHvL12M= +github.com/pelletier/go-toml/v2 v2.2.3/go.mod h1:MfCQTFTvCcUyyvvwm1+G6H/jORL20Xlb6rzQu9GuUkc= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= +github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= +github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA= +github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= +github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= +github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= +github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= +github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= +github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI= +github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08= +github.com/ugorji/go/codec v1.2.12 h1:9LC83zGrHhuUA9l16C9AHXAqEV/2wBQ4nkvumAE65EE= +github.com/ugorji/go/codec v1.2.12/go.mod h1:UNopzCgEMSXjBc6AOMqYvWC1ktqTAfzJZUZgYf6w6lg= +golang.org/x/arch v0.14.0 h1:z9JUEZWr8x4rR0OU6c4/4t6E6jOZ8/QBS2bBYBm4tx4= +golang.org/x/arch v0.14.0/go.mod h1:FEVrYAQjsQXMVJ1nsMoVVXPZg6p2JE2mx8psSWTDQys= +golang.org/x/crypto v0.34.0 h1:+/C6tk6rf/+t5DhUketUbD1aNGqiSX3j15Z6xuIDlBA= +golang.org/x/crypto v0.34.0/go.mod h1:dy7dXNW32cAb/6/PRuTNsix8T+vJAqvuIy5Bli/x0YQ= +golang.org/x/net v0.35.0 h1:T5GQRQb2y08kTAByq9L4/bz8cipCdA8FbRTXewonqY8= +golang.org/x/net v0.35.0/go.mod h1:EglIi67kWsHKlRzzVMUD93VMSWGFOMSZgxFjparz1Qk= +golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.30.0 h1:QjkSwP/36a20jFYWkSue1YwXzLmsV5Gfq7Eiy72C1uc= +golang.org/x/sys v0.30.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/text v0.22.0 h1:bofq7m3/HAFvbF51jz3Q9wLg3jkvSPuiZu/pD1XwgtM= +golang.org/x/text v0.22.0/go.mod h1:YRoo4H8PVmsu+E3Ou7cqLVH8oXWIHVoX0jqUWALQhfY= +google.golang.org/protobuf v1.36.5 h1:tPhr+woSbjfYvY6/GPufUoYizxw1cF/yFoxJ2fmpwlM= +google.golang.org/protobuf v1.36.5/go.mod h1:9fA7Ob0pmnwhb644+1+CVWFRbNajQ6iRojtC/QF5bRE= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +nullprogram.com/x/optparse v1.0.0/go.mod h1:KdyPE+Igbe0jQUrVfMqDMeJQIJZEuyV7pjYmp6pbG50= +rsc.io/pdf v0.1.1/go.mod h1:n8OzWcQ6Sp37PL01nO98y4iUCRdTGarVfzxY20ICaU4= diff --git a/main.go b/main.go new file mode 100644 index 000000000..932bbd8d4 --- /dev/null +++ b/main.go @@ -0,0 +1,32 @@ +package main + +import ( + "challenge2016/routes" + "challenge2016/services" + "fmt" + + "github.com/gin-gonic/gin" +) + +func main() { + var err error + _, err = services.LoadCities("cities.csv") + if err != nil { + fmt.Println("Error loading cities:", err) + return + } + fmt.Println("Cities loaded successfully.") + + router := gin.Default() + + router.SetTrustedProxies([]string{"127.0.0.1"}) + + router.GET("/check", routes.CheckDistribution) + router.POST("/distributor", routes.AddDistributor) + router.POST("/permission", routes.AddPermission) + + // please refer to the documentation : + // this is the api documentation link for better understanding of the API routes: + // "https://documenter.getpostman.com/view/25819639/2sAYdcrCTq" this contains the description of the endpoints. + router.Run(":8080") +} diff --git a/models/distributor.go b/models/distributor.go new file mode 100644 index 000000000..50cfde987 --- /dev/null +++ b/models/distributor.go @@ -0,0 +1,88 @@ +package models + +import ( + "fmt" + "strings" +) + +type Distributor struct { + Name string + Parent *Distributor + Includes map[string]bool + Excludes map[string]bool +} + +// creates a new distributor. +func NewDistributor(name string, parent *Distributor) *Distributor { + return &Distributor{ + Name: name, + Parent: parent, + Includes: make(map[string]bool), + Excludes: make(map[string]bool), + } +} + +// AddPermission adds an include or exclude permission. +func (d *Distributor) AddPermission(permissionType, region string) error { + region = strings.ToUpper(region) + if permissionType == "INCLUDE" { + if d.Parent != nil && !d.Parent.Includes[region] { + return fmt.Errorf("parent distributor does not have rights for %s", region) + } + d.Includes[region] = true + } else if permissionType == "EXCLUDE" { + d.Excludes[region] = true + } else { + return fmt.Errorf("invalid permission type: %s", permissionType) + } + return nil +} + +func (d *Distributor) CanDistribute(city, state, country string) bool { + city = strings.ToUpper(strings.TrimSpace(city)) + state = strings.ToUpper(strings.TrimSpace(state)) + country = strings.ToUpper(strings.TrimSpace(country)) + + loc := fmt.Sprintf("%s-%s-%s", city, state, country) + stateLoc := fmt.Sprintf("%s-%s", state, country) + countryLoc := country + + // If explicitly excluded at any level, return false + if d.isExcluded(loc, stateLoc, countryLoc) { + return false + } + + // If included at any level, return true + if d.isIncluded(loc, stateLoc, countryLoc) { + return true + } + + // If the parent distributor has permissions, check those as well + if d.Parent != nil { + return d.Parent.CanDistribute(city, state, country) + } + + return false +} + +// Helper method to check exclusion +func (d *Distributor) isExcluded(loc, stateLoc, countryLoc string) bool { + if d.Excludes[loc] || d.Excludes[stateLoc] || d.Excludes[countryLoc] { + return true + } + if d.Parent != nil { + return d.Parent.isExcluded(loc, stateLoc, countryLoc) + } + return false +} + +// Helper method to check inclusion +func (d *Distributor) isIncluded(loc, stateLoc, countryLoc string) bool { + if d.Includes[loc] || d.Includes[stateLoc] || d.Includes[countryLoc] { + return true + } + if d.Parent != nil { + return d.Parent.isIncluded(loc, stateLoc, countryLoc) + } + return false +} diff --git a/models/geo.go b/models/geo.go new file mode 100644 index 000000000..89db113b4 --- /dev/null +++ b/models/geo.go @@ -0,0 +1,16 @@ +package models + +type GeoNode struct { + Name string + Children map[string]*GeoNode +} + +// retrieves an existing child node or creates a new one. +func GetOrCreateChild(parent *GeoNode, name string) *GeoNode { + if child, exists := parent.Children[name]; exists { + return child + } + child := &GeoNode{Name: name, Children: make(map[string]*GeoNode)} + parent.Children[name] = child + return child +} diff --git a/routes/api.go b/routes/api.go new file mode 100644 index 000000000..c9e96f6d0 --- /dev/null +++ b/routes/api.go @@ -0,0 +1,68 @@ +package routes + +import ( + "challenge2016/services" + "net/http" + + "github.com/gin-gonic/gin" +) + +// CheckDistribution API Handler +func CheckDistribution(c *gin.Context) { + distributorName := c.Query("distributor") + city := c.Query("city") + state := c.Query("state") + country := c.Query("country") + + distributor, exists := services.Distributors[distributorName] + if !exists { + c.JSON(http.StatusBadRequest, gin.H{"error": "Distributor not found"}) + return + } + + result := distributor.CanDistribute(city, state, country) + c.JSON(http.StatusOK, gin.H{"distributor": distributorName, "canDistribute": result}) +} + +// AddDistributor API Handler +func AddDistributor(c *gin.Context) { + name := c.Query("name") + parent := c.Query("parent") + + if name == "" { + c.JSON(http.StatusBadRequest, gin.H{"error": "Distributor name is required"}) + return + } + + distributor, err := services.CreateDistributor(name, parent) + if err != nil { + c.JSON(http.StatusConflict, gin.H{"error": err.Error()}) // 409 Conflict for duplicate distributor + return + } + + c.JSON(http.StatusCreated, gin.H{ + "message": "Distributor created successfully", + "distributor": distributor.Name, + }) +} + +// AddPermission API Handler +func AddPermission(c *gin.Context) { + distributorName := c.Query("distributor") + permissionType := c.Query("type") + region := c.Query("region") + + distributor, exists := services.Distributors[distributorName] + if !exists { + c.JSON(http.StatusBadRequest, gin.H{"error": "Distributor not found"}) + return + } + + err := distributor.AddPermission(permissionType, region) + if err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) + return + } + + c.JSON(http.StatusOK, gin.H{"message": "Permission added successfully"}) +} diff --git a/services/city_loader.go b/services/city_loader.go new file mode 100644 index 000000000..9730a336c --- /dev/null +++ b/services/city_loader.go @@ -0,0 +1,31 @@ +package services + +import ( + "challenge2016/models" + "encoding/csv" + "os" +) + +// LoadCities parses the cities.csv file. +func LoadCities(filename string) (*models.GeoNode, error) { + file, err := os.Open(filename) + if err != nil { + return nil, err + } + defer file.Close() + + reader := csv.NewReader(file) + records, err := reader.ReadAll() + if err != nil { + return nil, err + } + + root := &models.GeoNode{Name: "World", Children: make(map[string]*models.GeoNode)} + for _, record := range records[1:] { + city, state, country := record[3], record[4], record[5] + countryNode := models.GetOrCreateChild(root, country) + stateNode := models.GetOrCreateChild(countryNode, state) + models.GetOrCreateChild(stateNode, city) + } + return root, nil +} diff --git a/services/distribution_service.go b/services/distribution_service.go new file mode 100644 index 000000000..f2f2fb81f --- /dev/null +++ b/services/distribution_service.go @@ -0,0 +1,25 @@ +package services + +import ( + "challenge2016/models" + "fmt" +) + +var Distributors = make(map[string]*models.Distributor) + +// CreateDistributor creates a new distributor if it doesn't already exist. +func CreateDistributor(name, parentName string) (*models.Distributor, error) { + // Check if distributor already exists + if _, exists := Distributors[name]; exists { + return nil, fmt.Errorf("Distributor '%s' already exists", name) + } + + var parent *models.Distributor + if parentName != "" { + parent = Distributors[parentName] + } + + d := models.NewDistributor(name, parent) + Distributors[name] = d + return d, nil +}