feat(checkout): let the admin choose the details asked at checkout
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:
co-authored by
Claude Sonnet 5.5
parent
178652ef14
commit
f9bfdc9d3c
@@ -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
|
||||
}
|
||||
@@ -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,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):
|
||||
|
||||
@@ -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" }
|
||||
|
||||
@@ -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])
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user