feat(checkout): let the admin choose the details asked at checkout
ci-api / test (push) Successful in 20m38s
ci-web / test (push) Successful in 11m20s

The admin enables or disables each option (phone, address, Snapchat,
Instagram, Telegram, SimpleX, WhatsApp, Signal, notes, preferred time)
from a new "Checkout fields" page; the customer's name is always asked.

Backend
- checkoutfields module: single-row settings (CHECK id = 1), public GET
  and admin GET/PUT.
- orders: answers stored as JSONB (contacts, info_sup); the customer
  phone moves from customer_phone to contacts.phone (migration 000034
  copies existing values before dropping the column).
- Orders are validated against the live settings: disabled options and
  unknown keys are dropped, enabled phone/address are required, and
  format, length and control characters are checked.
- The Telegram notification includes the answers.

Frontend
- Checkout form generated from the enabled options; admin settings page;
  answers shown in the order list and detail.
- API calls live in src/api (checkoutFields.ts, orders.ts); ApiError
  keeps the response body so the rejected field can be reported.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Xor290
2026-10-04 16:16:22 +02:00
co-authored by Claude Sonnet 5.5
parent 178652ef14
commit f9bfdc9d3c
37 changed files with 1579 additions and 119 deletions
@@ -0,0 +1,153 @@
package checkoutfields_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/checkoutfields"
)
// fakeRepository garde la ligne unique en mémoire. Comme le vrai dépôt, Update
// remplace TOUS les champs, y compris ceux à false.
type fakeRepository struct {
mu sync.Mutex
row *checkoutfields.CheckoutField
}
func newFakeRepository() *fakeRepository {
return &fakeRepository{row: &checkoutfields.CheckoutField{ID: 1, CheckoutPhone: true, CheckoutAddress: true}}
}
func (r *fakeRepository) Get(context.Context) (*checkoutfields.CheckoutField, error) {
r.mu.Lock()
defer r.mu.Unlock()
cp := *r.row
return &cp, nil
}
func (r *fakeRepository) Update(_ context.Context, f *checkoutfields.CheckoutField) (*checkoutfields.CheckoutField, error) {
r.mu.Lock()
defer r.mu.Unlock()
cp := *f
cp.ID = 1
r.row = &cp
out := cp
return &out, nil
}
func newRouter() *gin.Engine {
gin.SetMode(gin.TestMode)
r := gin.New()
h := checkoutfields.NewHandler(checkoutfields.NewService(newFakeRepository()))
api := r.Group("/api")
checkoutfields.RegisterPublicRoutes(api, h)
checkoutfields.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]bool {
t.Helper()
var m map[string]bool
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/checkout-fields", "")
if w.Code != http.StatusOK {
t.Fatalf("HTTP %d, attendu 200", w.Code)
}
m := decode(t, w)
if !m["phone"] || !m["address"] || m["snap"] || m["hour"] {
t.Errorf("valeurs par défaut inattendues: %v", m)
}
}
func TestUpdate_CanDisableAFieldThatWasEnabled(t *testing.T) {
r := newRouter()
// phone et address sont à true au départ : tout mettre à false doit
// persister (un Update qui ignorerait les zéros les laisserait à true).
w := do(r, "PUT", "/api/admin/checkout-fields", `{"signal":true}`)
if w.Code != http.StatusOK {
t.Fatalf("HTTP %d: %s", w.Code, w.Body)
}
m := decode(t, w)
if m["phone"] || m["address"] {
t.Errorf("phone/address devraient être à false: %v", m)
}
if !m["signal"] {
t.Errorf("signal devrait être à true: %v", m)
}
if got := decode(t, do(r, "GET", "/api/checkout-fields", "")); got["phone"] || !got["signal"] {
t.Errorf("le GET public ne reflète pas la mise à jour: %v", got)
}
}
func TestUpdate_RejectsInvalidBody(t *testing.T) {
for _, body := range []string{`not json`, `{"phone":"yes"}`} {
if w := do(newRouter(), "PUT", "/api/admin/checkout-fields", body); w.Code != http.StatusBadRequest {
t.Errorf("body %q : HTTP %d, attendu 400", body, w.Code)
}
}
}
func TestAdminRoute_RequiresAdminMiddleware(t *testing.T) {
gin.SetMode(gin.TestMode)
r := gin.New()
h := checkoutfields.NewHandler(checkoutfields.NewService(newFakeRepository()))
api := r.Group("/api")
checkoutfields.RegisterPublicRoutes(api, h)
checkoutfields.RegisterAdminRoutes(api, h, func(c *gin.Context) { c.AbortWithStatus(http.StatusUnauthorized) })
if w := do(r, "PUT", "/api/admin/checkout-fields", `{"phone":true}`); w.Code != http.StatusUnauthorized {
t.Errorf("PUT admin sans droit : HTTP %d, attendu 401", w.Code)
}
if w := do(r, "GET", "/api/checkout-fields", ""); w.Code != http.StatusOK {
t.Errorf("GET public : HTTP %d, attendu 200", w.Code)
}
}
// Les noms de colonnes de la migration 000032 doivent être ceux que GORM
// déduit des champs de la struct : sinon la requête échouerait en production
// alors que les tests avec le faux dépôt passeraient.
func TestModelColumnsMatchMigration(t *testing.T) {
want := []string{
"id", "checkout_phone", "checkout_address", "checkout_snap", "checkout_insta",
"checkout_telegram", "checkout_simple_x", "checkout_whatsapp", "checkout_signal",
"checkout_notes", "checkout_hour",
}
s, err := schema.Parse(&checkoutfields.CheckoutField{}, &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 != "checkout_fields" {
t.Errorf("table %q, attendu checkout_fields", s.Table)
}
}