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
+10 -1
View File
@@ -9,6 +9,7 @@ import (
"backend/internal/modules/auth"
"backend/internal/modules/categories"
"backend/internal/modules/checkoutfields"
"backend/internal/modules/contactlinks"
"backend/internal/modules/customerverification"
"backend/internal/modules/media"
@@ -85,6 +86,11 @@ func main() {
unitsService := units.NewService(unitsRepo)
unitsHandler := units.NewHandler(unitsService)
// --- Checkout fields module ---
checkoutFieldsRepo := checkoutfields.NewRepository(database)
checkoutFieldsService := checkoutfields.NewService(checkoutFieldsRepo)
checkoutFieldsHandler := checkoutfields.NewHandler(checkoutFieldsService)
// --- Products module ---
productsRepo := products.NewRepository(database)
productsService := products.NewService(productsRepo, categoriesRepo)
@@ -121,7 +127,7 @@ func main() {
// --- Orders module (depends on products/units/pricing for authoritative
// pricing, and on telegram as its pluggable OrderNotifier) ---
ordersRepo := orders.NewRepository(database)
ordersService := orders.NewService(ordersRepo, productsService, unitsService, pricingService, telegramService)
ordersService := orders.NewService(ordersRepo, productsService, unitsService, pricingService, telegramService, checkoutFieldsService)
ordersHandler := orders.NewHandler(ordersService)
requireAdmin := appmiddleware.RequireAdmin(cfg.JWT.Secret)
@@ -166,6 +172,9 @@ func main() {
units.RegisterAdminRoutes(api, unitsHandler, requireAdmin)
units.RegisterPublicRoutes(api, unitsHandler)
checkoutfields.RegisterAdminRoutes(api, checkoutFieldsHandler, requireAdmin)
checkoutfields.RegisterPublicRoutes(api, checkoutFieldsHandler)
products.RegisterAdminRoutes(api, productsHandler, requireAdmin)
products.RegisterPublicRoutes(api, productsHandler)
@@ -0,0 +1,80 @@
package checkoutfields
import (
"errors"
"net/http"
"github.com/gin-gonic/gin"
)
type Handler struct {
service *Service
}
func NewHandler(service *Service) *Handler {
return &Handler{service: service}
}
func toPayload(f *CheckoutField) settingsPayload {
return settingsPayload{
Phone: f.CheckoutPhone,
Address: f.CheckoutAddress,
Snap: f.CheckoutSnap,
Insta: f.CheckoutInsta,
Telegram: f.CheckoutTelegram,
SimpleX: f.CheckoutSimpleX,
Whatsapp: f.CheckoutWhatsapp,
Signal: f.CheckoutSignal,
Notes: f.CheckoutNotes,
Hour: f.CheckoutHour,
}
}
func (p settingsPayload) toModel() *CheckoutField {
return &CheckoutField{
CheckoutPhone: p.Phone,
CheckoutAddress: p.Address,
CheckoutSnap: p.Snap,
CheckoutInsta: p.Insta,
CheckoutTelegram: p.Telegram,
CheckoutSimpleX: p.SimpleX,
CheckoutWhatsapp: p.Whatsapp,
CheckoutSignal: p.Signal,
CheckoutNotes: p.Notes,
CheckoutHour: p.Hour,
}
}
func (h *Handler) fail(c *gin.Context, err error, msg string) {
if errors.Is(err, ErrNotFound) {
c.JSON(http.StatusNotFound, gin.H{"error": "checkout fields not found"})
return
}
c.JSON(http.StatusInternalServerError, gin.H{"error": msg})
}
// Get : lecture publique, utilisée par le storefront pour savoir quels champs
// afficher au checkout.
func (h *Handler) Get(c *gin.Context) {
f, err := h.service.Get(c.Request.Context())
if err != nil {
h.fail(c, err, "failed to load checkout fields")
return
}
c.JSON(http.StatusOK, toPayload(f))
}
// Update : écriture admin de tous les 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
}
f, err := h.service.Update(c.Request.Context(), req.toModel())
if err != nil {
h.fail(c, err, "failed to update checkout fields")
return
}
c.JSON(http.StatusOK, toPayload(f))
}
@@ -0,0 +1,30 @@
package checkoutfields
type CheckoutField struct {
ID int16 `gorm:"primaryKey"`
CheckoutPhone bool `gorm:"not null;default:false"`
CheckoutAddress bool `gorm:"not null;default:false"`
CheckoutSnap bool `gorm:"not null;default:false"`
CheckoutInsta bool `gorm:"not null;default:false"`
CheckoutTelegram bool `gorm:"not null;default:false"`
CheckoutSimpleX bool `gorm:"not null;default:false"`
CheckoutWhatsapp bool `gorm:"not null;default:false"`
CheckoutSignal bool `gorm:"not null;default:false"`
CheckoutNotes bool `gorm:"not null;default:false"`
CheckoutHour bool `gorm:"not null;default:false"`
}
type settingsPayload struct {
Phone bool `json:"phone"`
Address bool `json:"address"`
Snap bool `json:"snap"`
Insta bool `json:"insta"`
Telegram bool `json:"telegram"`
SimpleX bool `json:"simplex"`
Whatsapp bool `json:"whatsapp"`
Signal bool `json:"signal"`
Notes bool `json:"notes"`
Hour bool `json:"hour"`
}
func (CheckoutField) TableName() string { return "checkout_fields" }
@@ -0,0 +1,54 @@
package checkoutfields
import (
"context"
"errors"
"gorm.io/gorm"
)
// singletonID : l'unique ligne de checkout_fields (voir la contrainte
// CHECK (id = 1) de la migration 000032).
const singletonID int16 = 1
var ErrNotFound = errors.New("checkout fields not found")
type Repository interface {
Get(ctx context.Context) (*CheckoutField, error)
Update(ctx context.Context, f *CheckoutField) (*CheckoutField, error)
}
type gormRepository struct {
db *gorm.DB
}
func NewRepository(db *gorm.DB) Repository {
return &gormRepository{db: db}
}
func (r *gormRepository) Get(ctx context.Context) (*CheckoutField, error) {
var f CheckoutField
err := r.db.WithContext(ctx).First(&f, singletonID).Error
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, ErrNotFound
}
if err != nil {
return nil, err
}
return &f, 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 un champ.
func (r *gormRepository) Update(ctx context.Context, f *CheckoutField) (*CheckoutField, error) {
f.ID = singletonID
res := r.db.WithContext(ctx).Model(&CheckoutField{}).Where("id = ?", singletonID).Select("*").Updates(f)
if res.Error != nil {
return nil, res.Error
}
if res.RowsAffected == 0 {
return nil, ErrNotFound
}
return r.Get(ctx)
}
@@ -0,0 +1,15 @@
package checkoutfields
import "github.com/gin-gonic/gin"
func RegisterAdminRoutes(rg *gin.RouterGroup, h *Handler, requireAdmin gin.HandlerFunc) {
group := rg.Group("/admin/checkout-fields", requireAdmin)
group.GET("", h.Get)
group.PUT("", h.Update)
}
// RegisterPublicRoutes expose les réglages en lecture seule : le storefront
// en a besoin pour n'afficher que les champs demandés au checkout.
func RegisterPublicRoutes(rg *gin.RouterGroup, h *Handler) {
rg.GET("/checkout-fields", h.Get)
}
@@ -0,0 +1,21 @@
package checkoutfields
import "context"
type Service struct {
repo Repository
}
func NewService(repo Repository) *Service {
return &Service{repo: repo}
}
func (s *Service) Get(ctx context.Context) (*CheckoutField, error) {
return s.repo.Get(ctx)
}
// Update remplace tous les réglages. Le nom du client est toujours demandé
// (et obligatoire) : il n'est donc pas un réglage.
func (s *Service) Update(ctx context.Context, f *CheckoutField) (*CheckoutField, error) {
return s.repo.Update(ctx, f)
}
@@ -0,0 +1,189 @@
package orders
import (
"context"
"errors"
"regexp"
"strings"
"unicode"
"unicode/utf8"
"backend/internal/modules/checkoutfields"
)
// CheckoutSettings : quels champs l'admin demande au client (voir le module
// checkoutfields). Défini côté consommateur comme les autres dépendances ;
// *checkoutfields.Service le satisfait.
type CheckoutSettings interface {
Get(ctx context.Context) (*checkoutfields.CheckoutField, error)
}
var ErrInvalidField = errors.New("invalid checkout field")
// Raisons d'un FieldError, renvoyées telles quelles au frontend.
const (
ReasonRequired = "required"
ReasonTooLong = "too_long"
ReasonFormat = "invalid_format"
ReasonCharacters = "invalid_characters"
ReasonTooMany = "too_many_fields"
)
// FieldError désigne le champ refusé et pourquoi. errors.Is(err,
// ErrInvalidField) est vrai pour toute erreur de ce type.
type FieldError struct {
Field string
Reason string
}
func (e *FieldError) Error() string { return "invalid checkout field " + e.Field + ": " + e.Reason }
func (e *FieldError) Is(target error) bool { return target == ErrInvalidField }
const (
maxNameLen = 100
maxHandleLen = 100
maxAddressLen = 300
maxNotesLen = 1000
maxPhoneLen = 30
maxIncomingKeys = 20 // borne la taille des maps reçues, avant tout traitement
)
var hourPattern = regexp.MustCompile(`^([01][0-9]|2[0-3]):[0-5][0-9]$`)
type fieldSpec struct {
key string
enabled func(*checkoutfields.CheckoutField) bool
required bool // exigé quand l'option est activée
maxLen int
check func(string) bool // nil = aucun format imposé
badForm string // raison renvoyée si check échoue
}
// Champs de la map Contacts : téléphone et messageries. Seuls le téléphone est
// obligatoire quand il est activé : on ne peut pas exiger tous les comptes.
var contactSpecs = []fieldSpec{
{ContactPhone, func(f *checkoutfields.CheckoutField) bool { return f.CheckoutPhone }, true, maxPhoneLen, validPhone, ReasonFormat},
{ContactSnap, func(f *checkoutfields.CheckoutField) bool { return f.CheckoutSnap }, false, maxHandleLen, nil, ""},
{ContactInsta, func(f *checkoutfields.CheckoutField) bool { return f.CheckoutInsta }, false, maxHandleLen, nil, ""},
{ContactTelegram, func(f *checkoutfields.CheckoutField) bool { return f.CheckoutTelegram }, false, maxHandleLen, nil, ""},
{ContactSimpleX, func(f *checkoutfields.CheckoutField) bool { return f.CheckoutSimpleX }, false, maxHandleLen, nil, ""},
{ContactWhatsapp, func(f *checkoutfields.CheckoutField) bool { return f.CheckoutWhatsapp }, false, maxHandleLen, nil, ""},
{ContactSignal, func(f *checkoutfields.CheckoutField) bool { return f.CheckoutSignal }, false, maxHandleLen, nil, ""},
}
// Champs de la map InfoSup : adresse (obligatoire si activée) et heure.
var infoSupSpecs = []fieldSpec{
{ContactAddress, func(f *checkoutfields.CheckoutField) bool { return f.CheckoutAddress }, true, maxAddressLen, nil, ""},
{ContactHour, func(f *checkoutfields.CheckoutField) bool { return f.CheckoutHour }, false, 5, hourPattern.MatchString, ReasonFormat},
}
// applyCheckoutSettings valide et nettoie les réponses du client selon les
// options activées par l'admin. Le client ne définit jamais les règles : elles
// sont relues en base à chaque commande.
//
// - une réponse à une option désactivée, ou à une clé inconnue, est ignorée
// (une page de checkout restée ouverte après un changement de l'admin ne
// doit pas faire échouer la commande) ;
// - une option obligatoire activée sans réponse est refusée ;
// - les valeurs sont nettoyées (espaces) et bornées en longueur.
func applyCheckoutSettings(f *checkoutfields.CheckoutField, in *CreateInput) error {
if len(in.Contacts) > maxIncomingKeys {
return &FieldError{Field: "contacts", Reason: ReasonTooMany}
}
if len(in.InfoSup) > maxIncomingKeys {
return &FieldError{Field: "info_sup", Reason: ReasonTooMany}
}
in.CustomerName = strings.TrimSpace(in.CustomerName)
if in.CustomerName == "" {
return &FieldError{Field: "customer_name", Reason: ReasonRequired}
}
if utf8.RuneCountInString(in.CustomerName) > maxNameLen {
return &FieldError{Field: "customer_name", Reason: ReasonTooLong}
}
if hasControlChars(in.CustomerName, false) {
return &FieldError{Field: "customer_name", Reason: ReasonCharacters}
}
contacts, err := cleanGroup(f, contactSpecs, in.Contacts)
if err != nil {
return err
}
infoSup, err := cleanGroup(f, infoSupSpecs, in.InfoSup)
if err != nil {
return err
}
in.Contacts, in.InfoSup = contacts, infoSup
if !f.CheckoutNotes {
in.Notes = ""
return nil
}
in.Notes = strings.TrimSpace(in.Notes)
if utf8.RuneCountInString(in.Notes) > maxNotesLen {
return &FieldError{Field: "notes", Reason: ReasonTooLong}
}
if hasControlChars(in.Notes, true) {
return &FieldError{Field: "notes", Reason: ReasonCharacters}
}
return nil
}
func cleanGroup(f *checkoutfields.CheckoutField, specs []fieldSpec, raw map[string]string) (map[string]string, error) {
out := map[string]string{}
for _, spec := range specs {
if !spec.enabled(f) {
continue
}
value := strings.TrimSpace(raw[spec.key])
if value == "" {
if spec.required {
return nil, &FieldError{Field: spec.key, Reason: ReasonRequired}
}
continue
}
if utf8.RuneCountInString(value) > spec.maxLen {
return nil, &FieldError{Field: spec.key, Reason: ReasonTooLong}
}
if hasControlChars(value, spec.key == ContactAddress) {
return nil, &FieldError{Field: spec.key, Reason: ReasonCharacters}
}
if spec.check != nil && !spec.check(value) {
return nil, &FieldError{Field: spec.key, Reason: spec.badForm}
}
out[spec.key] = value
}
return out, nil
}
// hasControlChars refuse les caractères de contrôle (retours à la ligne et
// tabulations compris, sauf si allowNewline) : ils fausseraient la
// notification Telegram et l'affichage admin.
func hasControlChars(s string, allowNewline bool) bool {
for _, r := range s {
if allowNewline && (r == '\n' || r == '\r') {
continue
}
if unicode.IsControl(r) {
return true
}
}
return false
}
// validPhone : chiffres, espaces, points, tirets et parenthèses, avec un +
// éventuel en tête ; entre 6 et 15 chiffres (borne E.164).
func validPhone(s string) bool {
digits := 0
for i, r := range s {
switch {
case r >= '0' && r <= '9':
digits++
case r == '+' && i == 0:
case r == ' ' || r == '.' || r == '-' || r == '(' || r == ')':
default:
return false
}
}
return digits >= 6 && digits <= 15
}
+100
View File
@@ -0,0 +1,100 @@
package orders
import (
"database/sql/driver"
"encoding/json"
"fmt"
)
const (
ContactSnap = "snap"
ContactInsta = "insta"
ContactTelegram = "telegram"
ContactSimpleX = "simplex"
ContactWhatsapp = "whatsapp"
ContactSignal = "signal"
ContactPhone = "phone"
)
const (
ContactAddress = "address"
ContactHour = "hour"
)
// Contacts : valeurs saisies par le client, stockées en JSONB. Une colonne
// JSON évite une migration à chaque nouvelle option. Le téléphone et les
// notes gardent leurs colonnes dédiées (customer_phone, notes).
type Contacts map[string]string
type InfoSup map[string]string
// Value écrit la map en JSON ; une map nil devient {} (la colonne est NOT NULL).
func (c Contacts) Value() (driver.Value, error) {
if c == nil {
return "{}", nil
}
b, err := json.Marshal(c)
if err != nil {
return nil, err
}
return string(b), nil
}
// Scan lit le JSON renvoyé par la base ; NULL donne une map vide.
func (c *Contacts) Scan(src any) error {
var raw []byte
switch v := src.(type) {
case nil:
*c = Contacts{}
return nil
case []byte:
raw = v
case string:
raw = []byte(v)
default:
return fmt.Errorf("orders: cannot scan %T into Contacts", src)
}
out := Contacts{}
if len(raw) > 0 {
if err := json.Unmarshal(raw, &out); err != nil {
return fmt.Errorf("orders: invalid contacts JSON: %w", err)
}
}
*c = out
return nil
}
func (i InfoSup) Value() (driver.Value, error) {
if i == nil {
return "{}", nil
}
b, err := json.Marshal(i)
if err != nil {
return nil, err
}
return string(b), nil
}
func (i *InfoSup) Scan(src any) error {
var raw []byte
switch v := src.(type) {
case nil:
*i = InfoSup{}
return nil
case []byte:
raw = v
case string:
raw = []byte(v)
default:
return fmt.Errorf("orders: cannot scan %T into Contacts", src)
}
out := InfoSup{}
if len(raw) > 0 {
if err := json.Unmarshal(raw, &out); err != nil {
return fmt.Errorf("orders: invalid contacts JSON: %w", err)
}
}
*i = out
return nil
}
+27 -24
View File
@@ -27,11 +27,11 @@ type itemRequest struct {
}
type createRequest struct {
CustomerName string `json:"customer_name" binding:"required"`
CustomerEmail string `json:"customer_email" binding:"required,email"`
CustomerPhone string `json:"customer_phone"`
Notes string `json:"notes"`
Items []itemRequest `json:"items" binding:"required,min=1,dive"`
CustomerName string `json:"customer_name" binding:"required"`
Contacts Contacts `json:"contacts"`
InfoSup InfoSup `json:"info_sup"`
Notes string `json:"notes"`
Items []itemRequest `json:"items" binding:"required,min=1,dive"`
}
type orderItemResponse struct {
@@ -45,23 +45,23 @@ type orderItemResponse struct {
}
type orderResponse struct {
ID uuid.UUID `json:"id"`
CustomerName string `json:"customer_name"`
CustomerEmail string `json:"customer_email"`
CustomerPhone string `json:"customer_phone"`
TotalCents int64 `json:"total_cents"`
Notes string `json:"notes"`
Items []orderItemResponse `json:"items,omitempty"`
ID uuid.UUID `json:"id"`
CustomerName string `json:"customer_name"`
Contacts Contacts `json:"contacts"`
InfoSup InfoSup `json:"info_sup"`
TotalCents int64 `json:"total_cents"`
Notes string `json:"notes"`
Items []orderItemResponse `json:"items,omitempty"`
}
func toResponse(order *Order, items []*OrderItem) orderResponse {
resp := orderResponse{
ID: order.ID,
CustomerName: order.CustomerName,
CustomerEmail: order.CustomerEmail,
CustomerPhone: order.CustomerPhone,
TotalCents: order.TotalCents,
Notes: order.Notes,
ID: order.ID,
CustomerName: order.CustomerName,
Contacts: order.Contacts,
InfoSup: order.InfoSup,
TotalCents: order.TotalCents,
Notes: order.Notes,
}
for _, item := range items {
resp.Items = append(resp.Items, orderItemResponse{
@@ -103,12 +103,12 @@ func (h *Handler) Create(c *gin.Context) {
}
order, orderItems, err := h.service.Create(c.Request.Context(), CreateInput{
CustomerID: customerID,
CustomerName: req.CustomerName,
CustomerEmail: req.CustomerEmail,
CustomerPhone: req.CustomerPhone,
Notes: req.Notes,
Items: items,
CustomerID: customerID,
CustomerName: req.CustomerName,
Contacts: req.Contacts,
InfoSup: req.InfoSup,
Notes: req.Notes,
Items: items,
})
if err != nil {
h.respondCreateError(c, err)
@@ -137,7 +137,10 @@ func (h *Handler) ListMine(c *gin.Context) {
}
func (h *Handler) respondCreateError(c *gin.Context, err error) {
var fieldErr *FieldError
switch {
case errors.As(err, &fieldErr):
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid field", "field": fieldErr.Field, "reason": fieldErr.Reason})
case errors.Is(err, ErrEmptyOrder), errors.Is(err, ErrProductMismatch):
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
case errors.Is(err, pricing.ErrNotFound):
+9 -9
View File
@@ -15,15 +15,15 @@ import (
)
type Order struct {
ID uuid.UUID `gorm:"type:uuid;primaryKey"`
CustomerID *uuid.UUID `gorm:"type:uuid;index"`
CustomerName string `gorm:"not null"`
CustomerEmail string `gorm:"not null"`
CustomerPhone string `gorm:"not null;default:''"`
TotalCents int64 `gorm:"not null;default:0"`
Notes string `gorm:"not null;default:''"`
CreatedAt time.Time
UpdatedAt time.Time
ID uuid.UUID `gorm:"type:uuid;primaryKey"`
CustomerID *uuid.UUID `gorm:"type:uuid;index"`
CustomerName string `gorm:"not null"`
TotalCents int64 `gorm:"not null;default:0"`
Notes string `gorm:"not null;default:''"`
Contacts Contacts `gorm:"type:jsonb;not null;default:'{}'"`
InfoSup InfoSup `gorm:"type:jsonb;not null;default:'{}'"`
CreatedAt time.Time
UpdatedAt time.Time
}
func (Order) TableName() string { return "orders" }
+41 -15
View File
@@ -4,6 +4,7 @@ import (
"context"
"errors"
"fmt"
"sort"
"strings"
"github.com/google/uuid"
@@ -46,10 +47,11 @@ type Service struct {
units UnitFinder
prices PriceResolver
notifier OrderNotifier
settings CheckoutSettings
}
func NewService(repo Repository, products ProductFinder, units UnitFinder, prices PriceResolver, notifier OrderNotifier) *Service {
return &Service{repo: repo, products: products, units: units, prices: prices, notifier: notifier}
func NewService(repo Repository, products ProductFinder, units UnitFinder, prices PriceResolver, notifier OrderNotifier, settings CheckoutSettings) *Service {
return &Service{repo: repo, products: products, units: units, prices: prices, notifier: notifier, settings: settings}
}
type ItemInput struct {
@@ -59,12 +61,12 @@ type ItemInput struct {
}
type CreateInput struct {
CustomerID *uuid.UUID
CustomerName string
CustomerEmail string
CustomerPhone string
Notes string
Items []ItemInput
CustomerID *uuid.UUID
CustomerName string
Contacts Contacts
InfoSup InfoSup
Notes string
Items []ItemInput
}
func (s *Service) Create(ctx context.Context, in CreateInput) (*Order, []*OrderItem, error) {
@@ -72,13 +74,23 @@ func (s *Service) Create(ctx context.Context, in CreateInput) (*Order, []*OrderI
return nil, nil, ErrEmptyOrder
}
// Les règles du formulaire (champs demandés, obligatoires) sont relues en
// base à chaque commande : le client ne les définit jamais.
checkout, err := s.settings.Get(ctx)
if err != nil {
return nil, nil, fmt.Errorf("load checkout settings: %w", err)
}
if err := applyCheckoutSettings(checkout, &in); err != nil {
return nil, nil, err
}
order := &Order{
ID: uuid.New(),
CustomerID: in.CustomerID,
CustomerName: in.CustomerName,
CustomerEmail: in.CustomerEmail,
CustomerPhone: in.CustomerPhone,
Notes: in.Notes,
ID: uuid.New(),
CustomerID: in.CustomerID,
CustomerName: in.CustomerName,
Contacts: in.Contacts,
InfoSup: in.InfoSup,
Notes: in.Notes,
}
items := make([]*OrderItem, 0, len(in.Items))
@@ -146,7 +158,9 @@ func (s *Service) ListByCustomer(ctx context.Context, customerID uuid.UUID) ([]*
func summarizeNewOrder(order *Order, items []*OrderItem) string {
var b strings.Builder
fmt.Fprintf(&b, "New order from %s (%s)\n", order.CustomerName, order.CustomerEmail)
fmt.Fprintf(&b, "New order from %s\n", order.CustomerName)
writeSorted(&b, order.Contacts)
writeSorted(&b, order.InfoSup)
for _, item := range items {
fmt.Fprintf(&b, "- %dx %s (%.2f %s) = %.2f\n",
item.Multiplier, item.ProductName, item.TierQuantity, item.UnitSymbol, centsToUnits(item.TotalCents))
@@ -158,3 +172,15 @@ func summarizeNewOrder(order *Order, items []*OrderItem) string {
func centsToUnits(cents int64) float64 {
return float64(cents) / 100
}
// writeSorted ajoute "clé: valeur" par ligne, triées pour une notification stable.
func writeSorted(b *strings.Builder, m map[string]string) {
keys := make([]string, 0, len(m))
for k := range m {
keys = append(keys, k)
}
sort.Strings(keys)
for _, k := range keys {
fmt.Fprintf(b, "%s: %s\n", k, m[k])
}
}
@@ -0,0 +1,2 @@
ALTER TABLE orders
ADD COLUMN customer_email TEXT NOT NULL DEFAULT '';
@@ -0,0 +1,2 @@
ALTER TABLE orders
DROP COLUMN customer_email;
@@ -0,0 +1 @@
DROP TABLE IF EXISTS checkout_fields;
@@ -0,0 +1,18 @@
-- Réglages du formulaire de commande (quels champs le client doit renseigner).
-- Une seule ligne : CHECK (id = 1) interdit toute autre ligne, sinon un bug
-- pourrait en créer une 2e et le service lirait l'une ou l'autre au hasard.
CREATE TABLE checkout_fields (
id SMALLINT PRIMARY KEY DEFAULT 1 CHECK (id = 1),
checkout_phone BOOLEAN NOT NULL DEFAULT true,
checkout_address BOOLEAN NOT NULL DEFAULT true,
checkout_snap BOOLEAN NOT NULL DEFAULT false,
checkout_insta BOOLEAN NOT NULL DEFAULT false,
checkout_telegram BOOLEAN NOT NULL DEFAULT false,
checkout_simple_x BOOLEAN NOT NULL DEFAULT false,
checkout_whatsapp BOOLEAN NOT NULL DEFAULT false,
checkout_signal BOOLEAN NOT NULL DEFAULT false,
checkout_notes BOOLEAN NOT NULL DEFAULT false,
checkout_hour BOOLEAN NOT NULL DEFAULT false
);
INSERT INTO checkout_fields (id) VALUES (1);
@@ -0,0 +1,3 @@
ALTER TABLE orders
DROP COLUMN IF EXISTS info_sup,
DROP COLUMN IF EXISTS contacts;
@@ -0,0 +1,5 @@
-- Réponses du client aux options de contact activées par l'admin (adresse,
-- messageries, heure) : une colonne JSON plutôt qu'une colonne par option.
ALTER TABLE orders
ADD COLUMN contacts JSONB NOT NULL DEFAULT '{}'::jsonb,
ADD COLUMN info_sup JSONB NOT NULL DEFAULT '{}'::jsonb;
@@ -0,0 +1,5 @@
ALTER TABLE orders
ADD COLUMN customer_phone TEXT NOT NULL DEFAULT '';
UPDATE orders
SET customer_phone = COALESCE(contacts->>'phone', '');
@@ -0,0 +1,8 @@
-- Le téléphone vit désormais dans contacts->>'phone' avec les messageries
-- (voir 000033) : les anciennes commandes sont recopiées avant de supprimer
-- la colonne.
UPDATE orders
SET contacts = contacts || jsonb_build_object('phone', customer_phone)
WHERE customer_phone <> '';
ALTER TABLE orders DROP COLUMN customer_phone;
@@ -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)
}
}
+255
View File
@@ -0,0 +1,255 @@
package orders_test
import (
"context"
"errors"
"strings"
"testing"
"backend/internal/modules/checkoutfields"
"backend/internal/modules/orders"
)
// create passe une commande valide (un article) avec les réponses données.
func (f *testFixture) create(in orders.CreateInput) (*orders.Order, error) {
in.Items = []orders.ItemInput{{ProductID: f.productID, PriceTierID: f.tierID, Multiplier: 1}}
order, _, err := f.service().Create(context.Background(), in)
return order, err
}
func requireFieldError(t *testing.T, err error, field, reason string) {
t.Helper()
if !errors.Is(err, orders.ErrInvalidField) {
t.Fatalf("erreur = %v, attendu ErrInvalidField", err)
}
var fe *orders.FieldError
if !errors.As(err, &fe) || fe.Field != field || fe.Reason != reason {
t.Fatalf("erreur = %v, attendu champ %q raison %q", err, field, reason)
}
}
func TestCheckout_NameIsAlwaysRequired(t *testing.T) {
for _, name := range []string{"", " "} {
_, err := newFixture().create(orders.CreateInput{CustomerName: name})
requireFieldError(t, err, "customer_name", orders.ReasonRequired)
}
_, err := newFixture().create(orders.CreateInput{CustomerName: strings.Repeat("a", 101)})
requireFieldError(t, err, "customer_name", orders.ReasonTooLong)
}
func TestCheckout_DisabledFieldsAreDroppedNotStored(t *testing.T) {
f := newFixture() // aucune option activée
order, err := f.create(orders.CreateInput{
CustomerName: "Alice",
Notes: "sonnez deux fois",
Contacts: orders.Contacts{orders.ContactPhone: "+33612345678", orders.ContactSnap: "alice"},
InfoSup: orders.InfoSup{orders.ContactAddress: "12 rue de Paris", orders.ContactHour: "18:30"},
})
if err != nil {
t.Fatalf("Create() error = %v (un champ désactivé doit être ignoré, pas refusé)", err)
}
if len(order.Contacts) != 0 || len(order.InfoSup) != 0 || order.Notes != "" {
t.Errorf("réponses à des options désactivées conservées: contacts=%v info_sup=%v notes=%q",
order.Contacts, order.InfoSup, order.Notes)
}
}
func TestCheckout_UnknownKeysAreDropped(t *testing.T) {
f := newFixture()
f.settings.fields.CheckoutSignal = true
order, err := f.create(orders.CreateInput{
CustomerName: "Alice",
Contacts: orders.Contacts{orders.ContactSignal: "alice.01", "admin": "true", "<script>": "x"},
})
if err != nil {
t.Fatal(err)
}
if len(order.Contacts) != 1 || order.Contacts[orders.ContactSignal] != "alice.01" {
t.Errorf("contacts = %v, attendu seulement signal", order.Contacts)
}
}
func TestCheckout_EnabledPhoneAndAddressAreRequired(t *testing.T) {
f := newFixture()
f.settings.fields.CheckoutPhone = true
f.settings.fields.CheckoutAddress = true
_, err := f.create(orders.CreateInput{CustomerName: "Alice", InfoSup: orders.InfoSup{orders.ContactAddress: "1 rue X"}})
requireFieldError(t, err, "phone", orders.ReasonRequired)
_, err = f.create(orders.CreateInput{CustomerName: "Alice", Contacts: orders.Contacts{orders.ContactPhone: "0612345678"}})
requireFieldError(t, err, "address", orders.ReasonRequired)
// Une valeur d'espaces ne compte pas comme une réponse.
_, err = f.create(orders.CreateInput{
CustomerName: "Alice",
Contacts: orders.Contacts{orders.ContactPhone: "0612345678"},
InfoSup: orders.InfoSup{orders.ContactAddress: " "},
})
requireFieldError(t, err, "address", orders.ReasonRequired)
order, err := f.create(orders.CreateInput{
CustomerName: "Alice",
Contacts: orders.Contacts{orders.ContactPhone: " 06 12 34 56 78 "},
InfoSup: orders.InfoSup{orders.ContactAddress: " 1 rue X "},
})
if err != nil {
t.Fatal(err)
}
if order.Contacts[orders.ContactPhone] != "06 12 34 56 78" || order.InfoSup[orders.ContactAddress] != "1 rue X" {
t.Errorf("valeurs non nettoyées: %v %v", order.Contacts, order.InfoSup)
}
}
func TestCheckout_MessengersAreOptionalWhenEnabled(t *testing.T) {
f := newFixture()
f.settings.fields.CheckoutSnap = true
f.settings.fields.CheckoutTelegram = true
f.settings.fields.CheckoutHour = true
order, err := f.create(orders.CreateInput{CustomerName: "Alice", Contacts: orders.Contacts{orders.ContactTelegram: "@alice"}})
if err != nil {
t.Fatalf("Create() error = %v (messageries et heure sont facultatives)", err)
}
if len(order.Contacts) != 1 || order.Contacts[orders.ContactTelegram] != "@alice" {
t.Errorf("contacts = %v", order.Contacts)
}
}
func TestCheckout_PhoneFormat(t *testing.T) {
f := newFixture()
f.settings.fields.CheckoutPhone = true
for _, ok := range []string{"+33612345678", "06 12 34 56 78", "(01) 23-45-67-89", "0612.34.56.78"} {
if _, err := f.create(orders.CreateInput{CustomerName: "A", Contacts: orders.Contacts{orders.ContactPhone: ok}}); err != nil {
t.Errorf("téléphone %q refusé: %v", ok, err)
}
}
for _, bad := range []string{"abc", "12345", "1234567890123456", "06+12345678", "0612345678; DROP TABLE"} {
_, err := f.create(orders.CreateInput{CustomerName: "A", Contacts: orders.Contacts{orders.ContactPhone: bad}})
if !errors.Is(err, orders.ErrInvalidField) {
t.Errorf("téléphone %q accepté (erreur = %v)", bad, err)
}
}
}
func TestCheckout_HourFormat(t *testing.T) {
f := newFixture()
f.settings.fields.CheckoutHour = true
for _, ok := range []string{"00:00", "09:05", "18:30", "23:59"} {
if _, err := f.create(orders.CreateInput{CustomerName: "A", InfoSup: orders.InfoSup{orders.ContactHour: ok}}); err != nil {
t.Errorf("heure %q refusée: %v", ok, err)
}
}
for _, bad := range []string{"24:00", "12:60", "9:30", "1830", "18h30", "ab:cd"} {
_, err := f.create(orders.CreateInput{CustomerName: "A", InfoSup: orders.InfoSup{orders.ContactHour: bad}})
requireFieldError(t, err, "hour", orders.ReasonFormat)
}
}
func TestCheckout_LimitsAndControlCharacters(t *testing.T) {
f := newFixture()
f.settings.fields.CheckoutAddress = true
f.settings.fields.CheckoutSnap = true
f.settings.fields.CheckoutNotes = true
_, err := f.create(orders.CreateInput{CustomerName: "A", InfoSup: orders.InfoSup{orders.ContactAddress: strings.Repeat("a", 301)}})
requireFieldError(t, err, "address", orders.ReasonTooLong)
addr := orders.InfoSup{orders.ContactAddress: "1 rue X"}
_, err = f.create(orders.CreateInput{CustomerName: "A", InfoSup: addr, Contacts: orders.Contacts{orders.ContactSnap: strings.Repeat("a", 101)}})
requireFieldError(t, err, "snap", orders.ReasonTooLong)
// Un retour à la ligne dans un pseudo permettrait de falsifier la notification.
_, err = f.create(orders.CreateInput{CustomerName: "A", InfoSup: addr, Contacts: orders.Contacts{orders.ContactSnap: "alice\nTotal: 0.00"}})
requireFieldError(t, err, "snap", orders.ReasonCharacters)
_, err = f.create(orders.CreateInput{CustomerName: "Alice\nTotal: 0.00", InfoSup: addr})
requireFieldError(t, err, "customer_name", orders.ReasonCharacters)
_, err = f.create(orders.CreateInput{CustomerName: "A", InfoSup: addr, Notes: strings.Repeat("n", 1001)})
requireFieldError(t, err, "notes", orders.ReasonTooLong)
// Les notes et l'adresse peuvent contenir des retours à la ligne.
order, err := f.create(orders.CreateInput{CustomerName: "A", InfoSup: orders.InfoSup{orders.ContactAddress: "1 rue X\nBât. B"}, Notes: "ligne 1\nligne 2"})
if err != nil || order.Notes != "ligne 1\nligne 2" {
t.Errorf("notes multi-lignes refusées ou altérées: %v %q", err, order.Notes)
}
}
func TestCheckout_RejectsOversizedMaps(t *testing.T) {
big := orders.Contacts{}
for i := 0; i < 21; i++ {
big[strings.Repeat("k", i+1)] = "v"
}
_, err := newFixture().create(orders.CreateInput{CustomerName: "A", Contacts: big})
requireFieldError(t, err, "contacts", orders.ReasonTooMany)
}
func TestCheckout_NotesOnlyKeptWhenEnabled(t *testing.T) {
f := newFixture()
f.settings.fields.CheckoutNotes = true
order, err := f.create(orders.CreateInput{CustomerName: "A", Notes: " sans oignons "})
if err != nil || order.Notes != "sans oignons" {
t.Errorf("notes = %q, err = %v", order.Notes, err)
}
}
func TestCheckout_SettingsFailureFailsTheOrder(t *testing.T) {
f := newFixture()
f.settings.err = errors.New("db down")
if _, err := f.create(orders.CreateInput{CustomerName: "A"}); err == nil || errors.Is(err, orders.ErrInvalidField) {
t.Errorf("erreur = %v, attendu une erreur serveur (pas une erreur de champ)", err)
}
if len(f.repo.orders) != 0 {
t.Error("une commande a été créée alors que les réglages n'ont pas pu être lus")
}
}
func TestCheckout_NotificationIncludesAnswersWithoutInjection(t *testing.T) {
f := newFixture()
f.settings.fields.CheckoutPhone = true
f.settings.fields.CheckoutHour = true
if _, err := f.create(orders.CreateInput{
CustomerName: "Alice",
Contacts: orders.Contacts{orders.ContactPhone: "0612345678"},
InfoSup: orders.InfoSup{orders.ContactHour: "18:30"},
}); err != nil {
t.Fatal(err)
}
if len(f.notifier.newOrderCalls) != 1 {
t.Fatalf("%d notifications, attendu 1", len(f.notifier.newOrderCalls))
}
msg := f.notifier.newOrderCalls[0]
for _, want := range []string{"New order from Alice", "phone: 0612345678", "hour: 18:30"} {
if !strings.Contains(msg, want) {
t.Errorf("notification sans %q :\n%s", want, msg)
}
}
}
// Garde-fou : le contrat avec le module checkoutfields (une option activée
// d'un côté doit avoir sa clé de l'autre).
func TestCheckout_EveryOptionHasAKey(t *testing.T) {
all := &checkoutfields.CheckoutField{
CheckoutPhone: true, CheckoutAddress: true, CheckoutSnap: true, CheckoutInsta: true,
CheckoutTelegram: true, CheckoutSimpleX: true, CheckoutWhatsapp: true, CheckoutSignal: true,
CheckoutHour: true,
}
f := newFixture()
f.settings.fields = all
contacts := orders.Contacts{}
for _, k := range []string{orders.ContactPhone, orders.ContactSnap, orders.ContactInsta, orders.ContactTelegram,
orders.ContactSimpleX, orders.ContactWhatsapp, orders.ContactSignal} {
contacts[k] = "0612345678"
}
order, err := f.create(orders.CreateInput{
CustomerName: "A",
Contacts: contacts,
InfoSup: orders.InfoSup{orders.ContactAddress: "1 rue X", orders.ContactHour: "10:00"},
})
if err != nil {
t.Fatal(err)
}
if len(order.Contacts) != 7 || len(order.InfoSup) != 2 {
t.Errorf("contacts=%d (attendu 7) info_sup=%d (attendu 2) : une option n'a pas de clé", len(order.Contacts), len(order.InfoSup))
}
}
+57
View File
@@ -0,0 +1,57 @@
package orders_test
import (
"sync"
"testing"
"gorm.io/gorm/schema"
"backend/internal/modules/orders"
)
// Régression : un champ de type struct sans Valuer/Scanner faisait échouer
// l'analyse du modèle par GORM au premier accès à la base, alors que
// `go build` passait.
func TestOrderModelIsValidForGORM(t *testing.T) {
s, err := schema.Parse(&orders.Order{}, &sync.Map{}, schema.NamingStrategy{})
if err != nil {
t.Fatalf("schema.Parse(Order) error = %v", err)
}
f := s.LookUpField("contacts")
if f == nil {
t.Fatalf("colonne contacts absente (colonnes: %v)", s.DBNames)
}
}
func TestContacts_RoundTrip(t *testing.T) {
in := orders.Contacts{orders.ContactWhatsapp: "+33612345678", orders.ContactHour: "18:30"}
v, err := in.Value()
if err != nil {
t.Fatal(err)
}
var out orders.Contacts
if err := out.Scan(v); err != nil {
t.Fatal(err)
}
if len(out) != 2 || out[orders.ContactWhatsapp] != "+33612345678" || out[orders.ContactHour] != "18:30" {
t.Errorf("relu = %v, attendu %v", out, in)
}
}
func TestContacts_NilAndNullAreEmpty(t *testing.T) {
var nilMap orders.Contacts
v, err := nilMap.Value()
if err != nil || v != "{}" {
t.Errorf("Value(nil) = %v, %v ; attendu \"{}\"", v, err)
}
var out orders.Contacts
if err := out.Scan(nil); err != nil || out == nil || len(out) != 0 {
t.Errorf("Scan(nil) = %v, %v ; attendu une map vide non nil", out, err)
}
if err := out.Scan([]byte(`{`)); err == nil {
t.Error("Scan d'un JSON invalide : erreur attendue")
}
if err := out.Scan(42); err == nil {
t.Error("Scan d'un type inattendu : erreur attendue")
}
}
+99
View File
@@ -0,0 +1,99 @@
package orders_test
import (
"sync"
"testing"
"gorm.io/gorm/schema"
"backend/internal/modules/orders"
)
// Régression : un champ de type map sans Valuer/Scanner faisait échouer
// l'analyse du modèle par GORM au premier accès à la base, alors que
// `go build` passait. Chaque colonne JSONB d'Order est vérifiée ici.
func TestOrderModelHasInfoSupColumn(t *testing.T) {
s, err := schema.Parse(&orders.Order{}, &sync.Map{}, schema.NamingStrategy{})
if err != nil {
t.Fatalf("schema.Parse(Order) error = %v", err)
}
f := s.LookUpField("info_sup")
if f == nil {
t.Fatalf("colonne info_sup absente (colonnes: %v)", s.DBNames)
}
if got := string(f.DataType); got != "jsonb" {
t.Errorf("info_sup : type %q, attendu jsonb", got)
}
}
func TestInfoSup_RoundTrip(t *testing.T) {
in := orders.InfoSup{orders.ContactAddress: "12 rue de Paris", orders.ContactHour: "18:30"}
v, err := in.Value()
if err != nil {
t.Fatal(err)
}
var out orders.InfoSup
if err := out.Scan(v); err != nil {
t.Fatal(err)
}
if len(out) != 2 || out[orders.ContactAddress] != "12 rue de Paris" || out[orders.ContactHour] != "18:30" {
t.Errorf("relu = %v, attendu %v", out, in)
}
}
// La base renvoie du JSONB en []byte (pgx) ou en string selon le driver.
func TestInfoSup_ScanAcceptsBytesAndString(t *testing.T) {
for name, src := range map[string]any{
"bytes": []byte(`{"hour":"09:00"}`),
"string": `{"hour":"09:00"}`,
} {
var out orders.InfoSup
if err := out.Scan(src); err != nil {
t.Errorf("%s : %v", name, err)
continue
}
if out[orders.ContactHour] != "09:00" {
t.Errorf("%s : relu = %v", name, out)
}
}
}
func TestInfoSup_NilAndNullAreEmpty(t *testing.T) {
var nilMap orders.InfoSup
v, err := nilMap.Value()
if err != nil || v != "{}" {
t.Errorf("Value(nil) = %v, %v ; attendu \"{}\"", v, err)
}
var out orders.InfoSup
if err := out.Scan(nil); err != nil || out == nil || len(out) != 0 {
t.Errorf("Scan(nil) = %v, %v ; attendu une map vide non nil", out, err)
}
// Une map vide non nil s'écrit aussi {} (colonne NOT NULL).
if v, err := (orders.InfoSup{}).Value(); err != nil || v != "{}" {
t.Errorf("Value(vide) = %v, %v ; attendu \"{}\"", v, err)
}
}
func TestInfoSup_ScanRejectsInvalidInput(t *testing.T) {
var out orders.InfoSup
if err := out.Scan([]byte(`{`)); err == nil {
t.Error("Scan d'un JSON invalide : erreur attendue")
}
if err := out.Scan(42); err == nil {
t.Error("Scan d'un type inattendu : erreur attendue")
}
}
// Contacts et InfoSup ne doivent pas partager d'état : écrire l'un ne change pas l'autre.
func TestContactsAndInfoSup_AreIndependent(t *testing.T) {
o := orders.Order{
Contacts: orders.Contacts{orders.ContactWhatsapp: "+33612345678"},
InfoSup: orders.InfoSup{orders.ContactHour: "18:30"},
}
if _, ok := o.InfoSup[orders.ContactWhatsapp]; ok {
t.Error("InfoSup contient une clé de Contacts")
}
if _, ok := o.Contacts[orders.ContactHour]; ok {
t.Error("Contacts contient une clé d'InfoSup")
}
}
+25 -9
View File
@@ -7,6 +7,7 @@ import (
"github.com/google/uuid"
"backend/internal/modules/checkoutfields"
"backend/internal/modules/orders"
"backend/internal/modules/pricing"
"backend/internal/modules/products"
@@ -101,6 +102,22 @@ func (f *fakePrices) PriceForQuantity(_ context.Context, tierID uuid.UUID, multi
return t.PriceCents * multiplier, t, nil
}
// fakeSettings sert des réglages de checkout fixes. La valeur par défaut
// (aucune option activée) ne demande rien d'autre que le nom, ce qui laisse
// les tests existants inchangés.
type fakeSettings struct {
fields *checkoutfields.CheckoutField
err error
}
func (s *fakeSettings) Get(context.Context) (*checkoutfields.CheckoutField, error) {
if s.err != nil {
return nil, s.err
}
cp := *s.fields
return &cp, nil
}
type fakeNotifier struct {
newOrderCalls []string
}
@@ -117,6 +134,7 @@ type testFixture struct {
units *fakeUnits
prices *fakePrices
notifier *fakeNotifier
settings *fakeSettings
productID uuid.UUID
unitID uuid.UUID
@@ -140,6 +158,7 @@ func newFixture() *testFixture {
tierID: {ID: tierID, ProductID: productID, UnitID: unitID, Quantity: 5, PriceCents: 4500},
}},
notifier: &fakeNotifier{},
settings: &fakeSettings{fields: &checkoutfields.CheckoutField{ID: 1}},
productID: productID,
unitID: unitID,
tierID: tierID,
@@ -147,7 +166,7 @@ func newFixture() *testFixture {
}
func (f *testFixture) service() *orders.Service {
return orders.NewService(f.repo, f.products, f.units, f.prices, f.notifier)
return orders.NewService(f.repo, f.products, f.units, f.prices, f.notifier, f.settings)
}
func TestService_Create_ComputesTotalAndNotifies(t *testing.T) {
@@ -155,8 +174,7 @@ func TestService_Create_ComputesTotalAndNotifies(t *testing.T) {
svc := f.service()
order, items, err := svc.Create(context.Background(), orders.CreateInput{
CustomerName: "Alice",
CustomerEmail: "alice@example.com",
CustomerName: "Alice",
Items: []orders.ItemInput{
{ProductID: f.productID, PriceTierID: f.tierID, Multiplier: 2},
},
@@ -179,7 +197,7 @@ func TestService_Create_RejectsEmptyOrder(t *testing.T) {
f := newFixture()
svc := f.service()
_, _, err := svc.Create(context.Background(), orders.CreateInput{CustomerName: "Alice", CustomerEmail: "a@example.com"})
_, _, err := svc.Create(context.Background(), orders.CreateInput{CustomerName: "Alice"})
if !errors.Is(err, orders.ErrEmptyOrder) {
t.Fatalf("Create() error = %v, want ErrEmptyOrder", err)
}
@@ -193,8 +211,7 @@ func TestService_Create_RejectsTierProductMismatch(t *testing.T) {
f.products.byID[otherProduct] = &products.Product{ID: otherProduct, Name: "Other", IsActive: true}
_, _, err := svc.Create(context.Background(), orders.CreateInput{
CustomerName: "Alice",
CustomerEmail: "alice@example.com",
CustomerName: "Alice",
Items: []orders.ItemInput{
// tierID actually belongs to f.productID, not otherProduct.
{ProductID: otherProduct, PriceTierID: f.tierID, Multiplier: 1},
@@ -211,9 +228,8 @@ func TestService_List_ReturnsAllOrders(t *testing.T) {
for range 2 {
if _, _, err := svc.Create(context.Background(), orders.CreateInput{
CustomerName: "Alice",
CustomerEmail: "alice@example.com",
Items: []orders.ItemInput{{ProductID: f.productID, PriceTierID: f.tierID, Multiplier: 1}},
CustomerName: "Alice",
Items: []orders.ItemInput{{ProductID: f.productID, PriceTierID: f.tierID, Multiplier: 1}},
}); err != nil {
t.Fatalf("Create() error = %v", err)
}
+2
View File
@@ -13,6 +13,7 @@ import AppearanceSettingsPage from "./features/admin/AppearanceSettingsPage";
import UsersPage from "./features/admin/UsersPage";
import CategoriesPage from "./features/admin/CategoriesPage";
import UnitsPage from "./features/admin/UnitsPage";
import CheckoutFieldsPage from "./features/admin/CheckoutFieldsPage";
import ProductsPage from "./features/admin/ProductsPage";
import ProductEditPage from "./features/admin/ProductEditPage";
import OrdersPage from "./features/admin/OrdersPage";
@@ -74,6 +75,7 @@ export default function App() {
<Route path="products/:id" element={<ProductEditPage />} />
<Route path="orders" element={<OrdersPage />} />
<Route path="orders/:id" element={<OrderDetailPage />} />
<Route path="checkout-fields" element={<CheckoutFieldsPage />} />
<Route path="notifications/telegram" element={<TelegramSettingsPage />} />
<Route path="contact-links" element={<ContactLinksPage />} />
<Route path="customer-accounts" element={<CustomerAccountsPage />} />
+37
View File
@@ -0,0 +1,37 @@
import { apiFetch } from "./client";
// Options the admin can ask the customer for at checkout (the customer's
// name is always asked and is not an option). Mirrors the JSON keys of the
// backend's checkoutfields module.
export const CHECKOUT_OPTION_KEYS = [
"phone",
"address",
"snap",
"insta",
"telegram",
"simplex",
"whatsapp",
"signal",
"notes",
"hour",
] as const;
export type CheckoutOptionKey = (typeof CHECKOUT_OPTION_KEYS)[number];
export type CheckoutOptions = Record<CheckoutOptionKey, boolean>;
// Public: the storefront reads this to know which fields to show.
export function getCheckoutOptions(): Promise<CheckoutOptions> {
return apiFetch<CheckoutOptions>("/api/checkout-fields");
}
export function getAdminCheckoutOptions(): Promise<CheckoutOptions> {
return apiFetch<CheckoutOptions>("/api/admin/checkout-fields");
}
// Replaces every option at once.
export function updateCheckoutOptions(options: CheckoutOptions): Promise<CheckoutOptions> {
return apiFetch<CheckoutOptions>("/api/admin/checkout-fields", {
method: "PUT",
body: JSON.stringify(options),
});
}
+10 -4
View File
@@ -1,8 +1,12 @@
export class ApiError extends Error {
status: number;
constructor(message: string, status: number) {
// Parsed JSON error body, when the server sent one (e.g. the offending
// field and reason of a rejected checkout).
body?: unknown;
constructor(message: string, status: number, body?: unknown) {
super(message);
this.status = status;
this.body = body;
}
}
@@ -57,13 +61,15 @@ function createAuthClient(refreshPath: string, noRetryPaths: string[]): AuthClie
if (!res.ok) {
let message = `Request failed with status ${res.status}`;
let body: unknown;
try {
const body = (await res.json()) as { error?: string };
if (body?.error) message = body.error;
const parsed = (await res.json()) as { error?: string };
body = parsed;
if (parsed?.error) message = parsed.error;
} catch {
// response had no JSON body
}
throw new ApiError(message, res.status);
throw new ApiError(message, res.status, body);
}
// Some endpoints reply 201/200 with no body at all (e.g. attaching a
+25
View File
@@ -0,0 +1,25 @@
import { apiFetch, customerApiFetch } from "./client";
import type { Order } from "./types";
export interface CreateOrderInput {
customer_name: string;
contacts: Record<string, string>;
info_sup: Record<string, string>;
notes: string;
items: { product_id: string; price_tier_id: string; multiplier: number }[];
}
// customerApiFetch attaches the logged-in customer's bearer token so the
// backend's customer/verification gates can authenticate the request.
export function createOrder(input: CreateOrderInput): Promise<Order> {
return customerApiFetch<Order>("/api/orders", { method: "POST", body: JSON.stringify(input) });
}
export async function listAdminOrders(): Promise<Order[]> {
const data = await apiFetch<{ orders: Order[] }>("/api/admin/orders");
return data.orders;
}
export function getAdminOrder(id: string): Promise<Order> {
return apiFetch<Order>(`/api/admin/orders/${id}`);
}
+5 -2
View File
@@ -127,8 +127,11 @@ export interface OrderItem {
export interface Order {
id: string;
customer_name: string;
customer_email: string;
customer_phone: string;
// Answers to the checkout options the admin enabled (see
// api/checkoutFields.ts): phone and messengers in `contacts`, address and
// preferred hour in `info_sup`.
contacts?: Record<string, string>;
info_sup?: Record<string, string>;
total_cents: number;
notes: string;
items?: OrderItem[];
+4 -1
View File
@@ -28,7 +28,10 @@ const NAV_SECTIONS: { titleKey: MessageKey; items: { to: string; labelKey: Messa
},
{
titleKey: "layout.admin.nav.sales",
items: [{ to: "/admin/orders", labelKey: "layout.admin.nav.orders" }],
items: [
{ to: "/admin/orders", labelKey: "layout.admin.nav.orders" },
{ to: "/admin/checkout-fields", labelKey: "layout.admin.nav.checkoutFields" },
],
},
{
titleKey: "layout.admin.nav.communication",
@@ -0,0 +1,81 @@
import { useEffect, useState, type FormEvent } from "react";
import {
getAdminCheckoutOptions,
updateCheckoutOptions,
type CheckoutOptions,
} from "../../api/checkoutFields";
import { useI18n } from "../../i18n/LanguageContext";
import { useToast } from "../../ui/ToastContext";
import { CHECKOUT_FIELDS } from "../checkout/fields";
// Lets the admin choose which details the customer must give when ordering.
// The customer's name is always asked, so it is not listed here.
export default function CheckoutFieldsPage() {
const { t } = useI18n();
const toast = useToast();
const [options, setOptions] = useState<CheckoutOptions | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [saving, setSaving] = useState(false);
useEffect(() => {
getAdminCheckoutOptions()
.then(setOptions)
.catch(() => setError(t("admin.checkoutFields.loadError")))
.finally(() => setLoading(false));
}, [t]);
async function handleSubmit(e: FormEvent) {
e.preventDefault();
if (!options) return;
setSaving(true);
try {
setOptions(await updateCheckoutOptions(options));
toast.success(t("admin.checkoutFields.saved"));
} catch {
toast.error(t("admin.checkoutFields.saveError"));
} finally {
setSaving(false);
}
}
if (loading) return <div className="page-loading">{t("common.loading")}</div>;
return (
<div>
<h1>{t("admin.checkoutFields.title")}</h1>
{error && <div className="alert alert-error">{error}</div>}
{options && (
<div className="panel">
<p style={{ color: "var(--color-text-muted)" }}>{t("admin.checkoutFields.hint")}</p>
<form onSubmit={handleSubmit}>
{CHECKOUT_FIELDS.map((field) => (
<div className="field field-inline" key={field.key}>
<input
id={`option-${field.key}`}
type="checkbox"
checked={options[field.key]}
onChange={(e) => setOptions({ ...options, [field.key]: e.target.checked })}
/>
<label htmlFor={`option-${field.key}`}>
{t(field.labelKey)}
{field.required && (
<span style={{ color: "var(--color-text-muted)", fontSize: "0.85rem" }}>
{" "}
— {t("admin.checkoutFields.requiredWhenEnabled")}
</span>
)}
</label>
</div>
))}
<div className="form-actions">
<button type="submit" className="btn btn-primary" disabled={saving}>
{saving ? t("common.saving") : t("common.save")}
</button>
</div>
</form>
</div>
)}
</div>
);
}
@@ -1,8 +1,9 @@
import { useEffect, useState } from "react";
import { Link, useParams } from "react-router-dom";
import { apiFetch } from "../../api/client";
import { getAdminOrder } from "../../api/orders";
import { formatCents, type Order } from "../../api/types";
import { useI18n } from "../../i18n/LanguageContext";
import { CHECKOUT_FIELDS } from "../checkout/fields";
export default function OrderDetailPage() {
const { t } = useI18n();
@@ -13,7 +14,7 @@ export default function OrderDetailPage() {
function load() {
setLoading(true);
apiFetch<Order>(`/api/admin/orders/${id}`)
getAdminOrder(id!)
.then(setOrder)
.catch(() => setLoadError(t("admin.orderDetail.loadError")))
.finally(() => setLoading(false));
@@ -24,6 +25,18 @@ export default function OrderDetailPage() {
if (loading) return <div className="page-loading">{t("common.loading")}</div>;
if (!order) return <div className="alert alert-error">{t("admin.orderDetail.notFound")}</div>;
// Answers to the options enabled when the order was placed, in the same
// order as the checkout form. Keys the form no longer knows are shown raw
// rather than dropped.
const stored = { ...order.contacts, ...order.info_sup };
const known = new Set<string>(CHECKOUT_FIELDS.map((f) => f.key));
const answers = [
...CHECKOUT_FIELDS.filter((f) => stored[f.key]).map((f) => ({ key: f.key, label: t(f.labelKey), value: stored[f.key] })),
...Object.entries(stored)
.filter(([k, v]) => v && !known.has(k))
.map(([k, v]) => ({ key: k, label: k, value: v })),
];
return (
<div>
<p>
@@ -34,10 +47,17 @@ export default function OrderDetailPage() {
<div className="panel">
<h2>{t("admin.orderDetail.customerTitle")}</h2>
<p>
{order.customer_name} &mdash; {order.customer_email}
{order.customer_phone && ` — ${order.customer_phone}`}
</p>
<p>{order.customer_name}</p>
{answers.length > 0 && (
<dl style={{ margin: 0 }}>
{answers.map((a) => (
<div key={a.key} style={{ display: "flex", gap: "0.5rem" }}>
<dt style={{ color: "var(--color-text-muted)" }}>{a.label} :</dt>
<dd style={{ margin: 0, whiteSpace: "pre-line" }}>{a.value}</dd>
</div>
))}
</dl>
)}
{order.notes && (
<p style={{ color: "var(--color-text-muted)" }}>
{t("admin.orderDetail.notes")} {order.notes}
+5 -5
View File
@@ -1,6 +1,6 @@
import { useEffect, useState } from "react";
import { Link } from "react-router-dom";
import { apiFetch } from "../../api/client";
import { listAdminOrders } from "../../api/orders";
import { formatCents, type Order } from "../../api/types";
import { useI18n } from "../../i18n/LanguageContext";
@@ -12,8 +12,8 @@ export default function OrdersPage() {
useEffect(() => {
setLoading(true);
apiFetch<{ orders: Order[] }>("/api/admin/orders")
.then((data) => setOrders(data.orders))
listAdminOrders()
.then(setOrders)
.catch(() => setError(t("admin.orders.loadError")))
.finally(() => setLoading(false));
}, [t]);
@@ -30,7 +30,7 @@ export default function OrdersPage() {
<thead>
<tr>
<th>{t("admin.orders.colCustomer")}</th>
<th>{t("admin.orders.colEmail")}</th>
<th>{t("admin.orders.colPhone")}</th>
<th>{t("admin.orders.colTotal")}</th>
<th></th>
</tr>
@@ -39,7 +39,7 @@ export default function OrdersPage() {
{orders.map((o) => (
<tr key={o.id}>
<td>{o.customer_name}</td>
<td>{o.customer_email}</td>
<td>{o.contacts?.phone ?? ""}</td>
<td>{formatCents(o.total_cents)}</td>
<td>
<Link className="btn" to={`/admin/orders/${o.id}`}>
+40
View File
@@ -0,0 +1,40 @@
import type { CheckoutOptionKey } from "../../api/checkoutFields";
import type { MessageKey } from "../../i18n/messages";
// Where a checkout answer is sent (and stored): `contacts` holds the phone
// and messengers, `info_sup` the address and preferred hour, `notes` the
// free-text note. Same split as the backend's orders module.
export type CheckoutTarget = "contacts" | "info_sup" | "notes";
export interface CheckoutFieldDef {
key: CheckoutOptionKey;
target: CheckoutTarget;
input: "tel" | "text" | "textarea" | "time";
// The backend refuses an enabled option left empty only for these two.
required: boolean;
maxLength: number;
labelKey: MessageKey;
}
// Order = display order on the checkout form and in the admin settings.
export const CHECKOUT_FIELDS: CheckoutFieldDef[] = [
{ key: "phone", target: "contacts", input: "tel", required: true, maxLength: 30, labelKey: "checkout.field.phone" },
{ key: "address", target: "info_sup", input: "textarea", required: true, maxLength: 300, labelKey: "checkout.field.address" },
{ key: "hour", target: "info_sup", input: "time", required: false, maxLength: 5, labelKey: "checkout.field.hour" },
{ key: "snap", target: "contacts", input: "text", required: false, maxLength: 100, labelKey: "checkout.field.snap" },
{ key: "insta", target: "contacts", input: "text", required: false, maxLength: 100, labelKey: "checkout.field.insta" },
{ key: "telegram", target: "contacts", input: "text", required: false, maxLength: 100, labelKey: "checkout.field.telegram" },
{ key: "simplex", target: "contacts", input: "text", required: false, maxLength: 100, labelKey: "checkout.field.simplex" },
{ key: "whatsapp", target: "contacts", input: "text", required: false, maxLength: 100, labelKey: "checkout.field.whatsapp" },
{ key: "signal", target: "contacts", input: "text", required: false, maxLength: 100, labelKey: "checkout.field.signal" },
{ key: "notes", target: "notes", input: "textarea", required: false, maxLength: 1000, labelKey: "checkout.field.notes" },
];
// Reasons the backend can give for a rejected field.
export const CHECKOUT_REASON_KEYS: Record<string, MessageKey> = {
required: "checkout.reason.required",
too_long: "checkout.reason.tooLong",
invalid_format: "checkout.reason.invalidFormat",
invalid_characters: "checkout.reason.invalidCharacters",
too_many_fields: "checkout.reason.tooManyFields",
};
@@ -1,12 +1,23 @@
import { useState, type FormEvent } from "react";
import { Link, useNavigate } from "react-router-dom";
import { ApiError, customerApiFetch } from "../../api/client";
import type { Order } from "../../api/types";
import { ApiError } from "../../api/client";
import { createOrder } from "../../api/orders";
import { useCart } from "./CartContext";
import { useCustomerAuth } from "./CustomerAuthContext";
import { useSiteSettings } from "./SiteSettingsContext";
import { useCheckoutOptions } from "./useCheckoutOptions";
import { CHECKOUT_FIELDS, CHECKOUT_REASON_KEYS } from "../checkout/fields";
import { useI18n } from "../../i18n/LanguageContext";
// The backend answers 400 {error: "invalid field", field, reason} for a
// refused checkout answer.
function rejectedField(err: unknown): { field: string; reason: string } | null {
if (!(err instanceof ApiError) || err.status !== 400) return null;
const body = err.body as { field?: unknown; reason?: unknown } | undefined;
if (typeof body?.field !== "string" || typeof body?.reason !== "string") return null;
return { field: body.field, reason: body.reason };
}
export default function CheckoutPage() {
const { t } = useI18n();
const { items, totalCents, clear } = useCart();
@@ -14,10 +25,11 @@ export default function CheckoutPage() {
const site = useSiteSettings();
const navigate = useNavigate();
const { options } = useCheckoutOptions();
const [name, setName] = useState("");
const [email, setEmail] = useState("");
const [phone, setPhone] = useState("");
const [notes, setNotes] = useState("");
// One answer per enabled option, keyed by option key (phone, address, ...).
const [answers, setAnswers] = useState<Record<string, string>>({});
const [submitting, setSubmitting] = useState(false);
const [error, setError] = useState<string | null>(null);
@@ -62,27 +74,41 @@ export default function CheckoutPage() {
setSubmitting(true);
setError(null);
try {
// customerApiFetch attaches the logged-in customer's bearer token
// (when there is one) so RequireCustomer/RequireApprovedVerification
// can authenticate the request; guests simply send no token.
const order = await customerApiFetch<Order>("/api/orders", {
method: "POST",
body: JSON.stringify({
customer_name: name,
customer_email: email,
customer_phone: phone,
notes,
items: items.map((item) => ({
product_id: item.productId,
price_tier_id: item.priceTierId,
multiplier: item.multiplier,
})),
}),
// Only the options the admin enabled are sent; the server re-checks
// them against the real settings and ignores anything else.
const contacts: Record<string, string> = {};
const infoSup: Record<string, string> = {};
let notes = "";
for (const field of CHECKOUT_FIELDS) {
if (!options?.[field.key]) continue;
const value = (answers[field.key] ?? "").trim();
if (field.target === "contacts") contacts[field.key] = value;
else if (field.target === "info_sup") infoSup[field.key] = value;
else notes = value;
}
const order = await createOrder({
customer_name: name,
contacts,
info_sup: infoSup,
notes,
items: items.map((item) => ({
product_id: item.productId,
price_tier_id: item.priceTierId,
multiplier: item.multiplier,
})),
});
clear();
navigate("/order-confirmation", { state: { order } });
} catch (err) {
if (err instanceof ApiError && (err.status === 403 || err.status === 401)) {
const rejected = rejectedField(err);
if (rejected) {
// The server named the field it refused: say which one and why.
const def = CHECKOUT_FIELDS.find((f) => f.key === rejected.field);
const field = def ? t(def.labelKey) : rejected.field === "customer_name" ? t("storefront.checkout.fullName") : rejected.field;
const reasonKey = CHECKOUT_REASON_KEYS[rejected.reason];
setError(t("storefront.checkout.invalidField", { field, reason: reasonKey ? t(reasonKey) : rejected.reason }));
} else if (err instanceof ApiError && (err.status === 403 || err.status === 401)) {
// Surface the backend's own message: it explains *why* checkout is
// blocked (e.g. "ordering requires a customer account, which is
// currently disabled" or "identity verification must be approved
@@ -106,29 +132,41 @@ export default function CheckoutPage() {
<label htmlFor="name">{t("storefront.checkout.fullName")}</label>
<input id="name" value={name} onChange={(e) => setName(e.target.value)} required />
</div>
<div className="field">
<label htmlFor="checkout-email">{t("storefront.checkout.email")}</label>
<input
id="checkout-email"
type="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
required
/>
</div>
<div className="field">
<label htmlFor="phone">{t("storefront.checkout.phone")}</label>
<input id="phone" value={phone} onChange={(e) => setPhone(e.target.value)} />
</div>
<div className="field">
<label htmlFor="notes">{t("storefront.checkout.notes")}</label>
<textarea id="notes" rows={3} value={notes} onChange={(e) => setNotes(e.target.value)} />
</div>
{options &&
CHECKOUT_FIELDS.filter((field) => options[field.key]).map((field) => {
const id = `checkout-${field.key}`;
const value = answers[field.key] ?? "";
const onChange = (v: string) => setAnswers((prev) => ({ ...prev, [field.key]: v }));
return (
<div className="field" key={field.key}>
<label htmlFor={id}>{t(field.labelKey)}</label>
{field.input === "textarea" ? (
<textarea
id={id}
rows={3}
value={value}
maxLength={field.maxLength}
required={field.required}
onChange={(e) => onChange(e.target.value)}
/>
) : (
<input
id={id}
type={field.input}
value={value}
maxLength={field.maxLength}
required={field.required}
onChange={(e) => onChange(e.target.value)}
/>
)}
</div>
);
})}
<p>
<strong>{t("storefront.checkout.total", { amount: (totalCents / 100).toFixed(2) })}</strong>
</p>
<div className="form-actions">
<button type="submit" className="btn btn-primary" disabled={submitting}>
<button type="submit" className="btn btn-primary" disabled={submitting || !options}>
{submitting ? t("storefront.checkout.submitting") : t("storefront.checkout.submit")}
</button>
</div>
@@ -0,0 +1,32 @@
import { useEffect, useState } from "react";
import { getCheckoutOptions, type CheckoutOptions } from "../../api/checkoutFields";
// Same as the migration's defaults: if the settings cannot be read the form
// still asks for the essentials, and the server stays the source of truth
// (it validates every order against the real settings).
const FALLBACK: CheckoutOptions = {
phone: true,
address: true,
snap: false,
insta: false,
telegram: false,
simplex: false,
whatsapp: false,
signal: false,
notes: false,
hour: false,
};
// Not cached on purpose: the admin can change the options at any time and a
// checkout should reflect them on the next visit.
export function useCheckoutOptions(): { options: CheckoutOptions | null } {
const [options, setOptions] = useState<CheckoutOptions | null>(null);
useEffect(() => {
getCheckoutOptions()
.then(setOptions)
.catch(() => setOptions(FALLBACK));
}, []);
return { options };
}
+24 -2
View File
@@ -250,7 +250,7 @@ export const messages = {
"admin.orders.title": { en: "Orders", fr: "Commandes", es: "Pedidos", de: "Bestellungen" },
"admin.orders.loadError": { en: "Failed to load orders.", fr: "Échec du chargement des commandes.", es: "No se pudieron cargar los pedidos.", de: "Bestellungen konnten nicht geladen werden." },
"admin.orders.colCustomer": { en: "Customer", fr: "Client", es: "Cliente", de: "Kunde" },
"admin.orders.colEmail": { en: "Email", fr: "E-mail", es: "Correo electrónico", de: "E-Mail" },
"admin.orders.colPhone": { en: "Phone", fr: "Téléphone", es: "Teléfono", de: "Telefon" },
"admin.orders.colTotal": { en: "Total", fr: "Total", es: "Total", de: "Gesamt" },
"admin.orders.view": { en: "View", fr: "Voir", es: "Ver", de: "Ansehen" },
@@ -385,6 +385,29 @@ export const messages = {
"storefront.cart.total": { en: "Total: {{amount}}", fr: "Total : {{amount}}", es: "Total: {{amount}}", de: "Gesamt: {{amount}}" },
"storefront.cart.checkout": { en: "Checkout", fr: "Commander", es: "Pagar", de: "Zur Kasse" },
"layout.admin.nav.checkoutFields": { en: "Checkout fields", fr: "Champs de commande", es: "Campos del pedido", de: "Bestellfelder" },
"admin.checkoutFields.title": { en: "Checkout fields", fr: "Champs de commande", es: "Campos del pedido", de: "Bestellfelder" },
"admin.checkoutFields.hint": { en: "Choose what the customer has to provide when ordering. The customer's name is always asked.", fr: "Choisissez ce que le client doit renseigner à la commande. Le nom du client est toujours demandé.", es: "Elige qué debe indicar el cliente al pedir. El nombre del cliente siempre se solicita.", de: "Wählen Sie, was der Kunde bei der Bestellung angeben muss. Der Name des Kunden wird immer abgefragt." },
"admin.checkoutFields.requiredWhenEnabled": { en: "required when enabled", fr: "obligatoire si activé", es: "obligatorio si se activa", de: "Pflichtfeld, wenn aktiviert" },
"admin.checkoutFields.loadError": { en: "Failed to load the checkout fields.", fr: "Échec du chargement des champs de commande.", es: "No se pudieron cargar los campos del pedido.", de: "Bestellfelder konnten nicht geladen werden." },
"admin.checkoutFields.saved": { en: "Checkout fields saved.", fr: "Champs de commande enregistrés.", es: "Campos del pedido guardados.", de: "Bestellfelder gespeichert." },
"admin.checkoutFields.saveError": { en: "Failed to save the checkout fields.", fr: "Échec de l'enregistrement des champs de commande.", es: "No se pudieron guardar los campos del pedido.", de: "Bestellfelder konnten nicht gespeichert werden." },
"checkout.field.phone": { en: "Phone", fr: "Téléphone", es: "Teléfono", de: "Telefon" },
"checkout.field.address": { en: "Address", fr: "Adresse", es: "Dirección", de: "Adresse" },
"checkout.field.hour": { en: "Preferred time", fr: "Heure souhaitée", es: "Hora preferida", de: "Gewünschte Uhrzeit" },
"checkout.field.snap": { en: "Snapchat", fr: "Snapchat", es: "Snapchat", de: "Snapchat" },
"checkout.field.insta": { en: "Instagram", fr: "Instagram", es: "Instagram", de: "Instagram" },
"checkout.field.telegram": { en: "Telegram", fr: "Telegram", es: "Telegram", de: "Telegram" },
"checkout.field.simplex": { en: "SimpleX", fr: "SimpleX", es: "SimpleX", de: "SimpleX" },
"checkout.field.whatsapp": { en: "WhatsApp", fr: "WhatsApp", es: "WhatsApp", de: "WhatsApp" },
"checkout.field.signal": { en: "Signal", fr: "Signal", es: "Signal", de: "Signal" },
"checkout.field.notes": { en: "Notes", fr: "Notes", es: "Notas", de: "Notizen" },
"checkout.reason.required": { en: "required", fr: "obligatoire", es: "obligatorio", de: "erforderlich" },
"checkout.reason.tooLong": { en: "too long", fr: "trop long", es: "demasiado largo", de: "zu lang" },
"checkout.reason.invalidFormat": { en: "invalid format", fr: "format invalide", es: "formato no válido", de: "ungültiges Format" },
"checkout.reason.invalidCharacters": { en: "invalid characters", fr: "caractères invalides", es: "caracteres no válidos", de: "ungültige Zeichen" },
"checkout.reason.tooManyFields": { en: "too many fields", fr: "trop de champs", es: "demasiados campos", de: "zu viele Felder" },
"storefront.checkout.invalidField": { en: "Invalid information: {{field}} ({{reason}}).", fr: "Information invalide : {{field}} ({{reason}}).", es: "Información no válida: {{field}} ({{reason}}).", de: "Ungültige Angabe: {{field}} ({{reason}})." },
// --- storefront checkout ---
"storefront.checkout.title": { en: "Checkout", fr: "Commande", es: "Pago", de: "Kasse" },
"storefront.checkout.emptyCart": { en: "Your cart is empty.", fr: "Votre panier est vide.", es: "Tu carrito está vacío.", de: "Dein Warenkorb ist leer." },
@@ -394,7 +417,6 @@ export const messages = {
"storefront.checkout.loginRequiredLink": { en: "Sign in or create one", fr: "Connectez-vous ou créez-en un", es: "Inicia sesión o crea una", de: "Anmelden oder eins erstellen" },
"storefront.checkout.loginRequiredSuffix": { en: ", then come back to checkout.", fr: ", puis revenez commander.", es: ", y luego vuelve a pagar.", de: ", und kehre dann zur Kasse zurück." },
"storefront.checkout.fullName": { en: "Full name", fr: "Nom complet", es: "Nombre completo", de: "Vollständiger Name" },
"storefront.checkout.email": { en: "Email", fr: "E-mail", es: "Correo electrónico", de: "E-Mail" },
"storefront.checkout.phone": { en: "Phone", fr: "Téléphone", es: "Teléfono", de: "Telefon" },
"storefront.checkout.notes": { en: "Notes", fr: "Notes", es: "Notas", de: "Notizen" },
"storefront.checkout.total": { en: "Total: {{amount}}", fr: "Total : {{amount}}", es: "Total: {{amount}}", de: "Gesamt: {{amount}}" },