Files
controle-de-estoque-cli/internal/service/inventory_service.go
T
2026-07-15 18:47:19 -03:00

92 lines
1.9 KiB
Go

package service
import (
"controle-de-estoque/internal/model"
"controle-de-estoque/internal/repository"
"errors"
"strconv"
"strings"
)
type InventorySevice struct {
repo repository.InventoryRepository
}
func NewInventoryService(repo repository.InventoryRepository) *InventorySevice {
return &InventorySevice{repo: repo}
}
func (s *InventorySevice) CreateProduct(
name string,
category string,
price float64,
quantity int) (*model.Product, error) {
if name == "" {
return nil, errors.New("O nome é obrigatório")
}
if quantity < 0 {
return nil, errors.New("A quantidade não pode ser negativa!")
}
productInput := &model.ProductInput{
Name: name,
Category: category,
Price: price,
Quantity: quantity,
}
product := s.repo.Create(productInput)
return product, nil
}
func (s *InventorySevice) ListProducts() map[int]*model.Product {
return s.repo.FindAll()
}
func (s *InventorySevice) GetProduct(id int) (*model.Product, error) {
return s.repo.FindByID(id)
}
func (s *InventorySevice) UpdateProduct(id int, field, value string) (*model.Product, error) {
product, err := s.repo.FindByID(id)
if err != nil {
return nil, err
}
switch strings.ToLower(field) {
case "nome", "name":
product.Name = value
case "categoria", "category":
product.Category = value
case "preco", "preço", "price":
price, err := strconv.ParseFloat(value, 64)
if err != nil {
return nil, errors.New("Preço inválido")
}
product.Price = price
case "quantidade", "quantity":
quantity, err := strconv.Atoi(value)
if err != nil {
return nil, errors.New("Quantidade inválida")
}
product.Quantity = quantity
default:
return nil, errors.New("Campo inválido")
}
err = s.repo.Update(product)
if err != nil {
return nil, err
}
return product, nil
}
func (s *InventorySevice) DeleteProduct(id int) error {
return s.repo.Delete(id)
}