diff --git a/backend/gestion/db/db_address.go b/backend/gestion/db/db_address.go index bb90c0fe..26324967 100644 --- a/backend/gestion/db/db_address.go +++ b/backend/gestion/db/db_address.go @@ -18,6 +18,7 @@ func (d *Database) CheckAddress(addressByUser *models.Command) error { return fmt.Errorf("checkAddress: %w", result.Error) } + // Pas de correspondance exacte — fallback sur une comparaison normalisée // (accents/casse/espaces) pour rattraper les variantes mineures de saisie. corrections, err := d.AllAddress() if err != nil { diff --git a/backend/gestion/db/db_command_items.go b/backend/gestion/db/db_command_items.go index 75c6ddbf..23ed5a24 100644 --- a/backend/gestion/db/db_command_items.go +++ b/backend/gestion/db/db_command_items.go @@ -40,6 +40,7 @@ func (d *Database) InsertCommandItemsBatch(items []commandItemFull) error { // ============================================ // VALIDATION HELPERS +// ============================================ func validateCommandID(commandID int) error { if commandID <= 0 { @@ -232,6 +233,7 @@ 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"` @@ -261,6 +263,7 @@ 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, @@ -309,6 +312,7 @@ 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, @@ -352,6 +356,7 @@ 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"` @@ -376,7 +381,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.is_reward, ci.reward_pool_key, + ci.quantite, ci.prix, ci.promo_discount, 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, @@ -406,7 +411,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, + "quantite": row.Quantite, "prix": row.Prix, "promo_discount": row.PromoDiscount, "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, diff --git a/backend/gestion/db/db_commands.go b/backend/gestion/db/db_commands.go index e39bbab8..d9004ca8 100644 --- a/backend/gestion/db/db_commands.go +++ b/backend/gestion/db/db_commands.go @@ -274,7 +274,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").Limit(1000).Scan(&rows).Error; err != nil { + if err := gdb.Order("c.created_at DESC").Scan(&rows).Error; err != nil { return nil, fmt.Errorf("erreur lors de la récupération des commandes: %w", err) } diff --git a/backend/gestion/handlers/commands.go b/backend/gestion/handlers/commands.go index 86f15024..df4fcfa0 100644 --- a/backend/gestion/handlers/commands.go +++ b/backend/gestion/handlers/commands.go @@ -290,11 +290,16 @@ 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. + // 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. 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) } } @@ -305,6 +310,19 @@ 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" diff --git a/backend/gestion/handlers/deleviry.go b/backend/gestion/handlers/deleviry.go index 0e36d91c..b062e64c 100644 --- a/backend/gestion/handlers/deleviry.go +++ b/backend/gestion/handlers/deleviry.go @@ -73,10 +73,11 @@ 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"], - "is_reward": item["is_reward"], + "produit": item["produit"], + "quantite": item["quantite"], + "prix": item["prix"], + "promo_discount": item["promo_discount"], + "is_reward": item["is_reward"], } } @@ -155,10 +156,11 @@ 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"], - "is_reward": item["is_reward"], + "produit": item["produit"], + "quantite": item["quantite"], + "prix": item["prix"], + "promo_discount": item["promo_discount"], + "is_reward": item["is_reward"], } } @@ -173,6 +175,7 @@ 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), @@ -623,3 +626,9 @@ 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 +} diff --git a/backend/gestion/main.go b/backend/gestion/main.go index 7995fcf7..86b5ef73 100644 --- a/backend/gestion/main.go +++ b/backend/gestion/main.go @@ -166,7 +166,7 @@ func main() { r.Use(sessions.Sessions("mysession", store)) r.Use(cors.New(cors.Config{ - AllowOrigins: []string{"https://uber-demo.club"}, + 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"}, AllowMethods: []string{"GET", "POST", "PUT", "DELETE", "OPTIONS", "PATCH"}, AllowHeaders: []string{"Origin", "Content-Type", "Accept", "Authorization", "X-Request-ID"}, ExposeHeaders: []string{"Content-Length"}, diff --git a/backend/gestion/tests/address_proposal_livreur_notif_test.go b/backend/gestion/tests/address_proposal_livreur_notif_test.go new file mode 100644 index 00000000..ed95360a --- /dev/null +++ b/backend/gestion/tests/address_proposal_livreur_notif_test.go @@ -0,0 +1,107 @@ +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()) + } +} diff --git a/backend/gestion/tests/deleviry_promo_test.go b/backend/gestion/tests/deleviry_promo_test.go new file mode 100644 index 00000000..ba448f7f --- /dev/null +++ b/backend/gestion/tests/deleviry_promo_test.go @@ -0,0 +1,135 @@ +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()) + } +}