92 lines
2.5 KiB
Go
92 lines
2.5 KiB
Go
package db
|
|
|
|
import (
|
|
"bytes"
|
|
"encoding/json"
|
|
"fmt"
|
|
"log"
|
|
"net/http"
|
|
"time"
|
|
)
|
|
|
|
func (d *Database) NotifyClient(username string, commandID int, notifType, message string) error {
|
|
// Sauvegarder la notification dans Redis
|
|
notifKey := fmt.Sprintf("notifications:%s", username)
|
|
|
|
notification := map[string]interface{}{
|
|
"command_id": commandID,
|
|
"type": notifType,
|
|
"message": message,
|
|
"created_at": time.Now().Format(time.RFC3339),
|
|
"read": false,
|
|
}
|
|
|
|
notifJSON, _ := json.Marshal(notification)
|
|
Redis.LPush(RedisCtx, notifKey, notifJSON)
|
|
Redis.Expire(RedisCtx, notifKey, 7*24*time.Hour)
|
|
|
|
// Envoyer push notification si le client a un token enregistré
|
|
pushToken, err := d.GetClientPushToken(username)
|
|
if err == nil && pushToken != "" {
|
|
go sendExpoPush(pushToken, "Uber Stup", message, commandID, notifType)
|
|
}
|
|
|
|
log.Printf("📬 Notification envoyée à %s: %s", username, message)
|
|
return nil
|
|
}
|
|
|
|
func sendExpoPush(token, title, body string, commandID int, notifType string) {
|
|
payload := map[string]interface{}{
|
|
"to": token,
|
|
"title": title,
|
|
"body": body,
|
|
"channelId": "orders",
|
|
"data": map[string]interface{}{
|
|
"command_id": commandID,
|
|
"type": notifType,
|
|
},
|
|
"sound": "default",
|
|
}
|
|
|
|
jsonBody, err := json.Marshal(payload)
|
|
if err != nil {
|
|
log.Printf("❌ [EXPO_PUSH] Erreur marshal: %v", err)
|
|
return
|
|
}
|
|
|
|
req, err := http.NewRequest("POST", "https://exp.host/--/api/v2/push/send", bytes.NewBuffer(jsonBody))
|
|
if err != nil {
|
|
log.Printf("❌ [EXPO_PUSH] Erreur création requête: %v", err)
|
|
return
|
|
}
|
|
req.Header.Set("Content-Type", "application/json")
|
|
req.Header.Set("Accept", "application/json")
|
|
req.Header.Set("Accept-Encoding", "gzip, deflate")
|
|
|
|
client := &http.Client{Timeout: 10 * time.Second}
|
|
resp, err := client.Do(req)
|
|
if err != nil {
|
|
log.Printf("❌ [EXPO_PUSH] Erreur envoi: %v", err)
|
|
return
|
|
}
|
|
defer resp.Body.Close()
|
|
|
|
log.Printf("✅ [EXPO_PUSH] Push envoyé à %s (status: %d)", token, resp.StatusCode)
|
|
}
|
|
|
|
// AddDeliveryRating ajoute une note pour un livreur
|
|
func (d *Database) AddDeliveryRating(livreurUsername string, commandID, rating int, comment string) error {
|
|
query := `
|
|
INSERT INTO delivery_ratings (livreur_username, command_id, rating, comment, created_at)
|
|
VALUES (?, ?, ?, ?, NOW())
|
|
`
|
|
_, err := d.Exec(query, livreurUsername, commandID, rating, comment)
|
|
if err != nil {
|
|
log.Printf("⚠️ Erreur sauvegarde note livreur: %v", err)
|
|
return err
|
|
}
|
|
|
|
log.Printf("⭐ Note %d/5 ajoutée pour livreur %s (commande %d)", rating, livreurUsername, commandID)
|
|
return nil
|
|
}
|