@@ -61,6 +61,20 @@ func (d *Database) GetAllProductsInBasket(username string) ([]models.Panier, err
|
||||
return baskets, nil
|
||||
}
|
||||
|
||||
// GetActiveRewardPoolKey retourne le reward_pool_key de la récompense
|
||||
// actuellement dans le panier du client, ou "" si aucune.
|
||||
func (d *Database) GetActiveRewardPoolKey(username string) (string, error) {
|
||||
var poolKey string
|
||||
err := d.GDB.Raw(`
|
||||
SELECT reward_pool_key FROM baskets
|
||||
WHERE username = ? AND is_reward = true AND reward_pool_key != ''
|
||||
LIMIT 1`, username).Scan(&poolKey).Error
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("erreur lecture récompense panier: %w", err)
|
||||
}
|
||||
return poolKey, nil
|
||||
}
|
||||
|
||||
// AddRewardsToBasket ajoute plusieurs produits récompense au panier (is_reward = true),
|
||||
// au prix fourni par l'appelant dans chaque RewardItem.Price (0 pour un produit offert,
|
||||
// ou le prix effectif déjà calculé pour une remise — voir handlers/points.go).
|
||||
@@ -202,21 +216,58 @@ func (d *Database) AddToBasket(username string, productID int, quantity float64)
|
||||
|
||||
// DeleteProductFromBasket supprime un produit spécifique du panier.
|
||||
// Le stock n'est pas restitué car il n'a pas été décrémenté à l'ajout.
|
||||
// Si l'article supprimé est une récompense, la réservation de points
|
||||
// correspondante (points_redeemed) est libérée dans la même transaction —
|
||||
// sinon le client perdrait définitivement un "slot" de récompense pour
|
||||
// avoir simplement retiré l'article de son panier avant de commander.
|
||||
func (d *Database) DeleteProductFromBasket(basketID int) error {
|
||||
result := d.GDB.Exec(`DELETE FROM baskets WHERE id = ?`, basketID)
|
||||
if result.Error != nil {
|
||||
return fmt.Errorf("erreur lors de la suppression du produit: %w", result.Error)
|
||||
return d.GDB.Transaction(func(tx *gorm.DB) error {
|
||||
var deleted struct {
|
||||
Username string `gorm:"column:username"`
|
||||
IsReward bool `gorm:"column:is_reward"`
|
||||
RewardPoolKey string `gorm:"column:reward_pool_key"`
|
||||
}
|
||||
if result.RowsAffected == 0 {
|
||||
if err := tx.Raw(`
|
||||
DELETE FROM baskets WHERE id = ?
|
||||
RETURNING username, is_reward, reward_pool_key`, basketID).
|
||||
Scan(&deleted).Error; err != nil {
|
||||
return fmt.Errorf("erreur lors de la suppression du produit: %w", err)
|
||||
}
|
||||
if deleted.Username == "" {
|
||||
return fmt.Errorf("produit non trouvé dans le panier")
|
||||
}
|
||||
if deleted.IsReward && deleted.RewardPoolKey != "" {
|
||||
if err := releaseRewardReservationTx(tx, deleted.Username, deleted.RewardPoolKey); err != nil {
|
||||
return fmt.Errorf("erreur libération réservation récompense: %w", err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
// ClearBasket vide complètement le panier d'un utilisateur.
|
||||
// Le stock n'est pas restitué car il n'a pas été décrémenté à l'ajout.
|
||||
// ClearBasket vide complètement le panier d'un utilisateur. Le stock n'est
|
||||
// pas restitué car il n'a pas été décrémenté à l'ajout. Si le panier contient
|
||||
// une récompense, la réservation de points correspondante est libérée (voir
|
||||
// DeleteProductFromBasket).
|
||||
func (d *Database) ClearBasket(username string) error {
|
||||
return d.GDB.Exec(`DELETE FROM baskets WHERE username = ?`, username).Error
|
||||
return d.GDB.Transaction(func(tx *gorm.DB) error {
|
||||
var poolKeys []string
|
||||
if err := tx.Raw(`
|
||||
SELECT DISTINCT reward_pool_key FROM baskets
|
||||
WHERE username = ? AND is_reward = true AND reward_pool_key != ''`, username).
|
||||
Scan(&poolKeys).Error; err != nil {
|
||||
return fmt.Errorf("erreur lecture récompenses panier: %w", err)
|
||||
}
|
||||
if err := tx.Exec(`DELETE FROM baskets WHERE username = ?`, username).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
for _, poolKey := range poolKeys {
|
||||
if err := releaseRewardReservationTx(tx, username, poolKey); err != nil {
|
||||
return fmt.Errorf("erreur libération réservation récompense pool=%s: %w", poolKey, err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
func (d *Database) GetBasketItemOwner(basketID int) (string, error) {
|
||||
|
||||
@@ -90,6 +90,10 @@ func (d *Database) CancelCommandAtomic(commandID int, username, reason string, f
|
||||
}
|
||||
log.Printf("✅ [CancelAtomic] Stock remboursé")
|
||||
|
||||
if err := d.ReleaseRewardReservationsForCommandTx(tx, commandID, username); err != nil {
|
||||
log.Printf("⚠️ [CancelAtomic] Erreur libération réservation récompense: %v", err)
|
||||
}
|
||||
|
||||
if err := tx.Exec(`
|
||||
UPDATE clients
|
||||
SET cancellations_count = COALESCE(cancellations_count, 0) + 1,
|
||||
@@ -192,10 +196,17 @@ func (d *Database) DeleteCommandAtomic(commandID int, deletedBy, role string) er
|
||||
return fmt.Errorf("commande non trouvée")
|
||||
}
|
||||
|
||||
// Jamais de suppression physique d'une commande déjà livrée/approuvée
|
||||
// (preuve de transaction) — quel que soit le rôle appelant. Seule une
|
||||
// annulation logique (CancelCommandByAdminAtomic) reste possible.
|
||||
if cmdResult.Status == "approved" || cmdResult.Status == "livre" {
|
||||
return fmt.Errorf("commande déjà livrée/approuvée: suppression impossible")
|
||||
}
|
||||
|
||||
log.Printf("📋 [DeleteAtomic] Trouvée - status=%s, client=%s", cmdResult.Status, cmdResult.Username)
|
||||
|
||||
// ✅ Ne restitue le stock QUE si pas déjà fait
|
||||
stockAlreadyRestored := cmdResult.Status == "cancelled" || cmdResult.Status == "approved" || cmdResult.Status == "livre"
|
||||
stockAlreadyRestored := cmdResult.Status == "cancelled"
|
||||
if !stockAlreadyRestored {
|
||||
if err := tx.Exec(`
|
||||
UPDATE products p
|
||||
@@ -324,24 +335,19 @@ func (d *Database) AddClientPenalty(username string, points int) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// CancelCommandByAdminAtomic transitionne une commande vers 'cancelled' depuis le
|
||||
// panel admin/cabine de façon atomique (verrou FOR UPDATE sur la commande) : le
|
||||
// remboursement de stock et le changement de statut se font dans la même
|
||||
// transaction, conditionnés à une lecture du statut précédent faite sous verrou.
|
||||
// Corrige un double remboursement possible sur double-tap/appel concurrent —
|
||||
// l'ancien code (RestoreCommandStock + UpdateCommandStatus appelés séparément
|
||||
// par le handler) lisait le statut puis restaurait le stock hors transaction,
|
||||
// laissant une fenêtre où deux requêtes concurrentes lisaient toutes les deux
|
||||
// "pas encore annulée" et remboursaient chacune le stock.
|
||||
func (d *Database) CancelCommandByAdminAtomic(commandID int) error {
|
||||
return d.GDB.Transaction(func(tx *gorm.DB) error {
|
||||
var prevStatus string
|
||||
if err := tx.Raw(`SELECT status FROM commandes WHERE id = ? FOR UPDATE`, commandID).Scan(&prevStatus).Error; err != nil {
|
||||
var cmd struct {
|
||||
Status string `gorm:"column:status"`
|
||||
Username string `gorm:"column:username"`
|
||||
}
|
||||
if err := tx.Raw(`SELECT status, username FROM commandes WHERE id = ? FOR UPDATE`, commandID).Scan(&cmd).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if prevStatus == "" {
|
||||
if cmd.Status == "" {
|
||||
return fmt.Errorf("commande non trouvée")
|
||||
}
|
||||
prevStatus := cmd.Status
|
||||
|
||||
noRestoreStatuses := []string{"cancelled", "approved", "livre"}
|
||||
if !slices.Contains(noRestoreStatuses, prevStatus) {
|
||||
@@ -359,6 +365,12 @@ func (d *Database) CancelCommandByAdminAtomic(commandID int) error {
|
||||
}
|
||||
}
|
||||
|
||||
if prevStatus != "approved" && cmd.Username != "" {
|
||||
if err := d.ReleaseRewardReservationsForCommandTx(tx, commandID, cmd.Username); err != nil {
|
||||
log.Printf("⚠️ [CancelByAdminAtomic] Erreur libération réservation récompense: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
if err := tx.Exec(`UPDATE commandes SET status = 'cancelled', updated_at = CURRENT_TIMESTAMP WHERE id = ?`, commandID).Error; err != nil {
|
||||
return fmt.Errorf("erreur mise à jour statut: %w", err)
|
||||
}
|
||||
@@ -366,16 +378,16 @@ func (d *Database) CancelCommandByAdminAtomic(commandID int) error {
|
||||
})
|
||||
}
|
||||
|
||||
// CancelDeliveryByLivreurAtomic annule une commande côté livreur et restaure le stock
|
||||
// de manière atomique (verrou FOR UPDATE + transition conditionnée à l'ancien statut).
|
||||
// Idempotent : si la commande est déjà annulée, ne touche pas au stock et renvoie
|
||||
// alreadyCancelled=true — évite un remboursement en double en cas de double appel
|
||||
// (double-tap, retry réseau, ou commande déjà annulée par un autre canal).
|
||||
func (d *Database) CancelDeliveryByLivreurAtomic(commandID int) (alreadyCancelled bool, prevStatus string, err error) {
|
||||
err = d.GDB.Transaction(func(tx *gorm.DB) error {
|
||||
if e := tx.Raw(`SELECT status FROM commandes WHERE id = ? FOR UPDATE`, commandID).Scan(&prevStatus).Error; e != nil {
|
||||
var cmd struct {
|
||||
Status string `gorm:"column:status"`
|
||||
Username string `gorm:"column:username"`
|
||||
}
|
||||
if e := tx.Raw(`SELECT status, username FROM commandes WHERE id = ? FOR UPDATE`, commandID).Scan(&cmd).Error; e != nil {
|
||||
return e
|
||||
}
|
||||
prevStatus = cmd.Status
|
||||
if prevStatus == "" {
|
||||
return fmt.Errorf("commande non trouvée")
|
||||
}
|
||||
@@ -406,6 +418,12 @@ func (d *Database) CancelDeliveryByLivreurAtomic(commandID int) (alreadyCancelle
|
||||
WHERE agg.product_id = p.id`, commandID).Error; e != nil {
|
||||
return fmt.Errorf("erreur remboursement stock: %w", e)
|
||||
}
|
||||
|
||||
if prevStatus != "approved" && cmd.Username != "" {
|
||||
if e := d.ReleaseRewardReservationsForCommandTx(tx, commandID, cmd.Username); e != nil {
|
||||
log.Printf("⚠️ [CancelDeliveryByLivreurAtomic] Erreur libération réservation récompense: %v", e)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
return
|
||||
|
||||
@@ -600,10 +600,12 @@ func (d *Database) CalculateAndAddPointsForCommandTx(tx *gorm.DB, commandID int,
|
||||
|
||||
log.Printf("💰 [CalcPointsTx] points par pool: %v, total=%d", poolPts, totalPoints)
|
||||
|
||||
if totalPoints == 0 {
|
||||
return 0, "", nil
|
||||
}
|
||||
|
||||
// totalPoints == 0 ne doit sauter que le crédit (rien à créditer) — pas
|
||||
// l'ÉTAPE 3 plus bas, qui doit tourner même sans aucun point gagné sur
|
||||
// cette commande : sinon un article récompense d'une commande dont le
|
||||
// reste du panier n'atteint aucun palier de points ne verrait jamais sa
|
||||
// réservation libérée/son solde débité à l'approbation.
|
||||
if totalPoints > 0 {
|
||||
if len(categoryParts) > 0 {
|
||||
pointCategory = strings.Join(categoryParts, " & ")
|
||||
} else {
|
||||
@@ -630,24 +632,28 @@ func (d *Database) CalculateAndAddPointsForCommandTx(tx *gorm.DB, commandID int,
|
||||
}
|
||||
|
||||
log.Printf("🎉 [CalcPointsTx] SUCCÈS - %d points [%s] → %s", totalPoints, pointCategory, username)
|
||||
|
||||
// ✅ ÉTAPE 3: Déduire les points des récompenses reçues dans cette commande
|
||||
var rewardItems []struct {
|
||||
RewardPoolKey string `gorm:"column:reward_pool_key"`
|
||||
}
|
||||
|
||||
// ✅ ÉTAPE 3: Déduire les points des récompenses reçues dans cette commande.
|
||||
// DISTINCT sur reward_pool_key : une seule réclamation (un seul claim, un
|
||||
// seul threshold consommé) peut avoir ajouté plusieurs lignes pour le même
|
||||
// pool (toutes les catégories/produits éligibles) — sans ce DISTINCT, une
|
||||
// commande avec plusieurs lignes récompense pour le même pool débiterait
|
||||
// threshold points plusieurs fois pour une seule récompense réellement
|
||||
// accordée.
|
||||
var poolKeys []string
|
||||
if err := tx.Raw(`
|
||||
SELECT reward_pool_key FROM command_items
|
||||
SELECT DISTINCT reward_pool_key FROM command_items
|
||||
WHERE command_id = ? AND is_reward = true AND reward_pool_key != ''
|
||||
`, commandID).Scan(&rewardItems).Error; err != nil {
|
||||
`, commandID).Scan(&poolKeys).Error; err != nil {
|
||||
log.Printf("⚠️ [CalcPointsTx] Erreur query reward items: %v", err)
|
||||
}
|
||||
|
||||
for _, ri := range rewardItems {
|
||||
for _, poolKey := range poolKeys {
|
||||
if settings.PointsReward == nil || settings.PointsReward.Threshold <= 0 {
|
||||
break
|
||||
}
|
||||
threshold := settings.PointsReward.Threshold
|
||||
poolKey := ri.RewardPoolKey
|
||||
// Déduire threshold points de points_extra[poolKey] (plancher à 0)
|
||||
if err := tx.Exec(`
|
||||
UPDATE clients
|
||||
@@ -777,8 +783,34 @@ func claimPoolRewardTx(tx *gorm.DB, username, poolKey string, threshold int) (re
|
||||
return earned - (row.Redeemed + 1), nil
|
||||
}
|
||||
|
||||
// ClaimPoolReward réclame une récompense pour un pool donné si le client a assez de points.
|
||||
// Retourne le nombre de récompenses disponibles restantes après la réclamation.
|
||||
func releaseRewardReservationTx(tx *gorm.DB, username, poolKey string) error {
|
||||
return tx.Exec(`
|
||||
UPDATE clients
|
||||
SET points_redeemed = jsonb_set(
|
||||
COALESCE(points_redeemed, '{}'::jsonb),
|
||||
ARRAY[?],
|
||||
to_jsonb(GREATEST(0, COALESCE((points_redeemed->>?)::int, 0) - 1))
|
||||
), updated_at = CURRENT_TIMESTAMP
|
||||
WHERE username = ?`,
|
||||
poolKey, poolKey, username).Error
|
||||
}
|
||||
|
||||
func (d *Database) ReleaseRewardReservationsForCommandTx(tx *gorm.DB, commandID int, username string) error {
|
||||
var poolKeys []string
|
||||
if err := tx.Raw(`
|
||||
SELECT DISTINCT reward_pool_key FROM command_items
|
||||
WHERE command_id = ? AND is_reward = true AND reward_pool_key != ''
|
||||
`, commandID).Scan(&poolKeys).Error; err != nil {
|
||||
return fmt.Errorf("erreur lecture récompenses commande: %w", err)
|
||||
}
|
||||
for _, poolKey := range poolKeys {
|
||||
if err := releaseRewardReservationTx(tx, username, poolKey); err != nil {
|
||||
return fmt.Errorf("erreur libération réservation récompense pool=%s: %w", poolKey, err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (d *Database) ClaimPoolReward(username, poolKey string, threshold int) (remainingAvailable int, err error) {
|
||||
err = d.GDB.Transaction(func(tx *gorm.DB) error {
|
||||
var err error
|
||||
|
||||
@@ -388,9 +388,12 @@ func DeleteCommandByCabine(c *gin.Context) {
|
||||
if err != nil {
|
||||
log.Printf("❌ [DELETE_COMMAND] Erreur: %v", err)
|
||||
|
||||
if err.Error() == "commande non trouvée" {
|
||||
switch err.Error() {
|
||||
case "commande non trouvée":
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "Commande non trouvée"})
|
||||
} else {
|
||||
case "commande déjà livrée/approuvée: suppression impossible":
|
||||
c.JSON(http.StatusConflict, gin.H{"error": "Commande déjà livrée/approuvée - utilisez l'annulation plutôt que la suppression"})
|
||||
default:
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "Erreur lors de la suppression"})
|
||||
}
|
||||
return
|
||||
|
||||
@@ -1272,15 +1272,30 @@ func UpdateCommandStatusAdmin(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
if req.Status == "cancelled" {
|
||||
switch req.Status {
|
||||
case "cancelled":
|
||||
if err := database.CancelCommandByAdminAtomic(commandID); err != nil {
|
||||
utils.ServerErr(c, "Impossible d'annuler la commande", err)
|
||||
return
|
||||
}
|
||||
} else if err := database.UpdateCommandStatus(commandID, req.Status); err != nil {
|
||||
case "approved":
|
||||
// Passe par le même chemin que StaffApproveDelivery (points + stats
|
||||
// cohérents) au lieu d'un UPDATE brut du statut.
|
||||
staffUsername, err := safeGetUsername(c)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "Authentification requise"})
|
||||
return
|
||||
}
|
||||
if _, _, _, err := database.ApproveDeliveryAtomicByStaff(commandID, staffUsername); err != nil {
|
||||
utils.ServerErr(c, "Impossible de confirmer la réception", err)
|
||||
return
|
||||
}
|
||||
default:
|
||||
if err := database.UpdateCommandStatus(commandID, req.Status); err != nil {
|
||||
utils.ServerErr(c, "Impossible de mettre à jour le statut", err)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
log.Printf("✅ [STATUS_ADMIN] Cmd %d → %s (par %s)", commandID, req.Status, role)
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
|
||||
@@ -79,12 +79,28 @@ func IPNWebhook(c *gin.Context) {
|
||||
func GetCommandPaymentStatus(c *gin.Context) {
|
||||
database := c.MustGet("database").(*db.Database)
|
||||
|
||||
username, exists := c.Get("username")
|
||||
if !exists {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "Authentification requise"})
|
||||
return
|
||||
}
|
||||
|
||||
commandID, err := strconv.Atoi(c.Param("id"))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "id de commande invalide"})
|
||||
return
|
||||
}
|
||||
|
||||
command, err := database.GetCommandByID(commandID)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "Commande non trouvée"})
|
||||
return
|
||||
}
|
||||
if cmdUsername, _ := command["username"].(string); cmdUsername != username.(string) {
|
||||
c.JSON(http.StatusForbidden, gin.H{"error": "Cette commande ne vous appartient pas"})
|
||||
return
|
||||
}
|
||||
|
||||
payment, err := database.GetCryptoPaymentByCommandID(commandID)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "erreur base de données"})
|
||||
|
||||
@@ -418,6 +418,106 @@ func ClaimMyReward(c *gin.Context) {
|
||||
})
|
||||
}
|
||||
|
||||
// SwapMyRewardProduct change le produit choisi pour la récompense déjà en
|
||||
// panier, sans consommer une nouvelle réservation de points : le pool et
|
||||
// l'éligibilité sont redérivés côté serveur (jamais depuis une donnée
|
||||
// envoyée par le client), via la même logique de candidats que ClaimMyReward.
|
||||
func SwapMyRewardProduct(c *gin.Context) {
|
||||
username := c.GetString("username")
|
||||
if username == "" {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "Non authentifié"})
|
||||
return
|
||||
}
|
||||
|
||||
var req struct {
|
||||
ProductID int `json:"product_id" binding:"required"`
|
||||
}
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "product_id requis"})
|
||||
return
|
||||
}
|
||||
|
||||
database := c.MustGet("database").(*db.Database)
|
||||
|
||||
poolKey, err := database.GetActiveRewardPoolKey(username)
|
||||
if err != nil {
|
||||
utils.ServerErr(c, "Erreur lecture panier", err)
|
||||
return
|
||||
}
|
||||
if poolKey == "" {
|
||||
c.JSON(http.StatusConflict, gin.H{"error": "Aucune récompense active dans le panier"})
|
||||
return
|
||||
}
|
||||
|
||||
settings, err := database.GetSettings()
|
||||
if err != nil {
|
||||
utils.ServerErr(c, "Erreur lecture paramètres", err)
|
||||
return
|
||||
}
|
||||
if !settings.PointsEnabled {
|
||||
c.JSON(http.StatusForbidden, gin.H{"error": "Système de points désactivé"})
|
||||
return
|
||||
}
|
||||
reward := settings.PointsReward
|
||||
if reward == nil || reward.Threshold <= 0 {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "Aucune récompense configurée"})
|
||||
return
|
||||
}
|
||||
|
||||
var selectedPool *models.PointsPool
|
||||
for i := range settings.PointsPools {
|
||||
if settings.PointsPools[i].Key == poolKey {
|
||||
selectedPool = &settings.PointsPools[i]
|
||||
break
|
||||
}
|
||||
}
|
||||
if selectedPool == nil {
|
||||
c.JSON(http.StatusConflict, gin.H{"error": "Pool introuvable"})
|
||||
return
|
||||
}
|
||||
poolCategories := make(map[string]bool, len(selectedPool.Categories))
|
||||
for _, cat := range selectedPool.Categories {
|
||||
poolCategories[cat] = true
|
||||
}
|
||||
|
||||
candidates, err := resolveCategoryRewardCandidates(database, reward)
|
||||
if err != nil {
|
||||
utils.ServerErr(c, "Erreur résolution produits récompense", err)
|
||||
return
|
||||
}
|
||||
|
||||
var newItem *models.RewardItem
|
||||
for _, cand := range candidates {
|
||||
if cand.ProductID != req.ProductID || !poolCategories[cand.Category] {
|
||||
continue
|
||||
}
|
||||
price, err := effectiveRewardPrice(database, cand.ProductID, cand.Quantity, cand.Type)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusConflict, gin.H{"error": "Récompense momentanément indisponible, contactez le support"})
|
||||
return
|
||||
}
|
||||
newItem = &models.RewardItem{ProductID: cand.ProductID, Quantity: cand.Quantity, Price: price}
|
||||
break
|
||||
}
|
||||
if newItem == nil {
|
||||
c.JSON(http.StatusForbidden, gin.H{"error": "Ce produit n'est pas éligible pour cette récompense"})
|
||||
return
|
||||
}
|
||||
|
||||
added, err := database.AddRewardsToBasket(username, []models.RewardItem{*newItem}, poolKey)
|
||||
if err != nil {
|
||||
utils.ServerErr(c, "Erreur changement de produit récompense", err)
|
||||
return
|
||||
}
|
||||
|
||||
var productNames []string
|
||||
for _, item := range added {
|
||||
productNames = append(productNames, item.ProductName)
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{"success": true, "product_names": productNames})
|
||||
}
|
||||
|
||||
func AdminResetClientRedeemed(c *gin.Context) {
|
||||
username := c.Param("username")
|
||||
poolKey := c.Query("pool_key")
|
||||
|
||||
@@ -121,6 +121,7 @@ func SetupRoutes(router *gin.Engine, database *db.Database, geoService *services
|
||||
// 🏆 POINTS & RÉCOMPENSES CLIENT
|
||||
cartGroupV1.GET("/points/rewards", handlers.GetMyPointsRewards)
|
||||
cartGroupV1.POST("/points/claim", handlers.ClaimMyReward)
|
||||
cartGroupV1.PUT("/points/swap", handlers.SwapMyRewardProduct)
|
||||
|
||||
// 💸 STATUT PAIEMENT CRYPTO
|
||||
cartGroupV1.GET("/commands/:id/payment-status", handlers.GetCommandPaymentStatus)
|
||||
|
||||
@@ -0,0 +1,824 @@
|
||||
package tests
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"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); err != nil {
|
||||
t.Fatalf("CancelDeliveryByLivreurAtomic: %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.StatusOK {
|
||||
t.Fatalf("status HTTP: 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)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,215 @@
|
||||
package tests
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"gestion/handlers"
|
||||
"gestion/models"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strconv"
|
||||
"testing"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func statusAdminCtx(commandID int, status string) (*gin.Context, *httptest.ResponseRecorder) {
|
||||
body, _ := json.Marshal(map[string]string{"status": status})
|
||||
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.Set("username", "admin_test")
|
||||
c.Params = gin.Params{{Key: "id", Value: strconv.Itoa(commandID)}}
|
||||
return c, rec
|
||||
}
|
||||
|
||||
// ════════════════════════════════════════════════════════════════════════
|
||||
// DeleteCommandByCabine / DeleteCommandAtomic — refus sur commande
|
||||
// déjà livrée/approuvée (plus de suppression physique d'une preuve de
|
||||
// transaction, quel que soit le rôle).
|
||||
// ════════════════════════════════════════════════════════════════════════
|
||||
|
||||
func TestDeleteCommandByCabine_RejectsApprovedOrder(t *testing.T) {
|
||||
cleanupStockTestData(t)
|
||||
username := newTestClient(t, "delcab_approved")
|
||||
productID := newTestProduct(t, "DelCabApproved", 10)
|
||||
cmdID := newTestCommandWithItem(t, username, "approved", "", productID, 1, 10)
|
||||
|
||||
c, rec := cmdContext(http.MethodDelete, testUserPrefix+"delcab_approved_actor", "cabine", nil, cmdID)
|
||||
handlers.DeleteCommandByCabine(c)
|
||||
|
||||
if rec.Code != http.StatusConflict {
|
||||
t.Fatalf("status HTTP: got=%d want=%d body=%s", rec.Code, http.StatusConflict, rec.Body.String())
|
||||
}
|
||||
var count int64
|
||||
testDB.GDB.Raw(`SELECT COUNT(*) FROM commandes WHERE id = ?`, cmdID).Scan(&count)
|
||||
if count != 1 {
|
||||
t.Errorf("la commande approuvée ne doit pas être supprimée: got=%d lignes want=1", count)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeleteCommandByCabine_RejectsDeliveredOrder(t *testing.T) {
|
||||
cleanupStockTestData(t)
|
||||
username := newTestClient(t, "delcab_livre")
|
||||
productID := newTestProduct(t, "DelCabLivre", 10)
|
||||
cmdID := newTestCommandWithItem(t, username, "livre", "", productID, 1, 10)
|
||||
|
||||
c, rec := cmdContext(http.MethodDelete, testUserPrefix+"delcab_livre_actor", "admin", nil, cmdID)
|
||||
handlers.DeleteCommandByCabine(c)
|
||||
|
||||
if rec.Code != http.StatusConflict {
|
||||
t.Fatalf("status HTTP: got=%d want=%d body=%s", rec.Code, http.StatusConflict, rec.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
// Régression: le cas non-terminal (pending) doit toujours fonctionner.
|
||||
func TestDeleteCommandByCabine_StillWorksOnPendingOrder(t *testing.T) {
|
||||
cleanupStockTestData(t)
|
||||
username := newTestClient(t, "delcab_pending_ok")
|
||||
productID := newTestProduct(t, "DelCabPendingOk", 10)
|
||||
cmdID := newTestCommandWithItem(t, username, "pending", "", productID, 1, 10)
|
||||
|
||||
c, rec := cmdContext(http.MethodDelete, testUserPrefix+"delcab_pending_actor", "cabine", nil, cmdID)
|
||||
handlers.DeleteCommandByCabine(c)
|
||||
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("status HTTP: got=%d want=%d body=%s", rec.Code, http.StatusOK, rec.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
// ════════════════════════════════════════════════════════════════════════
|
||||
// UpdateCommandStatusAdmin — le passage à "approved" doit déléguer à
|
||||
// ApproveDeliveryAtomicByStaff (points crédités), pas un UPDATE brut.
|
||||
// ════════════════════════════════════════════════════════════════════════
|
||||
|
||||
func TestUpdateCommandStatusAdmin_ApprovedDelegatesToStaffApproval(t *testing.T) {
|
||||
cleanupStockTestData(t)
|
||||
username := newTestClient(t, "statusadmin_approve_ok")
|
||||
productID := newTestProduct(t, "StatusAdminApproveOk", 20)
|
||||
setPointsPoolsSettings(t, []models.PointsPool{
|
||||
{Key: "pool_0", Name: "Pool Test", Categories: []string{"test"}, Tiers: []models.PointsTier{{Min: 0, Max: 0, Points: 6}}},
|
||||
})
|
||||
cmdID := newTestCommandWithItem(t, username, "livre", "", productID, 1, 10)
|
||||
|
||||
c, rec := statusAdminCtx(cmdID, "approved")
|
||||
handlers.UpdateCommandStatusAdmin(c)
|
||||
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("status HTTP: got=%d body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
if got := commandStatus(t, cmdID); got != "approved" {
|
||||
t.Errorf("statut: got=%s want=approved", got)
|
||||
}
|
||||
// Preuve que ça passe bien par le pipeline transactionnel et pas un
|
||||
// UPDATE brut : les points sont effectivement crédités.
|
||||
if got := clientPointsExtra(t, username)["pool_0"]; got != 6 {
|
||||
t.Errorf("points_extra après passage à 'approved' via ce endpoint: got=%d want=6 (doit passer par ApproveDeliveryAtomicByStaff)", got)
|
||||
}
|
||||
}
|
||||
|
||||
// Ne doit pas permettre de sauter l'étape "livre" depuis un statut trop en
|
||||
// amont (ApproveDeliveryAtomicByStaff a ses propres garde-fous de statut).
|
||||
func TestUpdateCommandStatusAdmin_ApprovedFromPendingIsRejected(t *testing.T) {
|
||||
cleanupStockTestData(t)
|
||||
username := newTestClient(t, "statusadmin_approve_pending")
|
||||
productID := newTestProduct(t, "StatusAdminApprovePending", 20)
|
||||
setPointsPoolsSettings(t, []models.PointsPool{
|
||||
{Key: "pool_0", Name: "Pool Test", Categories: []string{"test"}, Tiers: []models.PointsTier{{Min: 0, Max: 0, Points: 6}}},
|
||||
})
|
||||
cmdID := newTestCommandWithItem(t, username, "cancelled", "", productID, 1, 10)
|
||||
|
||||
c, rec := statusAdminCtx(cmdID, "approved")
|
||||
handlers.UpdateCommandStatusAdmin(c)
|
||||
|
||||
if rec.Code == http.StatusOK {
|
||||
t.Fatalf("approuver une commande 'cancelled' ne doit pas réussir: body=%s", rec.Body.String())
|
||||
}
|
||||
if got := commandStatus(t, cmdID); got != "cancelled" {
|
||||
t.Errorf("le statut ne doit pas changer sur un rejet: got=%s want=cancelled", got)
|
||||
}
|
||||
if got := clientPointsExtra(t, username)["pool_0"]; got != 0 {
|
||||
t.Errorf("aucun point ne doit être crédité sur un rejet: got=%d want=0", got)
|
||||
}
|
||||
}
|
||||
|
||||
// Régression: le passage à "cancelled" via ce même endpoint continue de
|
||||
// fonctionner (chemin déjà correct, CancelCommandByAdminAtomic).
|
||||
func TestUpdateCommandStatusAdmin_CancelledStillWorks(t *testing.T) {
|
||||
cleanupStockTestData(t)
|
||||
username := newTestClient(t, "statusadmin_cancel_ok")
|
||||
productID := newTestProduct(t, "StatusAdminCancelOk", 20)
|
||||
cmdID := newTestCommandWithItem(t, username, "pending", "", productID, 1, 10)
|
||||
|
||||
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 := commandStatus(t, cmdID); got != "cancelled" {
|
||||
t.Errorf("statut: got=%s want=cancelled", got)
|
||||
}
|
||||
}
|
||||
|
||||
// ════════════════════════════════════════════════════════════════════════
|
||||
// GetCommandPaymentStatus — IDOR : un client ne doit voir que le paiement
|
||||
// crypto de ses propres commandes.
|
||||
// ════════════════════════════════════════════════════════════════════════
|
||||
|
||||
func newTestCryptoPayment(t *testing.T, commandID int) {
|
||||
t.Helper()
|
||||
if err := testDB.GDB.Exec(
|
||||
`INSERT INTO crypto_payments (command_id, nowpayment_id, status, price_amount, price_currency, pay_currency, pay_address, pay_amount)
|
||||
VALUES (?, 'np-test-id', 'waiting', 10.00, 'eur', 'btc', 'bc1qtestaddress', 0.0001)`,
|
||||
commandID,
|
||||
).Error; err != nil {
|
||||
t.Fatalf("newTestCryptoPayment: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetCommandPaymentStatus_RejectsOtherClientsOrder(t *testing.T) {
|
||||
cleanupStockTestData(t)
|
||||
owner := newTestClient(t, "payment_idor_owner")
|
||||
intruder := newTestClient(t, "payment_idor_intruder")
|
||||
productID := newTestProduct(t, "PaymentIDORProduct", 10)
|
||||
cmdID := newTestCommandWithItem(t, owner, "pending_payment", "", productID, 1, 10)
|
||||
newTestCryptoPayment(t, cmdID)
|
||||
|
||||
c, rec := cmdContext(http.MethodGet, intruder, "client", nil, cmdID)
|
||||
handlers.GetCommandPaymentStatus(c)
|
||||
|
||||
if rec.Code != http.StatusForbidden {
|
||||
t.Fatalf("status HTTP: got=%d want=%d body=%s", rec.Code, http.StatusForbidden, rec.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetCommandPaymentStatus_AllowsOwner(t *testing.T) {
|
||||
cleanupStockTestData(t)
|
||||
owner := newTestClient(t, "payment_idor_owner_ok")
|
||||
productID := newTestProduct(t, "PaymentIDOROwnerOk", 10)
|
||||
cmdID := newTestCommandWithItem(t, owner, "pending_payment", "", productID, 1, 10)
|
||||
newTestCryptoPayment(t, cmdID)
|
||||
|
||||
c, rec := cmdContext(http.MethodGet, owner, "client", nil, cmdID)
|
||||
handlers.GetCommandPaymentStatus(c)
|
||||
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("status HTTP: got=%d want=%d body=%s", rec.Code, http.StatusOK, rec.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetCommandPaymentStatus_UnknownCommandReturns404(t *testing.T) {
|
||||
cleanupStockTestData(t)
|
||||
username := newTestClient(t, "payment_idor_unknown")
|
||||
|
||||
c, rec := cmdContext(http.MethodGet, username, "client", nil, 99999999)
|
||||
handlers.GetCommandPaymentStatus(c)
|
||||
|
||||
if rec.Code != http.StatusNotFound {
|
||||
t.Fatalf("status HTTP: got=%d want=%d body=%s", rec.Code, http.StatusNotFound, rec.Body.String())
|
||||
}
|
||||
}
|
||||
@@ -204,22 +204,58 @@ func TestDeleteCommandAtomic_DoesNotRefundAlreadyCancelledOrApprovedOrder(t *tes
|
||||
}
|
||||
}
|
||||
|
||||
// Régression: une commande "livrée" (marchandise déjà sortie du stock au
|
||||
// checkout, remise au client) ne doit pas voir son stock remboursé lors
|
||||
// d'une suppression — symétrique à CancelCommandByAdminAtomic qui exclut
|
||||
// déjà "livre" de son remboursement.
|
||||
func TestDeleteCommandAtomic_DoesNotRefundDeliveredOrder(t *testing.T) {
|
||||
// Sécurité: une commande déjà "livre" ou "approved" (preuve de transaction)
|
||||
// ne doit jamais pouvoir être supprimée physiquement, quel que soit le rôle
|
||||
// appelant (admin ou cabine) — seule une annulation logique reste possible.
|
||||
// La commande et son stock restent donc intacts.
|
||||
func TestDeleteCommandAtomic_RejectsDeliveredOrder(t *testing.T) {
|
||||
cleanupStockTestData(t)
|
||||
username := newTestClient(t, "delete_admin_livre")
|
||||
productID := newTestProduct(t, "DeleteAdminLivre", 5)
|
||||
cmdID := newTestCommandWithItem(t, username, "livre", "", productID, 4, 40)
|
||||
|
||||
if err := testDB.DeleteCommandAtomic(cmdID, "admin_test", "admin"); err != nil {
|
||||
t.Fatalf("DeleteCommandAtomic: %v", err)
|
||||
if err := testDB.DeleteCommandAtomic(cmdID, "admin_test", "admin"); err == nil {
|
||||
t.Fatal("la suppression d'une commande 'livre' doit être refusée")
|
||||
}
|
||||
|
||||
if got := productStock(t, productID); got != 5 {
|
||||
t.Errorf("stock ne doit pas être remboursé pour une commande déjà livrée: got=%.2f want=5", got)
|
||||
t.Errorf("stock ne doit pas bouger pour une suppression refusée: got=%.2f want=5", got)
|
||||
}
|
||||
if got := commandStatus(t, cmdID); got != "livre" {
|
||||
t.Errorf("la commande ne doit pas être touchée: got status=%s want=livre", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeleteCommandAtomic_RejectsApprovedOrder(t *testing.T) {
|
||||
cleanupStockTestData(t)
|
||||
username := newTestClient(t, "delete_admin_approved")
|
||||
productID := newTestProduct(t, "DeleteAdminApproved", 5)
|
||||
cmdID := newTestCommandWithItem(t, username, "approved", "", productID, 4, 40)
|
||||
|
||||
if err := testDB.DeleteCommandAtomic(cmdID, "admin_test", "admin"); err == nil {
|
||||
t.Fatal("la suppression d'une commande 'approved' doit être refusée")
|
||||
}
|
||||
|
||||
if got := productStock(t, productID); got != 5 {
|
||||
t.Errorf("stock ne doit pas bouger pour une suppression refusée: got=%.2f want=5", got)
|
||||
}
|
||||
var count int64
|
||||
testDB.GDB.Raw(`SELECT COUNT(*) FROM commandes WHERE id = ?`, cmdID).Scan(&count)
|
||||
if count != 1 {
|
||||
t.Errorf("la commande ne doit pas être supprimée: got=%d lignes restantes want=1", count)
|
||||
}
|
||||
}
|
||||
|
||||
// Appelé par un rôle "cabine" : même refus qu'un admin, le contrôle est au
|
||||
// niveau DB et ne dépend pas du rôle.
|
||||
func TestDeleteCommandAtomic_RejectsApprovedOrder_EvenForCabine(t *testing.T) {
|
||||
cleanupStockTestData(t)
|
||||
username := newTestClient(t, "delete_cabine_approved")
|
||||
productID := newTestProduct(t, "DeleteCabineApproved", 5)
|
||||
cmdID := newTestCommandWithItem(t, username, "approved", "", productID, 4, 40)
|
||||
|
||||
if err := testDB.DeleteCommandAtomic(cmdID, "cabine_test", "cabine"); err == nil {
|
||||
t.Fatal("la suppression d'une commande 'approved' doit être refusée pour cabine aussi")
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user