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,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
|
||||
}
|
||||
Reference in New Issue
Block a user