-
Notifications
You must be signed in to change notification settings - Fork 0
/
billing.go
169 lines (146 loc) · 5.72 KB
/
billing.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
package billing
import (
"context"
"github.com/gazebo-web/cloudsim/pkg/simulations"
"github.com/gazebo-web/fuel-server/bundles/users"
"github.com/gazebo-web/gz-go/v7"
apiCredits "gitlab.com/ignitionrobotics/billing/credits/pkg/api"
credits "gitlab.com/ignitionrobotics/billing/credits/pkg/client"
apiPayments "gitlab.com/ignitionrobotics/billing/payments/pkg/api"
payments "gitlab.com/ignitionrobotics/billing/payments/pkg/client"
"net/url"
"time"
)
// CreateSessionRequest is used to create a new payment session.
type CreateSessionRequest struct {
// SuccessURL is the url where to redirect users after a payment succeeds.
SuccessURL string `json:"success_url"`
// CancelURL is the url where to redirect users after a payment fails.
CancelURL string `json:"cancel_url"`
// Handle is the username of the user that is starting the payment session.
Handle string `json:"-"`
}
// CreateSessionResponse is the response from calling Service.CreateSession.
type CreateSessionResponse apiPayments.CreateSessionResponse
// GetBalanceResponse is the response from calling Service.GetBalance.
type GetBalanceResponse apiCredits.GetBalanceResponse
// Service holds methods to interact with different billing services.
type Service interface {
// GetBalance returns the credits balance of the given user.
GetBalance(ctx context.Context, user *users.User) (GetBalanceResponse, error)
// CreateSession creates a new payment session.
CreateSession(ctx context.Context, in CreateSessionRequest) (CreateSessionResponse, error)
// IsEnabled returns true when this service is enabled.
IsEnabled() bool
// SubtractCredits subtracts the credits from the given user for the amount of time the given simulation has been running.
SubtractCredits(ctx context.Context, user *users.User, sim simulations.Simulation) error
}
// service is a Service implementation using the payments and credits V1 API.
type service struct {
// payments holds a PaymentsV1 client implementation.
payments payments.Client
// credits holds a CreditsV1 client implementation.
credits credits.Client
// applicationName is the name of the current application that consumes billing services.
// This value keeps all application transactions in the same context.
applicationName string
// logger is used to log relevant information in different methods.
logger gz.Logger
// enabled is set to true when this service is enabled.
enabled bool
// profitMargin is the value at which costs will be multiplied to determine the selling price.
profitMargin uint
}
// SubtractCredits subtracts the credits from the given user for the amount of time the given simulation has been running.
func (s *service) SubtractCredits(ctx context.Context, user *users.User, sim simulations.Simulation) error {
cost, rate, err := sim.GetCost()
if err != nil {
return err
}
_, err = s.credits.DecreaseCredits(ctx, apiCredits.DecreaseCreditsRequest{
Transaction: apiCredits.Transaction{
Handle: *user.Username,
Amount: s.applyProfitMargin(cost),
Currency: rate.Currency,
Application: s.applicationName,
},
})
if err != nil {
return err
}
return nil
}
// IsEnabled returns true when this service is enabled.
func (s *service) IsEnabled() bool {
return s.enabled
}
// CreateSession creates a new payment session.
func (s *service) CreateSession(ctx context.Context, req CreateSessionRequest) (CreateSessionResponse, error) {
s.logger.Debug("Creating session:", req)
res, err := s.payments.CreateSession(ctx, apiPayments.CreateSessionRequest{
Service: "stripe",
SuccessURL: req.SuccessURL,
CancelURL: req.CancelURL,
Handle: req.Handle,
Application: s.applicationName,
})
if err != nil {
return CreateSessionResponse{}, err
}
return CreateSessionResponse(res), nil
}
// GetBalance returns the credits balance of the given user.
func (s *service) GetBalance(ctx context.Context, user *users.User) (GetBalanceResponse, error) {
s.logger.Debug("Getting balance for user:", *user.Username)
res, err := s.credits.GetBalance(ctx, apiCredits.GetBalanceRequest{
Handle: *user.Username,
Application: s.applicationName,
})
if err != nil {
s.logger.Debug("Failed to get balance:", err)
return GetBalanceResponse{}, err
}
return GetBalanceResponse(res), nil
}
// applyProfitMargin applies the profit margin to the given cost and returns the final price.
func (s *service) applyProfitMargin(cost uint) uint {
return cost * s.profitMargin
}
// Config is used to configure new service implementations
type Config struct {
// CreditsURL contains the URL of the Credits API.
CreditsURL string
// PaymentsURL contains the URL of the Payments API.
PaymentsURL string
// ApplicationName contains the unique name for this application. Used to track billing operations and keep them
// in the same application context.
ApplicationName string
// Timeout is the amount of time a client can wait until a timeout occurs.
Timeout time.Duration
// Enabled is set to true if the service should be enabled.
Enabled bool
// ProfitMargin measures how much profit is generated from a simulation. Defines the amount by which the costs should be
// multiplied to generate a profit.
ProfitMargin uint
}
// NewService initializes a new Service implementation using the given config.
func NewService(cfg Config, logger gz.Logger) (Service, error) {
u, err := url.Parse(cfg.PaymentsURL)
if err != nil {
return nil, err
}
p := payments.NewPaymentsClientV1(u, cfg.Timeout)
u, err = url.Parse(cfg.CreditsURL)
if err != nil {
return nil, err
}
c := credits.NewCreditsClientV1(u, cfg.Timeout)
return &service{
payments: p,
credits: c,
applicationName: cfg.ApplicationName,
logger: logger,
enabled: cfg.Enabled,
profitMargin: cfg.ProfitMargin,
}, nil
}