Inicial
This commit is contained in:
@@ -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
|
||||
}
|
||||
Reference in New Issue
Block a user