relynolli-server/services/catalog.go

93 lines
2.5 KiB
Go
Raw Normal View History

2024-03-15 21:27:45 +03:00
package services
import (
"encoding/json"
"fmt"
"relynolli-server/internal"
"relynolli-server/models"
"strings"
2024-03-15 21:27:45 +03:00
)
func retrieveItems(stmt string, structure interface{}) {
db := internal.InitDatabase()
db.FetchRows(stmt, structure)
}
func retrieveCatalogItems(stmt string) []models.CatalogStructWeb {
var catalogList []models.CatalogStruct
var returnedList []models.CatalogStructWeb
retrieveItems(stmt, &catalogList)
for _, item := range catalogList {
itemProd := models.CatalogStructWeb{
Id: item.Id,
Code: item.Code,
Name: item.Name,
IsActive: item.IsActive,
DetailText: item.DetailText,
AvailableQuantity: item.AvailableQuantity,
}
json.Unmarshal(item.Price, &itemProd.Price)
json.Unmarshal(item.Properties, &itemProd.Properties)
returnedList = append(returnedList, itemProd)
}
return returnedList
}
func GetCatalogItems(limit int, offset int) []models.CatalogStructWeb {
stmt := fmt.Sprintf("select * from api_catalog order by id DESC limit %d offset %d;", limit, offset)
return retrieveCatalogItems(stmt)
}
func GetCatalogItem(code string) (models.CatalogStructWeb, error) {
stmt := fmt.Sprintf("select * from api_catalog where code = '%s';", code)
items := retrieveCatalogItems(stmt)
if len(items) == 0 {
return models.CatalogStructWeb{}, fmt.Errorf("Not founded catalog item with given code")
}
return retrieveCatalogItems(stmt)[0], nil
}
func GetCatalogItemById(id int) (models.CatalogStructWeb, error) {
stmt := fmt.Sprintf("select * from api_catalog where id = %d;", id)
items := retrieveCatalogItems(stmt)
if len(items) == 0 {
return models.CatalogStructWeb{}, fmt.Errorf("Not founded catalog item with given code")
}
return retrieveCatalogItems(stmt)[0], nil
}
func FilterCatalogItems(filters map[string][]string) []models.CatalogStructWeb {
// Generate stmt
propertiesSubStmt := "properties->>'$.%s' = '%s'"
stmt := "select * from api_catalog where %s"
sample := "(%s)"
filterList := [][]string{}
for key, filter := range filters {
if key == "isFilter" {
continue
}
subFilterArr := []string{}
values := strings.Split(filter[0], ",")
for _, val := range values {
subFilterArr = append(subFilterArr, fmt.Sprintf(propertiesSubStmt, key, val))
}
filterList = append(filterList, subFilterArr)
}
samples := []string{}
for _, arr := range filterList {
samples = append(samples, fmt.Sprintf(sample, strings.Join(arr, " or ")))
}
stmt = fmt.Sprintf(stmt, strings.Join(samples, " and "))
println(stmt)
return retrieveCatalogItems(stmt)
}