chore: update
This commit is contained in:
@@ -5,15 +5,15 @@ import (
|
||||
"gestion/models"
|
||||
)
|
||||
|
||||
func (d *Database) CreateAlert(username string) (models.AlertPolicy, error) {
|
||||
func (d *Database) CreateAlert(username string, message string) (models.AlertPolicy, error) {
|
||||
|
||||
query := `
|
||||
INSERT INTO alerte_policy (username, status)
|
||||
VALUES ($1, 'true')
|
||||
RETURNING id, username, status, created_at, updated_at
|
||||
INSERT INTO alerte_policy (username, status, message)
|
||||
VALUES ($1, 'true', $2)
|
||||
RETURNING id, username, status, message, created_at, updated_at
|
||||
`
|
||||
var alert models.AlertPolicy
|
||||
err := d.QueryRow(query, username).Scan(&alert.ID, &alert.Username, &alert.Status, &alert.CreatedAt, &alert.UpdatedAt)
|
||||
err := d.QueryRow(query, username, message).Scan(&alert.ID, &alert.Username, &alert.Status, &alert.Message, &alert.CreatedAt, &alert.UpdatedAt)
|
||||
if err != nil {
|
||||
return models.AlertPolicy{}, err
|
||||
}
|
||||
@@ -25,12 +25,12 @@ func (d *Database) CreateAlert(username string) (models.AlertPolicy, error) {
|
||||
func (d *Database) GetAlertPolicy(id int) (models.AlertPolicy, error) {
|
||||
|
||||
query := `
|
||||
SELECT id, username, status, created_at, updated_at
|
||||
SELECT id, username, status, message, created_at, updated_at
|
||||
FROM alerte_policy
|
||||
WHERE id = $1
|
||||
`
|
||||
var alert models.AlertPolicy
|
||||
err := d.QueryRow(query, id).Scan(&alert.ID, &alert.Username, &alert.Status, &alert.CreatedAt, &alert.UpdatedAt)
|
||||
err := d.QueryRow(query, id).Scan(&alert.ID, &alert.Username, &alert.Status, &alert.Message, &alert.CreatedAt, &alert.UpdatedAt)
|
||||
if err != nil {
|
||||
return models.AlertPolicy{}, err
|
||||
}
|
||||
@@ -42,7 +42,7 @@ func (d *Database) GetAlertPolicy(id int) (models.AlertPolicy, error) {
|
||||
func (d *Database) GetAllAlerts() ([]models.AlertPolicy, error) {
|
||||
|
||||
query := `
|
||||
SELECT id, username, status, created_at, updated_at
|
||||
SELECT id, username, status, message, created_at, updated_at
|
||||
FROM alerte_policy
|
||||
`
|
||||
rows, err := d.Query(query)
|
||||
@@ -54,7 +54,7 @@ func (d *Database) GetAllAlerts() ([]models.AlertPolicy, error) {
|
||||
var alerts []models.AlertPolicy
|
||||
for rows.Next() {
|
||||
var alert models.AlertPolicy
|
||||
err := rows.Scan(&alert.ID, &alert.Username, &alert.Status, &alert.CreatedAt, &alert.UpdatedAt)
|
||||
err := rows.Scan(&alert.ID, &alert.Username, &alert.Status, &alert.Message, &alert.CreatedAt, &alert.UpdatedAt)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -134,7 +134,7 @@ func (d *Database) ActivateAlert(id int) error {
|
||||
func (d *Database) GetActiveAlerts() ([]models.AlertPolicy, error) {
|
||||
|
||||
query := `
|
||||
SELECT id, username, status, created_at, updated_at
|
||||
SELECT id, username, status, message, created_at, updated_at
|
||||
FROM alerte_policy
|
||||
WHERE status = 'true'
|
||||
ORDER BY created_at DESC
|
||||
@@ -148,7 +148,7 @@ func (d *Database) GetActiveAlerts() ([]models.AlertPolicy, error) {
|
||||
var alerts []models.AlertPolicy
|
||||
for rows.Next() {
|
||||
var alert models.AlertPolicy
|
||||
err := rows.Scan(&alert.ID, &alert.Username, &alert.Status, &alert.CreatedAt, &alert.UpdatedAt)
|
||||
err := rows.Scan(&alert.ID, &alert.Username, &alert.Status, &alert.Message, &alert.CreatedAt, &alert.UpdatedAt)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -162,7 +162,7 @@ func (d *Database) GetActiveAlerts() ([]models.AlertPolicy, error) {
|
||||
func (d *Database) GetAlertsByUsername(username string) ([]models.AlertPolicy, error) {
|
||||
|
||||
query := `
|
||||
SELECT id, username, status, created_at, updated_at
|
||||
SELECT id, username, status, message, created_at, updated_at
|
||||
FROM alerte_policy
|
||||
WHERE username = $1
|
||||
ORDER BY created_at DESC
|
||||
@@ -176,7 +176,7 @@ func (d *Database) GetAlertsByUsername(username string) ([]models.AlertPolicy, e
|
||||
var alerts []models.AlertPolicy
|
||||
for rows.Next() {
|
||||
var alert models.AlertPolicy
|
||||
err := rows.Scan(&alert.ID, &alert.Username, &alert.Status, &alert.CreatedAt, &alert.UpdatedAt)
|
||||
err := rows.Scan(&alert.ID, &alert.Username, &alert.Status, &alert.Message, &alert.CreatedAt, &alert.UpdatedAt)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"regexp"
|
||||
)
|
||||
|
||||
var hexColorRegex = regexp.MustCompile(`^#[0-9A-Fa-f]{6}$`)
|
||||
|
||||
type Category struct {
|
||||
ID int `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Color string `json:"color"`
|
||||
IsComingSoon bool `json:"is_coming_soon"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
}
|
||||
|
||||
func ValidateCategoryColor(color string) error {
|
||||
if color == "" {
|
||||
return nil // valeur par défaut utilisée
|
||||
}
|
||||
if !hexColorRegex.MatchString(color) {
|
||||
return fmt.Errorf("couleur invalide : format hexadécimal requis (ex: #7c3aed)")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (d *Database) GetAllCategories() ([]Category, error) {
|
||||
rows, err := d.Query(`SELECT id, name, color, is_coming_soon, created_at FROM categories ORDER BY name ASC`)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var categories []Category
|
||||
for rows.Next() {
|
||||
var c Category
|
||||
if err := rows.Scan(&c.ID, &c.Name, &c.Color, &c.IsComingSoon, &c.CreatedAt); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
categories = append(categories, c)
|
||||
}
|
||||
if categories == nil {
|
||||
categories = []Category{}
|
||||
}
|
||||
return categories, nil
|
||||
}
|
||||
|
||||
func (d *Database) CreateCategory(name, color string, isComingSoon bool) (*Category, error) {
|
||||
if color == "" {
|
||||
color = "#7c3aed"
|
||||
}
|
||||
var c Category
|
||||
err := d.QueryRow(
|
||||
`INSERT INTO categories (name, color, is_coming_soon) VALUES ($1, $2, $3) RETURNING id, name, color, is_coming_soon, created_at`,
|
||||
name, color, isComingSoon,
|
||||
).Scan(&c.ID, &c.Name, &c.Color, &c.IsComingSoon, &c.CreatedAt)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &c, nil
|
||||
}
|
||||
|
||||
func (d *Database) UpdateCategory(id int, name, color string, isComingSoon bool) (*Category, error) {
|
||||
if color == "" {
|
||||
color = "#7c3aed"
|
||||
}
|
||||
var c Category
|
||||
err := d.QueryRow(
|
||||
`UPDATE categories SET name = $1, color = $2, is_coming_soon = $3 WHERE id = $4 RETURNING id, name, color, is_coming_soon, created_at`,
|
||||
name, color, isComingSoon, id,
|
||||
).Scan(&c.ID, &c.Name, &c.Color, &c.IsComingSoon, &c.CreatedAt)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &c, nil
|
||||
}
|
||||
|
||||
func (d *Database) DeleteCategory(id int) error {
|
||||
var count int
|
||||
err := d.QueryRow(`SELECT COUNT(*) FROM products WHERE category = (SELECT name FROM categories WHERE id = $1)`, id).Scan(&count)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if count > 0 {
|
||||
return fmt.Errorf("catégorie utilisée par %d produit(s)", count)
|
||||
}
|
||||
res, err := d.Exec(`DELETE FROM categories WHERE id = $1`, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
n, _ := res.RowsAffected()
|
||||
if n == 0 {
|
||||
return fmt.Errorf("catégorie non trouvée")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (d *Database) CategoryExists(name string) (bool, error) {
|
||||
var count int
|
||||
err := d.QueryRow(`SELECT COUNT(*) FROM categories WHERE name = $1`, name).Scan(&count)
|
||||
return count > 0, err
|
||||
}
|
||||
@@ -57,7 +57,7 @@ func (d *Database) GetClientByID(id int) (*models.Client, error) {
|
||||
|
||||
// GetAllClients récupère tous les clients
|
||||
func (d *Database) GetAllClients() ([]*models.Client, error) {
|
||||
query := `SELECT id, username, password, nom, prenom, telephone, command, point, point_zipette, amende, created_at
|
||||
query := `SELECT id, username, password, nom, prenom, telephone, command, point, point_zipette, amende, referral_balance, created_at
|
||||
FROM clients ORDER BY created_at DESC`
|
||||
|
||||
rows, err := d.Query(query)
|
||||
@@ -80,6 +80,7 @@ func (d *Database) GetAllClients() ([]*models.Client, error) {
|
||||
&client.Point,
|
||||
&client.PointZipette,
|
||||
&client.Amende,
|
||||
&client.ReferralBalance,
|
||||
&client.CreatedAt,
|
||||
)
|
||||
if err != nil {
|
||||
@@ -212,7 +213,7 @@ func (d *Database) GetClientStats(clientID int) (map[string]interface{}, error)
|
||||
|
||||
countQuery := `SELECT
|
||||
COUNT(*) as total,
|
||||
SUM(CASE WHEN status = 'pending' OR status = 'support' OR status = 'livre' THEN 1 ELSE 0 END) as pending,
|
||||
SUM(CASE WHEN status = 'pending' OR status = 'livre' THEN 1 ELSE 0 END) as pending,
|
||||
SUM(CASE WHEN status = 'approved' THEN 1 ELSE 0 END) as completed
|
||||
FROM commandes WHERE username = $1`
|
||||
|
||||
@@ -856,128 +857,159 @@ func (d *Database) CalculateAndAddPointsForCommand(commandID int, username strin
|
||||
return totalPoints, nil
|
||||
}
|
||||
|
||||
func (d *Database) CalculateAndAddPointsForCommandTx(tx *sql.Tx, commandID int, username string) (int, error) {
|
||||
func (d *Database) CalculateAndAddPointsForCommandTx(tx *sql.Tx, commandID int, username string) (int, string, error) {
|
||||
log.Printf("💰 [CalcPointsTx] START - cmd=%d, user=%s", commandID, username)
|
||||
|
||||
// Charger les paramètres globaux
|
||||
settings, err := d.GetSettings()
|
||||
if err != nil {
|
||||
log.Printf("⚠️ [CalcPointsTx] Erreur lecture settings, utilisation des défauts: %v", err)
|
||||
settings = DefaultSettings()
|
||||
}
|
||||
|
||||
// Construire les sets de catégories par pool
|
||||
weedCats := make(map[string]bool)
|
||||
for _, cat := range settings.PointsCategoriesWeed {
|
||||
weedCats[strings.ToLower(cat)] = true
|
||||
}
|
||||
zipetteCats := make(map[string]bool)
|
||||
for _, cat := range settings.PointsCategoriesZipette {
|
||||
zipetteCats[strings.ToLower(cat)] = true
|
||||
}
|
||||
// pool "total" → toujours compté dans le pool weed (point)
|
||||
totalCats := make(map[string]bool)
|
||||
for _, cat := range settings.PointsCategoriesTotal {
|
||||
totalCats[strings.ToLower(cat)] = true
|
||||
}
|
||||
|
||||
// Si aucune catégorie configurée → pas de points
|
||||
if !settings.PointsSeparated {
|
||||
// Mode non-séparé : seul le pool Total est actif
|
||||
if len(weedCats) == 0 && len(zipetteCats) == 0 && len(totalCats) == 0 {
|
||||
log.Printf("ℹ️ [CalcPointsTx] Mode non-séparé : aucune catégorie configurée → 0 points")
|
||||
return 0, "", nil
|
||||
}
|
||||
} else {
|
||||
// Mode séparé : seuls W et Z sont actifs (T ignoré)
|
||||
if len(weedCats) == 0 && len(zipetteCats) == 0 {
|
||||
log.Printf("ℹ️ [CalcPointsTx] Mode séparé : aucune catégorie W/Z configurée → 0 points")
|
||||
return 0, "", nil
|
||||
}
|
||||
}
|
||||
|
||||
// ✅ ÉTAPE 1: Récupérer tous les items de la commande avec leurs catégories
|
||||
query := `
|
||||
SELECT ci.quantite, ci.prix, COALESCE(p.category, 'weed_hash') as category
|
||||
rows, err := tx.Query(`
|
||||
SELECT ci.quantite, ci.prix, COALESCE(p.category, '') as category
|
||||
FROM command_items ci
|
||||
LEFT JOIN products p ON ci.product_id = p.id
|
||||
WHERE ci.command_id = $1
|
||||
`
|
||||
|
||||
rows, err := tx.Query(query, commandID)
|
||||
`, commandID)
|
||||
if err != nil {
|
||||
log.Printf("❌ [CalcPointsTx] Erreur query items: %v", err)
|
||||
return 0, fmt.Errorf("erreur récupération items: %w", err)
|
||||
return 0, "", fmt.Errorf("erreur récupération items: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
type ItemPoints struct {
|
||||
Category string
|
||||
Quantite float64
|
||||
Prix float64
|
||||
}
|
||||
|
||||
var items []ItemPoints
|
||||
totalPrixWeedHash := 0.0
|
||||
var itemCount int
|
||||
totalPrixWeed := 0.0
|
||||
totalPrixZipette := 0.0
|
||||
totalPrixTotal := 0.0
|
||||
|
||||
for rows.Next() {
|
||||
var item ItemPoints
|
||||
if err := rows.Scan(&item.Quantite, &item.Prix, &item.Category); err != nil {
|
||||
var quantite, prix float64
|
||||
var category string
|
||||
if err := rows.Scan(&quantite, &prix, &category); err != nil {
|
||||
log.Printf("❌ [CalcPointsTx] Erreur scan: %v", err)
|
||||
return 0, fmt.Errorf("erreur lecture item: %w", err)
|
||||
return 0, "", fmt.Errorf("erreur lecture item: %w", err)
|
||||
}
|
||||
|
||||
items = append(items, item)
|
||||
|
||||
// Cumuler par catégorie
|
||||
categoryLower := strings.ToLower(item.Category)
|
||||
if categoryLower == "zipette&co" || categoryLower == "zipette_co" {
|
||||
totalPrixZipette += item.Prix
|
||||
} else if categoryLower == "gros&semi" || categoryLower == "gros_semi" {
|
||||
// gros&semi → 0 points, on ne cumule pas
|
||||
} else {
|
||||
// weed_hash ou autres catégories
|
||||
totalPrixWeedHash += item.Prix
|
||||
itemCount++
|
||||
catLower := strings.ToLower(category)
|
||||
if weedCats[catLower] {
|
||||
totalPrixWeed += prix
|
||||
} else if zipetteCats[catLower] {
|
||||
totalPrixZipette += prix
|
||||
} else if totalCats[catLower] {
|
||||
totalPrixTotal += prix
|
||||
}
|
||||
}
|
||||
|
||||
if err = rows.Err(); err != nil {
|
||||
log.Printf("❌ [CalcPointsTx] Erreur rows: %v", err)
|
||||
return 0, fmt.Errorf("erreur itération items: %w", err)
|
||||
return 0, "", fmt.Errorf("erreur itération items: %w", err)
|
||||
}
|
||||
|
||||
if len(items) == 0 {
|
||||
if itemCount == 0 {
|
||||
log.Printf("⚠️ [CalcPointsTx] Aucun item trouvé pour cmd %d", commandID)
|
||||
return 0, nil
|
||||
return 0, "", nil
|
||||
}
|
||||
|
||||
log.Printf("📊 [CalcPointsTx] %d items - weed_hash: %.2f€, zipette: %.2f€",
|
||||
len(items), totalPrixWeedHash, totalPrixZipette)
|
||||
log.Printf("📊 [CalcPointsTx] %d items - weed: %.2f€, zipette: %.2f€, total: %.2f€",
|
||||
itemCount, totalPrixWeed, totalPrixZipette, totalPrixTotal)
|
||||
|
||||
// ✅ ÉTAPE 2: Calculer les points par catégorie avec le bon barème
|
||||
pointsWeedHash := 0
|
||||
switch {
|
||||
case totalPrixWeedHash >= 30 && totalPrixWeedHash <= 50:
|
||||
pointsWeedHash = 1
|
||||
case totalPrixWeedHash >= 60 && totalPrixWeedHash <= 150:
|
||||
pointsWeedHash = 2
|
||||
case totalPrixWeedHash >= 160 && totalPrixWeedHash <= 300:
|
||||
pointsWeedHash = 3
|
||||
case totalPrixWeedHash >= 310 && totalPrixWeedHash <= 400:
|
||||
pointsWeedHash = 5
|
||||
case totalPrixWeedHash >= 400:
|
||||
pointsWeedHash = 10
|
||||
}
|
||||
// ✅ ÉTAPE 2: Calculer les points
|
||||
var totalPoints int
|
||||
var pointCategory string
|
||||
var result sql.Result
|
||||
|
||||
pointsZipette := 0
|
||||
switch {
|
||||
case totalPrixZipette >= 30 && totalPrixZipette <= 100:
|
||||
pointsZipette = 1
|
||||
case totalPrixZipette >= 110 && totalPrixZipette <= 200:
|
||||
pointsZipette = 2
|
||||
case totalPrixZipette >= 210:
|
||||
pointsZipette = 3
|
||||
}
|
||||
if !settings.PointsSeparated {
|
||||
// ── Mode non-séparé : Barème Total appliqué sur W + Z + T ──────────────
|
||||
allTotal := totalPrixWeed + totalPrixZipette + totalPrixTotal
|
||||
totalPoints = CalcPointsFromTiers(allTotal, settings.PointsTotalTiers)
|
||||
pointCategory = "total"
|
||||
|
||||
totalPoints := pointsWeedHash + pointsZipette
|
||||
log.Printf("💰 [CalcPointsTx] Mode non-séparé - total: %.2f€ → %d pts (barème Total)",
|
||||
allTotal, totalPoints)
|
||||
|
||||
log.Printf("💰 [CalcPointsTx] Points calculés - weed_hash: %d, zipette: %d, total: %d",
|
||||
pointsWeedHash, pointsZipette, totalPoints)
|
||||
if totalPoints == 0 {
|
||||
return 0, "", nil
|
||||
}
|
||||
|
||||
// ✅ ÉTAPE 3: Mettre à jour les points du client (dans la transaction)
|
||||
if pointsWeedHash > 0 || pointsZipette > 0 {
|
||||
updateQuery := `
|
||||
result, err = tx.Exec(`
|
||||
UPDATE clients
|
||||
SET
|
||||
point = point + $1,
|
||||
point_zipette = point_zipette + $2,
|
||||
updated_at = CURRENT_TIMESTAMP
|
||||
SET point = point + $1, updated_at = CURRENT_TIMESTAMP
|
||||
WHERE username = $2
|
||||
`, totalPoints, username)
|
||||
} else {
|
||||
// ── Mode séparé : Barèmes W et Z, pool T ignoré ────────────────────────
|
||||
pointsWeed := CalcPointsFromTiers(totalPrixWeed, settings.PointsWeedTiers)
|
||||
pointsZipette := CalcPointsFromTiers(totalPrixZipette, settings.PointsZipetteTiers)
|
||||
totalPoints = pointsWeed + pointsZipette
|
||||
|
||||
log.Printf("💰 [CalcPointsTx] Mode séparé - weed: %d pts, zipette: %d pts",
|
||||
pointsWeed, pointsZipette)
|
||||
|
||||
if totalPoints == 0 {
|
||||
return 0, "", nil
|
||||
}
|
||||
|
||||
if pointsWeed > 0 && pointsZipette > 0 {
|
||||
pointCategory = "mixed"
|
||||
} else if pointsZipette > 0 {
|
||||
pointCategory = "zipette&co"
|
||||
} else {
|
||||
pointCategory = "weed&hash"
|
||||
}
|
||||
|
||||
result, err = tx.Exec(`
|
||||
UPDATE clients
|
||||
SET point = point + $1, point_zipette = point_zipette + $2, updated_at = CURRENT_TIMESTAMP
|
||||
WHERE username = $3
|
||||
`
|
||||
|
||||
result, err := tx.Exec(updateQuery, pointsWeedHash, pointsZipette, username)
|
||||
if err != nil {
|
||||
log.Printf("❌ [CalcPointsTx] Erreur UPDATE points: %v", err)
|
||||
return 0, fmt.Errorf("erreur mise à jour points: %w", err)
|
||||
}
|
||||
|
||||
rows, _ := result.RowsAffected()
|
||||
if rows == 0 {
|
||||
log.Printf("⚠️ [CalcPointsTx] Client %s non trouvé", username)
|
||||
return 0, fmt.Errorf("client non trouvé")
|
||||
}
|
||||
|
||||
log.Printf("✅ [CalcPointsTx] Points ajoutés: +%d weed_hash, +%d zipette pour %s",
|
||||
pointsWeedHash, pointsZipette, username)
|
||||
`, pointsWeed, pointsZipette, username)
|
||||
}
|
||||
|
||||
log.Printf("🎉 [CalcPointsTx] SUCCÈS - Total %d points attribués", totalPoints)
|
||||
if err != nil {
|
||||
log.Printf("❌ [CalcPointsTx] Erreur UPDATE points: %v", err)
|
||||
return 0, "", fmt.Errorf("erreur mise à jour points: %w", err)
|
||||
}
|
||||
affected, _ := result.RowsAffected()
|
||||
if affected == 0 {
|
||||
log.Printf("⚠️ [CalcPointsTx] Client %s non trouvé", username)
|
||||
return 0, "", fmt.Errorf("client non trouvé")
|
||||
}
|
||||
|
||||
return totalPoints, nil
|
||||
log.Printf("🎉 [CalcPointsTx] SUCCÈS - %d points [%s] → %s", totalPoints, pointCategory, username)
|
||||
|
||||
return totalPoints, pointCategory, nil
|
||||
}
|
||||
|
||||
func (d *Database) CanUserAccessCommand(
|
||||
|
||||
@@ -213,6 +213,7 @@ func (d *Database) GetCommandItems(commandID int) ([]map[string]interface{}, err
|
||||
c.status as command_status,
|
||||
c.adresse as command_address,
|
||||
c.total_prix,
|
||||
c.referral_used,
|
||||
c.livreur_assign,
|
||||
c.created_at as command_created_at,
|
||||
COALESCE(p.category, 'weed_hash') as category
|
||||
@@ -241,13 +242,14 @@ func (d *Database) GetCommandItems(commandID int) ([]map[string]interface{}, err
|
||||
var createdAt, updatedAt, commandCreatedAt time.Time
|
||||
var commandStatus, commandAddress, livreurAssign sql.NullString
|
||||
var category string
|
||||
var referralUsed float64
|
||||
|
||||
// ✅ FIX: Utiliser &productID (sql.NullInt64)
|
||||
err := rows.Scan(
|
||||
&id, &commandID, &produit, &productID, &quantite, &prix,
|
||||
&clientUsername, &clientNom, &clientPrenom, &clientTelephone, &deliveryAddress, &status,
|
||||
&createdAt, &updatedAt,
|
||||
&commandStatus, &commandAddress, &totalPrix, &livreurAssign, &commandCreatedAt,
|
||||
&commandStatus, &commandAddress, &totalPrix, &referralUsed, &livreurAssign, &commandCreatedAt,
|
||||
&category,
|
||||
)
|
||||
|
||||
@@ -281,6 +283,7 @@ func (d *Database) GetCommandItems(commandID int) ([]map[string]interface{}, err
|
||||
"command_status": commandStatus.String,
|
||||
"command_address": commandAddress.String,
|
||||
"total_prix": totalPrix,
|
||||
"referral_used": referralUsed,
|
||||
"livreur_assign": livreurAssign.String,
|
||||
"command_created_at": commandCreatedAt,
|
||||
"category": category,
|
||||
|
||||
@@ -26,7 +26,7 @@ func (d *Database) GetAllCommandsOldestFirst(status, username string) ([]map[str
|
||||
|
||||
// Filtrer par status
|
||||
if status != "" {
|
||||
validStatuses := []string{"pending", "assigned", "en_route", "livre", "approved", "cancelled", "disabled", "support"}
|
||||
validStatuses := []string{"pending", "assigned", "en_route", "livre", "approved", "cancelled", "disabled"}
|
||||
isValid := false
|
||||
for _, vs := range validStatuses {
|
||||
if status == vs {
|
||||
|
||||
@@ -53,7 +53,6 @@ func validateCommandStatus(status string) error {
|
||||
"approved": true,
|
||||
"cancelled": true,
|
||||
"disabled": true,
|
||||
"support": true,
|
||||
}
|
||||
|
||||
if !validStatuses[status] {
|
||||
@@ -423,10 +422,15 @@ func (d *Database) GetCommandCount() (int, error) {
|
||||
return count, nil
|
||||
}
|
||||
|
||||
func (d *Database) SetCommandReferralUsed(commandID int, amount float64) error {
|
||||
_, err := d.Exec(`UPDATE commandes SET referral_used = $1 WHERE id = $2`, amount, commandID)
|
||||
return err
|
||||
}
|
||||
|
||||
func (d *Database) GetCommandByID(id int) (map[string]interface{}, error) {
|
||||
// ✅ Déjà sécurisé avec paramètre $1
|
||||
query := `SELECT id, username, status, adresse, total_prix, livreur_assign, created_at, updated_at,
|
||||
proposed_address, address_proposal_status
|
||||
proposed_address, address_proposal_status, referral_used
|
||||
FROM commandes WHERE id = $1`
|
||||
|
||||
var commandID int
|
||||
@@ -434,7 +438,7 @@ func (d *Database) GetCommandByID(id int) (map[string]interface{}, error) {
|
||||
var livreurAssign sql.NullString
|
||||
var proposedAddress sql.NullString
|
||||
var addressProposalStatus string
|
||||
var totalPrix float64
|
||||
var totalPrix, referralUsed float64
|
||||
var createdAt, updatedAt time.Time
|
||||
|
||||
err := d.QueryRow(query, id).Scan(
|
||||
@@ -448,6 +452,7 @@ func (d *Database) GetCommandByID(id int) (map[string]interface{}, error) {
|
||||
&updatedAt,
|
||||
&proposedAddress,
|
||||
&addressProposalStatus,
|
||||
&referralUsed,
|
||||
)
|
||||
|
||||
if err == sql.ErrNoRows {
|
||||
@@ -466,6 +471,7 @@ func (d *Database) GetCommandByID(id int) (map[string]interface{}, error) {
|
||||
"created_at": createdAt,
|
||||
"updated_at": updatedAt,
|
||||
"address_proposal_status": addressProposalStatus,
|
||||
"referral_used": referralUsed,
|
||||
}
|
||||
|
||||
if livreurAssign.Valid {
|
||||
@@ -595,7 +601,7 @@ func (d *Database) RespondToAddressProposal(commandID int, clientUsername string
|
||||
// UpdateCommandStatus met à jour le statut d'une commande
|
||||
func (d *Database) UpdateCommandStatus(commandID int, status string) error {
|
||||
// ✅ SÉCURITÉ: Validation du statut
|
||||
validStatuses := []string{"pending", "assigned", "en_route", "arrived", "livre", "approved", "cancelled", "disabled", "support"}
|
||||
validStatuses := []string{"pending", "assigned", "en_route", "arrived", "livre", "approved", "cancelled", "disabled"}
|
||||
isValid := false
|
||||
for _, vs := range validStatuses {
|
||||
if status == vs {
|
||||
@@ -706,7 +712,7 @@ func (d *Database) GetCommandsWithFilter(status, username string, excludeApprove
|
||||
|
||||
// ✅ Filtrer par status si fourni avec validation
|
||||
if status != "" {
|
||||
validStatuses := []string{"pending", "assigned", "en_route", "arrived", "livre", "approved", "cancelled", "disabled", "support"}
|
||||
validStatuses := []string{"pending", "assigned", "en_route", "arrived", "livre", "approved", "cancelled", "disabled"}
|
||||
isValid := false
|
||||
for _, vs := range validStatuses {
|
||||
if status == vs {
|
||||
@@ -832,7 +838,7 @@ func (d *Database) ValidateDeliveryAtomic(commandID int, adminUsername string) (
|
||||
currentStatus, cmdUsername, livreurAssign)
|
||||
|
||||
// ✅ ÉTAPE 3: Vérifier que le statut permet la validation
|
||||
validStatuses := []string{"assigned", "en_route", "pending", "support", "livre"}
|
||||
validStatuses := []string{"assigned", "en_route", "pending", "livre"}
|
||||
isValid := false
|
||||
for _, s := range validStatuses {
|
||||
if currentStatus == s {
|
||||
@@ -878,7 +884,7 @@ func (d *Database) ValidateDeliveryAtomic(commandID int, adminUsername string) (
|
||||
log.Printf("🔍 [ValidateAtomic] Calcul points pour client: %s", cmdUsername)
|
||||
|
||||
// Utiliser la version transactionnelle du calcul de points
|
||||
points, err := d.CalculateAndAddPointsForCommandTx(tx, commandID, cmdUsername)
|
||||
points, _, err := d.CalculateAndAddPointsForCommandTx(tx, commandID, cmdUsername)
|
||||
if err != nil {
|
||||
log.Printf("❌ [ValidateAtomic] Erreur calcul/ajout points: %v", err)
|
||||
return 0, fmt.Errorf("erreur attribution points: %w", err)
|
||||
@@ -957,14 +963,14 @@ func (d *Database) ValidateDeliveryAtomic(commandID int, adminUsername string) (
|
||||
}
|
||||
|
||||
// ApproveDeliveryAtomic - Version atomique pour approbation client
|
||||
func (d *Database) ApproveDeliveryAtomic(commandID int, username string) (int, error) {
|
||||
func (d *Database) ApproveDeliveryAtomic(commandID int, username string) (int, string, error) {
|
||||
log.Printf("🔒 [ApproveAtomic] START - cmd=%d, client=%s", commandID, username)
|
||||
|
||||
// ✅ ÉTAPE 1: Démarrer une transaction
|
||||
tx, err := d.Begin()
|
||||
if err != nil {
|
||||
log.Printf("❌ [ApproveAtomic] Erreur début transaction: %v", err)
|
||||
return 0, fmt.Errorf("erreur transaction: %w", err)
|
||||
return 0, "", fmt.Errorf("erreur transaction: %w", err)
|
||||
}
|
||||
defer tx.Rollback()
|
||||
|
||||
@@ -979,11 +985,11 @@ func (d *Database) ApproveDeliveryAtomic(commandID int, username string) (int, e
|
||||
|
||||
if err == sql.ErrNoRows {
|
||||
log.Printf("❌ [ApproveAtomic] Commande %d non trouvée", commandID)
|
||||
return 0, fmt.Errorf("commande non trouvée")
|
||||
return 0, "", fmt.Errorf("commande non trouvée")
|
||||
}
|
||||
if err != nil {
|
||||
log.Printf("❌ [ApproveAtomic] Erreur SELECT: %v", err)
|
||||
return 0, fmt.Errorf("erreur lecture commande: %w", err)
|
||||
return 0, "", fmt.Errorf("erreur lecture commande: %w", err)
|
||||
}
|
||||
|
||||
log.Printf("📋 [ApproveAtomic] Commande trouvée - status=%s, owner=%s", currentStatus, cmdUsername)
|
||||
@@ -992,13 +998,13 @@ func (d *Database) ApproveDeliveryAtomic(commandID int, username string) (int, e
|
||||
if cmdUsername != username {
|
||||
log.Printf("❌ [ApproveAtomic] Commande n'appartient pas à %s (propriétaire: %s)",
|
||||
username, cmdUsername)
|
||||
return 0, fmt.Errorf("cette commande ne vous appartient pas")
|
||||
return 0, "", fmt.Errorf("cette commande ne vous appartient pas")
|
||||
}
|
||||
|
||||
// ✅ ÉTAPE 4: Vérifier le statut
|
||||
if currentStatus != "livre" {
|
||||
log.Printf("❌ [ApproveAtomic] Statut invalide: %s (attendu: livre)", currentStatus)
|
||||
return 0, fmt.Errorf("commande doit être en statut 'livre' (statut actuel: %s)", currentStatus)
|
||||
return 0, "", fmt.Errorf("commande doit être en statut 'livre' (statut actuel: %s)", currentStatus)
|
||||
}
|
||||
|
||||
// ✅ ÉTAPE 5: UPDATE avec vérification du statut
|
||||
@@ -1010,25 +1016,25 @@ func (d *Database) ApproveDeliveryAtomic(commandID int, username string) (int, e
|
||||
|
||||
if err != nil {
|
||||
log.Printf("❌ [ApproveAtomic] Erreur UPDATE: %v", err)
|
||||
return 0, fmt.Errorf("erreur mise à jour statut: %w", err)
|
||||
return 0, "", fmt.Errorf("erreur mise à jour statut: %w", err)
|
||||
}
|
||||
|
||||
rows, _ := result.RowsAffected()
|
||||
if rows == 0 {
|
||||
log.Printf("❌ [ApproveAtomic] Commande %d déjà modifiée (race condition évitée)", commandID)
|
||||
return 0, fmt.Errorf("commande déjà approuvée ou modifiée")
|
||||
return 0, "", fmt.Errorf("commande déjà approuvée ou modifiée")
|
||||
}
|
||||
|
||||
log.Printf("✅ [ApproveAtomic] Statut mis à jour: livre → approved")
|
||||
|
||||
// ✅ ÉTAPE 6: Calculer et ajouter les points
|
||||
totalPoints, err := d.CalculateAndAddPointsForCommandTx(tx, commandID, username)
|
||||
totalPoints, pointCategory, err := d.CalculateAndAddPointsForCommandTx(tx, commandID, username)
|
||||
if err != nil {
|
||||
log.Printf("❌ [ApproveAtomic] Erreur calcul points: %v", err)
|
||||
return 0, fmt.Errorf("erreur attribution points: %w", err)
|
||||
return 0, "", fmt.Errorf("erreur attribution points: %w", err)
|
||||
}
|
||||
|
||||
log.Printf("✅ [ApproveAtomic] %d points attribués à %s", totalPoints, username)
|
||||
log.Printf("✅ [ApproveAtomic] %d points [%s] attribués à %s", totalPoints, pointCategory, username)
|
||||
|
||||
// ✅ ÉTAPE 7: Incrémenter le compteur de commandes
|
||||
_, err = tx.Exec(`
|
||||
@@ -1046,7 +1052,7 @@ func (d *Database) ApproveDeliveryAtomic(commandID int, username string) (int, e
|
||||
INSERT INTO command_logs (command_id, status, message, author, created_at)
|
||||
VALUES ($1, $2, $3, $4, CURRENT_TIMESTAMP)
|
||||
`, commandID, "approved",
|
||||
fmt.Sprintf("Livraison confirmée par le client %s - %d points attribués", username, totalPoints),
|
||||
fmt.Sprintf("Livraison confirmée par le client %s - %d points [%s] attribués", username, totalPoints, pointCategory),
|
||||
username)
|
||||
|
||||
if err != nil {
|
||||
@@ -1056,11 +1062,11 @@ func (d *Database) ApproveDeliveryAtomic(commandID int, username string) (int, e
|
||||
// ✅ ÉTAPE 9: Commit
|
||||
if err := tx.Commit(); err != nil {
|
||||
log.Printf("❌ [ApproveAtomic] Erreur COMMIT: %v", err)
|
||||
return 0, fmt.Errorf("erreur commit transaction: %w", err)
|
||||
return 0, "", fmt.Errorf("erreur commit transaction: %w", err)
|
||||
}
|
||||
|
||||
log.Printf("🎉 [ApproveAtomic] SUCCÈS - Commande %d approuvée, %d points attribués",
|
||||
commandID, totalPoints)
|
||||
log.Printf("🎉 [ApproveAtomic] SUCCÈS - Commande %d approuvée, %d points [%s] attribués",
|
||||
commandID, totalPoints, pointCategory)
|
||||
|
||||
// ✅ ÉTAPE 10: Optimiser queue livreur (async, après commit)
|
||||
if livreurAssign != "" {
|
||||
@@ -1087,16 +1093,16 @@ func (d *Database) ApproveDeliveryAtomic(commandID int, username string) (int, e
|
||||
log.Printf("✅ [ApproveAtomic] Caches invalidés")
|
||||
}()
|
||||
|
||||
return totalPoints, nil
|
||||
return totalPoints, pointCategory, nil
|
||||
}
|
||||
|
||||
// ApproveDeliveryAtomicByStaff - Confirmation de réception par admin ou cabine à la place du client
|
||||
func (d *Database) ApproveDeliveryAtomicByStaff(commandID int, staffUsername string) (int, string, error) {
|
||||
func (d *Database) ApproveDeliveryAtomicByStaff(commandID int, staffUsername string) (int, string, string, error) {
|
||||
log.Printf("🔒 [ApproveAtomicStaff] START - cmd=%d, staff=%s", commandID, staffUsername)
|
||||
|
||||
tx, err := d.Begin()
|
||||
if err != nil {
|
||||
return 0, "", fmt.Errorf("erreur transaction: %w", err)
|
||||
return 0, "", "", fmt.Errorf("erreur transaction: %w", err)
|
||||
}
|
||||
defer tx.Rollback()
|
||||
|
||||
@@ -1109,14 +1115,14 @@ func (d *Database) ApproveDeliveryAtomicByStaff(commandID int, staffUsername str
|
||||
`, commandID).Scan(¤tStatus, &clientUsername, &livreurAssign)
|
||||
|
||||
if err == sql.ErrNoRows {
|
||||
return 0, "", fmt.Errorf("commande non trouvée")
|
||||
return 0, "", "", fmt.Errorf("commande non trouvée")
|
||||
}
|
||||
if err != nil {
|
||||
return 0, "", fmt.Errorf("erreur lecture commande: %w", err)
|
||||
return 0, "", "", fmt.Errorf("erreur lecture commande: %w", err)
|
||||
}
|
||||
|
||||
if currentStatus != "livre" {
|
||||
return 0, "", fmt.Errorf("commande doit être en statut 'livre' (statut actuel: %s)", currentStatus)
|
||||
return 0, "", "", fmt.Errorf("commande doit être en statut 'livre' (statut actuel: %s)", currentStatus)
|
||||
}
|
||||
|
||||
result, err := tx.Exec(`
|
||||
@@ -1125,17 +1131,17 @@ func (d *Database) ApproveDeliveryAtomicByStaff(commandID int, staffUsername str
|
||||
WHERE id = $1 AND status = 'livre'
|
||||
`, commandID)
|
||||
if err != nil {
|
||||
return 0, "", fmt.Errorf("erreur mise à jour statut: %w", err)
|
||||
return 0, "", "", fmt.Errorf("erreur mise à jour statut: %w", err)
|
||||
}
|
||||
|
||||
rows, _ := result.RowsAffected()
|
||||
if rows == 0 {
|
||||
return 0, "", fmt.Errorf("commande déjà approuvée ou modifiée")
|
||||
return 0, "", "", fmt.Errorf("commande déjà approuvée ou modifiée")
|
||||
}
|
||||
|
||||
totalPoints, err := d.CalculateAndAddPointsForCommandTx(tx, commandID, clientUsername)
|
||||
totalPoints, pointCategory, err := d.CalculateAndAddPointsForCommandTx(tx, commandID, clientUsername)
|
||||
if err != nil {
|
||||
return 0, "", fmt.Errorf("erreur attribution points: %w", err)
|
||||
return 0, "", "", fmt.Errorf("erreur attribution points: %w", err)
|
||||
}
|
||||
|
||||
_, err = tx.Exec(`
|
||||
@@ -1158,7 +1164,7 @@ func (d *Database) ApproveDeliveryAtomicByStaff(commandID int, staffUsername str
|
||||
}
|
||||
|
||||
if err := tx.Commit(); err != nil {
|
||||
return 0, "", fmt.Errorf("erreur commit: %w", err)
|
||||
return 0, "", "", fmt.Errorf("erreur commit: %w", err)
|
||||
}
|
||||
|
||||
log.Printf("🎉 [ApproveAtomicStaff] SUCCÈS - cmd=%d approuvée par %s, %d points → client %s",
|
||||
@@ -1178,5 +1184,5 @@ func (d *Database) ApproveDeliveryAtomicByStaff(commandID int, staffUsername str
|
||||
Redis.Del(RedisCtx, fmt.Sprintf("client:%s:commands", clientUsername))
|
||||
}()
|
||||
|
||||
return totalPoints, clientUsername, nil
|
||||
return totalPoints, pointCategory, clientUsername, nil
|
||||
}
|
||||
|
||||
@@ -111,7 +111,7 @@ func (d *Database) AssignDeliveryPerson(commandID int, livreurUsername string) e
|
||||
}
|
||||
|
||||
// ✅ Vérifier le statut
|
||||
validStatusesForAssignment := []string{"pending", "support"}
|
||||
validStatusesForAssignment := []string{"pending"}
|
||||
isValidStatus := false
|
||||
for _, vs := range validStatusesForAssignment {
|
||||
if currentStatus == vs {
|
||||
@@ -132,10 +132,10 @@ func (d *Database) AssignDeliveryPerson(commandID int, livreurUsername string) e
|
||||
// ============================================
|
||||
updateQuery := `UPDATE commandes
|
||||
SET livreur_assign = $1,
|
||||
status = 'support',
|
||||
status = 'assigned',
|
||||
updated_at = CURRENT_TIMESTAMP
|
||||
WHERE id = $2
|
||||
AND status IN ('pending', 'support')
|
||||
AND status IN ('pending')
|
||||
AND (livreur_assign IS NULL OR livreur_assign = '' OR livreur_assign = $1)`
|
||||
|
||||
result, err := tx.Exec(updateQuery, livreurUsername, commandID)
|
||||
@@ -159,10 +159,10 @@ func (d *Database) AssignDeliveryPerson(commandID int, livreurUsername string) e
|
||||
// ============================================
|
||||
// ÉTAPE 5: Ajouter un log (DANS la transaction)
|
||||
// ============================================
|
||||
logQuery := `INSERT INTO command_logs (command_id, status, message, actor, created_at)
|
||||
logQuery := `INSERT INTO command_logs (command_id, status, message, author, created_at)
|
||||
VALUES ($1, $2, $3, $4, CURRENT_TIMESTAMP)`
|
||||
|
||||
_, err = tx.Exec(logQuery, commandID, "support",
|
||||
_, err = tx.Exec(logQuery, commandID, "assigned",
|
||||
fmt.Sprintf("Livraison assignée au livreur %s", livreurUsername),
|
||||
"admin")
|
||||
if err != nil {
|
||||
@@ -180,7 +180,7 @@ func (d *Database) AssignDeliveryPerson(commandID int, livreurUsername string) e
|
||||
}
|
||||
|
||||
log.Printf("🎉 [AssignDeliveryPerson] SUCCÈS - Commande %d assignée à %s", commandID, livreurUsername)
|
||||
log.Printf(" Workflow: pending → ✅ support (TRANSACTION COMMITTED)")
|
||||
log.Printf(" Workflow: pending → ✅ assigned (TRANSACTION COMMITTED)")
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -356,7 +356,7 @@ func (d *Database) ApproveDelivery(commandID int, clientUsername string) error {
|
||||
// ============================================
|
||||
// ÉTAPE 5: Ajouter un log (DANS la transaction)
|
||||
// ============================================
|
||||
logQuery := `INSERT INTO command_logs (command_id, status, message, actor, created_at)
|
||||
logQuery := `INSERT INTO command_logs (command_id, status, message, author, created_at)
|
||||
VALUES ($1, $2, $3, $4, CURRENT_TIMESTAMP)`
|
||||
|
||||
_, err = tx.Exec(logQuery, commandID, "approved",
|
||||
|
||||
@@ -84,7 +84,6 @@ func ValidateStatuses(statuses string) ([]string, error) {
|
||||
// Liste blanche complète
|
||||
validStatusMap := map[string]bool{
|
||||
"pending": true,
|
||||
"support": true,
|
||||
"assigned": true,
|
||||
"en_route": true,
|
||||
"arrived": true,
|
||||
|
||||
@@ -133,6 +133,34 @@ func InitDB() *Database {
|
||||
log.Fatalf("❌ Erreur migration command_items.quantite: %v", err)
|
||||
}
|
||||
|
||||
// Migration: ajouter colonne color pour les catégories
|
||||
if _, err = database.Exec(`ALTER TABLE categories ADD COLUMN IF NOT EXISTS color VARCHAR(7) NOT NULL DEFAULT '#7c3aed'`); err != nil {
|
||||
log.Fatalf("❌ Erreur migration categories.color: %v", err)
|
||||
}
|
||||
|
||||
// Migration: ajouter colonne is_coming_soon pour les catégories
|
||||
if _, err = database.Exec(`ALTER TABLE categories ADD COLUMN IF NOT EXISTS is_coming_soon BOOLEAN NOT NULL DEFAULT FALSE`); err != nil {
|
||||
log.Fatalf("❌ Erreur migration categories.is_coming_soon: %v", err)
|
||||
}
|
||||
|
||||
// Migration: table paramètres globaux de l'application
|
||||
if _, err = database.Exec(`CREATE TABLE IF NOT EXISTS app_settings (
|
||||
key VARCHAR(100) PRIMARY KEY,
|
||||
value TEXT NOT NULL
|
||||
)`); err != nil {
|
||||
log.Fatalf("❌ Erreur migration app_settings: %v", err)
|
||||
}
|
||||
|
||||
// Migration: ajouter colonne message pour les alertes police (type d'alerte)
|
||||
if _, err = database.Exec(`ALTER TABLE alerte_policy ADD COLUMN IF NOT EXISTS message VARCHAR(200) NOT NULL DEFAULT ''`); err != nil {
|
||||
log.Fatalf("❌ Erreur migration alerte_policy.message: %v", err)
|
||||
}
|
||||
|
||||
// Migration: montant de parrainage utilisé pour la commande
|
||||
if _, err = database.Exec(`ALTER TABLE commandes ADD COLUMN IF NOT EXISTS referral_used FLOAT NOT NULL DEFAULT 0`); err != nil {
|
||||
log.Fatalf("❌ Erreur migration commandes.referral_used: %v", err)
|
||||
}
|
||||
|
||||
// Lancer le nettoyage périodique des tokens expirés
|
||||
go database.cleanExpiredTokensPeriodically()
|
||||
|
||||
@@ -178,9 +206,11 @@ func (db *Database) createTables() error {
|
||||
cancel_commande INTEGER DEFAULT 0,
|
||||
cancellations_count INTEGER DEFAULT 0 NOT NULL,
|
||||
last_penalty_reason TEXT DEFAULT NULL,
|
||||
referral_balance NUMERIC(10,2) DEFAULT 0.0,
|
||||
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||||
);`,
|
||||
`ALTER TABLE clients ADD COLUMN IF NOT EXISTS referral_balance NUMERIC(10,2) DEFAULT 0.0;`,
|
||||
|
||||
// ============================
|
||||
// TABLE jwt_tokens
|
||||
@@ -195,6 +225,16 @@ func (db *Database) createTables() error {
|
||||
CHECK (date_fin > date_save)
|
||||
);`,
|
||||
|
||||
// ============================
|
||||
// TABLE categories
|
||||
// ============================
|
||||
`CREATE TABLE IF NOT EXISTS categories (
|
||||
id SERIAL PRIMARY KEY,
|
||||
name VARCHAR(100) NOT NULL UNIQUE,
|
||||
color VARCHAR(7) NOT NULL DEFAULT '#7c3aed',
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||||
);`,
|
||||
|
||||
// ============================
|
||||
// TABLE products
|
||||
// ============================
|
||||
|
||||
@@ -131,6 +131,47 @@ func (d *Database) NotifyLivreur(username string, commandID int, notifType, mess
|
||||
return nil
|
||||
}
|
||||
|
||||
// NotifyAllAdminCabine stocke une notification Redis pour tous les admins/cabines
|
||||
// et envoie un push aux ceux qui ont un token. Appelé dès qu'une nouvelle commande est créée.
|
||||
func (d *Database) NotifyAllAdminCabine(commandID int, clientUsername, deliveryAddr string) {
|
||||
rows, err := d.Query(
|
||||
`SELECT username, COALESCE(push_token, '') FROM users WHERE role IN ('admin','cabine')`,
|
||||
)
|
||||
if err != nil {
|
||||
log.Printf("❌ [ADMIN_NOTIF] Erreur lecture users admin/cabine: %v", err)
|
||||
return
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
msg := fmt.Sprintf("Nouvelle commande #%d de %s — %s", commandID, clientUsername, deliveryAddr)
|
||||
|
||||
notification := map[string]interface{}{
|
||||
"command_id": commandID,
|
||||
"type": "new_order",
|
||||
"message": msg,
|
||||
"created_at": time.Now().Format(time.RFC3339),
|
||||
"read": false,
|
||||
}
|
||||
notifJSON, _ := json.Marshal(notification)
|
||||
|
||||
sent := 0
|
||||
for rows.Next() {
|
||||
var username, token string
|
||||
if err := rows.Scan(&username, &token); err != nil {
|
||||
continue
|
||||
}
|
||||
notifKey := fmt.Sprintf("notifications:%s", username)
|
||||
Redis.LPush(RedisCtx, notifKey, notifJSON)
|
||||
Redis.Expire(RedisCtx, notifKey, 7*24*time.Hour)
|
||||
|
||||
if token != "" {
|
||||
go sendExpoPushWithChannel(token, "Nouvelle commande", msg, commandID, "new_order", "orders")
|
||||
sent++
|
||||
}
|
||||
}
|
||||
log.Printf("📬 [ADMIN_NOTIF] Notif Redis + push (%d tokens) pour commande #%d", sent, commandID)
|
||||
}
|
||||
|
||||
// AddDeliveryRating ajoute une note pour un livreur
|
||||
func (d *Database) AddDeliveryRating(livreurUsername string, commandID, rating int, comment string) error {
|
||||
query := `
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
// GetClientReferralBalance retourne le solde parrainage d'un client.
|
||||
func (d *Database) GetClientReferralBalance(username string) (float64, error) {
|
||||
var balance float64
|
||||
err := d.QueryRow(
|
||||
`SELECT referral_balance FROM clients WHERE username = $1`,
|
||||
username,
|
||||
).Scan(&balance)
|
||||
if err == sql.ErrNoRows {
|
||||
return 0, fmt.Errorf("client non trouvé")
|
||||
}
|
||||
return balance, err
|
||||
}
|
||||
|
||||
// CreditClientReferral ajoute un montant au solde parrainage d'un client.
|
||||
func (d *Database) CreditClientReferral(username string, amount float64) error {
|
||||
if amount <= 0 {
|
||||
return fmt.Errorf("le montant doit être positif")
|
||||
}
|
||||
res, err := d.Exec(
|
||||
`UPDATE clients SET referral_balance = referral_balance + $1 WHERE username = $2`,
|
||||
amount, username,
|
||||
)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
n, _ := res.RowsAffected()
|
||||
if n == 0 {
|
||||
return fmt.Errorf("client non trouvé")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// UseClientReferralBalance déduit un montant du solde parrainage dans une transaction.
|
||||
// Retourne une erreur si le solde est insuffisant.
|
||||
func (d *Database) UseClientReferralBalance(tx *sql.Tx, username string, amount float64) error {
|
||||
if amount <= 0 {
|
||||
return nil
|
||||
}
|
||||
var balance float64
|
||||
err := tx.QueryRow(
|
||||
`SELECT referral_balance FROM clients WHERE username = $1 FOR UPDATE`,
|
||||
username,
|
||||
).Scan(&balance)
|
||||
if err != nil {
|
||||
return fmt.Errorf("client non trouvé")
|
||||
}
|
||||
if balance < amount {
|
||||
return fmt.Errorf("solde parrainage insuffisant (disponible: %.2f€)", balance)
|
||||
}
|
||||
_, err = tx.Exec(
|
||||
`UPDATE clients SET referral_balance = referral_balance - $1 WHERE username = $2`,
|
||||
amount, username,
|
||||
)
|
||||
return err
|
||||
}
|
||||
@@ -0,0 +1,285 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
// DaySchedule représente les horaires de livraison pour un jour de la semaine
|
||||
type DaySchedule struct {
|
||||
Enabled bool `json:"enabled"`
|
||||
OpenTime string `json:"open_time"` // ex: "09:00"
|
||||
CloseTime string `json:"close_time"` // ex: "20:00"
|
||||
}
|
||||
|
||||
// DeliverySchedule représente les horaires de livraison pour chaque jour
|
||||
type DeliverySchedule struct {
|
||||
Monday DaySchedule `json:"monday"`
|
||||
Tuesday DaySchedule `json:"tuesday"`
|
||||
Wednesday DaySchedule `json:"wednesday"`
|
||||
Thursday DaySchedule `json:"thursday"`
|
||||
Friday DaySchedule `json:"friday"`
|
||||
Saturday DaySchedule `json:"saturday"`
|
||||
Sunday DaySchedule `json:"sunday"`
|
||||
}
|
||||
|
||||
// DefaultDeliverySchedule retourne un planning de livraison par défaut (tous les jours, 9h-20h)
|
||||
func DefaultDeliverySchedule() DeliverySchedule {
|
||||
day := DaySchedule{Enabled: true, OpenTime: "09:00", CloseTime: "20:00"}
|
||||
return DeliverySchedule{
|
||||
Monday: day, Tuesday: day, Wednesday: day, Thursday: day,
|
||||
Friday: day, Saturday: day, Sunday: day,
|
||||
}
|
||||
}
|
||||
|
||||
// PostalZone représente une zone de livraison avec un minimum de commande
|
||||
type PostalZone struct {
|
||||
Name string `json:"name"`
|
||||
MinAmount float64 `json:"min_amount"`
|
||||
Codes []string `json:"codes"`
|
||||
}
|
||||
|
||||
// PointsTier représente un palier du barème de points
|
||||
// Si Max == 0, il n'y a pas de borne supérieure (illimité)
|
||||
type PointsTier struct {
|
||||
Min float64 `json:"min"`
|
||||
Max float64 `json:"max"` // 0 = illimité
|
||||
Points int `json:"points"`
|
||||
}
|
||||
|
||||
// CalcPointsFromTiers retourne le nombre de points correspondant au total selon les paliers
|
||||
func CalcPointsFromTiers(total float64, tiers []PointsTier) int {
|
||||
for _, t := range tiers {
|
||||
if total >= t.Min && (t.Max == 0 || total <= t.Max) {
|
||||
return t.Points
|
||||
}
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
// AppSettings contient les paramètres globaux de l'application
|
||||
type AppSettings struct {
|
||||
PenaltiesEnabled bool `json:"penalties_enabled"`
|
||||
ShowAmendeScore bool `json:"show_amende_score"` // afficher le score d'amendes aux clients/cabine
|
||||
PointsEnabled bool `json:"points_enabled"` // afficher/activer le système de points
|
||||
PointsCategoriesWeed []string `json:"points_categories_weed"` // catégories → pool point (weed)
|
||||
PointsCategoriesZipette []string `json:"points_categories_zipette"` // catégories → pool point_zipette
|
||||
PointsCategoriesTotal []string `json:"points_categories_total"` // catégories → pool total (point, sans séparation)
|
||||
PointsSeparated bool `json:"points_separated"` // true = weed/zipette séparés, false = tout dans point
|
||||
// Barème de points par paliers configurables
|
||||
PointsWeedTiers []PointsTier `json:"points_weed_tiers"`
|
||||
PointsZipetteTiers []PointsTier `json:"points_zipette_tiers"`
|
||||
PointsTotalTiers []PointsTier `json:"points_total_tiers"`
|
||||
ReferralEnabled bool `json:"referral_enabled"` // activer/désactiver le système de parrainage
|
||||
DeliverySchedule DeliverySchedule `json:"delivery_schedule"` // horaires de livraison par jour
|
||||
PostalZones []PostalZone `json:"postal_zones"` // zones de livraison avec minimum de commande
|
||||
}
|
||||
|
||||
// DefaultSettings retourne les paramètres par défaut
|
||||
func DefaultSettings() AppSettings {
|
||||
return AppSettings{
|
||||
PenaltiesEnabled: true,
|
||||
ShowAmendeScore: true,
|
||||
PointsEnabled: true,
|
||||
ReferralEnabled: true,
|
||||
PointsCategoriesWeed: []string{},
|
||||
PointsCategoriesZipette: []string{},
|
||||
PointsCategoriesTotal: []string{},
|
||||
PointsSeparated: true,
|
||||
PointsWeedTiers: []PointsTier{
|
||||
{Min: 30, Max: 50, Points: 1},
|
||||
{Min: 60, Max: 150, Points: 2},
|
||||
{Min: 160, Max: 300, Points: 3},
|
||||
{Min: 310, Max: 400, Points: 5},
|
||||
{Min: 401, Max: 0, Points: 10},
|
||||
},
|
||||
PointsZipetteTiers: []PointsTier{
|
||||
{Min: 30, Max: 100, Points: 1},
|
||||
{Min: 110, Max: 200, Points: 2},
|
||||
{Min: 210, Max: 0, Points: 3},
|
||||
},
|
||||
PointsTotalTiers: []PointsTier{},
|
||||
DeliverySchedule: DefaultDeliverySchedule(),
|
||||
PostalZones: []PostalZone{
|
||||
{Name: "Zone 30€", MinAmount: 30, Codes: []string{"44000", "44100", "44200", "44300"}},
|
||||
{Name: "Zone 50€", MinAmount: 50, Codes: []string{
|
||||
"44400", "44880", "44120", "44230", "44115",
|
||||
"44980", "44470", "44240", "44700", "44800", "44340", "44620", "44830",
|
||||
}},
|
||||
{Name: "Zone 100€", MinAmount: 100, Codes: []string{
|
||||
"44860", "44220", "44118", "44710", "44690", "44119",
|
||||
}},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// GetSettings récupère les paramètres depuis la DB
|
||||
func (d *Database) GetSettings() (AppSettings, error) {
|
||||
settings := DefaultSettings()
|
||||
|
||||
rows, err := d.Query(`SELECT key, value FROM app_settings`)
|
||||
if err != nil {
|
||||
return settings, fmt.Errorf("erreur lecture settings: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
for rows.Next() {
|
||||
var key, value string
|
||||
if err := rows.Scan(&key, &value); err != nil {
|
||||
continue
|
||||
}
|
||||
switch key {
|
||||
case "penalties_enabled":
|
||||
settings.PenaltiesEnabled = value == "true"
|
||||
case "show_amende_score":
|
||||
settings.ShowAmendeScore = value == "true"
|
||||
case "points_enabled":
|
||||
settings.PointsEnabled = value == "true"
|
||||
case "points_categories_weed":
|
||||
var cats []string
|
||||
if err := json.Unmarshal([]byte(value), &cats); err == nil {
|
||||
settings.PointsCategoriesWeed = cats
|
||||
}
|
||||
case "points_categories_zipette":
|
||||
var cats []string
|
||||
if err := json.Unmarshal([]byte(value), &cats); err == nil {
|
||||
settings.PointsCategoriesZipette = cats
|
||||
}
|
||||
case "points_categories_total":
|
||||
var cats []string
|
||||
if err := json.Unmarshal([]byte(value), &cats); err == nil {
|
||||
settings.PointsCategoriesTotal = cats
|
||||
}
|
||||
case "points_separated":
|
||||
settings.PointsSeparated = value == "true"
|
||||
case "points_weed_tiers":
|
||||
var tiers []PointsTier
|
||||
if err := json.Unmarshal([]byte(value), &tiers); err == nil {
|
||||
settings.PointsWeedTiers = tiers
|
||||
}
|
||||
case "points_zipette_tiers":
|
||||
var tiers []PointsTier
|
||||
if err := json.Unmarshal([]byte(value), &tiers); err == nil {
|
||||
settings.PointsZipetteTiers = tiers
|
||||
}
|
||||
case "points_total_tiers":
|
||||
var tiers []PointsTier
|
||||
if err := json.Unmarshal([]byte(value), &tiers); err == nil {
|
||||
settings.PointsTotalTiers = tiers
|
||||
}
|
||||
case "referral_enabled":
|
||||
settings.ReferralEnabled = value == "true"
|
||||
case "delivery_schedule":
|
||||
var sched DeliverySchedule
|
||||
if err := json.Unmarshal([]byte(value), &sched); err == nil {
|
||||
settings.DeliverySchedule = sched
|
||||
}
|
||||
case "postal_zones":
|
||||
var zones []PostalZone
|
||||
if err := json.Unmarshal([]byte(value), &zones); err == nil {
|
||||
settings.PostalZones = zones
|
||||
}
|
||||
}
|
||||
}
|
||||
return settings, rows.Err()
|
||||
}
|
||||
|
||||
// UpdateSettings sauvegarde les paramètres dans la DB
|
||||
func (d *Database) UpdateSettings(s AppSettings) error {
|
||||
boolStr := func(b bool) string {
|
||||
if b {
|
||||
return "true"
|
||||
}
|
||||
return "false"
|
||||
}
|
||||
if s.PointsCategoriesWeed == nil {
|
||||
s.PointsCategoriesWeed = []string{}
|
||||
}
|
||||
if s.PointsCategoriesZipette == nil {
|
||||
s.PointsCategoriesZipette = []string{}
|
||||
}
|
||||
if s.PointsCategoriesTotal == nil {
|
||||
s.PointsCategoriesTotal = []string{}
|
||||
}
|
||||
|
||||
weedJSON, err := json.Marshal(s.PointsCategoriesWeed)
|
||||
if err != nil {
|
||||
return fmt.Errorf("erreur sérialisation weed: %w", err)
|
||||
}
|
||||
zipetteJSON, err := json.Marshal(s.PointsCategoriesZipette)
|
||||
if err != nil {
|
||||
return fmt.Errorf("erreur sérialisation zipette: %w", err)
|
||||
}
|
||||
totalJSON, err := json.Marshal(s.PointsCategoriesTotal)
|
||||
if err != nil {
|
||||
return fmt.Errorf("erreur sérialisation total: %w", err)
|
||||
}
|
||||
|
||||
tx, err := d.Begin()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
|
||||
upsert := `INSERT INTO app_settings (key, value) VALUES ($1, $2)
|
||||
ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value`
|
||||
|
||||
if s.PointsWeedTiers == nil {
|
||||
s.PointsWeedTiers = []PointsTier{}
|
||||
}
|
||||
if s.PointsZipetteTiers == nil {
|
||||
s.PointsZipetteTiers = []PointsTier{}
|
||||
}
|
||||
if s.PointsTotalTiers == nil {
|
||||
s.PointsTotalTiers = []PointsTier{}
|
||||
}
|
||||
weedTiersJSON, err := json.Marshal(s.PointsWeedTiers)
|
||||
if err != nil {
|
||||
return fmt.Errorf("erreur sérialisation weed tiers: %w", err)
|
||||
}
|
||||
zipetteTiersJSON, err := json.Marshal(s.PointsZipetteTiers)
|
||||
if err != nil {
|
||||
return fmt.Errorf("erreur sérialisation zipette tiers: %w", err)
|
||||
}
|
||||
totalTiersJSON, err := json.Marshal(s.PointsTotalTiers)
|
||||
if err != nil {
|
||||
return fmt.Errorf("erreur sérialisation total tiers: %w", err)
|
||||
}
|
||||
|
||||
pairs := [][2]string{
|
||||
{"penalties_enabled", boolStr(s.PenaltiesEnabled)},
|
||||
{"show_amende_score", boolStr(s.ShowAmendeScore)},
|
||||
{"points_enabled", boolStr(s.PointsEnabled)},
|
||||
{"points_categories_weed", string(weedJSON)},
|
||||
{"points_categories_zipette", string(zipetteJSON)},
|
||||
{"points_categories_total", string(totalJSON)},
|
||||
{"points_separated", boolStr(s.PointsSeparated)},
|
||||
{"points_weed_tiers", string(weedTiersJSON)},
|
||||
{"points_zipette_tiers", string(zipetteTiersJSON)},
|
||||
{"points_total_tiers", string(totalTiersJSON)},
|
||||
{"referral_enabled", boolStr(s.ReferralEnabled)},
|
||||
}
|
||||
|
||||
schedJSON, err := json.Marshal(s.DeliverySchedule)
|
||||
if err != nil {
|
||||
return fmt.Errorf("erreur sérialisation delivery_schedule: %w", err)
|
||||
}
|
||||
pairs = append(pairs, [2]string{"delivery_schedule", string(schedJSON)})
|
||||
|
||||
if s.PostalZones == nil {
|
||||
s.PostalZones = []PostalZone{}
|
||||
}
|
||||
zonesJSON, err := json.Marshal(s.PostalZones)
|
||||
if err != nil {
|
||||
return fmt.Errorf("erreur sérialisation postal_zones: %w", err)
|
||||
}
|
||||
pairs = append(pairs, [2]string{"postal_zones", string(zonesJSON)})
|
||||
|
||||
for _, p := range pairs {
|
||||
if _, err = tx.Exec(upsert, p[0], p[1]); err != nil {
|
||||
return fmt.Errorf("erreur upsert %s: %w", p[0], err)
|
||||
}
|
||||
}
|
||||
|
||||
return tx.Commit()
|
||||
}
|
||||
Reference in New Issue
Block a user