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)
}
}
+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)
}