chore: build
Backend - Build & Lint / build (push) Successful in 31m25s
Frontend Admin - EAS Build / build (push) Successful in 1h24m40s

This commit is contained in:
Xor290
2026-11-15 22:05:14 +01:00
parent 3ce40dd2be
commit beb78bf062
14 changed files with 1204 additions and 35 deletions
+12
View File
@@ -1,6 +1,7 @@
package db
import (
"errors"
"fmt"
"log"
"slices"
@@ -348,6 +349,12 @@ func (d *Database) CancelCommandByAdminAtomic(commandID int) error {
return fmt.Errorf("commande non trouvée")
}
prevStatus := cmd.Status
if prevStatus == "cancelled" {
return nil
}
if prevStatus == "approved" {
return ErrCommandLocked
}
noRestoreStatuses := []string{"cancelled", "approved", "livre"}
if !slices.Contains(noRestoreStatuses, prevStatus) {
@@ -395,6 +402,9 @@ func (d *Database) CancelDeliveryByLivreurAtomic(commandID int) (alreadyCancelle
alreadyCancelled = true
return nil
}
if prevStatus == "livre" || prevStatus == "approved" {
return ErrCommandAlreadyDelivered
}
result := tx.Exec(`
UPDATE commandes SET status = 'cancelled', updated_at = CURRENT_TIMESTAMP
@@ -428,3 +438,5 @@ func (d *Database) CancelDeliveryByLivreurAtomic(commandID int) (alreadyCancelle
})
return
}
var ErrCommandAlreadyDelivered = errors.New("commande déjà livrée : annulation impossible")
+51 -16
View File
@@ -6,7 +6,9 @@ import (
"fmt"
"gestion/models"
"log"
"math"
"slices"
"sort"
"strings"
"time"
@@ -58,6 +60,34 @@ type basketItem struct {
PromoDiscount float64 `gorm:"column:promo_discount"`
}
// Les articles récompense sont des produits physiques : ils sortent du stock comme les autres.
func decrementBasketStockTx(tx *gorm.DB, items []basketItem) error {
totals := make(map[int]float64)
for _, item := range items {
totals[item.ProductID] += item.Quantity
}
ids := make([]int, 0, len(totals))
for id := range totals {
totals[id] = math.Round(totals[id]*1000) / 1000
ids = append(ids, id)
}
sort.Ints(ids)
for _, id := range ids {
var currentStock float64
if err := tx.Raw(`SELECT stock FROM products WHERE id = ? FOR UPDATE`, id).Scan(&currentStock).Error; err != nil {
return fmt.Errorf("erreur lecture stock produit %d: %w", id, err)
}
if currentStock < totals[id] {
return fmt.Errorf("stock insuffisant pour le produit %d", id)
}
if err := tx.Exec(`UPDATE products SET stock = stock - ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?`, totals[id], id).Error; err != nil {
return fmt.Errorf("erreur décrémentation stock produit %d: %w", id, err)
}
}
return nil
}
// validateCommandStatus vérifie si le statut est valide
func validateCommandStatus(status string) error {
validStatuses := map[string]bool{
@@ -128,6 +158,14 @@ func (d *Database) CreateCommandWithAddress(username, deliveryAddress string) (*
return fmt.Errorf("montant de commande invalide: %.2f€", totalPrix)
}
// Stock verrouillé avant l'insertion des command_items : leur clé étrangère
// pose un verrou partagé sur products, et le reprendre ensuite en FOR UPDATE
// provoquait des deadlocks entre checkouts simultanés. Ordre par id pour la
// même raison quand plusieurs produits sont commandés.
if err := decrementBasketStockTx(tx, basketItems); err != nil {
return err
}
var cmdResult struct {
ID int `gorm:"column:id"`
ClientOrderID int `gorm:"column:client_order_id"`
@@ -176,21 +214,6 @@ func (d *Database) CreateCommandWithAddress(username, deliveryAddress string) (*
return fmt.Errorf("erreur insertion items: %w", err)
}
// Les articles récompense (payés en points) restent des produits physiques
// réellement distribués : le stock doit être décrémenté comme pour un
// article payant.
for _, item := range basketItems {
var currentStock float64
if err := tx.Raw(`SELECT stock FROM products WHERE id = ? FOR UPDATE`, item.ProductID).Scan(&currentStock).Error; err != nil {
return fmt.Errorf("erreur lecture stock produit %d: %w", item.ProductID, err)
}
if currentStock < item.Quantity {
return fmt.Errorf("stock insuffisant pour le produit %d", item.ProductID)
}
if err := tx.Exec(`UPDATE products SET stock = stock - ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?`, item.Quantity, item.ProductID).Error; err != nil {
return fmt.Errorf("erreur décrémentation stock produit %d: %w", item.ProductID, err)
}
}
if err := tx.Exec(`DELETE FROM baskets WHERE username = ?`, username).Error; err != nil {
return err
}
@@ -561,7 +584,9 @@ func (d *Database) UpdateCommandStatus(commandID int, status string) error {
return err
}
result := d.GDB.Model(&models.Command{}).Where("id = ?", commandID).Updates(map[string]any{
result := d.GDB.Model(&models.Command{}).
Where("id = ? AND status NOT IN ?", commandID, lockedCommandStatuses).
Updates(map[string]any{
"status": status,
"updated_at": time.Now(),
})
@@ -569,12 +594,22 @@ func (d *Database) UpdateCommandStatus(commandID int, status string) error {
return fmt.Errorf("erreur lors de la mise à jour du statut: %w", result.Error)
}
if result.RowsAffected == 0 {
var exists bool
d.GDB.Raw(`SELECT EXISTS(SELECT 1 FROM commandes WHERE id = ?)`, commandID).Scan(&exists)
if exists {
return ErrCommandLocked
}
return fmt.Errorf("commande non trouvée")
}
return nil
}
// Une commande annulée ou approuvée ne change plus de statut : le stock a déjà été rendu ou est parti.
var lockedCommandStatuses = []string{"cancelled", "approved"}
var ErrCommandLocked = errors.New("commande annulée ou approuvée : statut non modifiable")
func (d *Database) AddCommandLog(commandID int, status, message, author string) error {
sanitizedMessage := sanitizeLogMessage(message)
sanitizedAuthor := sanitizeLogMessage(author)
+18 -1
View File
@@ -105,6 +105,23 @@ func InitDB() *Database {
log.Fatalf("❌ Erreur migration unit products: %v", err)
}
// Migration: products.stock 2 → 3 décimales, même précision que les quantités commandées (0,001 g)
if _, err = database.Exec(`
DO $$
BEGIN
IF EXISTS (
SELECT 1 FROM information_schema.columns
WHERE table_name = 'products' AND column_name = 'stock'
AND numeric_scale IS DISTINCT FROM 3
) THEN
ALTER TABLE products ALTER COLUMN stock TYPE NUMERIC(10,3);
END IF;
END
$$;
`); err != nil {
log.Fatalf("❌ Erreur migration products.stock: %v", err)
}
// Migration: baskets.quantity INTEGER → NUMERIC(10,3) pour supporter les quantités fractionnaires (ex: 0.5g)
if _, err = database.Exec(`
DO $$
@@ -404,7 +421,7 @@ func (db *Database) createTables() error {
id SERIAL PRIMARY KEY,
name VARCHAR(255) NOT NULL,
category VARCHAR(100) NOT NULL,
stock DECIMAL(10,2) NOT NULL DEFAULT 0,
stock NUMERIC(10,3) NOT NULL DEFAULT 0,
unit VARCHAR(10) NOT NULL DEFAULT 'u',
description TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
+14
View File
@@ -326,3 +326,17 @@ func (d *Database) GetProductNameByID(productID int) (string, error) {
}
return result.Name, nil
}
// CountOpenProductUsage compte les paniers et les commandes non terminées contenant le produit.
func (d *Database) CountOpenProductUsage(productID int) (baskets int, commands int, err error) {
if err = d.GDB.Raw(`SELECT COUNT(DISTINCT username) FROM baskets WHERE product_id = ?`, productID).Scan(&baskets).Error; err != nil {
return 0, 0, fmt.Errorf("erreur comptage paniers: %w", err)
}
if err = d.GDB.Raw(`
SELECT COUNT(DISTINCT c.id) FROM command_items ci
JOIN commandes c ON c.id = ci.command_id
WHERE ci.product_id = ? AND c.status NOT IN ('cancelled', 'approved', 'livre')`, productID).Scan(&commands).Error; err != nil {
return 0, 0, fmt.Errorf("erreur comptage commandes: %w", err)
}
return baskets, commands, nil
}
+9
View File
@@ -4,6 +4,7 @@ import (
"bytes"
"encoding/csv"
"encoding/json"
"errors"
"fmt"
"gestion/db"
"gestion/services"
@@ -1332,6 +1333,10 @@ func UpdateCommandStatusAdmin(c *gin.Context) {
switch req.Status {
case "cancelled":
if err := database.CancelCommandByAdminAtomic(commandID); err != nil {
if errors.Is(err, db.ErrCommandLocked) {
c.JSON(http.StatusConflict, gin.H{"error": "Commande approuvée : annulation impossible"})
return
}
utils.ServerErr(c, "Impossible d'annuler la commande", err)
return
}
@@ -1349,6 +1354,10 @@ func UpdateCommandStatusAdmin(c *gin.Context) {
}
default:
if err := database.UpdateCommandStatus(commandID, req.Status); err != nil {
if errors.Is(err, db.ErrCommandLocked) {
c.JSON(http.StatusConflict, gin.H{"error": "Commande annulée ou approuvée : statut non modifiable"})
return
}
utils.ServerErr(c, "Impossible de mettre à jour le statut", err)
return
}
+32
View File
@@ -2,6 +2,7 @@ package handlers
import (
"encoding/json"
"errors"
"fmt"
"gestion/db"
"gestion/models"
@@ -184,6 +185,13 @@ func GetDeliveryDetails(c *gin.Context) {
})
}
// Le livreur avance dans l'ordre : assignée → en route → arrivé → livrée.
var livreurNextStatus = map[string]string{
"assigned": "en_route",
"en_route": "arrived",
"arrived": "livre",
}
func UpdateDeliveryStatus(c *gin.Context) {
database := c.MustGet("database").(*db.Database)
@@ -248,6 +256,22 @@ func UpdateDeliveryStatus(c *gin.Context) {
return
}
currentStatus, _ := command["status"].(string)
if req.Status != "cancelled" {
if currentStatus == req.Status {
c.JSON(http.StatusOK, gin.H{"success": true, "message": "Statut déjà à jour", "command_id": commandID, "status": currentStatus})
return
}
if livreurNextStatus[currentStatus] != req.Status {
c.JSON(http.StatusConflict, gin.H{
"error": "Transition de statut non autorisée",
"current_status": currentStatus,
"received": req.Status,
})
return
}
}
if req.Status == "livre" {
if req.Latitude == 0 || req.Longitude == 0 {
c.JSON(http.StatusBadRequest, gin.H{"error": "Coordonnées GPS requises pour confirmer la livraison"})
@@ -273,6 +297,10 @@ func UpdateDeliveryStatus(c *gin.Context) {
// double appel (double-tap, retry réseau, commande déjà annulée ailleurs).
if req.Status == "cancelled" {
alreadyCancelled, prevStatus, cancelErr := database.CancelDeliveryByLivreurAtomic(commandID)
if errors.Is(cancelErr, db.ErrCommandAlreadyDelivered) {
c.JSON(http.StatusConflict, gin.H{"error": "Commande déjà livrée : annulation impossible"})
return
}
if cancelErr != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"error": "Erreur mise à jour",
@@ -306,6 +334,10 @@ func UpdateDeliveryStatus(c *gin.Context) {
}
}
} else if err := database.UpdateCommandStatus(commandID, req.Status); err != nil {
if errors.Is(err, db.ErrCommandLocked) {
c.JSON(http.StatusConflict, gin.H{"error": "Commande annulée ou approuvée : statut non modifiable"})
return
}
c.JSON(http.StatusInternalServerError, gin.H{
"error": "Erreur mise à jour",
})
+20 -1
View File
@@ -510,7 +510,7 @@ func UpdateProduct(c *gin.Context) {
return
}
_, err = database.GetProductByID(id)
current, err := database.GetProductByID(id)
if err != nil {
c.JSON(http.StatusNotFound, gin.H{"error": "Produit non trouvé"})
return
@@ -574,6 +574,25 @@ func UpdateProduct(c *gin.Context) {
}
}
// L'unité n'est qu'un libellé : la changer réinterpréterait les quantités des paniers et commandes en cours.
if current.Unit != "" && updateData.Unit != current.Unit {
baskets, commands, err := database.CountOpenProductUsage(id)
if err != nil {
utils.ServerErr(c, "Erreur vérification paniers et commandes", err)
return
}
if baskets > 0 || commands > 0 {
c.JSON(http.StatusConflict, gin.H{
"error": fmt.Sprintf("Impossible de changer l'unité (%s → %s) : produit présent dans %d panier(s) et %d commande(s) en cours", current.Unit, updateData.Unit, baskets, commands),
"open_baskets": baskets,
"open_commands": commands,
"current_unit": current.Unit,
"requested_unit": updateData.Unit,
})
return
}
}
log.Printf("🔄 [UpdateProduct] %s met à jour produit #%d", username, id)
comingSoon := false
+6 -6
View File
@@ -66,7 +66,7 @@ func TestUpdateDeliveryStatus_GPS_ValidatesDeliveryAtModerateDistance(t *testing
livreur := newTestClient(t, "gps_livreur_within")
client := newTestClient(t, "gps_client_within")
productID := newTestProduct(t, "GPSWithin", 10)
cmdID := newTestCommandWithItem(t, client, "en_route", livreur, productID, 1, 10)
cmdID := newTestCommandWithItem(t, client, "arrived", livreur, productID, 1, 10)
setCommandDestination(t, cmdID, nantesLat, nantesLon)
livreurLat, livreurLon := destinationPointNorthOf(nantesLat, nantesLon, 200)
@@ -90,7 +90,7 @@ func TestUpdateDeliveryStatus_GPS_FarBeyondOldThresholdStillValidatesDelivery(t
livreur := newTestClient(t, "gps_livreur_far")
client := newTestClient(t, "gps_client_far")
productID := newTestProduct(t, "GPSFar", 10)
cmdID := newTestCommandWithItem(t, client, "en_route", livreur, productID, 1, 10)
cmdID := newTestCommandWithItem(t, client, "arrived", livreur, productID, 1, 10)
setCommandDestination(t, cmdID, nantesLat, nantesLon)
livreurLat, livreurLon := destinationPointNorthOf(nantesLat, nantesLon, 5000) // 5km : loin de toute ancienne limite
@@ -111,7 +111,7 @@ func TestUpdateDeliveryStatus_GPS_MissingCoordinatesRejected(t *testing.T) {
livreur := newTestClient(t, "gps_livreur_missing_coords")
client := newTestClient(t, "gps_client_missing_coords")
productID := newTestProduct(t, "GPSMissingCoords", 10)
cmdID := newTestCommandWithItem(t, client, "en_route", livreur, productID, 1, 10)
cmdID := newTestCommandWithItem(t, client, "arrived", livreur, productID, 1, 10)
setCommandDestination(t, cmdID, nantesLat, nantesLon)
body, _ := json.Marshal(map[string]any{"status": "livre"}) // latitude/longitude absents (zéro)
@@ -121,8 +121,8 @@ func TestUpdateDeliveryStatus_GPS_MissingCoordinatesRejected(t *testing.T) {
if rec.Code != http.StatusBadRequest {
t.Fatalf("status HTTP sans coordonnées: got=%d want=%d body=%s", rec.Code, http.StatusBadRequest, rec.Body.String())
}
if got := commandStatus(t, cmdID); got != "en_route" {
t.Errorf("le statut ne doit pas changer sans coordonnées GPS: got=%s want=en_route", got)
if got := commandStatus(t, cmdID); got != "arrived" {
t.Errorf("le statut ne doit pas changer sans coordonnées GPS: got=%s want=arrived", got)
}
}
@@ -134,7 +134,7 @@ func TestUpdateDeliveryStatus_GPS_MissingDestinationCoordinatesSkipsValidation(t
livreur := newTestClient(t, "gps_livreur_no_dest")
client := newTestClient(t, "gps_client_no_dest")
productID := newTestProduct(t, "GPSNoDest", 10)
cmdID := newTestCommandWithItem(t, client, "en_route", livreur, productID, 1, 10)
cmdID := newTestCommandWithItem(t, client, "arrived", livreur, productID, 1, 10)
// Pas d'appel à setCommandDestination : dest_latitude/dest_longitude restent à 0/NULL.
body, _ := json.Marshal(map[string]any{"status": "livre", "latitude": 48.8566, "longitude": 2.3522}) // Paris, sans rapport
@@ -3,6 +3,7 @@ package tests
import (
"bytes"
"encoding/json"
"errors"
"gestion/db"
"gestion/handlers"
"gestion/models"
@@ -671,8 +672,8 @@ func TestCancelDeliveryByLivreurAtomic_AlreadyApproved_DoesNotTouchPoints(t *tes
cmdID := newTestCommandWithItem(t, username, "approved", testUserPrefix+"livreurY", paidProductID, 1, 10)
insertRewardCommandItem(t, cmdID, rewardProductID, 1, 0, "pool_0")
if _, _, err := testDB.CancelDeliveryByLivreurAtomic(cmdID); err != nil {
t.Fatalf("CancelDeliveryByLivreurAtomic: %v", err)
if _, _, err := testDB.CancelDeliveryByLivreurAtomic(cmdID); !errors.Is(err, db.ErrCommandAlreadyDelivered) {
t.Fatalf("une commande approuvée ne doit pas être annulable par le livreur: err=%v", err)
}
if got := clientPointsRedeemed(t, username)["pool_0"]; got != 5 {
@@ -736,8 +737,8 @@ func TestUpdateCommandStatusAdmin_AlreadyApprovedWithRewardItem_DoesNotTouchPoin
c, rec := adminCancelCtx(cmdID)
handlers.UpdateCommandStatusAdmin(c)
if rec.Code != http.StatusOK {
t.Fatalf("status HTTP: got=%d body=%s", rec.Code, rec.Body.String())
if rec.Code != http.StatusConflict {
t.Fatalf("une commande approuvée ne doit pas être annulable: got=%d body=%s", rec.Code, rec.Body.String())
}
if got := clientPointsRedeemed(t, username)["pool_0"]; got != 3 {
@@ -821,4 +822,3 @@ func TestCalculateAndAddPointsForCommandTx_MultipleRewardRowsSamePool_Decrements
t.Errorf("redeemed après approbation (2 lignes, même pool, une seule réservation): got=%d want=1", got)
}
}
@@ -0,0 +1,500 @@
package tests
import (
"fmt"
"gestion/models"
"math"
"math/rand"
"strings"
"sync"
"testing"
)
// Simulations sur un produit à exactement 1000 g.
func newProduct1000g(t *testing.T, name string) (int, string) {
t.Helper()
cat := "cat1000_" + name
id := newTestProduct(t, name, 1000)
testDB.GDB.Exec(`UPDATE products SET unit = 'g', category = ? WHERE id = ?`, cat, id)
testDB.GDB.Exec(`INSERT INTO product_prices (product_id, quantity, price, active_price) VALUES (?, 0.001, 0.01, true)`, id)
return id, cat
}
// Stock attendu = 1000 − quantités des commandes non annulées encore en base.
func expectedFromOrders(t *testing.T, productID int) float64 {
t.Helper()
var sold float64
testDB.GDB.Raw(`
SELECT COALESCE(SUM(ci.quantite), 0)::float8 FROM command_items ci
JOIN commandes c ON c.id = ci.command_id
WHERE ci.product_id = ? AND c.status <> 'cancelled'`, productID).Scan(&sold)
return 1000 - sold
}
func expectNear(t *testing.T, productID int, want float64, why string) {
t.Helper()
got := productStock(t, productID)
if math.Abs(got-want) > 1e-9 {
t.Errorf("❌ stock=%.3f g, attendu=%.3f g (écart %+.3f) — %s", got, want, got-want, why)
} else {
t.Logf("✅ stock=%.3f g — %s", got, why)
}
}
func checkout(username string, items map[int]float64, order []int) (int, error) {
for _, pid := range order {
if _, err := testDB.AddToBasket(username, pid, items[pid]); err != nil {
return 0, err
}
}
cmd, err := testDB.CreateCommandWithAddress(username, "1 rue de test")
if err != nil {
return 0, err
}
return cmd.ID, nil
}
func TestSimulation1000g(t *testing.T) {
const liv = testUserPrefix + "livreur1000"
type sc struct {
name string
run func(t *testing.T)
}
scenarios := []sc{
{"01_grammes_fractionnaires_achat_et_annulation", func(t *testing.T) {
for _, q := range []float64{0.5, 0.25, 0.125, 0.1, 0.001, 0.005, 3.333, 2.75, 999.999} {
t.Run(fmt.Sprintf("%.3fg", q), func(t *testing.T) {
cleanupStockTestData(t)
u := newTestClient(t, "frac")
p, _ := newProduct1000g(t, "frac")
id, err := checkout(u, map[int]float64{p: q}, []int{p})
if err != nil {
t.Fatalf("checkout %.3f g : %v", q, err)
}
expectNear(t, p, 1000-q, fmt.Sprintf("achat de %.3f g", q))
testDB.CancelCommandAtomic(id, u, "test", false)
expectNear(t, p, 1000, "annulation")
})
}
}},
{"02_huit_fois_0_125g_puis_tout_annuler", func(t *testing.T) {
cleanupStockTestData(t)
p, _ := newProduct1000g(t, "x8")
var ids []int
var users []string
for i := 0; i < 8; i++ {
u := newTestClient(t, fmt.Sprintf("x8_%d", i))
id, err := checkout(u, map[int]float64{p: 0.125}, []int{p})
if err != nil {
t.Fatalf("checkout : %v", err)
}
ids, users = append(ids, id), append(users, u)
}
expectNear(t, p, 999, "8 × 0,125 g vendus")
for i, id := range ids {
testDB.CancelCommandAtomic(id, users[i], "test", false)
}
expectNear(t, p, 1000, "8 annulations")
}},
{"03_mille_ventes_de_1g", func(t *testing.T) {
cleanupStockTestData(t)
p, _ := newProduct1000g(t, "x1000")
u := newTestClient(t, "x1000")
for i := 0; i < 1000; i++ {
if _, err := checkout(u, map[int]float64{p: 1}, []int{p}); err != nil {
t.Fatalf("vente %d : %v", i+1, err)
}
}
expectNear(t, p, 0, "1000 ventes de 1 g")
_, err := testDB.AddToBasket(u, p, 0.001)
if err == nil {
t.Errorf("❌ ajout de 0,001 g accepté avec un stock à 0")
} else {
t.Logf("✅ ajout refusé à stock 0 : %v", err)
}
}},
{"04_vendre_exactement_1000g_d_un_coup", func(t *testing.T) {
cleanupStockTestData(t)
p, _ := newProduct1000g(t, "all")
u := newTestClient(t, "all")
if _, err := checkout(u, map[int]float64{p: 1000}, []int{p}); err != nil {
t.Fatalf("checkout 1000 g : %v", err)
}
expectNear(t, p, 0, "1000 g vendus")
u2 := newTestClient(t, "all2")
if _, err := testDB.AddToBasket(u2, p, 0.001); err == nil {
t.Errorf("❌ 0,001 g ajoutable après épuisement")
}
}},
{"05_1000_001g_refuse", func(t *testing.T) {
cleanupStockTestData(t)
p, _ := newProduct1000g(t, "over")
u := newTestClient(t, "over")
if _, err := testDB.AddToBasket(u, p, 1000.001); err == nil {
t.Errorf("❌ 1000,001 g accepté")
} else {
t.Logf("✅ refusé : %v", err)
}
expectNear(t, p, 1000, "rien vendu")
}},
{"06_12_clients_x_100g_en_parallele", func(t *testing.T) {
cleanupStockTestData(t)
p, _ := newProduct1000g(t, "par100")
var users []string
for i := 0; i < 12; i++ {
u := newTestClient(t, fmt.Sprintf("par100_%d", i))
testDB.AddToBasket(u, p, 100)
users = append(users, u)
}
var wg sync.WaitGroup
var mu sync.Mutex
ok, deadlocks := 0, 0
for _, u := range users {
wg.Add(1)
go func(u string) {
defer wg.Done()
_, err := testDB.CreateCommandWithAddress(u, "1 rue de test")
mu.Lock()
defer mu.Unlock()
if err == nil {
ok++
} else if strings.Contains(err.Error(), "deadlock") {
deadlocks++
}
}(u)
}
wg.Wait()
t.Logf("commandes acceptées=%d, deadlocks=%d", ok, deadlocks)
if ok != 10 {
t.Errorf("❌ %d commandes de 100 g acceptées, attendu 10", ok)
}
expectNear(t, p, 0, "stock épuisé en parallèle")
}},
{"07_50_clients_x_25g_en_parallele", func(t *testing.T) {
cleanupStockTestData(t)
p, _ := newProduct1000g(t, "par25")
var users []string
for i := 0; i < 50; i++ {
u := newTestClient(t, fmt.Sprintf("par25_%d", i))
testDB.AddToBasket(u, p, 25)
users = append(users, u)
}
var wg sync.WaitGroup
var mu sync.Mutex
ok := 0
for _, u := range users {
wg.Add(1)
go func(u string) {
defer wg.Done()
if _, err := testDB.CreateCommandWithAddress(u, "1 rue de test"); err == nil {
mu.Lock()
ok++
mu.Unlock()
}
}(u)
}
wg.Wait()
if ok != 40 {
t.Errorf("❌ %d commandes de 25 g acceptées, attendu 40", ok)
} else {
t.Logf("✅ 40 commandes acceptées sur 50")
}
expectNear(t, p, 0, "1000 g vendus")
}},
{"08_ventes_et_annulations_en_parallele", func(t *testing.T) {
cleanupStockTestData(t)
p, _ := newProduct1000g(t, "mix")
type o struct {
u string
id int
}
var orders []o
for i := 0; i < 20; i++ {
u := newTestClient(t, fmt.Sprintf("mixa_%d", i))
id, err := checkout(u, map[int]float64{p: 10}, []int{p})
if err != nil {
t.Fatalf("checkout : %v", err)
}
orders = append(orders, o{u, id})
}
var buyers []string
for i := 0; i < 20; i++ {
u := newTestClient(t, fmt.Sprintf("mixb_%d", i))
testDB.AddToBasket(u, p, 10)
buyers = append(buyers, u)
}
var wg sync.WaitGroup
for i := 0; i < 20; i++ {
wg.Add(2)
go func(x o) { defer wg.Done(); testDB.CancelCommandAtomic(x.id, x.u, "test", false) }(orders[i])
go func(u string) { defer wg.Done(); testDB.CreateCommandWithAddress(u, "1 rue de test") }(buyers[i])
}
wg.Wait()
expectNear(t, p, expectedFromOrders(t, p), "20 annulations + 20 ventes simultanées")
}},
{"09_offre_10g_achetes_1g_offert", func(t *testing.T) {
cleanupStockTestData(t)
p, cat := newProduct1000g(t, "gift")
restore := enableFreeGift(t, cat, 10, 1)
defer restore()
u := newTestClient(t, "gift")
id, err := checkout(u, map[int]float64{p: 10}, []int{p})
if err != nil {
t.Fatalf("checkout : %v", err)
}
expectNear(t, p, 989, "10 g achetés + 1 g offert")
testDB.CancelCommandAtomic(id, u, "test", false)
expectNear(t, p, 1000, "annulation : 11 g rendus")
}},
{"10_offre_qui_depasse_le_stock", func(t *testing.T) {
cleanupStockTestData(t)
p, cat := newProduct1000g(t, "giftover")
restore := enableFreeGift(t, cat, 995, 10)
defer restore()
u := newTestClient(t, "giftover")
_, err := testDB.AddToBasket(u, p, 995)
if err == nil {
t.Errorf("❌ 995 g + 10 g offerts acceptés avec 1000 g en stock")
} else {
t.Logf("✅ refusé : %v", err)
}
expectNear(t, p, 1000, "rien vendu")
}},
{"11_offre_ajouts_successifs_dans_le_panier", func(t *testing.T) {
cleanupStockTestData(t)
p, cat := newProduct1000g(t, "giftadd")
restore := enableFreeGift(t, cat, 10, 1)
defer restore()
u := newTestClient(t, "giftadd")
testDB.AddToBasket(u, p, 5)
testDB.AddToBasket(u, p, 5)
var qty float64
testDB.GDB.Raw(`SELECT quantity::float8 FROM baskets WHERE username = ? AND product_id = ?`, u, p).Scan(&qty)
t.Logf("panier après 5 g + 5 g : %.3f g (offre non déclenchée car chaque ajout < 10 g)", qty)
testDB.CreateCommandWithAddress(u, "1 rue de test")
expectNear(t, p, 1000-qty, "stock déduit de la quantité réelle du panier")
}},
{"12_recompense_et_achat_meme_produit_au_gramme", func(t *testing.T) {
cleanupStockTestData(t)
p, _ := newProduct1000g(t, "rew")
u := newTestClient(t, "rew")
testDB.GDB.Exec(`INSERT INTO baskets (username, product_id, quantity, price, is_reward, reward_pool_key, created_at)
VALUES (?, ?, 1.5, 0, true, 'pool_0', NOW())`, u, p)
id, err := checkout(u, map[int]float64{p: 998.5}, []int{p})
if err != nil {
t.Fatalf("checkout : %v", err)
}
expectNear(t, p, 0, "998,5 g payés + 1,5 g récompense")
testDB.CancelCommandAtomic(id, u, "test", false)
expectNear(t, p, 1000, "annulation")
}},
{"13_recompense_qui_fait_depasser_le_stock", func(t *testing.T) {
cleanupStockTestData(t)
p, _ := newProduct1000g(t, "rewover")
u := newTestClient(t, "rewover")
testDB.GDB.Exec(`INSERT INTO baskets (username, product_id, quantity, price, is_reward, reward_pool_key, created_at)
VALUES (?, ?, 2, 0, true, 'pool_0', NOW())`, u, p)
testDB.AddToBasket(u, p, 999)
_, err := testDB.CreateCommandWithAddress(u, "1 rue de test")
if err == nil {
t.Errorf("❌ 999 g + 2 g récompense acceptés")
} else {
t.Logf("✅ refusé : %v", err)
}
expectNear(t, p, 1000, "transaction annulée, rien déduit")
}},
{"14_commande_multi_produits_suppression_article_puis_annulation", func(t *testing.T) {
cleanupStockTestData(t)
a, _ := newProduct1000g(t, "ma")
b, _ := newProduct1000g(t, "mb")
u := newTestClient(t, "multi")
id, err := checkout(u, map[int]float64{a: 12.5, b: 7.25}, []int{a, b})
if err != nil {
t.Fatalf("checkout : %v", err)
}
expectNear(t, a, 987.5, "A : 12,5 g")
expectNear(t, b, 992.75, "B : 7,25 g")
var itemA int
testDB.GDB.Raw(`SELECT id FROM command_items WHERE command_id = ? AND product_id = ?`, id, a).Scan(&itemA)
testDB.DeleteCommandItem(id, itemA)
expectNear(t, a, 1000, "article A retiré")
simAdminStatus(t, id, "cancelled")
expectNear(t, a, 1000, "A après annulation (pas de double remboursement)")
expectNear(t, b, 1000, "B après annulation")
}},
{"15_suppressions_simultanees_du_meme_article", func(t *testing.T) {
cleanupStockTestData(t)
p, _ := newProduct1000g(t, "delpar")
u := newTestClient(t, "delpar")
id, _ := checkout(u, map[int]float64{p: 40}, []int{p})
var item int
testDB.GDB.Raw(`SELECT id FROM command_items WHERE command_id = ?`, id).Scan(&item)
var wg sync.WaitGroup
for i := 0; i < 5; i++ {
wg.Add(1)
go func() { defer wg.Done(); testDB.DeleteCommandItem(id, item) }()
}
wg.Wait()
expectNear(t, p, 1000, "5 suppressions simultanées du même article")
}},
{"16_suppression_article_et_annulation_simultanees", func(t *testing.T) {
cleanupStockTestData(t)
p, _ := newProduct1000g(t, "delcancel")
u := newTestClient(t, "delcancel")
id, _ := checkout(u, map[int]float64{p: 40}, []int{p})
var item int
testDB.GDB.Raw(`SELECT id FROM command_items WHERE command_id = ?`, id).Scan(&item)
var wg sync.WaitGroup
wg.Add(3)
go func() { defer wg.Done(); testDB.DeleteCommandItem(id, item) }()
go func() { defer wg.Done(); testDB.CancelCommandByAdminAtomic(id) }()
go func() { defer wg.Done(); testDB.DeleteCommandAtomic(id, "admin", "admin") }()
wg.Wait()
expectNear(t, p, 1000, "suppression article + annulation + suppression commande en même temps")
}},
{"17_admin_fixe_le_stock_pendant_des_ventes", func(t *testing.T) {
cleanupStockTestData(t)
p, _ := newProduct1000g(t, "setpar")
var users []string
for i := 0; i < 10; i++ {
u := newTestClient(t, fmt.Sprintf("setpar_%d", i))
testDB.AddToBasket(u, p, 10)
users = append(users, u)
}
var wg sync.WaitGroup
wg.Add(1)
go func() { defer wg.Done(); testDB.SetProductStock(p, 1000) }()
for _, u := range users {
wg.Add(1)
go func(u string) { defer wg.Done(); testDB.CreateCommandWithAddress(u, "1 rue de test") }(u)
}
wg.Wait()
got := productStock(t, p)
sold := 1000 - expectedFromOrders(t, p)
t.Logf("ℹ️ stock final=%.3f g, vendu=%.3f g : la valeur « fixer à 1000 » écrase les ventes passées avant elle (comportement voulu d'un inventaire)", got, sold)
}},
{"18_deux_produits_ordre_inverse_en_parallele", func(t *testing.T) {
cleanupStockTestData(t)
a, _ := newProduct1000g(t, "da")
b, _ := newProduct1000g(t, "db")
type job struct {
u string
order []int
}
var jobs []job
for i := 0; i < 20; i++ {
u := newTestClient(t, fmt.Sprintf("dl_%d", i))
order := []int{a, b}
if i%2 == 1 {
order = []int{b, a}
}
for _, pid := range order {
testDB.AddToBasket(u, pid, 5)
}
jobs = append(jobs, job{u, order})
}
var wg sync.WaitGroup
var mu sync.Mutex
ok, deadlocks := 0, 0
for _, j := range jobs {
wg.Add(1)
go func(j job) {
defer wg.Done()
_, err := testDB.CreateCommandWithAddress(j.u, "1 rue de test")
mu.Lock()
defer mu.Unlock()
if err == nil {
ok++
} else if strings.Contains(err.Error(), "deadlock") {
deadlocks++
}
}(j)
}
wg.Wait()
if deadlocks > 0 {
t.Errorf("❌ %d/20 commandes refusées pour deadlock alors que le stock suffit (A puis B vs B puis A)", deadlocks)
} else {
t.Logf("✅ 20/20 commandes acceptées")
}
expectNear(t, a, expectedFromOrders(t, a), "A cohérent avec les commandes")
expectNear(t, b, expectedFromOrders(t, b), "B cohérent avec les commandes")
}},
{"19_cycle_de_vie_aleatoire_60_commandes", func(t *testing.T) {
cleanupStockTestData(t)
p, _ := newProduct1000g(t, "fuzz")
rng := rand.New(rand.NewSource(42))
qtys := []float64{0.5, 1, 2.5, 3.333, 5, 10, 0.125, 0.001, 7.75, 20}
type o struct {
u string
id int
}
var orders []o
for i := 0; i < 60; i++ {
u := newTestClient(t, fmt.Sprintf("fuzz_%d", i))
id, err := checkout(u, map[int]float64{p: qtys[rng.Intn(len(qtys))]}, []int{p})
if err != nil {
t.Fatalf("checkout : %v", err)
}
orders = append(orders, o{u, id})
}
var wg sync.WaitGroup
actions := map[string]int{}
for _, x := range orders {
a := rng.Intn(8)
names := []string{"client_annule", "admin_annule", "livreur_annule", "livree_approuvee", "article_supprime", "commande_supprimee", "rien", "admin_rouvre_apres_annulation"}
actions[names[a]]++
setStatus(t, x.id, "assigned", liv)
wg.Add(1)
go func(x o, a int) {
defer wg.Done()
switch a {
case 0:
testDB.CancelCommandAtomic(x.id, x.u, "test", true)
case 1:
testDB.CancelCommandByAdminAtomic(x.id)
case 2:
testDB.CancelDeliveryByLivreurAtomic(x.id)
case 3:
testDB.GDB.Exec(`UPDATE commandes SET status = 'livre' WHERE id = ?`, x.id)
testDB.ApproveDeliveryAtomicByStaff(x.id, "staff")
testDB.CancelDeliveryByLivreurAtomic(x.id)
case 4:
var item int
testDB.GDB.Raw(`SELECT id FROM command_items WHERE command_id = ?`, x.id).Scan(&item)
testDB.DeleteCommandItem(x.id, item)
case 5:
testDB.DeleteCommandAtomic(x.id, "admin", "admin")
case 7:
testDB.CancelCommandByAdminAtomic(x.id)
testDB.UpdateCommandStatus(x.id, "pending")
testDB.CancelCommandByAdminAtomic(x.id)
}
}(x, a)
}
wg.Wait()
t.Logf("actions : %v", actions)
expectNear(t, p, expectedFromOrders(t, p), "stock = 1000 − commandes encore actives")
}},
}
for _, s := range scenarios {
t.Run(s.name, s.run)
}
}
func enableFreeGift(t *testing.T, category string, buy, free float64) func() {
t.Helper()
before, err := testDB.GetSettings()
if err != nil {
t.Fatalf("GetSettings : %v", err)
}
s := before
s.FreeGiftsEnabled = true
s.FreeGifts = []models.CategoryFreeGiftConfig{{Category: category, AllProducts: true, Tiers: []models.FreeGiftTier{{BuyQuantity: buy, FreeQuantity: free}}}}
if err := testDB.UpdateSettings(s); err != nil {
t.Fatalf("UpdateSettings : %v", err)
}
return func() { testDB.UpdateSettings(before) }
}
@@ -0,0 +1,389 @@
package tests
import (
"bytes"
"encoding/json"
"gestion/handlers"
"net/http"
"net/http/httptest"
"strconv"
"sync"
"testing"
"github.com/gin-gonic/gin"
)
// Simulations bout en bout du stock contre la base du lab.
// Convention : chaque produit démarre à 10 en stock.
func simCheckout(t *testing.T, username string, productID int, qty float64) int {
t.Helper()
if _, err := testDB.AddToBasket(username, productID, qty); err != nil {
t.Fatalf("AddToBasket: %v", err)
}
cmd, err := testDB.CreateCommandWithAddress(username, "1 rue de test")
if err != nil {
t.Fatalf("checkout: %v", err)
}
return cmd.ID
}
func simAdminStatus(t *testing.T, cmdID int, status string) int {
t.Helper()
body, _ := json.Marshal(map[string]string{"status": status})
req := httptest.NewRequest(http.MethodPut, "/x", bytes.NewReader(body))
req.Header.Set("Content-Type", "application/json")
rec := httptest.NewRecorder()
c, _ := gin.CreateTestContext(rec)
c.Request = req
c.Set("database", testDB)
c.Set("role", "admin")
c.Set("username", testUserPrefix+"admin")
c.Params = gin.Params{{Key: "id", Value: strconv.Itoa(cmdID)}}
handlers.UpdateCommandStatusAdmin(c)
return rec.Code
}
func simLivreurStatus(t *testing.T, cmdID int, livreur, status string) int {
t.Helper()
body, _ := json.Marshal(map[string]any{"status": status, "latitude": 48.85, "longitude": 2.35})
req := httptest.NewRequest(http.MethodPut, "/x", bytes.NewReader(body))
req.Header.Set("Content-Type", "application/json")
rec := httptest.NewRecorder()
c, _ := gin.CreateTestContext(rec)
c.Request = req
c.Set("database", testDB)
c.Set("role", "livreur")
c.Set("username", livreur)
c.Params = gin.Params{{Key: "id", Value: strconv.Itoa(cmdID)}}
handlers.UpdateDeliveryStatus(c)
return rec.Code
}
func setStatus(t *testing.T, cmdID int, status, livreur string) {
t.Helper()
testDB.GDB.Exec(`UPDATE commandes SET status = ?, livreur_assign = NULLIF(?, '') WHERE id = ?`, status, livreur, cmdID)
}
func redeemed(t *testing.T, username, pool string) int {
t.Helper()
var n int
testDB.GDB.Raw(`SELECT COALESCE((points_redeemed->>?)::int, 0) FROM clients WHERE username = ?`, pool, username).Scan(&n)
return n
}
func expectStock(t *testing.T, productID int, want float64, why string) {
t.Helper()
if got := productStock(t, productID); got != want {
t.Errorf("❌ stock=%.0f, attendu=%.0f — %s", got, want, why)
} else {
t.Logf("✅ stock=%.0f — %s", got, why)
}
}
func TestSimulationStock(t *testing.T) {
type scenario struct {
name string
run func(t *testing.T, user string, pid int)
}
const liv = testUserPrefix + "livreur"
scenarios := []scenario{
{"01_checkout_decremente", func(t *testing.T, u string, p int) {
simCheckout(t, u, p, 3)
expectStock(t, p, 7, "commande de 3")
}},
{"02_panier_ne_reserve_pas", func(t *testing.T, u string, p int) {
testDB.AddToBasket(u, p, 4)
expectStock(t, p, 10, "ajout panier sans commande")
}},
{"03_panier_cumule_au_dela_du_stock", func(t *testing.T, u string, p int) {
_, e1 := testDB.AddToBasket(u, p, 6)
_, e2 := testDB.AddToBasket(u, p, 6)
t.Logf("ajout 6 : err=%v, ajout 6 : err=%v (panier=12 pour stock 10)", e1, e2)
_, err := testDB.CreateCommandWithAddress(u, "1 rue de test")
if err == nil {
t.Errorf("❌ checkout de 12 accepté avec 10 en stock")
} else {
t.Logf("✅ checkout refusé : %v", err)
}
expectStock(t, p, 10, "checkout refusé, rien ne bouge")
}},
{"04_annulation_client", func(t *testing.T, u string, p int) {
id := simCheckout(t, u, p, 3)
testDB.CancelCommandAtomic(id, u, "test", false)
expectStock(t, p, 10, "client annule")
}},
{"05_double_annulation_client", func(t *testing.T, u string, p int) {
id := simCheckout(t, u, p, 3)
testDB.CancelCommandAtomic(id, u, "test", false)
_, err := testDB.CancelCommandAtomic(id, u, "test", false)
t.Logf("2e annulation : %v", err)
expectStock(t, p, 10, "double annulation client")
}},
{"06_admin_annule", func(t *testing.T, u string, p int) {
id := simCheckout(t, u, p, 3)
simAdminStatus(t, id, "cancelled")
expectStock(t, p, 10, "admin annule")
}},
{"07_admin_annule_rouvre_annule", func(t *testing.T, u string, p int) {
id := simCheckout(t, u, p, 3)
simAdminStatus(t, id, "cancelled")
if code := simAdminStatus(t, id, "pending"); code != http.StatusConflict {
t.Errorf("❌ réouverture cancelled→pending acceptée : HTTP %d", code)
}
simAdminStatus(t, id, "cancelled")
expectStock(t, p, 10, "réouverture refusée, ré-annulation sans effet")
}},
{"08_admin_rouvre_puis_livre", func(t *testing.T, u string, p int) {
id := simCheckout(t, u, p, 3)
simAdminStatus(t, id, "cancelled")
simAdminStatus(t, id, "pending")
simAdminStatus(t, id, "approved")
if st := commandStatus(t, id); st != "cancelled" {
t.Errorf("❌ statut final=%s, attendu=cancelled", st)
}
expectStock(t, p, 10, "commande annulée : ni réouverture ni approbation")
}},
{"09_admin_annule_commande_livre", func(t *testing.T, u string, p int) {
id := simCheckout(t, u, p, 3)
setStatus(t, id, "livre", liv)
simAdminStatus(t, id, "cancelled")
expectStock(t, p, 7, "admin annule une commande déjà livrée")
}},
{"10_admin_annule_commande_approved", func(t *testing.T, u string, p int) {
id := simCheckout(t, u, p, 3)
setStatus(t, id, "approved", liv)
simAdminStatus(t, id, "cancelled")
expectStock(t, p, 7, "admin annule une commande approuvée")
}},
{"11_admin_approved_vers_pending_puis_annule", func(t *testing.T, u string, p int) {
id := simCheckout(t, u, p, 3)
setStatus(t, id, "approved", liv)
if code := simAdminStatus(t, id, "pending"); code != http.StatusConflict {
t.Errorf("❌ approved→pending accepté : HTTP %d", code)
}
if code := simAdminStatus(t, id, "cancelled"); code != http.StatusConflict {
t.Errorf("❌ annulation d'une commande approuvée acceptée : HTTP %d", code)
}
expectStock(t, p, 7, "commande approuvée verrouillée")
}},
{"12_livreur_annule_en_route", func(t *testing.T, u string, p int) {
id := simCheckout(t, u, p, 3)
setStatus(t, id, "en_route", liv)
code := simLivreurStatus(t, id, liv, "cancelled")
t.Logf("HTTP %d", code)
expectStock(t, p, 10, "livreur annule en route")
}},
{"13_livreur_annule_commande_livre", func(t *testing.T, u string, p int) {
id := simCheckout(t, u, p, 3)
setStatus(t, id, "livre", liv)
if code := simLivreurStatus(t, id, liv, "cancelled"); code != http.StatusConflict {
t.Errorf("❌ annulation livreur d'une commande livrée : HTTP %d", code)
}
expectStock(t, p, 7, "livreur annule une commande déjà livrée")
}},
{"14_livreur_annule_commande_approved", func(t *testing.T, u string, p int) {
id := simCheckout(t, u, p, 3)
setStatus(t, id, "approved", liv)
if code := simLivreurStatus(t, id, liv, "cancelled"); code != http.StatusConflict {
t.Errorf("❌ annulation livreur d'une commande approuvée : HTTP %d", code)
}
expectStock(t, p, 7, "livreur annule une commande approuvée")
}},
{"15_livreur_annule_rouvre_annule", func(t *testing.T, u string, p int) {
id := simCheckout(t, u, p, 3)
setStatus(t, id, "assigned", liv)
simLivreurStatus(t, id, liv, "cancelled")
if code := simLivreurStatus(t, id, liv, "assigned"); code != http.StatusConflict {
t.Errorf("❌ livreur cancelled→assigned accepté : HTTP %d", code)
}
simLivreurStatus(t, id, liv, "cancelled")
expectStock(t, p, 10, "livreur annule / rouvre / annule")
}},
{"15b_livreur_transitions_dans_l_ordre", func(t *testing.T, u string, p int) {
id := simCheckout(t, u, p, 3)
setStatus(t, id, "assigned", liv)
steps := []struct {
status string
want int
}{
{"arrived", http.StatusConflict},
{"livre", http.StatusConflict},
{"en_route", http.StatusOK},
{"en_route", http.StatusOK},
{"livre", http.StatusConflict},
{"arrived", http.StatusOK},
{"en_route", http.StatusConflict},
{"livre", http.StatusOK},
{"cancelled", http.StatusConflict},
}
for _, st := range steps {
if code := simLivreurStatus(t, id, liv, st.status); code != st.want {
t.Errorf("❌ → %s : HTTP %d, attendu %d (statut=%s)", st.status, code, st.want, commandStatus(t, id))
} else {
t.Logf("✅ → %s : HTTP %d", st.status, code)
}
}
expectStock(t, p, 7, "livraison complète")
}},
{"16_livreur_puis_admin_annulent", func(t *testing.T, u string, p int) {
id := simCheckout(t, u, p, 3)
setStatus(t, id, "assigned", liv)
simLivreurStatus(t, id, liv, "cancelled")
simAdminStatus(t, id, "cancelled")
expectStock(t, p, 10, "livreur puis admin annulent")
}},
{"17_suppression_article", func(t *testing.T, u string, p int) {
id := simCheckout(t, u, p, 3)
var itemID int
testDB.GDB.Raw(`SELECT id FROM command_items WHERE command_id = ?`, id).Scan(&itemID)
testDB.DeleteCommandItem(id, itemID)
expectStock(t, p, 10, "article supprimé de la commande")
}},
{"18_suppression_article_puis_annulation", func(t *testing.T, u string, p int) {
id := simCheckout(t, u, p, 3)
var itemID int
testDB.GDB.Raw(`SELECT id FROM command_items WHERE command_id = ?`, id).Scan(&itemID)
testDB.DeleteCommandItem(id, itemID)
simAdminStatus(t, id, "cancelled")
expectStock(t, p, 10, "article supprimé puis commande annulée")
}},
{"19_suppression_commande_annulee", func(t *testing.T, u string, p int) {
id := simCheckout(t, u, p, 3)
simAdminStatus(t, id, "cancelled")
testDB.DeleteCommandAtomic(id, "admin", "admin")
expectStock(t, p, 10, "commande annulée puis supprimée")
}},
{"20_suppression_commande_rouverte", func(t *testing.T, u string, p int) {
id := simCheckout(t, u, p, 3)
simAdminStatus(t, id, "cancelled")
simAdminStatus(t, id, "pending")
testDB.DeleteCommandAtomic(id, "admin", "admin")
expectStock(t, p, 10, "commande annulée, rouverte puis supprimée")
}},
{"21_crypto_echec_creation_paiement", func(t *testing.T, u string, p int) {
// Reproduit ValidateBasket : commande créée en 'pending', NowPayments échoue,
// CancelCryptoCommand est appelé avant le passage en 'pending_payment'.
id := simCheckout(t, u, p, 3)
err := testDB.CancelCryptoCommand(id)
t.Logf("CancelCryptoCommand : err=%v, statut=%s", err, commandStatus(t, id))
expectStock(t, p, 10, "paiement crypto jamais initié")
}},
{"22_crypto_expire", func(t *testing.T, u string, p int) {
id := simCheckout(t, u, p, 3)
setStatus(t, id, "pending_payment", "")
testDB.CancelCryptoCommand(id)
testDB.CancelCryptoCommand(id)
expectStock(t, p, 10, "paiement expiré (webhook + cron)")
}},
{"23_crypto_admin_annule_puis_expire", func(t *testing.T, u string, p int) {
id := simCheckout(t, u, p, 3)
setStatus(t, id, "pending_payment", "")
simAdminStatus(t, id, "cancelled")
testDB.CancelCryptoCommand(id)
expectStock(t, p, 10, "admin annule puis paiement expire")
}},
{"24_recompense_crypto_expire_libere_points", func(t *testing.T, u string, p int) {
testDB.GDB.Exec(`UPDATE clients SET points_redeemed = '{"pool_0":1}' WHERE username = ?`, u)
testDB.GDB.Exec(`INSERT INTO baskets (username, product_id, quantity, price, is_reward, reward_pool_key, created_at)
VALUES (?, ?, 1, 0, true, 'pool_0', NOW())`, u, p)
id := simCheckout(t, u, p, 2)
setStatus(t, id, "pending_payment", "")
testDB.CancelCryptoCommand(id)
expectStock(t, p, 10, "commande avec récompense, paiement expiré")
if n := redeemed(t, u, "pool_0"); n != 0 {
t.Errorf("❌ points_redeemed.pool_0=%d après expiration : la récompense est perdue", n)
} else {
t.Logf("✅ récompense rendue")
}
}},
{"25_recompense_meme_produit", func(t *testing.T, u string, p int) {
testDB.GDB.Exec(`INSERT INTO baskets (username, product_id, quantity, price, is_reward, reward_pool_key, created_at)
VALUES (?, ?, 1, 0, true, 'pool_0', NOW())`, u, p)
id := simCheckout(t, u, p, 2)
expectStock(t, p, 7, "2 payés + 1 récompense")
testDB.CancelCommandAtomic(id, u, "test", false)
expectStock(t, p, 10, "annulation")
}},
{"26_ancien_front_edite_produit_avec_stock_perime", func(t *testing.T, u string, p int) {
// L'admin ouvre la fiche (stock affiché 10), une vente passe, il enregistre.
stale := productStock(t, p)
simCheckout(t, u, p, 3)
cat := newTestCategory(t, "sim26")
body, _ := json.Marshal(map[string]any{
"name": testProductPrefix + "sim26", "category": cat, "description": "renommé",
"stock": stale, "unit": "u", "prices": []map[string]any{{"quantity": 1, "price": 10}},
})
c, rec := jsonStockContext("admin", body, p)
handlers.UpdateProduct(c)
t.Logf("UpdateProduct : HTTP %d", rec.Code)
expectStock(t, p, 7, "édition de la fiche sans toucher au stock pendant une vente")
}},
{"26b_admin_edite_produit_sans_envoyer_le_stock", func(t *testing.T, u string, p int) {
// Nouveau panel admin : le stock n'est plus envoyé s'il n'a pas été modifié.
simCheckout(t, u, p, 3)
cat := newTestCategory(t, "sim26b")
body, _ := json.Marshal(map[string]any{
"name": testProductPrefix + "sim26b", "category": cat, "description": "renommé",
"unit": "u", "prices": []map[string]any{{"quantity": 1, "price": 10}},
})
c, rec := jsonStockContext("admin", body, p)
handlers.UpdateProduct(c)
if rec.Code != http.StatusOK {
t.Fatalf("UpdateProduct : HTTP %d %s", rec.Code, rec.Body.String())
}
expectStock(t, p, 7, "édition de la fiche pendant une vente, stock non envoyé")
}},
{"27_derniere_unite_concurrente", func(t *testing.T, u string, p int) {
testDB.SetProductStock(p, 1)
users := []string{u, newTestClient(t, "sim27_b"), newTestClient(t, "sim27_c"), newTestClient(t, "sim27_d")}
for _, x := range users {
testDB.AddToBasket(x, p, 1)
}
var wg sync.WaitGroup
var mu sync.Mutex
ok := 0
for _, x := range users {
wg.Add(1)
go func(x string) {
defer wg.Done()
if _, err := testDB.CreateCommandWithAddress(x, "1 rue de test"); err == nil {
mu.Lock()
ok++
mu.Unlock()
}
}(x)
}
wg.Wait()
if ok != 1 {
t.Errorf("❌ %d commandes acceptées pour 1 unité", ok)
} else {
t.Logf("✅ 1 seule commande acceptée sur 4")
}
expectStock(t, p, 0, "dernière unité")
}},
{"28_annulations_concurrentes_tous_roles", func(t *testing.T, u string, p int) {
id := simCheckout(t, u, p, 3)
setStatus(t, id, "assigned", liv)
var wg sync.WaitGroup
for i := 0; i < 3; i++ {
wg.Add(3)
go func() { defer wg.Done(); testDB.CancelCommandAtomic(id, u, "test", true) }()
go func() { defer wg.Done(); testDB.CancelCommandByAdminAtomic(id) }()
go func() { defer wg.Done(); testDB.CancelDeliveryByLivreurAtomic(id) }()
}
wg.Wait()
expectStock(t, p, 10, "9 annulations simultanées client/admin/livreur")
}},
}
for _, sc := range scenarios {
t.Run(sc.name, func(t *testing.T) {
cleanupStockTestData(t)
user := newTestClient(t, "sim_"+sc.name)
pid := newTestProduct(t, "sim_"+sc.name, 10)
sc.run(t, user, pid)
})
}
}
@@ -0,0 +1,126 @@
package tests
import (
"encoding/json"
"gestion/handlers"
"math"
"testing"
)
// L'admin passe une fiche de « 1 kg » à « 1000 g » alors que des paniers et commandes existent.
func newKgProduct(t *testing.T, name string) (int, string) {
t.Helper()
cat := newTestCategory(t, "unit_"+name)
id := newTestProduct(t, name, 1)
testDB.GDB.Exec(`UPDATE products SET unit = 'kg', category = ? WHERE id = ?`, cat, id)
testDB.GDB.Exec(`DELETE FROM product_prices WHERE product_id = ?`, id)
testDB.GDB.Exec(`INSERT INTO product_prices (product_id, quantity, price, active_price) VALUES (?, 0.25, 30, true), (?, 0.5, 55, true), (?, 1, 100, true)`, id, id, id)
return id, cat
}
func adminEditProductCode(t *testing.T, productID int, cat, unit string) (int, string) {
t.Helper()
body, _ := json.Marshal(map[string]any{
"name": testProductPrefix + "unit", "category": cat, "description": "fiche test", "unit": unit,
"prices": []map[string]any{{"quantity": 250, "price": 30, "active_price": true}, {"quantity": 500, "price": 55, "active_price": true}, {"quantity": 1000, "price": 100, "active_price": true}},
})
c, rec := jsonStockContext("admin", body, productID)
handlers.UpdateProduct(c)
return rec.Code, rec.Body.String()
}
func productUnit(t *testing.T, productID int) string {
var u string
testDB.GDB.Raw(`SELECT unit FROM products WHERE id = ?`, productID).Scan(&u)
return u
}
func TestSimulationChangementUnite(t *testing.T) {
t.Run("A_changement_refuse_si_panier_ou_commande_en_cours", func(t *testing.T) {
cleanupStockTestData(t)
p, cat := newKgProduct(t, "unitA")
paul := newTestClient(t, "unit_paul")
paulCmd, err := checkout(paul, map[int]float64{p: 0.25}, []int{p})
if err != nil {
t.Fatalf("commande Paul : %v", err)
}
lea := newTestClient(t, "unit_lea")
testDB.AddToBasket(lea, p, 0.5)
code, body := adminEditProductCode(t, p, cat, "g")
if code != 409 || productUnit(t, p) != "kg" {
t.Errorf("❌ changement kg → g accepté avec un panier et une commande en cours : HTTP %d, unité=%s", code, productUnit(t, p))
} else {
t.Logf("✅ refusé : %s", body)
}
testDB.CreateCommandWithAddress(lea, "1 rue de test")
testDB.CancelCommandAtomic(paulCmd, paul, "test", false)
if got := productStock(t, p); got != 0.5 {
t.Errorf("❌ stock=%.3f kg, attendu 0,5 kg", got)
} else {
t.Logf("✅ stock=0,500 kg après la commande de Léa (500 g) et l'annulation de Paul (250 g)")
}
})
t.Run("B_changement_refuse_tant_qu_une_commande_est_en_route", func(t *testing.T) {
cleanupStockTestData(t)
p, cat := newKgProduct(t, "unitB")
u := newTestClient(t, "unit_route")
id, _ := checkout(u, map[int]float64{p: 0.25}, []int{p})
setStatus(t, id, "en_route", testUserPrefix+"liv")
if code, _ := adminEditProductCode(t, p, cat, "g"); code != 409 {
t.Errorf("❌ changement accepté avec une commande en route : HTTP %d", code)
} else {
t.Logf("✅ refusé avec une commande en route")
}
})
t.Run("C_changement_autorise_sans_panier_ni_commande_en_cours", func(t *testing.T) {
cleanupStockTestData(t)
p, cat := newKgProduct(t, "unitC")
u := newTestClient(t, "unit_done")
id, _ := checkout(u, map[int]float64{p: 0.25}, []int{p})
setStatus(t, id, "approved", "")
u2 := newTestClient(t, "unit_cancel")
id2, _ := checkout(u2, map[int]float64{p: 0.25}, []int{p})
testDB.CancelCommandAtomic(id2, u2, "test", false)
if code, body := adminEditProductCode(t, p, cat, "g"); code != 200 || productUnit(t, p) != "g" {
t.Errorf("❌ changement refusé alors que tout est terminé : HTTP %d %s", code, body)
} else {
t.Logf("✅ unité changée en g (seulement une commande approuvée et une annulée)")
}
})
t.Run("D_meme_unite_toujours_modifiable", func(t *testing.T) {
cleanupStockTestData(t)
p, cat := newKgProduct(t, "unitD")
u := newTestClient(t, "unit_same")
testDB.AddToBasket(u, p, 0.5)
if code, body := adminEditProductCode(t, p, cat, "kg"); code != 200 {
t.Errorf("❌ modification sans changer l'unité refusée : HTTP %d %s", code, body)
} else {
t.Logf("✅ fiche modifiée sans changer l'unité malgré un panier en cours")
}
})
t.Run("E_produit_en_kg_precision_au_gramme", func(t *testing.T) {
cleanupStockTestData(t)
p, _ := newKgProduct(t, "unitE")
testDB.GDB.Exec(`INSERT INTO product_prices (product_id, quantity, price, active_price) VALUES (?, 0.001, 0.1, true), (?, 0.125, 15, true)`, p, p)
real := 1000.0
for i, q := range []float64{0.125, 0.001, 0.001, 0.001, 0.125} {
u := newTestClient(t, "unitE_"+string(rune('a'+i)))
if _, err := checkout(u, map[int]float64{p: q}, []int{p}); err != nil {
t.Fatalf("vente %.3f kg : %v", q, err)
}
real -= q * 1000
t.Logf("vente %.0f g → stock app=%.0f g, réel=%.0f g", q*1000, productStock(t, p)*1000, real)
}
if got := productStock(t, p) * 1000; math.Abs(got-real) > 1e-6 {
t.Errorf("❌ app=%.0f g, réel=%.0f g (écart %+.0f g)", got, real, got-real)
}
})
}
+11
View File
@@ -644,6 +644,17 @@ export const updateProductAdmin = async (
return { success: true, data: data.data, message: data.message };
};
export const updateProductStockAdmin = async (
productId: number,
stock: number,
) => {
const { data } = await apiClient.post(
`${V2}/admin/protected/products/${productId}/stock`,
{ stock },
);
return { success: true, product: data.product };
};
export const deleteProductAdmin = async (productId: number) => {
const { data } = await apiClient.delete(
`${V2}/admin/protected/products/${productId}`,
@@ -23,6 +23,7 @@ import {
getAllProductsAdmin,
createProductAdmin,
updateProductAdmin,
updateProductStockAdmin,
deleteProductAdmin,
uploadProductMediaAdmin,
deleteProductMediaAdmin,
@@ -334,16 +335,20 @@ export default function ProductsScreen() {
}
}
// 2) Update product fields
// 2) Update product fields (sans le stock : il n'écrase pas les ventes en cours)
await updateProductAdmin(editingProduct.id, {
name: form.name.trim(),
category: form.category,
description: form.description.trim(),
stock: parseFloat(form.stock),
unit: form.unit,
prices,
coming_soon: form.comingSoon,
});
const newStock = parseFloat(form.stock);
if (newStock !== editingProduct.stock) {
await updateProductStockAdmin(editingProduct.id, newStock);
}
productId = editingProduct.id;
} else {
// ✅ FIX : Création avec FormData au bon format pour le backend Go