easyai-ai-gateway/apps/api/internal/runner/wallet.go

39 lines
1004 B
Go

package runner
import (
"context"
"fmt"
"strings"
"github.com/easyai/easyai-ai-gateway/apps/api/internal/auth"
"github.com/easyai/easyai-ai-gateway/apps/api/internal/store"
)
func (s *Service) ensureWalletBalance(ctx context.Context, user *auth.User, billings []any) error {
amounts := map[string]float64{}
for _, raw := range billings {
line, _ := raw.(map[string]any)
if line == nil {
continue
}
currency := strings.TrimSpace(stringFromAny(line["currency"]))
if currency == "" {
currency = "resource"
}
amounts[currency] = roundPrice(amounts[currency] + floatFromAny(line["amount"]))
}
for currency, amount := range amounts {
if amount <= 0 {
continue
}
availability, err := s.store.WalletAvailability(ctx, user, currency, amount)
if err != nil {
return err
}
if !availability.Enough {
return fmt.Errorf("%w: required %.6f %s, available %.6f", store.ErrInsufficientWalletBalance, amount, currency, availability.AvailableAmount)
}
}
return nil
}