chore: build
ci-api / test (push) Successful in 22m31s
ci-web / test (push) Successful in 11m35s

This commit is contained in:
Xor290
2026-10-23 16:51:57 +02:00
parent fe0e29d087
commit 4d1a5b9629
21 changed files with 1090 additions and 23 deletions
+9
View File
@@ -12,6 +12,7 @@ import (
"backend/internal/modules/checkoutfields"
"backend/internal/modules/contactlinks"
"backend/internal/modules/customerverification"
"backend/internal/modules/ldmod"
"backend/internal/modules/media"
"backend/internal/modules/orders"
"backend/internal/modules/pricing"
@@ -91,6 +92,11 @@ func main() {
checkoutFieldsService := checkoutfields.NewService(checkoutFieldsRepo)
checkoutFieldsHandler := checkoutfields.NewHandler(checkoutFieldsService)
// --- Light/dark mode module ---
ldModRepo := ldmod.NewRepository(database)
ldModService := ldmod.NewService(ldModRepo)
ldModHandler := ldmod.NewHandler(ldModService)
// --- Products module ---
productsRepo := products.NewRepository(database)
productsService := products.NewService(productsRepo, categoriesRepo)
@@ -175,6 +181,9 @@ func main() {
checkoutfields.RegisterAdminRoutes(api, checkoutFieldsHandler, requireAdmin)
checkoutfields.RegisterPublicRoutes(api, checkoutFieldsHandler)
ldmod.RegisterAdminRoutes(api, ldModHandler, requireAdmin)
ldmod.RegisterPublicRoutes(api, ldModHandler)
products.RegisterAdminRoutes(api, productsHandler, requireAdmin)
products.RegisterPublicRoutes(api, productsHandler)
+64
View File
@@ -0,0 +1,64 @@
package ldmod
import (
"errors"
"net/http"
"github.com/gin-gonic/gin"
)
type Handler struct {
service *Service
}
func NewHandler(service *Service) *Handler {
return &Handler{service: service}
}
// settingsPayload est à la fois la réponse et la requête.
type settingsPayload struct {
ToggleEnabled bool `json:"toggle_enabled"`
DefaultTheme string `json:"default_theme" binding:"omitempty,oneof=light dark"`
}
func toPayload(m *LDMod) settingsPayload {
return settingsPayload{ToggleEnabled: m.ToggleEnabled, DefaultTheme: m.DefaultTheme}
}
func (h *Handler) fail(c *gin.Context, err error, msg string) {
switch {
case errors.Is(err, ErrNotFound):
c.JSON(http.StatusNotFound, gin.H{"error": "ld mod settings not found"})
case errors.Is(err, ErrInvalidTheme):
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
default:
c.JSON(http.StatusInternalServerError, gin.H{"error": msg})
}
}
// Get : lecture publique, utilisée par le storefront pour savoir si le
// bouton de bascule clair/sombre doit s'afficher et, sinon, quel thème
// forcer.
func (h *Handler) Get(c *gin.Context) {
m, err := h.service.Get(c.Request.Context())
if err != nil {
h.fail(c, err, "failed to load theme settings")
return
}
c.JSON(http.StatusOK, toPayload(m))
}
// Update : écriture admin des deux réglages d'un coup.
func (h *Handler) Update(c *gin.Context) {
var req settingsPayload
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "validation error", "details": err.Error()})
return
}
m, err := h.service.Update(c.Request.Context(), &LDMod{ToggleEnabled: req.ToggleEnabled, DefaultTheme: req.DefaultTheme})
if err != nil {
h.fail(c, err, "failed to update theme settings")
return
}
c.JSON(http.StatusOK, toPayload(m))
}
+17
View File
@@ -0,0 +1,17 @@
package ldmod
// LDMod : réglage global du mode clair/sombre côté storefront. L'admin
// décide si le client peut basculer lui-même (ToggleEnabled) ou si le site
// reste figé sur DefaultTheme. Ligne unique, comme checkoutfields.
type LDMod struct {
ID int16 `gorm:"primaryKey"`
ToggleEnabled bool `gorm:"not null;default:true"`
DefaultTheme string `gorm:"not null;default:'dark'"`
}
func (LDMod) TableName() string { return "ld_mod" }
const (
ThemeLight = "light"
ThemeDark = "dark"
)
@@ -0,0 +1,54 @@
package ldmod
import (
"context"
"errors"
"gorm.io/gorm"
)
// singletonID : l'unique ligne de ld_mod (voir la contrainte CHECK (id = 1)
// de la migration 000035).
const singletonID int16 = 1
var ErrNotFound = errors.New("ld mod settings not found")
type Repository interface {
Get(ctx context.Context) (*LDMod, error)
Update(ctx context.Context, m *LDMod) (*LDMod, error)
}
type gormRepository struct {
db *gorm.DB
}
func NewRepository(db *gorm.DB) Repository {
return &gormRepository{db: db}
}
func (r *gormRepository) Get(ctx context.Context) (*LDMod, error) {
var m LDMod
err := r.db.WithContext(ctx).First(&m, singletonID).Error
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, ErrNotFound
}
if err != nil {
return nil, err
}
return &m, nil
}
// Update écrit tous les réglages sur la ligne unique. Select("*") est voulu :
// sans lui GORM ignore les champs à valeur zéro d'une struct, donc passer
// false n'écrirait rien et l'admin ne pourrait jamais désactiver le toggle.
func (r *gormRepository) Update(ctx context.Context, m *LDMod) (*LDMod, error) {
m.ID = singletonID
res := r.db.WithContext(ctx).Model(&LDMod{}).Where("id = ?", singletonID).Select("*").Updates(m)
if res.Error != nil {
return nil, res.Error
}
if res.RowsAffected == 0 {
return nil, ErrNotFound
}
return r.Get(ctx)
}
+16
View File
@@ -0,0 +1,16 @@
package ldmod
import "github.com/gin-gonic/gin"
func RegisterAdminRoutes(rg *gin.RouterGroup, h *Handler, requireAdmin gin.HandlerFunc) {
group := rg.Group("/admin/theme-settings", requireAdmin)
group.GET("", h.Get)
group.PUT("", h.Update)
}
// RegisterPublicRoutes expose les réglages en lecture seule : le storefront
// en a besoin pour savoir s'il doit afficher le bouton de bascule clair/
// sombre, et sinon quel thème forcer.
func RegisterPublicRoutes(rg *gin.RouterGroup, h *Handler) {
rg.GET("/theme-settings", h.Get)
}
+31
View File
@@ -0,0 +1,31 @@
package ldmod
import (
"context"
"errors"
)
var ErrInvalidTheme = errors.New("default_theme must be 'light' or 'dark'")
type Service struct {
repo Repository
}
func NewService(repo Repository) *Service {
return &Service{repo: repo}
}
func (s *Service) Get(ctx context.Context) (*LDMod, error) {
return s.repo.Get(ctx)
}
// Update remplace les deux réglages. default_theme n'a de sens que parmi les
// deux thèmes que le frontend sait rendre (voir theme/ThemeContext.tsx côté
// frontend) : le client ne doit jamais pouvoir pousser une valeur arbitraire
// qui ferait planter le rendu.
func (s *Service) Update(ctx context.Context, m *LDMod) (*LDMod, error) {
if m.DefaultTheme != ThemeLight && m.DefaultTheme != ThemeDark {
return nil, ErrInvalidTheme
}
return s.repo.Update(ctx, m)
}
@@ -0,0 +1 @@
DROP TABLE IF EXISTS ld_mod;
@@ -0,0 +1,11 @@
-- Réglage global du mode clair/sombre côté storefront : l'admin décide si le
-- client peut basculer lui-même (toggle_enabled) ou si le site reste figé
-- sur default_theme. Une seule ligne : CHECK (id = 1) interdit toute autre
-- ligne, comme checkout_fields (voir 000032).
CREATE TABLE ld_mod (
id SMALLINT PRIMARY KEY DEFAULT 1 CHECK (id = 1),
toggle_enabled BOOLEAN NOT NULL DEFAULT true,
default_theme TEXT NOT NULL DEFAULT 'dark' CHECK (default_theme IN ('light', 'dark'))
);
INSERT INTO ld_mod (id) VALUES (1);
+151
View File
@@ -0,0 +1,151 @@
package ldmod_test
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
"github.com/gin-gonic/gin"
"gorm.io/gorm/schema"
"backend/internal/modules/ldmod"
)
// fakeRepository garde la ligne unique en mémoire. Comme le vrai dépôt,
// Update remplace TOUS les champs.
type fakeRepository struct {
mu sync.Mutex
row *ldmod.LDMod
}
func newFakeRepository() *fakeRepository {
return &fakeRepository{row: &ldmod.LDMod{ID: 1, ToggleEnabled: true, DefaultTheme: ldmod.ThemeDark}}
}
func (r *fakeRepository) Get(context.Context) (*ldmod.LDMod, error) {
r.mu.Lock()
defer r.mu.Unlock()
cp := *r.row
return &cp, nil
}
func (r *fakeRepository) Update(_ context.Context, m *ldmod.LDMod) (*ldmod.LDMod, error) {
r.mu.Lock()
defer r.mu.Unlock()
cp := *m
cp.ID = 1
r.row = &cp
out := cp
return &out, nil
}
func newRouter() *gin.Engine {
gin.SetMode(gin.TestMode)
r := gin.New()
h := ldmod.NewHandler(ldmod.NewService(newFakeRepository()))
api := r.Group("/api")
ldmod.RegisterPublicRoutes(api, h)
ldmod.RegisterAdminRoutes(api, h, func(c *gin.Context) { c.Next() })
return r
}
func do(r *gin.Engine, method, path, body string) *httptest.ResponseRecorder {
req := httptest.NewRequest(method, path, strings.NewReader(body))
req.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
return w
}
func decode(t *testing.T, w *httptest.ResponseRecorder) map[string]any {
t.Helper()
var m map[string]any
if err := json.Unmarshal(w.Body.Bytes(), &m); err != nil {
t.Fatalf("réponse JSON invalide: %v (%s)", err, w.Body)
}
return m
}
func TestGet_ReturnsCurrentSettings(t *testing.T) {
w := do(newRouter(), "GET", "/api/theme-settings", "")
if w.Code != http.StatusOK {
t.Fatalf("HTTP %d, attendu 200", w.Code)
}
m := decode(t, w)
if m["toggle_enabled"] != true || m["default_theme"] != "dark" {
t.Errorf("valeurs par défaut inattendues: %v", m)
}
}
func TestUpdate_CanDisableToggleAndForceLight(t *testing.T) {
r := newRouter()
w := do(r, "PUT", "/api/admin/theme-settings", `{"toggle_enabled":false,"default_theme":"light"}`)
if w.Code != http.StatusOK {
t.Fatalf("HTTP %d: %s", w.Code, w.Body)
}
m := decode(t, w)
if m["toggle_enabled"] != false || m["default_theme"] != "light" {
t.Errorf("valeurs = %v", m)
}
// toggle_enabled=false doit bien persister (pas ignoré comme un zéro de struct Go).
if got := decode(t, do(r, "GET", "/api/theme-settings", "")); got["toggle_enabled"] != false {
t.Errorf("le GET public ne reflète pas la désactivation: %v", got)
}
}
func TestUpdate_RejectsInvalidTheme(t *testing.T) {
r := newRouter()
w := do(r, "PUT", "/api/admin/theme-settings", `{"toggle_enabled":true,"default_theme":"purple"}`)
if w.Code != http.StatusBadRequest {
t.Errorf("HTTP %d, attendu 400", w.Code)
}
}
func TestUpdate_RejectsInvalidBody(t *testing.T) {
w := do(newRouter(), "PUT", "/api/admin/theme-settings", `not json`)
if w.Code != http.StatusBadRequest {
t.Errorf("HTTP %d, attendu 400", w.Code)
}
}
func TestAdminRoute_RequiresAdminMiddleware(t *testing.T) {
gin.SetMode(gin.TestMode)
r := gin.New()
h := ldmod.NewHandler(ldmod.NewService(newFakeRepository()))
api := r.Group("/api")
ldmod.RegisterPublicRoutes(api, h)
ldmod.RegisterAdminRoutes(api, h, func(c *gin.Context) { c.AbortWithStatus(http.StatusUnauthorized) })
if w := do(r, "PUT", "/api/admin/theme-settings", `{"toggle_enabled":true,"default_theme":"dark"}`); w.Code != http.StatusUnauthorized {
t.Errorf("PUT admin sans droit : HTTP %d, attendu 401", w.Code)
}
if w := do(r, "GET", "/api/theme-settings", ""); w.Code != http.StatusOK {
t.Errorf("GET public : HTTP %d, attendu 200", w.Code)
}
}
// Les noms de colonnes de la migration 000035 doivent être ceux que GORM
// déduit des champs de la struct.
func TestModelColumnsMatchMigration(t *testing.T) {
want := []string{"id", "toggle_enabled", "default_theme"}
s, err := schema.Parse(&ldmod.LDMod{}, &sync.Map{}, schema.NamingStrategy{})
if err != nil {
t.Fatal(err)
}
got := map[string]bool{}
for _, f := range s.Fields {
got[f.DBName] = true
}
for _, col := range want {
if !got[col] {
t.Errorf("colonne %q absente du modèle (colonnes GORM: %v)", col, s.DBNames)
}
}
if s.Table != "ld_mod" {
t.Errorf("table %q, attendu ld_mod", s.Table)
}
}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.0 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.0 KiB