113 lines
2.2 KiB
Go
113 lines
2.2 KiB
Go
package endpoints
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"fmt"
|
|
"github.com/geotrace/geo"
|
|
"github.com/gin-gonic/gin"
|
|
"os"
|
|
cdek "relynolli-server/CDEK/v2"
|
|
"relynolli-server/internal"
|
|
"relynolli-server/models"
|
|
"relynolli-server/status"
|
|
"time"
|
|
)
|
|
|
|
type handlers struct{}
|
|
|
|
type Handlers interface {
|
|
GetDeliveryPoints(c *gin.Context)
|
|
}
|
|
|
|
func GetHandlers() Handlers {
|
|
return &handlers{}
|
|
}
|
|
|
|
type CoordRequest struct {
|
|
Lat float64 `form:"lat"`
|
|
Lon float64 `form:"lon"`
|
|
}
|
|
|
|
func (h *handlers) GetDeliveryPoints(c *gin.Context) {
|
|
|
|
query := new(CoordRequest)
|
|
ctx := context.Background()
|
|
|
|
err := c.ShouldBindQuery(&query)
|
|
meta := models.Meta{
|
|
RequestStarted: time.Now().Unix(),
|
|
RequestFinished: 0,
|
|
}
|
|
resp := models.Response{
|
|
Status: status.STATUS_OK,
|
|
Info: "",
|
|
Data: nil,
|
|
Meta: &meta,
|
|
}
|
|
|
|
if err != nil {
|
|
meta.RequestFinished = time.Now().Unix()
|
|
resp.Info = err.Error()
|
|
c.JSON(400, resp)
|
|
return
|
|
}
|
|
|
|
client := cdek.NewClient(&cdek.Options{
|
|
Endpoint: cdek.EndpointProd,
|
|
Credentials: &cdek.Credentials{ClientID: os.Getenv("CDEK_ACCOUNT_ID"),
|
|
ClientSecret: os.Getenv("CDEK_API_KEY")},
|
|
})
|
|
|
|
if err != nil {
|
|
meta.RequestFinished = time.Now().Unix()
|
|
resp.Info = err.Error()
|
|
c.JSON(400, resp)
|
|
return
|
|
}
|
|
|
|
rdb := internal.InitRedis()
|
|
|
|
keys, _ := rdb.Keys(ctx, "CDEK_DP:*").Result()
|
|
|
|
preflightResult := []cdek.DeliveryPoint{}
|
|
|
|
if len(keys) == 0 {
|
|
r1, _ := client.DeliveryPoints(ctx, &cdek.DeliveryPointsRequest{})
|
|
pipe := rdb.Pipeline()
|
|
for _, d := range *r1 {
|
|
str, _ := json.Marshal(d)
|
|
pipe.Set(ctx, fmt.Sprintf("CDEK_DP:%s", d.Code), str, -1).Err()
|
|
preflightResult = append(preflightResult, d)
|
|
}
|
|
pipe.Exec(ctx)
|
|
} else {
|
|
for _, key := range keys {
|
|
item := new(cdek.DeliveryPoint)
|
|
data, _ := rdb.Get(ctx, key).Result()
|
|
json.Unmarshal([]byte(data), item)
|
|
preflightResult = append(preflightResult, *item)
|
|
}
|
|
}
|
|
|
|
pointOrigin := geo.Point{
|
|
query.Lon,
|
|
query.Lat,
|
|
}
|
|
resultedArray := []cdek.DeliveryPoint{}
|
|
|
|
for _, d := range preflightResult {
|
|
p1 := geo.Point{
|
|
d.Location.Longitude,
|
|
d.Location.Latitude,
|
|
}
|
|
|
|
if pointOrigin.Distance(p1) < 10000 {
|
|
resultedArray = append(resultedArray, d)
|
|
}
|
|
}
|
|
meta.RequestFinished = time.Now().Unix()
|
|
resp.Data = resultedArray
|
|
c.JSON(200, resp)
|
|
}
|