This commit is contained in:
Luciano Milani
2026-07-02 12:47:55 +01:00
commit 5de37bb512
132 changed files with 28495 additions and 0 deletions
+108
View File
@@ -0,0 +1,108 @@
package catalog
import (
"errors"
"github.com/gofiber/fiber/v2"
"github.com/jackc/pgx/v5"
"github.com/techxcar/backend/internal/auth"
"github.com/techxcar/backend/pkg/database"
)
func RegisterRoutes(app *fiber.App, db *database.DB, secret string) {
ro := []fiber.Handler{
auth.RequireAuth(secret),
auth.RequireRole("tenant_admin", "manager", "technician"),
auth.TenantMiddleware(db),
}
write := []fiber.Handler{
auth.RequireAuth(secret),
auth.RequireRole("tenant_admin", "manager"),
auth.TenantMiddleware(db),
}
app.Get("/api/v1/catalog", append(ro, listItemsH())...)
app.Post("/api/v1/catalog", append(write, createItemH())...)
app.Put("/api/v1/catalog/:id", append(write, updateItemH())...)
app.Delete("/api/v1/catalog/:id", append(write, deleteItemH())...)
}
func listItemsH() fiber.Handler {
return func(c *fiber.Ctx) error {
conn := auth.GetConn(c)
list, err := ListItems(c.Context(), conn)
if err != nil {
return fiber.NewError(500, "erro ao listar catálogo")
}
if list == nil {
list = []*CatalogItem{}
}
return c.JSON(fiber.Map{"data": list, "error": nil})
}
}
type itemBody struct {
Code string `json:"code"`
Name string `json:"name"`
Category string `json:"category"`
Unit string `json:"unit"`
BasePrice float64 `json:"base_price"`
Active bool `json:"active"`
}
func createItemH() fiber.Handler {
return func(c *fiber.Ctx) error {
var b itemBody
if err := c.BodyParser(&b); err != nil {
return fiber.NewError(400, "corpo inválido")
}
if b.Code == "" || b.Name == "" || b.Category == "" || b.Unit == "" {
return fiber.NewError(400, "código, nome, categoria e unidade são obrigatórios")
}
validUnits := map[string]bool{"un": true, "hora": true, "litro": true, "kg": true}
if !validUnits[b.Unit] {
return fiber.NewError(400, "unidade inválida (un, hora, litro, kg)")
}
conn := auth.GetConn(c)
item, err := CreateItem(c.Context(), conn, b.Code, b.Name, b.Category, b.Unit, b.BasePrice)
if err != nil {
return fiber.NewError(500, "erro ao criar item")
}
return c.Status(201).JSON(fiber.Map{"data": item, "error": nil})
}
}
func updateItemH() fiber.Handler {
return func(c *fiber.Ctx) error {
var b itemBody
if err := c.BodyParser(&b); err != nil {
return fiber.NewError(400, "corpo inválido")
}
if b.Code == "" || b.Name == "" || b.Category == "" || b.Unit == "" {
return fiber.NewError(400, "código, nome, categoria e unidade são obrigatórios")
}
validUnits := map[string]bool{"un": true, "hora": true, "litro": true, "kg": true}
if !validUnits[b.Unit] {
return fiber.NewError(400, "unidade inválida (un, hora, litro, kg)")
}
conn := auth.GetConn(c)
item, err := UpdateItem(c.Context(), conn, c.Params("id"), b.Code, b.Name, b.Category, b.Unit, b.BasePrice, b.Active)
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return fiber.NewError(404, "item não encontrado")
}
return fiber.NewError(500, "erro ao actualizar item")
}
return c.JSON(fiber.Map{"data": item, "error": nil})
}
}
func deleteItemH() fiber.Handler {
return func(c *fiber.Ctx) error {
conn := auth.GetConn(c)
if err := DeleteItem(c.Context(), conn, c.Params("id")); err != nil {
return fiber.NewError(500, "erro ao eliminar item")
}
return c.SendStatus(204)
}
}
+67
View File
@@ -0,0 +1,67 @@
package catalog
import (
"context"
"time"
"github.com/jackc/pgx/v5/pgxpool"
)
type CatalogItem struct {
ID string `json:"id"`
Code string `json:"code"`
Name string `json:"name"`
Category string `json:"category"`
Unit string `json:"unit"`
BasePrice float64 `json:"base_price"`
Active bool `json:"active"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
func ListItems(ctx context.Context, conn *pgxpool.Conn) ([]*CatalogItem, error) {
rows, err := conn.Query(ctx, `
SELECT id, code, name, category, unit, base_price, active, created_at, updated_at
FROM catalog_items ORDER BY category, name`)
if err != nil {
return nil, err
}
defer rows.Close()
var list []*CatalogItem
for rows.Next() {
var i CatalogItem
if err := rows.Scan(&i.ID, &i.Code, &i.Name, &i.Category, &i.Unit,
&i.BasePrice, &i.Active, &i.CreatedAt, &i.UpdatedAt); err != nil {
return nil, err
}
list = append(list, &i)
}
return list, rows.Err()
}
func CreateItem(ctx context.Context, conn *pgxpool.Conn, code, name, category, unit string, basePrice float64) (*CatalogItem, error) {
var i CatalogItem
err := conn.QueryRow(ctx, `
INSERT INTO catalog_items (code, name, category, unit, base_price)
VALUES ($1, $2, $3, $4, $5)
RETURNING id, code, name, category, unit, base_price, active, created_at, updated_at`,
code, name, category, unit, basePrice).
Scan(&i.ID, &i.Code, &i.Name, &i.Category, &i.Unit, &i.BasePrice, &i.Active, &i.CreatedAt, &i.UpdatedAt)
return &i, err
}
func UpdateItem(ctx context.Context, conn *pgxpool.Conn, id, code, name, category, unit string, basePrice float64, active bool) (*CatalogItem, error) {
var i CatalogItem
err := conn.QueryRow(ctx, `
UPDATE catalog_items SET code=$2, name=$3, category=$4, unit=$5, base_price=$6, active=$7, updated_at=NOW()
WHERE id=$1
RETURNING id, code, name, category, unit, base_price, active, created_at, updated_at`,
id, code, name, category, unit, basePrice, active).
Scan(&i.ID, &i.Code, &i.Name, &i.Category, &i.Unit, &i.BasePrice, &i.Active, &i.CreatedAt, &i.UpdatedAt)
return &i, err
}
func DeleteItem(ctx context.Context, conn *pgxpool.Conn, id string) error {
_, err := conn.Exec(ctx, `DELETE FROM catalog_items WHERE id = $1`, id)
return err
}
@@ -0,0 +1,50 @@
package catalog_test
import (
"context"
"os"
"testing"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/techxcar/backend/internal/catalog"
)
func getTestConn(t *testing.T) *pgxpool.Conn {
t.Helper()
dsn := os.Getenv("TEST_DATABASE_URL")
if dsn == "" {
t.Skip("TEST_DATABASE_URL not set")
}
pool, err := pgxpool.New(context.Background(), dsn)
require.NoError(t, err)
t.Cleanup(func() { pool.Close() })
conn, err := pool.Acquire(context.Background())
require.NoError(t, err)
t.Cleanup(func() { conn.Release() })
_, err = conn.Exec(context.Background(), "SET search_path = tenant_test, public")
require.NoError(t, err)
return conn
}
func TestCatalogCRUD(t *testing.T) {
conn := getTestConn(t)
ctx := context.Background()
item, err := catalog.CreateItem(ctx, conn, "MO-5W40", "Óleo Motor 5W40", "lubrificantes", "litro", 12.50)
require.NoError(t, err)
assert.NotEmpty(t, item.ID)
assert.Equal(t, "MO-5W40", item.Code)
list, err := catalog.ListItems(ctx, conn)
require.NoError(t, err)
assert.GreaterOrEqual(t, len(list), 1)
updated, err := catalog.UpdateItem(ctx, conn, item.ID, "MO-5W40", "Óleo Motor 5W40 Sintético", "lubrificantes", "litro", 15.00, true)
require.NoError(t, err)
assert.Equal(t, 15.00, updated.BasePrice)
err = catalog.DeleteItem(ctx, conn, item.ID)
require.NoError(t, err)
}