Files
projet_gestion_commande/backend/gestion/db/db_payments.go
T
2026-03-28 17:00:00 +01:00

86 lines
2.7 KiB
Go

package db
import (
"fmt"
"gestion/models"
"log"
"gorm.io/gorm"
)
func (d *Database) CreateCryptoPayment(commandID int, nowPaymentID, status, priceCurrency, payCurrency, payAddress string, priceAmount, payAmount float64) (*models.CryptoPayment, error) {
p := models.CryptoPayment{
CommandID: commandID,
NowPaymentID: nowPaymentID,
Status: status,
PriceAmount: priceAmount,
PriceCurrency: priceCurrency,
PayCurrency: payCurrency,
PayAddress: payAddress,
PayAmount: payAmount,
}
if err := d.GDB.Create(&p).Error; err != nil {
return nil, fmt.Errorf("CreateCryptoPayment: %w", err)
}
return &p, nil
}
func (d *Database) GetCryptoPaymentByCommandID(commandID int) (*models.CryptoPayment, error) {
var p models.CryptoPayment
err := d.GDB.Where("command_id = ?", commandID).Order("created_at DESC").First(&p).Error
if err != nil {
if isNotFound(err) {
return nil, nil
}
return nil, err
}
return &p, nil
}
func (d *Database) GetCryptoPaymentByNowPaymentID(nowPaymentID string) (*models.CryptoPayment, error) {
var p models.CryptoPayment
err := d.GDB.Where("nowpayment_id = ?", nowPaymentID).First(&p).Error
if err != nil {
if isNotFound(err) {
return nil, nil
}
return nil, err
}
return &p, nil
}
func (d *Database) GetPendingCryptoPayments() ([]models.CryptoPayment, error) {
var payments []models.CryptoPayment
err := d.GDB.Where("status NOT IN ?", []string{"finished", "failed", "expired", "refunded"}).
Order("created_at ASC").Find(&payments).Error
return payments, err
}
func (d *Database) UpdateCryptoPaymentStatus(id int, status string, payAmount float64) error {
return d.GDB.Model(&models.CryptoPayment{}).Where("id = ?", id).
Updates(map[string]any{"status": status, "pay_amount": payAmount}).Error
}
func (d *Database) ActivateCryptoCommand(commandID int) error {
return d.GDB.Exec(`UPDATE commandes SET status = 'pending', updated_at = NOW() WHERE id = ? AND status = 'pending_payment'`, commandID).Error
}
func (d *Database) CancelCryptoCommand(commandID int) error {
return d.GDB.Transaction(func(tx *gorm.DB) error {
type item struct {
ProductID int
Quantite float64
}
var items []item
if err := tx.Raw(`SELECT product_id, quantite FROM command_items WHERE command_id = ?`, commandID).Scan(&items).Error; err != nil {
return err
}
for _, it := range items {
if err := tx.Exec(`UPDATE products SET stock = stock + ? WHERE id = ?`, it.Quantite, it.ProductID).Error; err != nil {
log.Printf("[CANCEL CRYPTO] erreur restauration stock produit %d: %v", it.ProductID, err)
}
}
return tx.Exec(`UPDATE commandes SET status = 'cancelled', updated_at = NOW() WHERE id = ? AND status = 'pending_payment'`, commandID).Error
})
}