36 lines
754 B
Go
36 lines
754 B
Go
package cart
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
type Summary struct {
|
|
ID int64
|
|
TotalItems int64
|
|
}
|
|
|
|
type Service struct {
|
|
db *gorm.DB
|
|
prefix string
|
|
}
|
|
|
|
func NewService(db *gorm.DB, prefix string) *Service {
|
|
return &Service{db: db, prefix: prefix}
|
|
}
|
|
|
|
func (s *Service) SummaryByID(ctx context.Context, cartID int64) (*Summary, error) {
|
|
var summary Summary
|
|
query := fmt.Sprintf("SELECT id_cart AS id, COALESCE(SUM(quantity), 0) AS total_items FROM %scart_product WHERE id_cart = ? GROUP BY id_cart", s.prefix)
|
|
result := s.db.WithContext(ctx).Raw(query, cartID).Scan(&summary)
|
|
if result.Error != nil {
|
|
return nil, result.Error
|
|
}
|
|
if result.RowsAffected == 0 {
|
|
return &Summary{ID: cartID}, nil
|
|
}
|
|
return &summary, nil
|
|
}
|