package tests import ( "bytes" "encoding/json" "errors" "gestion/db" "gestion/handlers" "gestion/models" "net/http" "net/http/httptest" "strconv" "testing" "github.com/gin-gonic/gin" "gorm.io/gorm" ) // clientPointsRedeemed lit uniquement le compteur de réservation // (points_redeemed), symétrique de clientPointsExtra (points_approval_test.go). func clientPointsRedeemed(t *testing.T, username string) map[string]int { t.Helper() _, redeemed, err := testDB.GetClientPointsAndRewards(username) if err != nil { t.Fatalf("GetClientPointsAndRewards: %v", err) } return redeemed } // setClientPoolRedeemed fixe directement points_redeemed[poolKey], pour // simuler un état (sentinelle non liée à la commande testée, ou valeur de // départ arbitraire) sans dépendre du flux normal de réclamation. func setClientPoolRedeemed(t *testing.T, username, poolKey string, value int) { t.Helper() if err := testDB.GDB.Exec( `UPDATE clients SET points_redeemed = jsonb_set(COALESCE(points_redeemed, '{}'::jsonb), ARRAY[?], to_jsonb(?::int)) WHERE username = ?`, poolKey, value, username, ).Error; err != nil { t.Fatalf("setClientPoolRedeemed: %v", err) } } func basketItemID(t *testing.T, username string, isReward bool) int { t.Helper() var id int if err := testDB.GDB.Raw( `SELECT id FROM baskets WHERE username = ? AND is_reward = ? ORDER BY created_at DESC LIMIT 1`, username, isReward, ).Scan(&id).Error; err != nil { t.Fatalf("basketItemID: %v", err) } if id == 0 { t.Fatalf("aucun article trouvé (username=%s, is_reward=%v)", username, isReward) } return id } func basketItemCount(t *testing.T, username string) int { t.Helper() var count int if err := testDB.GDB.Raw(`SELECT COUNT(*) FROM baskets WHERE username = ?`, username).Scan(&count).Error; err != nil { t.Fatalf("basketItemCount: %v", err) } return count } // ════════════════════════════════════════════════════════════════════════ // Correctif 1 — DeleteProductFromBasket / ClearBasket libèrent la réservation // (points_redeemed) quand l'article supprimé est une récompense, pour que le // client puisse en réclamer une autre avec les mêmes points. // ════════════════════════════════════════════════════════════════════════ func TestDeleteProductFromBasket_RewardItem_ReleasesReservation(t *testing.T) { cleanupStockTestData(t) username := newTestClient(t, "del_basket_reward_release") productID := newTestProduct(t, "DelBasketRewardRelease", 5) setClientPoolPoints(t, username, "pool_0", 20) if _, _, err := testDB.ClaimPoolRewardAndAddToBasket(username, "pool_0", 20, []models.RewardItem{{ProductID: productID, Quantity: 1, Price: 0}}); err != nil { t.Fatalf("ClaimPoolRewardAndAddToBasket: %v", err) } if got := clientPointsRedeemed(t, username)["pool_0"]; got != 1 { t.Fatalf("redeemed après claim: got=%d want=1", got) } rewardID := basketItemID(t, username, true) if err := testDB.DeleteProductFromBasket(rewardID); err != nil { t.Fatalf("DeleteProductFromBasket: %v", err) } if got := clientPointsRedeemed(t, username)["pool_0"]; got != 0 { t.Errorf("redeemed après suppression de la récompense du panier: got=%d want=0", got) } if rows := basketRewardItems(t, username); len(rows) != 0 { t.Errorf("panier devrait être vide de récompense: got=%d", len(rows)) } } // Le scénario exact signalé : supprimer, puis reclaquer une récompense // (même ou différente) doit de nouveau fonctionner. func TestDeleteProductFromBasket_RewardItem_AllowsReClaimAfterDeletion(t *testing.T) { cleanupStockTestData(t) username := newTestClient(t, "del_basket_reward_reclaim") productA := newTestProduct(t, "DelBasketReclaimA", 5) productB := newTestProduct(t, "DelBasketReclaimB", 5) setClientPoolPoints(t, username, "pool_0", 20) if _, _, err := testDB.ClaimPoolRewardAndAddToBasket(username, "pool_0", 20, []models.RewardItem{{ProductID: productA, Quantity: 1, Price: 0}}); err != nil { t.Fatalf("1er claim: %v", err) } testDB.DeleteProductFromBasket(basketItemID(t, username, true)) // Sans le correctif, ce second claim échoue ("pas de récompense // disponible") car points_redeemed est resté à 1 alors qu'aucun point // n'a jamais été réellement débité (points_extra inchangé). remaining, added, err := testDB.ClaimPoolRewardAndAddToBasket(username, "pool_0", 20, []models.RewardItem{{ProductID: productB, Quantity: 1, Price: 0}}) if err != nil { t.Fatalf("2e claim (après suppression) devrait réussir: %v", err) } if remaining != 0 { t.Errorf("remaining après 2e claim: got=%d want=0", remaining) } if len(added) != 1 || added[0].ProductID != productB { t.Errorf("le produit B devrait être ajouté au panier: %+v", added) } } func TestDeleteProductFromBasket_NonRewardItem_DoesNotAffectReservation(t *testing.T) { cleanupStockTestData(t) username := newTestClient(t, "del_basket_normal_item") rewardProductID := newTestProduct(t, "DelBasketNormalReward", 5) paidProductID := newTestProduct(t, "DelBasketNormalPaid", 20) setClientPoolPoints(t, username, "pool_0", 20) if _, _, err := testDB.ClaimPoolRewardAndAddToBasket(username, "pool_0", 20, []models.RewardItem{{ProductID: rewardProductID, Quantity: 1, Price: 0}}); err != nil { t.Fatalf("claim: %v", err) } paidItem, err := testDB.AddToBasket(username, paidProductID, 2) if err != nil { t.Fatalf("AddToBasket: %v", err) } if err := testDB.DeleteProductFromBasket(paidItem.ID); err != nil { t.Fatalf("DeleteProductFromBasket (article normal): %v", err) } if got := clientPointsRedeemed(t, username)["pool_0"]; got != 1 { t.Errorf("redeemed ne doit pas changer quand on supprime un article non-récompense: got=%d want=1", got) } if rows := basketRewardItems(t, username); len(rows) != 1 { t.Errorf("l'article récompense doit rester en panier: got=%d want=1", len(rows)) } } func TestDeleteProductFromBasket_UnknownID_ReturnsErrorAndTouchesNothing(t *testing.T) { cleanupStockTestData(t) username := newTestClient(t, "del_basket_unknown_id") setClientPoolPoints(t, username, "pool_0", 20) testDB.ClaimPoolReward(username, "pool_0", 20) // redeemed=1, sans article en panier if err := testDB.DeleteProductFromBasket(999999999); err == nil { t.Fatal("attendu une erreur pour un ID de panier inexistant") } if got := clientPointsRedeemed(t, username)["pool_0"]; got != 1 { t.Errorf("un ID inconnu ne doit rien libérer: got=%d want=1", got) } } func TestClearBasket_WithRewardItem_ReleasesReservation(t *testing.T) { cleanupStockTestData(t) username := newTestClient(t, "clear_basket_reward") rewardProductID := newTestProduct(t, "ClearBasketReward", 5) paidProductID := newTestProduct(t, "ClearBasketPaid", 20) setClientPoolPoints(t, username, "pool_0", 20) if _, _, err := testDB.ClaimPoolRewardAndAddToBasket(username, "pool_0", 20, []models.RewardItem{{ProductID: rewardProductID, Quantity: 1, Price: 0}}); err != nil { t.Fatalf("claim: %v", err) } if _, err := testDB.AddToBasket(username, paidProductID, 1); err != nil { t.Fatalf("AddToBasket: %v", err) } if err := testDB.ClearBasket(username); err != nil { t.Fatalf("ClearBasket: %v", err) } if got := basketItemCount(t, username); got != 0 { t.Errorf("panier devrait être vide: got=%d", got) } if got := clientPointsRedeemed(t, username)["pool_0"]; got != 0 { t.Errorf("redeemed après ClearBasket (panier contenait une récompense): got=%d want=0", got) } } func TestClearBasket_NoRewardItems_NoPointsChangeAndNoError(t *testing.T) { cleanupStockTestData(t) username := newTestClient(t, "clear_basket_no_reward") paidProductID := newTestProduct(t, "ClearBasketNoReward", 20) if _, err := testDB.AddToBasket(username, paidProductID, 1); err != nil { t.Fatalf("AddToBasket: %v", err) } if err := testDB.ClearBasket(username); err != nil { t.Fatalf("ClearBasket sans récompense ne doit pas échouer: %v", err) } if got := clientPointsRedeemed(t, username); len(got) != 0 { t.Errorf("aucun pool ne doit être touché: got=%v", got) } } func TestClearBasket_EmptyBasket_NoError(t *testing.T) { cleanupStockTestData(t) username := newTestClient(t, "clear_basket_empty") if err := testDB.ClearBasket(username); err != nil { t.Fatalf("ClearBasket sur un panier déjà vide ne doit pas échouer: %v", err) } } // Deux pools de récompense distincts dans le même panier (état obtenu ici en // insérant directement les lignes, pour couvrir le cas sans dépendre du flux // normal qui remplace les anciennes lignes récompense à chaque claim) : les // deux réservations doivent être libérées, pas seulement une. func TestClearBasket_MultipleDistinctRewardPools_ReleasesAllOfThem(t *testing.T) { cleanupStockTestData(t) username := newTestClient(t, "clear_basket_multi_pool") productA := newTestProduct(t, "ClearBasketMultiA", 5) productB := newTestProduct(t, "ClearBasketMultiB", 5) setClientPoolPoints(t, username, "pool_0", 20) setClientPoolPoints(t, username, "pool_1", 20) testDB.ClaimPoolReward(username, "pool_0", 20) testDB.ClaimPoolReward(username, "pool_1", 20) if err := testDB.GDB.Exec( `INSERT INTO baskets (username, product_id, quantity, price, is_reward, reward_pool_key, created_at) VALUES (?, ?, 1, 0, true, 'pool_0', CURRENT_TIMESTAMP), (?, ?, 1, 0, true, 'pool_1', CURRENT_TIMESTAMP)`, username, productA, username, productB, ).Error; err != nil { t.Fatalf("insertion panier multi-pool: %v", err) } if err := testDB.ClearBasket(username); err != nil { t.Fatalf("ClearBasket: %v", err) } redeemed := clientPointsRedeemed(t, username) if redeemed["pool_0"] != 0 { t.Errorf("pool_0 doit être libéré: got=%d want=0", redeemed["pool_0"]) } if redeemed["pool_1"] != 0 { t.Errorf("pool_1 doit être libéré: got=%d want=0", redeemed["pool_1"]) } } // ════════════════════════════════════════════════════════════════════════ // Correctif 2 — PUT /points/swap (handlers.SwapMyRewardProduct) : changer le // produit d'une récompense déjà en panier sans consommer une nouvelle // réservation, avec revalidation complète côté serveur. // ════════════════════════════════════════════════════════════════════════ func swapRewardContext(username string, body []byte) (*gin.Context, *httptest.ResponseRecorder) { req := httptest.NewRequest(http.MethodPut, "/api/v1/points/swap", 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("username", username) return c, rec } func TestSwapMyRewardProduct_SwapsToEligibleProductWithoutConsumingNewReservation(t *testing.T) { cleanupStockTestData(t) username := newTestClient(t, "swap_reward_ok") productA := newTestProduct(t, "SwapRewardOkA", 5) productB := newTestProduct(t, "SwapRewardOkB", 5) configureRewardSettings(t, &models.PointsReward{ Threshold: 20, CategoryConfigs: []models.RewardCategoryConfig{ {Category: "test", Type: "free_product", Products: []models.RewardProductQuantity{ {ProductID: productA, Quantity: 1}, {ProductID: productB, Quantity: 1}, }}, }, }) setClientPoolPoints(t, username, "pool_0", 20) claimBody, _ := json.Marshal(map[string]any{"pool_key": "pool_0", "product_id": productA}) cClaim, recClaim := claimRewardContext(username, claimBody) handlers.ClaimMyReward(cClaim) if recClaim.Code != http.StatusOK { t.Fatalf("claim initial: status=%d body=%s", recClaim.Code, recClaim.Body.String()) } if got := clientPointsRedeemed(t, username)["pool_0"]; got != 1 { t.Fatalf("redeemed après claim initial: got=%d want=1", got) } swapBody, _ := json.Marshal(map[string]any{"product_id": productB}) cSwap, recSwap := swapRewardContext(username, swapBody) handlers.SwapMyRewardProduct(cSwap) if recSwap.Code != http.StatusOK { t.Fatalf("swap: status=%d body=%s", recSwap.Code, recSwap.Body.String()) } rows := basketRewardItems(t, username) if len(rows) != 1 || rows[0].ProductID != productB { t.Fatalf("le panier doit contenir uniquement le produit B après swap: %+v", rows) } if rows[0].RewardPoolKey != "pool_0" { t.Errorf("reward_pool_key doit rester pool_0: got=%q", rows[0].RewardPoolKey) } // Le point central du correctif : aucune nouvelle réservation consommée. if got := clientPointsRedeemed(t, username)["pool_0"]; got != 1 { t.Errorf("redeemed ne doit pas bouger après un swap: got=%d want=1", got) } } // Le backend ne doit jamais faire confiance au product_id envoyé par le // client : un produit hors de toute config éligible pour le pool actif doit // être rejeté, et le panier ne doit pas être modifié. func TestSwapMyRewardProduct_RejectsIneligibleProduct(t *testing.T) { cleanupStockTestData(t) username := newTestClient(t, "swap_reward_ineligible") eligibleProduct := newTestProduct(t, "SwapRewardIneligibleOk", 5) otherProduct := newTestProduct(t, "SwapRewardIneligibleOther", 5) // jamais listé comme récompense configureRewardSettings(t, &models.PointsReward{ Threshold: 20, CategoryConfigs: []models.RewardCategoryConfig{ {Category: "test", Type: "free_product", Products: []models.RewardProductQuantity{ {ProductID: eligibleProduct, Quantity: 1}, }}, }, }) setClientPoolPoints(t, username, "pool_0", 20) claimBody, _ := json.Marshal(map[string]any{"pool_key": "pool_0"}) cClaim, _ := claimRewardContext(username, claimBody) handlers.ClaimMyReward(cClaim) swapBody, _ := json.Marshal(map[string]any{"product_id": otherProduct}) cSwap, recSwap := swapRewardContext(username, swapBody) handlers.SwapMyRewardProduct(cSwap) if recSwap.Code != http.StatusForbidden { t.Fatalf("status HTTP: got=%d want=%d body=%s", recSwap.Code, http.StatusForbidden, recSwap.Body.String()) } rows := basketRewardItems(t, username) if len(rows) != 1 || rows[0].ProductID != eligibleProduct { t.Errorf("le panier ne doit pas avoir changé: %+v", rows) } if got := clientPointsRedeemed(t, username)["pool_0"]; got != 1 { t.Errorf("redeemed ne doit pas bouger sur un swap rejeté: got=%d want=1", got) } } func TestSwapMyRewardProduct_NoActiveRewardInBasket_ReturnsConflict(t *testing.T) { cleanupStockTestData(t) username := newTestClient(t, "swap_reward_no_active") productID := newTestProduct(t, "SwapRewardNoActive", 5) configureRewardSettings(t, &models.PointsReward{ Threshold: 20, CategoryConfigs: []models.RewardCategoryConfig{ {Category: "test", Type: "free_product", AllProducts: true, Quantity: 1}, }, }) swapBody, _ := json.Marshal(map[string]any{"product_id": productID}) c, rec := swapRewardContext(username, swapBody) handlers.SwapMyRewardProduct(c) if rec.Code != http.StatusConflict { t.Fatalf("status HTTP: got=%d want=%d body=%s", rec.Code, http.StatusConflict, rec.Body.String()) } } func TestSwapMyRewardProduct_MissingProductID_ReturnsBadRequest(t *testing.T) { cleanupStockTestData(t) username := newTestClient(t, "swap_reward_missing_id") c, rec := swapRewardContext(username, []byte(`{}`)) handlers.SwapMyRewardProduct(c) if rec.Code != http.StatusBadRequest { t.Fatalf("status HTTP: got=%d want=%d body=%s", rec.Code, http.StatusBadRequest, rec.Body.String()) } } func TestSwapMyRewardProduct_PointsDisabled_Rejected(t *testing.T) { cleanupStockTestData(t) username := newTestClient(t, "swap_reward_disabled") productA := newTestProduct(t, "SwapRewardDisabledA", 5) productB := newTestProduct(t, "SwapRewardDisabledB", 5) settings := db.DefaultSettings() settings.PointsPools[0].Categories = []string{"test"} settings.PointsReward = &models.PointsReward{ Threshold: 20, CategoryConfigs: []models.RewardCategoryConfig{ {Category: "test", Type: "free_product", Products: []models.RewardProductQuantity{ {ProductID: productA, Quantity: 1}, {ProductID: productB, Quantity: 1}, }}, }, } if err := testDB.UpdateSettings(settings); err != nil { t.Fatalf("UpdateSettings (activé): %v", err) } setClientPoolPoints(t, username, "pool_0", 20) claimBody, _ := json.Marshal(map[string]any{"pool_key": "pool_0", "product_id": productA}) cClaim, _ := claimRewardContext(username, claimBody) handlers.ClaimMyReward(cClaim) settings.PointsEnabled = false if err := testDB.UpdateSettings(settings); err != nil { t.Fatalf("UpdateSettings (désactivé): %v", err) } swapBody, _ := json.Marshal(map[string]any{"product_id": productB}) c, rec := swapRewardContext(username, swapBody) handlers.SwapMyRewardProduct(c) if rec.Code != http.StatusForbidden { t.Fatalf("status HTTP: got=%d want=%d body=%s", rec.Code, http.StatusForbidden, rec.Body.String()) } } // Le prix effectif doit être recalculé à chaque swap, pas recopié de // l'ancienne ligne — ici le produit B a un palier de prix supérieur. func TestSwapMyRewardProduct_HalfPriceType_RecomputesPriceFromCurrentCatalog(t *testing.T) { cleanupStockTestData(t) username := newTestClient(t, "swap_reward_halfprice") productA := newTestProduct(t, "SwapRewardHalfA", 5) // prix catalogue 10.00€ (newTestProduct) productB := newTestProduct(t, "SwapRewardHalfB", 5) if err := testDB.GDB.Exec( `UPDATE product_prices SET price = 30.00 WHERE product_id = ? AND quantity = 1`, productB, ).Error; err != nil { t.Fatalf("maj prix produit B: %v", err) } configureRewardSettings(t, &models.PointsReward{ Threshold: 20, CategoryConfigs: []models.RewardCategoryConfig{ {Category: "test", Type: "half_price_product", Products: []models.RewardProductQuantity{ {ProductID: productA, Quantity: 1}, {ProductID: productB, Quantity: 1}, }}, }, }) setClientPoolPoints(t, username, "pool_0", 20) claimBody, _ := json.Marshal(map[string]any{"pool_key": "pool_0", "product_id": productA}) cClaim, recClaim := claimRewardContext(username, claimBody) handlers.ClaimMyReward(cClaim) if recClaim.Code != http.StatusOK { t.Fatalf("claim: status=%d body=%s", recClaim.Code, recClaim.Body.String()) } if rows := basketRewardItems(t, username); len(rows) != 1 || rows[0].Price != 5.0 { t.Fatalf("prix initial attendu 5.00€ (50%% de 10€): %+v", rows) } swapBody, _ := json.Marshal(map[string]any{"product_id": productB}) cSwap, recSwap := swapRewardContext(username, swapBody) handlers.SwapMyRewardProduct(cSwap) if recSwap.Code != http.StatusOK { t.Fatalf("swap: status=%d body=%s", recSwap.Code, recSwap.Body.String()) } rows := basketRewardItems(t, username) if len(rows) != 1 || rows[0].ProductID != productB { t.Fatalf("panier après swap: %+v", rows) } if rows[0].Price != 15.0 { t.Errorf("prix après swap attendu 15.00€ (50%% de 30€, recalculé): got=%.2f", rows[0].Price) } } // ════════════════════════════════════════════════════════════════════════ // Correctif 3 — libération de la réservation de récompense à l'annulation // avant "approved", et préservation stricte des points après "approved". // ════════════════════════════════════════════════════════════════════════ func TestReleaseRewardReservationsForCommandTx_SingleRewardItem_DecrementsOnce(t *testing.T) { cleanupStockTestData(t) username := newTestClient(t, "release_single") productID := newTestProduct(t, "ReleaseSingle", 5) setClientPoolPoints(t, username, "pool_0", 20) testDB.ClaimPoolReward(username, "pool_0", 20) // redeemed["pool_0"] = 1 cmdID := newTestCommandWithItem(t, username, "pending", "", productID, 1, 0) insertRewardCommandItem(t, cmdID, productID, 1, 0, "pool_0") if err := testDB.GDB.Transaction(func(tx *gorm.DB) error { return testDB.ReleaseRewardReservationsForCommandTx(tx, cmdID, username) }); err != nil { t.Fatalf("ReleaseRewardReservationsForCommandTx: %v", err) } if got := clientPointsRedeemed(t, username)["pool_0"]; got != 0 { t.Errorf("redeemed après libération: got=%d want=0", got) } } // Une seule réclamation peut avoir ajouté plusieurs lignes pour le même pool // (plusieurs produits éligibles) : une seule réservation doit être libérée, // pas une par ligne. func TestReleaseRewardReservationsForCommandTx_MultipleRowsSamePool_DecrementsOnlyOnce(t *testing.T) { cleanupStockTestData(t) username := newTestClient(t, "release_multi_row") productA := newTestProduct(t, "ReleaseMultiRowA", 5) productB := newTestProduct(t, "ReleaseMultiRowB", 5) // 2 au lieu de 1 pour distinguer "décrémenté une fois" (-> 1) de // "décrémenté une fois par ligne" (-> 0, bug visé par le DISTINCT). setClientPoolRedeemed(t, username, "pool_0", 2) cmdID := newTestCommandWithItem(t, username, "pending", "", productA, 1, 0) insertRewardCommandItem(t, cmdID, productA, 1, 0, "pool_0") insertRewardCommandItem(t, cmdID, productB, 1, 0, "pool_0") if err := testDB.GDB.Transaction(func(tx *gorm.DB) error { return testDB.ReleaseRewardReservationsForCommandTx(tx, cmdID, username) }); err != nil { t.Fatalf("ReleaseRewardReservationsForCommandTx: %v", err) } if got := clientPointsRedeemed(t, username)["pool_0"]; got != 1 { t.Errorf("redeemed après libération (2 lignes, même pool, une seule réservation): got=%d want=1", got) } } func TestReleaseRewardReservationsForCommandTx_MultiplePoolsInOneCommand_ReleasesEachIndependently(t *testing.T) { cleanupStockTestData(t) username := newTestClient(t, "release_multi_pool") productA := newTestProduct(t, "ReleaseMultiPoolA", 5) productB := newTestProduct(t, "ReleaseMultiPoolB", 5) setClientPoolRedeemed(t, username, "pool_0", 1) setClientPoolRedeemed(t, username, "pool_1", 1) cmdID := newTestCommandWithItem(t, username, "pending", "", productA, 1, 0) insertRewardCommandItem(t, cmdID, productA, 1, 0, "pool_0") insertRewardCommandItem(t, cmdID, productB, 1, 0, "pool_1") if err := testDB.GDB.Transaction(func(tx *gorm.DB) error { return testDB.ReleaseRewardReservationsForCommandTx(tx, cmdID, username) }); err != nil { t.Fatalf("ReleaseRewardReservationsForCommandTx: %v", err) } redeemed := clientPointsRedeemed(t, username) if redeemed["pool_0"] != 0 { t.Errorf("pool_0: got=%d want=0", redeemed["pool_0"]) } if redeemed["pool_1"] != 0 { t.Errorf("pool_1: got=%d want=0", redeemed["pool_1"]) } } func TestReleaseRewardReservationsForCommandTx_NoRewardItems_NoOp(t *testing.T) { cleanupStockTestData(t) username := newTestClient(t, "release_no_reward") productID := newTestProduct(t, "ReleaseNoReward", 5) setClientPoolRedeemed(t, username, "pool_0", 3) cmdID := newTestCommandWithItem(t, username, "pending", "", productID, 1, 0) if err := testDB.GDB.Transaction(func(tx *gorm.DB) error { return testDB.ReleaseRewardReservationsForCommandTx(tx, cmdID, username) }); err != nil { t.Fatalf("ReleaseRewardReservationsForCommandTx: %v", err) } if got := clientPointsRedeemed(t, username)["pool_0"]; got != 3 { t.Errorf("commande sans article récompense: redeemed ne doit pas bouger: got=%d want=3", got) } } func TestReleaseRewardReservationsForCommandTx_FloorsAtZero(t *testing.T) { cleanupStockTestData(t) username := newTestClient(t, "release_floor_zero") productID := newTestProduct(t, "ReleaseFloorZero", 5) // redeemed déjà à 0 (incohérence volontaire pour vérifier l'absence de négatif). cmdID := newTestCommandWithItem(t, username, "pending", "", productID, 1, 0) insertRewardCommandItem(t, cmdID, productID, 1, 0, "pool_0") if err := testDB.GDB.Transaction(func(tx *gorm.DB) error { return testDB.ReleaseRewardReservationsForCommandTx(tx, cmdID, username) }); err != nil { t.Fatalf("ReleaseRewardReservationsForCommandTx: %v", err) } if got := clientPointsRedeemed(t, username)["pool_0"]; got != 0 { t.Errorf("redeemed ne doit jamais devenir négatif: got=%d want=0", got) } } // ── Intégration avec les 3 chemins d'annulation réels ─────────────────────── func TestCancelCommandAtomic_WithRewardItem_ReleasesReservation(t *testing.T) { cleanupStockTestData(t) username := newTestClient(t, "cancel_client_reward") rewardProductID := newTestProduct(t, "CancelClientRewardFree", 5) paidProductID := newTestProduct(t, "CancelClientRewardPaid", 10) setClientPoolPoints(t, username, "pool_0", 20) testDB.ClaimPoolReward(username, "pool_0", 20) cmdID := newTestCommandWithItem(t, username, "pending", "", paidProductID, 1, 10) insertRewardCommandItem(t, cmdID, rewardProductID, 1, 0, "pool_0") if _, err := testDB.CancelCommandAtomic(cmdID, username, "test", false); err != nil { t.Fatalf("CancelCommandAtomic: %v", err) } if got := commandStatus(t, cmdID); got != "cancelled" { t.Errorf("statut: got=%s want=cancelled", got) } if got := clientPointsRedeemed(t, username)["pool_0"]; got != 0 { t.Errorf("redeemed après annulation client d'une commande avec récompense: got=%d want=0", got) } } func TestCancelCommandAtomic_WithoutRewardItem_DoesNotTouchPoints(t *testing.T) { cleanupStockTestData(t) username := newTestClient(t, "cancel_client_noreward") productID := newTestProduct(t, "CancelClientNoReward", 5) setClientPoolRedeemed(t, username, "pool_0", 2) // sentinelle sans rapport avec cette commande cmdID := newTestCommandWithItem(t, username, "pending", "", productID, 1, 10) if _, err := testDB.CancelCommandAtomic(cmdID, username, "test", false); err != nil { t.Fatalf("CancelCommandAtomic: %v", err) } if got := clientPointsRedeemed(t, username)["pool_0"]; got != 2 { t.Errorf("annulation sans récompense: redeemed ne doit pas bouger: got=%d want=2", got) } } func TestCancelDeliveryByLivreurAtomic_WithRewardItem_ReleasesReservation(t *testing.T) { cleanupStockTestData(t) username := newTestClient(t, "cancel_livreur_reward") rewardProductID := newTestProduct(t, "CancelLivreurRewardFree", 5) paidProductID := newTestProduct(t, "CancelLivreurRewardPaid", 10) setClientPoolPoints(t, username, "pool_0", 20) testDB.ClaimPoolReward(username, "pool_0", 20) cmdID := newTestCommandWithItem(t, username, "en_route", 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 got := clientPointsRedeemed(t, username)["pool_0"]; got != 0 { t.Errorf("redeemed après annulation livreur d'une commande avec récompense: got=%d want=0", got) } } // Un livreur ne devrait jamais voir une commande "approved" dans sa file, // mais si c'est pourtant le cas (incohérence), les points déjà réglés à // l'approbation ne doivent pas être rouverts. func TestCancelDeliveryByLivreurAtomic_AlreadyApproved_DoesNotTouchPoints(t *testing.T) { cleanupStockTestData(t) username := newTestClient(t, "cancel_livreur_approved") rewardProductID := newTestProduct(t, "CancelLivreurApprovedFree", 5) paidProductID := newTestProduct(t, "CancelLivreurApprovedPaid", 10) setClientPoolRedeemed(t, username, "pool_0", 5) // sentinelle : doit rester intacte cmdID := newTestCommandWithItem(t, username, "approved", testUserPrefix+"livreurY", paidProductID, 1, 10) insertRewardCommandItem(t, cmdID, rewardProductID, 1, 0, "pool_0") 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 { t.Errorf("une commande déjà approuvée ne doit jamais voir ses points retouchés: got=%d want=5", got) } } func adminCancelCtx(commandID int) (*gin.Context, *httptest.ResponseRecorder) { body, _ := json.Marshal(map[string]string{"status": "cancelled"}) req := httptest.NewRequest(http.MethodPut, "/api/v2/admin/protected/orders/x/status", 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.Params = gin.Params{{Key: "id", Value: strconv.Itoa(commandID)}} return c, rec } func TestUpdateCommandStatusAdmin_PreApprovedWithRewardItem_ReleasesReservation(t *testing.T) { cleanupStockTestData(t) username := newTestClient(t, "admincancel_reward_pre") rewardProductID := newTestProduct(t, "AdminCancelRewardPreFree", 5) paidProductID := newTestProduct(t, "AdminCancelRewardPrePaid", 10) setClientPoolPoints(t, username, "pool_0", 20) testDB.ClaimPoolReward(username, "pool_0", 20) cmdID := newTestCommandWithItem(t, username, "livre", "", paidProductID, 1, 10) insertRewardCommandItem(t, cmdID, rewardProductID, 1, 0, "pool_0") 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 got := clientPointsRedeemed(t, username)["pool_0"]; got != 0 { t.Errorf("redeemed après annulation admin d'une commande 'livre' avec récompense: got=%d want=0", got) } } // La règle métier centrale du correctif 3 : une commande déjà "approved" // (points gagnés déjà crédités, points de récompense déjà déduits au moment // de l'approbation) ne doit plus voir ses points touchés du tout quand un // admin l'annule après coup — ni la réservation, ni le solde. func TestUpdateCommandStatusAdmin_AlreadyApprovedWithRewardItem_DoesNotTouchPoints(t *testing.T) { cleanupStockTestData(t) username := newTestClient(t, "admincancel_reward_post") rewardProductID := newTestProduct(t, "AdminCancelRewardPostFree", 5) paidProductID := newTestProduct(t, "AdminCancelRewardPostPaid", 10) // Sentinelle : une réservation d'une AUTRE commande non liée, toujours en // cours, qui ne doit surtout pas être libérée par l'annulation de celle-ci. setClientPoolRedeemed(t, username, "pool_0", 3) setClientPoolPoints(t, username, "pool_0", 17) // solde déjà réglé par une approbation antérieure cmdID := newTestCommandWithItem(t, username, "approved", "", paidProductID, 1, 10) insertRewardCommandItem(t, cmdID, rewardProductID, 1, 0, "pool_0") pointsBefore := clientPointsExtra(t, username)["pool_0"] c, rec := adminCancelCtx(cmdID) handlers.UpdateCommandStatusAdmin(c) 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 { t.Errorf("redeemed ne doit pas bouger pour une commande déjà approuvée: got=%d want=3", got) } if got := clientPointsExtra(t, username)["pool_0"]; got != pointsBefore { t.Errorf("points_extra ne doit pas bouger pour une commande déjà approuvée: got=%d want=%d", got, pointsBefore) } } // ════════════════════════════════════════════════════════════════════════ // Correctif annexe — CalculateAndAddPointsForCommandTx ne doit déduire le // seuil qu'une fois par pool distinct, pas une fois par ligne récompense. // ════════════════════════════════════════════════════════════════════════ func TestCalculateAndAddPointsForCommandTx_MultipleRewardRowsSamePool_DeductsThresholdOnce(t *testing.T) { cleanupStockTestData(t) username := newTestClient(t, "points_dedup_reward_rows") paidProductID := newTestProduct(t, "PointsDedupPaid", 20) rewardProductA := newTestProduct(t, "PointsDedupRewardA", 5) rewardProductB := newTestProduct(t, "PointsDedupRewardB", 5) setPointsPoolsSettings(t, []models.PointsPool{ {Key: "pool_0", Name: "Pool Test", Categories: []string{"test"}, Tiers: []models.PointsTier{{Min: 0, Max: 0, Points: 3}}}, }) setPointsRewardSettings(t, models.PointsReward{Threshold: 20}) setClientPoolPoints(t, username, "pool_0", 25) cmdID := newTestCommandWithItem(t, username, "livre", "", paidProductID, 1, 10) // Simule une seule réclamation ayant ajouté 2 produits éligibles pour le // même pool (une seule réservation réellement consommée). insertRewardCommandItem(t, cmdID, rewardProductA, 1, 0, "pool_0") insertRewardCommandItem(t, cmdID, rewardProductB, 1, 0, "pool_0") testDB.GDB.Transaction(func(tx *gorm.DB) error { pts, _, err := testDB.CalculateAndAddPointsForCommandTx(tx, cmdID, username) if err != nil { t.Fatalf("CalculateAndAddPointsForCommandTx: %v", err) } if pts != 3 { t.Errorf("points gagnés sur l'article payant: got=%d want=3", pts) } return nil }) // 25 (initial) + 3 (gagnés) - 20 (seuil déduit UNE SEULE FOIS) = 8. // Sans le DISTINCT, le code déduirait 20 deux fois (une par ligne) et // finirait à 0 (plancher), pas 8. if got := clientPointsExtra(t, username)["pool_0"]; got != 8 { t.Errorf("points_extra après déduction d'une récompense à 2 lignes: got=%d want=8", got) } } func TestCalculateAndAddPointsForCommandTx_MultipleRewardRowsSamePool_DecrementsRedeemedOnce(t *testing.T) { cleanupStockTestData(t) username := newTestClient(t, "points_dedup_redeemed") paidProductID := newTestProduct(t, "PointsDedupRedeemedPaid", 20) rewardProductA := newTestProduct(t, "PointsDedupRedeemedA", 5) rewardProductB := newTestProduct(t, "PointsDedupRedeemedB", 5) setPointsPoolsSettings(t, []models.PointsPool{ {Key: "pool_0", Name: "Pool Test", Categories: []string{"test"}, Tiers: []models.PointsTier{{Min: 0, Max: 0, Points: 0}}}, }) setPointsRewardSettings(t, models.PointsReward{Threshold: 20}) setClientPoolPoints(t, username, "pool_0", 40) // 2 au lieu de 1 pour distinguer "décrémenté une fois" (-> 1) de // "décrémenté une fois par ligne" (-> 0). setClientPoolRedeemed(t, username, "pool_0", 2) cmdID := newTestCommandWithItem(t, username, "livre", "", paidProductID, 1, 10) insertRewardCommandItem(t, cmdID, rewardProductA, 1, 0, "pool_0") insertRewardCommandItem(t, cmdID, rewardProductB, 1, 0, "pool_0") testDB.GDB.Transaction(func(tx *gorm.DB) error { _, _, err := testDB.CalculateAndAddPointsForCommandTx(tx, cmdID, username) if err != nil { t.Fatalf("CalculateAndAddPointsForCommandTx: %v", err) } return nil }) if got := clientPointsRedeemed(t, username)["pool_0"]; got != 1 { t.Errorf("redeemed après approbation (2 lignes, même pool, une seule réservation): got=%d want=1", got) } }