Files
template-vitrine/backend/internal/modules/orders/service.go
T
Xor290andClaude Sonnet 5.5 f9bfdc9d3c
ci-api / test (push) Successful in 20m38s
ci-web / test (push) Successful in 11m20s
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>
2026-10-04 16:16:22 +02:00

187 lines
5.0 KiB
Go

package orders
import (
"context"
"errors"
"fmt"
"sort"
"strings"
"github.com/google/uuid"
"backend/internal/modules/pricing"
"backend/internal/modules/products"
"backend/internal/modules/units"
)
var (
ErrEmptyOrder = errors.New("order must contain at least one item")
ErrProductMismatch = errors.New("price tier does not belong to the requested product")
)
// The dependencies below are the minimal slices of other modules' services
// this module needs, defined on the consumer side (Go idiom) so orders
// never has to import their concrete handler/repository types.
type ProductFinder interface {
Get(ctx context.Context, id uuid.UUID) (*products.Product, error)
}
type UnitFinder interface {
Get(ctx context.Context, id uuid.UUID) (*units.Unit, error)
}
type PriceResolver interface {
PriceForQuantity(ctx context.Context, tierID uuid.UUID, multiplier int64) (int64, *pricing.PriceTier, error)
}
// OrderNotifier is satisfied by the telegram module's Service (and, later,
// any other notification channel) without orders ever depending on it
// directly.
type OrderNotifier interface {
NotifyNewOrder(ctx context.Context, summary string)
}
type Service struct {
repo Repository
products ProductFinder
units UnitFinder
prices PriceResolver
notifier OrderNotifier
settings CheckoutSettings
}
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 {
ProductID uuid.UUID
PriceTierID uuid.UUID
Multiplier int64
}
type CreateInput struct {
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) {
if len(in.Items) == 0 {
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,
Contacts: in.Contacts,
InfoSup: in.InfoSup,
Notes: in.Notes,
}
items := make([]*OrderItem, 0, len(in.Items))
var total int64
for _, in := range in.Items {
multiplier := in.Multiplier
if multiplier < 1 {
multiplier = 1
}
lineTotal, tier, err := s.prices.PriceForQuantity(ctx, in.PriceTierID, multiplier)
if err != nil {
return nil, nil, fmt.Errorf("resolve price tier %s: %w", in.PriceTierID, err)
}
if tier.ProductID != in.ProductID {
return nil, nil, ErrProductMismatch
}
product, err := s.products.Get(ctx, in.ProductID)
if err != nil {
return nil, nil, fmt.Errorf("resolve product %s: %w", in.ProductID, err)
}
unit, err := s.units.Get(ctx, tier.UnitID)
if err != nil {
return nil, nil, fmt.Errorf("resolve unit %s: %w", tier.UnitID, err)
}
items = append(items, &OrderItem{
ID: uuid.New(),
ProductID: &product.ID,
ProductName: product.Name,
PriceTierID: &tier.ID,
UnitSymbol: unit.Symbol,
TierQuantity: tier.Quantity,
Multiplier: multiplier,
UnitPriceCents: tier.PriceCents,
TotalCents: lineTotal,
})
total += lineTotal
}
order.TotalCents = total
if err := s.repo.Create(ctx, order, items); err != nil {
return nil, nil, err
}
s.notifier.NotifyNewOrder(context.Background(), summarizeNewOrder(order, items))
return order, items, nil
}
func (s *Service) Get(ctx context.Context, id uuid.UUID) (*Order, []*OrderItem, error) {
return s.repo.FindByID(ctx, id)
}
func (s *Service) List(ctx context.Context) ([]*Order, error) {
return s.repo.List(ctx)
}
func (s *Service) ListByCustomer(ctx context.Context, customerID uuid.UUID) ([]*Order, error) {
return s.repo.ListByCustomer(ctx, customerID)
}
func summarizeNewOrder(order *Order, items []*OrderItem) string {
var b strings.Builder
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))
}
fmt.Fprintf(&b, "Total: %.2f", centsToUnits(order.TotalCents))
return b.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])
}
}