Files
controle-de-estoque-cli/model/inventory.go
T
2026-07-15 00:44:32 -03:00

99 lines
1.8 KiB
Go

package model
import (
"errors"
"strconv"
"strings"
)
type ProductID int
var productID ProductID = 1
type Product struct {
ID ProductID
Name string
Category string
Price float64
Quantity int
}
type ProductInput struct {
Name string
Category string
Price float64
Quantity int
}
type Inventory struct {
products map[ProductID]Product
}
// função auxiliar para criar a instância do objeto Inventory
func NewInventory() *Inventory {
return &Inventory{products: make(map[ProductID]Product)}
}
func (e *Inventory) AddProduct(i *ProductInput) *Product {
product := Product{
ID: productID,
Name: i.Name,
Category: i.Category,
Price: i.Price,
Quantity: i.Quantity,
}
e.products[productID] = product
productID += 1
return &product
}
func (e *Inventory) FetchProducts() map[ProductID]Product {
return e.products
}
func (e *Inventory) UpdateProduct(id ProductID, field, value string) (*Product, error) {
product, ok := e.products[id]
if !ok {
return nil, errors.New("Produto não encontrado")
}
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")
}
e.products[id] = product
return &product, nil
}
func (e *Inventory) DeleteProduct(id ProductID) error {
if _, ok := e.products[id]; !ok {
return errors.New("Produto não encontrado")
}
delete(e.products, id)
return nil
}