package services import ( "encoding/json" "fmt" "relynolli-server/internal" "relynolli-server/models" "strings" ) 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 GetCatalogItemsCount() int { stmt := "select count(id) from api_catalog where available_quantity > 0 and is_active = 1;" var count int db := internal.InitDatabase() rows := db.Query(stmt) rows.Next() rows.Scan(&count) return count } func GetCatalogItems(limit int, offset int) []models.CatalogStructWeb { stmt := fmt.Sprintf("select * from api_catalog where available_quantity > 0 and is_active = 1 order by code 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, limit int, offset int) []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 } if key == "limit" { continue } if key == "page" { 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 ")) print("\n" + stmt + "\n") return retrieveCatalogItems(stmt + fmt.Sprintf("and is_active = 1 and available_quantity > 0;")) }