This commit is contained in:
CFOU
2026-09-14 20:50:19 +02:00
commit 3091fb4020
135 changed files with 10262 additions and 0 deletions
+109
View File
@@ -0,0 +1,109 @@
package units
import (
"errors"
"net/http"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
)
type Handler struct {
service *Service
}
func NewHandler(service *Service) *Handler {
return &Handler{service: service}
}
type unitResponse struct {
ID uuid.UUID `json:"id"`
Name string `json:"name"`
Symbol string `json:"symbol"`
}
func toResponse(u *Unit) unitResponse {
return unitResponse{ID: u.ID, Name: u.Name, Symbol: u.Symbol}
}
func (h *Handler) List(c *gin.Context) {
list, err := h.service.List(c.Request.Context())
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to list units"})
return
}
resp := make([]unitResponse, 0, len(list))
for _, u := range list {
resp = append(resp, toResponse(u))
}
c.JSON(http.StatusOK, gin.H{"units": resp})
}
type upsertRequest struct {
Name string `json:"name" binding:"required"`
Symbol string `json:"symbol" binding:"required"`
}
func (h *Handler) Create(c *gin.Context) {
var req upsertRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "validation error", "details": err.Error()})
return
}
u, err := h.service.Create(c.Request.Context(), req.Name, req.Symbol)
if err != nil {
if errors.Is(err, ErrSymbolTaken) {
c.JSON(http.StatusConflict, gin.H{"error": "symbol already in use"})
return
}
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to create unit"})
return
}
c.JSON(http.StatusCreated, toResponse(u))
}
func (h *Handler) Update(c *gin.Context) {
id, err := uuid.Parse(c.Param("id"))
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid id"})
return
}
var req upsertRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "validation error", "details": err.Error()})
return
}
u, err := h.service.Update(c.Request.Context(), id, req.Name, req.Symbol)
if err != nil {
switch {
case errors.Is(err, ErrNotFound):
c.JSON(http.StatusNotFound, gin.H{"error": "unit not found"})
case errors.Is(err, ErrSymbolTaken):
c.JSON(http.StatusConflict, gin.H{"error": "symbol already in use"})
default:
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to update unit"})
}
return
}
c.JSON(http.StatusOK, toResponse(u))
}
func (h *Handler) Delete(c *gin.Context) {
id, err := uuid.Parse(c.Param("id"))
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid id"})
return
}
if err := h.service.Delete(c.Request.Context(), id); err != nil {
switch {
case errors.Is(err, ErrNotFound):
c.JSON(http.StatusNotFound, gin.H{"error": "unit not found"})
case errors.Is(err, ErrInUse):
c.JSON(http.StatusConflict, gin.H{"error": "unit is used by existing price tiers"})
default:
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to delete unit"})
}
return
}
c.Status(http.StatusNoContent)
}
+19
View File
@@ -0,0 +1,19 @@
// Package units lets the admin define their own measurement units
// (kg, g, piece, carton, ...) instead of the code hard-coding a fixed list.
package units
import (
"time"
"github.com/google/uuid"
)
type Unit struct {
ID uuid.UUID `gorm:"type:uuid;primaryKey"`
Name string `gorm:"not null"`
Symbol string `gorm:"uniqueIndex;not null"`
CreatedAt time.Time
UpdatedAt time.Time
}
func (Unit) TableName() string { return "units" }
@@ -0,0 +1,94 @@
package units
import (
"context"
"errors"
"github.com/google/uuid"
"github.com/jackc/pgx/v5/pgconn"
"gorm.io/gorm"
)
var (
ErrNotFound = errors.New("unit not found")
ErrSymbolTaken = errors.New("symbol already in use")
ErrInUse = errors.New("unit is referenced by existing price tiers")
)
type Repository interface {
Create(ctx context.Context, u *Unit) error
FindByID(ctx context.Context, id uuid.UUID) (*Unit, error)
List(ctx context.Context) ([]*Unit, error)
Update(ctx context.Context, u *Unit) error
Delete(ctx context.Context, id uuid.UUID) error
}
type gormRepository struct {
db *gorm.DB
}
func NewRepository(db *gorm.DB) Repository {
return &gormRepository{db: db}
}
func (r *gormRepository) Create(ctx context.Context, u *Unit) error {
if err := r.db.WithContext(ctx).Create(u).Error; err != nil {
if isUniqueViolation(err) {
return ErrSymbolTaken
}
return err
}
return nil
}
func (r *gormRepository) FindByID(ctx context.Context, id uuid.UUID) (*Unit, error) {
var u Unit
err := r.db.WithContext(ctx).Where("id = ?", id).First(&u).Error
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, ErrNotFound
}
if err != nil {
return nil, err
}
return &u, nil
}
func (r *gormRepository) List(ctx context.Context) ([]*Unit, error) {
var list []*Unit
if err := r.db.WithContext(ctx).Order("name asc").Find(&list).Error; err != nil {
return nil, err
}
return list, nil
}
func (r *gormRepository) Update(ctx context.Context, u *Unit) error {
err := r.db.WithContext(ctx).Save(u).Error
if isUniqueViolation(err) {
return ErrSymbolTaken
}
return err
}
func (r *gormRepository) Delete(ctx context.Context, id uuid.UUID) error {
res := r.db.WithContext(ctx).Delete(&Unit{}, "id = ?", id)
if res.Error != nil {
if isForeignKeyViolation(res.Error) {
return ErrInUse
}
return res.Error
}
if res.RowsAffected == 0 {
return ErrNotFound
}
return nil
}
func isUniqueViolation(err error) bool {
var pgErr *pgconn.PgError
return errors.As(err, &pgErr) && pgErr.Code == "23505"
}
func isForeignKeyViolation(err error) bool {
var pgErr *pgconn.PgError
return errors.As(err, &pgErr) && pgErr.Code == "23503"
}
+11
View File
@@ -0,0 +1,11 @@
package units
import "github.com/gin-gonic/gin"
func RegisterAdminRoutes(rg *gin.RouterGroup, h *Handler, requireAdmin gin.HandlerFunc) {
group := rg.Group("/admin/units", requireAdmin)
group.GET("", h.List)
group.POST("", h.Create)
group.PUT("/:id", h.Update)
group.DELETE("/:id", h.Delete)
}
+48
View File
@@ -0,0 +1,48 @@
package units
import (
"context"
"github.com/google/uuid"
)
type Service struct {
repo Repository
}
func NewService(repo Repository) *Service {
return &Service{repo: repo}
}
func (s *Service) List(ctx context.Context) ([]*Unit, error) {
return s.repo.List(ctx)
}
func (s *Service) Get(ctx context.Context, id uuid.UUID) (*Unit, error) {
return s.repo.FindByID(ctx, id)
}
func (s *Service) Create(ctx context.Context, name, symbol string) (*Unit, error) {
u := &Unit{ID: uuid.New(), Name: name, Symbol: symbol}
if err := s.repo.Create(ctx, u); err != nil {
return nil, err
}
return u, nil
}
func (s *Service) Update(ctx context.Context, id uuid.UUID, name, symbol string) (*Unit, error) {
u, err := s.repo.FindByID(ctx, id)
if err != nil {
return nil, err
}
u.Name = name
u.Symbol = symbol
if err := s.repo.Update(ctx, u); err != nil {
return nil, err
}
return u, nil
}
func (s *Service) Delete(ctx context.Context, id uuid.UUID) error {
return s.repo.Delete(ctx, id)
}