chore: build
This commit is contained in:
@@ -1,6 +1,7 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"slices"
|
||||
@@ -348,6 +349,12 @@ func (d *Database) CancelCommandByAdminAtomic(commandID int) error {
|
||||
return fmt.Errorf("commande non trouvée")
|
||||
}
|
||||
prevStatus := cmd.Status
|
||||
if prevStatus == "cancelled" {
|
||||
return nil
|
||||
}
|
||||
if prevStatus == "approved" {
|
||||
return ErrCommandLocked
|
||||
}
|
||||
|
||||
noRestoreStatuses := []string{"cancelled", "approved", "livre"}
|
||||
if !slices.Contains(noRestoreStatuses, prevStatus) {
|
||||
@@ -395,6 +402,9 @@ func (d *Database) CancelDeliveryByLivreurAtomic(commandID int) (alreadyCancelle
|
||||
alreadyCancelled = true
|
||||
return nil
|
||||
}
|
||||
if prevStatus == "livre" || prevStatus == "approved" {
|
||||
return ErrCommandAlreadyDelivered
|
||||
}
|
||||
|
||||
result := tx.Exec(`
|
||||
UPDATE commandes SET status = 'cancelled', updated_at = CURRENT_TIMESTAMP
|
||||
@@ -428,3 +438,5 @@ func (d *Database) CancelDeliveryByLivreurAtomic(commandID int) (alreadyCancelle
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
var ErrCommandAlreadyDelivered = errors.New("commande déjà livrée : annulation impossible")
|
||||
|
||||
@@ -6,7 +6,9 @@ import (
|
||||
"fmt"
|
||||
"gestion/models"
|
||||
"log"
|
||||
"math"
|
||||
"slices"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
@@ -58,6 +60,34 @@ type basketItem struct {
|
||||
PromoDiscount float64 `gorm:"column:promo_discount"`
|
||||
}
|
||||
|
||||
// Les articles récompense sont des produits physiques : ils sortent du stock comme les autres.
|
||||
func decrementBasketStockTx(tx *gorm.DB, items []basketItem) error {
|
||||
totals := make(map[int]float64)
|
||||
for _, item := range items {
|
||||
totals[item.ProductID] += item.Quantity
|
||||
}
|
||||
ids := make([]int, 0, len(totals))
|
||||
for id := range totals {
|
||||
totals[id] = math.Round(totals[id]*1000) / 1000
|
||||
ids = append(ids, id)
|
||||
}
|
||||
sort.Ints(ids)
|
||||
|
||||
for _, id := range ids {
|
||||
var currentStock float64
|
||||
if err := tx.Raw(`SELECT stock FROM products WHERE id = ? FOR UPDATE`, id).Scan(¤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
|
||||
func validateCommandStatus(status string) error {
|
||||
validStatuses := map[string]bool{
|
||||
@@ -128,6 +158,14 @@ func (d *Database) CreateCommandWithAddress(username, deliveryAddress string) (*
|
||||
return fmt.Errorf("montant de commande invalide: %.2f€", totalPrix)
|
||||
}
|
||||
|
||||
// Stock verrouillé avant l'insertion des command_items : leur clé étrangère
|
||||
// pose un verrou partagé sur products, et le reprendre ensuite en FOR UPDATE
|
||||
// provoquait des deadlocks entre checkouts simultanés. Ordre par id pour la
|
||||
// même raison quand plusieurs produits sont commandés.
|
||||
if err := decrementBasketStockTx(tx, basketItems); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var cmdResult struct {
|
||||
ID int `gorm:"column:id"`
|
||||
ClientOrderID int `gorm:"column:client_order_id"`
|
||||
@@ -176,21 +214,6 @@ func (d *Database) CreateCommandWithAddress(username, deliveryAddress string) (*
|
||||
return fmt.Errorf("erreur insertion items: %w", err)
|
||||
}
|
||||
|
||||
// Les articles récompense (payés en points) restent des produits physiques
|
||||
// réellement distribués : le stock doit être décrémenté comme pour un
|
||||
// article payant.
|
||||
for _, item := range basketItems {
|
||||
var currentStock float64
|
||||
if err := tx.Raw(`SELECT stock FROM products WHERE id = ? FOR UPDATE`, item.ProductID).Scan(¤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
|
||||
}
|
||||
@@ -561,20 +584,32 @@ func (d *Database) UpdateCommandStatus(commandID int, status string) error {
|
||||
return err
|
||||
}
|
||||
|
||||
result := d.GDB.Model(&models.Command{}).Where("id = ?", commandID).Updates(map[string]any{
|
||||
"status": status,
|
||||
"updated_at": time.Now(),
|
||||
})
|
||||
result := d.GDB.Model(&models.Command{}).
|
||||
Where("id = ? AND status NOT IN ?", commandID, lockedCommandStatuses).
|
||||
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)
|
||||
|
||||
@@ -105,6 +105,23 @@ func InitDB() *Database {
|
||||
log.Fatalf("❌ Erreur migration unit products: %v", err)
|
||||
}
|
||||
|
||||
// Migration: products.stock 2 → 3 décimales, même précision que les quantités commandées (0,001 g)
|
||||
if _, err = database.Exec(`
|
||||
DO $$
|
||||
BEGIN
|
||||
IF EXISTS (
|
||||
SELECT 1 FROM information_schema.columns
|
||||
WHERE table_name = 'products' AND column_name = 'stock'
|
||||
AND numeric_scale IS DISTINCT FROM 3
|
||||
) THEN
|
||||
ALTER TABLE products ALTER COLUMN stock TYPE NUMERIC(10,3);
|
||||
END IF;
|
||||
END
|
||||
$$;
|
||||
`); err != nil {
|
||||
log.Fatalf("❌ Erreur migration products.stock: %v", err)
|
||||
}
|
||||
|
||||
// Migration: baskets.quantity INTEGER → NUMERIC(10,3) pour supporter les quantités fractionnaires (ex: 0.5g)
|
||||
if _, err = database.Exec(`
|
||||
DO $$
|
||||
@@ -404,7 +421,7 @@ func (db *Database) createTables() error {
|
||||
id SERIAL PRIMARY KEY,
|
||||
name VARCHAR(255) NOT NULL,
|
||||
category VARCHAR(100) NOT NULL,
|
||||
stock DECIMAL(10,2) NOT NULL DEFAULT 0,
|
||||
stock NUMERIC(10,3) NOT NULL DEFAULT 0,
|
||||
unit VARCHAR(10) NOT NULL DEFAULT 'u',
|
||||
description TEXT,
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
@@ -326,3 +326,17 @@ func (d *Database) GetProductNameByID(productID int) (string, error) {
|
||||
}
|
||||
return result.Name, nil
|
||||
}
|
||||
|
||||
// CountOpenProductUsage compte les paniers et les commandes non terminées contenant le produit.
|
||||
func (d *Database) CountOpenProductUsage(productID int) (baskets int, commands int, err error) {
|
||||
if err = d.GDB.Raw(`SELECT COUNT(DISTINCT username) FROM baskets WHERE product_id = ?`, productID).Scan(&baskets).Error; err != nil {
|
||||
return 0, 0, fmt.Errorf("erreur comptage paniers: %w", err)
|
||||
}
|
||||
if err = d.GDB.Raw(`
|
||||
SELECT COUNT(DISTINCT c.id) FROM command_items ci
|
||||
JOIN commandes c ON c.id = ci.command_id
|
||||
WHERE ci.product_id = ? AND c.status NOT IN ('cancelled', 'approved', 'livre')`, productID).Scan(&commands).Error; err != nil {
|
||||
return 0, 0, fmt.Errorf("erreur comptage commandes: %w", err)
|
||||
}
|
||||
return baskets, commands, nil
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user