@@ -0,0 +1,97 @@
|
||||
package storage_file
|
||||
|
||||
import (
|
||||
"cake_crm/internal/modules/storage"
|
||||
crm "cake_crm/proto"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"os"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrProductNotFound = errors.New("product not found")
|
||||
)
|
||||
|
||||
type storageFile struct{}
|
||||
|
||||
func NewStorageFile() storage.IStorage {
|
||||
return &storageFile{}
|
||||
}
|
||||
|
||||
func (s *storageFile) GetCatalog(_ context.Context) ([]*crm.Category, error) {
|
||||
data, err := os.ReadFile("resources/catalog.json")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var res []*crm.Category
|
||||
if err := json.Unmarshal(data, &res); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return res, nil
|
||||
}
|
||||
|
||||
func (s *storageFile) GetPositions(_ context.Context, id int64) ([]*crm.Product, error) {
|
||||
data, err := os.ReadFile("resources/products.json")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var products []*crm.Product
|
||||
if err := json.Unmarshal(data, &products); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
res := make([]*crm.Product, 0, len(products))
|
||||
for _, product := range products {
|
||||
if id == 0 || product.Category == id {
|
||||
res = append(res, product)
|
||||
}
|
||||
}
|
||||
return res, nil
|
||||
}
|
||||
|
||||
func (s *storageFile) GetProduct(_ context.Context, id int64) (*crm.Product, error) {
|
||||
data, err := os.ReadFile("resources/products.json")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var products []*crm.Product
|
||||
if err := json.Unmarshal(data, &products); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, product := range products {
|
||||
if product.Id == id {
|
||||
return product, nil
|
||||
}
|
||||
}
|
||||
return nil, ErrProductNotFound
|
||||
}
|
||||
|
||||
func (s *storageFile) GetBreadcrumbs(_ context.Context, id int64) ([]*crm.Category, error) {
|
||||
data, err := os.ReadFile("resources/catalog.json")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var categories []*crm.Category
|
||||
if err := json.Unmarshal(data, &categories); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return getBreadcrumbs(categories, id), nil
|
||||
}
|
||||
|
||||
func getBreadcrumbs(categories []*crm.Category, id int64) []*crm.Category {
|
||||
for _, category := range categories {
|
||||
if category.Id == id {
|
||||
category.Children = nil
|
||||
return []*crm.Category{category}
|
||||
}
|
||||
breadcrumbs := getBreadcrumbs(category.Children, id)
|
||||
if len(breadcrumbs) != 0 {
|
||||
res := make([]*crm.Category, 0, len(breadcrumbs)+1)
|
||||
category.Children = nil
|
||||
res = append(res, category)
|
||||
res = append(res, breadcrumbs...)
|
||||
return res
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
Reference in New Issue
Block a user