cake_crm/internal/app/server.go

107 lines
2.8 KiB
Go

package app
import (
"cake_crm/internal/modules/messenger"
"cake_crm/internal/modules/storage"
"cake_crm/internal/services/cart"
"cake_crm/internal/services/order"
proto "cake_crm/proto"
"context"
"fmt"
"google.golang.org/genproto/googleapis/api/httpbody"
"os"
)
type Server struct {
proto.UnsafeCRMServer
storage storage.IStorage
messenger messenger.IMessenger
cartService *cart.Service
orderService *order.Service
}
func NewServer(
storage storage.IStorage,
messenger messenger.IMessenger,
cartService *cart.Service,
orderService *order.Service,
) proto.CRMServer {
return &Server{
storage: storage,
messenger: messenger,
cartService: cartService,
orderService: orderService,
}
}
func (s *Server) GetCatalog(ctx context.Context, _ *proto.GetCatalogReq) (*proto.CatalogRsp, error) {
categories, err := s.storage.GetCatalog(ctx)
if err != nil {
return nil, err
}
return &proto.CatalogRsp{Categories: categories}, nil
}
func (s *Server) GetPositions(ctx context.Context, req *proto.GetPositionsReq) (*proto.PositionsRsp, error) {
products, err := s.storage.GetPositions(ctx, req.Id)
if err != nil {
return nil, err
}
return &proto.PositionsRsp{Products: products}, nil
}
func (s *Server) GetProduct(ctx context.Context, req *proto.GetProductReq) (*proto.ProductRsp, error) {
product, err := s.storage.GetProduct(ctx, req.Id)
if err != nil {
return nil, err
}
return &proto.ProductRsp{Product: product}, nil
}
func (s *Server) GetBreadcrumbs(ctx context.Context, req *proto.GetBreadcrumbsReq) (*proto.BreadcrumbsRsp, error) {
breadcrumbs, err := s.storage.GetBreadcrumbs(ctx, req.Id)
if err != nil {
return nil, err
}
return &proto.BreadcrumbsRsp{Categories: breadcrumbs}, nil
}
func (s *Server) Order(ctx context.Context, req *proto.OrderReq) (*proto.OrderRsp, error) {
enrichItems, err := s.cartService.GetCart(ctx, req.Order.Items)
if err != nil {
return nil, err
}
text, err := s.orderService.CreateOrderText(req, enrichItems)
if err != nil {
return nil, err
}
return &proto.OrderRsp{}, s.messenger.SendMessage(text)
}
func (s *Server) GetCart(ctx context.Context, req *proto.CartReq) (*proto.CartRsp, error) {
resp, err := s.cartService.GetCart(ctx, req.Items)
if err != nil {
return nil, err
}
return resp, nil
}
func (s *Server) GetImage(_ context.Context, req *proto.GetImageReq) (*httpbody.HttpBody, error) {
data, err := os.ReadFile(fmt.Sprintf("resources/images/%s", req.Name))
if err != nil {
return nil, err
}
return &httpbody.HttpBody{
ContentType: "image/jpeg",
Data: data,
}, nil
}
func (s *Server) Search(ctx context.Context, req *proto.SearchReq) (*proto.PositionsRsp, error) {
products, err := s.storage.GetPositionsByText(ctx, req.Text)
if err != nil {
return nil, err
}
return &proto.PositionsRsp{Products: products}, nil
}