98 lines
2.5 KiB
Go
98 lines
2.5 KiB
Go
package repository
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
|
|
"apskel-pos-be/internal/entities"
|
|
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
type CustomerPointsRepository interface {
|
|
GetCustomerTotalPoints(ctx context.Context, customerID string) (int64, error)
|
|
GetCustomerTotalTokens(ctx context.Context, customerID string) (int64, error)
|
|
GetCustomerPointsHistory(ctx context.Context, customerID string, limit int) ([]entities.CustomerPoints, error)
|
|
GetCustomerTokensHistory(ctx context.Context, customerID string, limit int) ([]entities.CustomerTokens, error)
|
|
}
|
|
|
|
type customerPointsRepository struct {
|
|
db *gorm.DB
|
|
}
|
|
|
|
func NewCustomerPointsRepository(db *gorm.DB) CustomerPointsRepository {
|
|
return &customerPointsRepository{
|
|
db: db,
|
|
}
|
|
}
|
|
|
|
func (r *customerPointsRepository) GetCustomerTotalPoints(ctx context.Context, customerID string) (int64, error) {
|
|
var totalPoints int64
|
|
|
|
err := r.db.WithContext(ctx).
|
|
Model(&entities.CustomerPoints{}).
|
|
Where("customer_id = ?", customerID).
|
|
Select("COALESCE(SUM(balance), 0)").
|
|
Scan(&totalPoints).Error
|
|
|
|
if err != nil {
|
|
return 0, fmt.Errorf("failed to get customer total points: %w", err)
|
|
}
|
|
|
|
return totalPoints, nil
|
|
}
|
|
|
|
func (r *customerPointsRepository) GetCustomerTotalTokens(ctx context.Context, customerID string) (int64, error) {
|
|
var totalTokens int64
|
|
|
|
err := r.db.WithContext(ctx).
|
|
Model(&entities.CustomerTokens{}).
|
|
Where("customer_id = ?", customerID).
|
|
Select("COALESCE(SUM(balance), 0)").
|
|
Scan(&totalTokens).Error
|
|
|
|
if err != nil {
|
|
return 0, fmt.Errorf("failed to get customer total tokens: %w", err)
|
|
}
|
|
|
|
return totalTokens, nil
|
|
}
|
|
|
|
func (r *customerPointsRepository) GetCustomerPointsHistory(ctx context.Context, customerID string, limit int) ([]entities.CustomerPoints, error) {
|
|
var pointsHistory []entities.CustomerPoints
|
|
|
|
query := r.db.WithContext(ctx).
|
|
Where("customer_id = ?", customerID).
|
|
Order("created_at DESC")
|
|
|
|
if limit > 0 {
|
|
query = query.Limit(limit)
|
|
}
|
|
|
|
err := query.Find(&pointsHistory).Error
|
|
if err != nil {
|
|
return nil, fmt.Errorf("failed to get customer points history: %w", err)
|
|
}
|
|
|
|
return pointsHistory, nil
|
|
}
|
|
|
|
func (r *customerPointsRepository) GetCustomerTokensHistory(ctx context.Context, customerID string, limit int) ([]entities.CustomerTokens, error) {
|
|
var tokensHistory []entities.CustomerTokens
|
|
|
|
query := r.db.WithContext(ctx).
|
|
Where("customer_id = ?", customerID).
|
|
Order("created_at DESC")
|
|
|
|
if limit > 0 {
|
|
query = query.Limit(limit)
|
|
}
|
|
|
|
err := query.Find(&tokensHistory).Error
|
|
if err != nil {
|
|
return nil, fmt.Errorf("failed to get customer tokens history: %w", err)
|
|
}
|
|
|
|
return tokensHistory, nil
|
|
}
|