-
Notifications
You must be signed in to change notification settings - Fork 390
/
accounts.go
242 lines (195 loc) · 7.67 KB
/
accounts.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
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
// Copyright (C) 2019 Storj Labs, Inc.
// See LICENSE for copying information.
package stripecoinpayments
import (
"context"
"errors"
"time"
"github.com/stripe/stripe-go"
"storj.io/common/uuid"
"storj.io/storj/satellite/payments"
)
// ensures that accounts implements payments.Accounts.
var _ payments.Accounts = (*accounts)(nil)
// accounts is an implementation of payments.Accounts.
//
// architecture: Service
type accounts struct {
service *Service
}
// CreditCards exposes all needed functionality to manage account credit cards.
func (accounts *accounts) CreditCards() payments.CreditCards {
return &creditCards{service: accounts.service}
}
// Invoices exposes all needed functionality to manage account invoices.
func (accounts *accounts) Invoices() payments.Invoices {
return &invoices{service: accounts.service}
}
// Setup creates a payment account for the user.
// If account is already set up it will return nil.
func (accounts *accounts) Setup(ctx context.Context, userID uuid.UUID, email string) (err error) {
defer mon.Task()(&ctx, userID, email)(&err)
_, err = accounts.service.db.Customers().GetCustomerID(ctx, userID)
if err == nil {
return nil
}
params := &stripe.CustomerParams{
Email: stripe.String(email),
}
customer, err := accounts.service.stripeClient.Customers().New(params)
if err != nil {
return Error.Wrap(err)
}
// TODO: delete customer from stripe, if db insertion fails
return Error.Wrap(accounts.service.db.Customers().Insert(ctx, userID, customer.ID))
}
// Balance returns an integer amount in cents that represents the current balance of payment account.
func (accounts *accounts) Balance(ctx context.Context, userID uuid.UUID) (_ payments.Balance, err error) {
defer mon.Task()(&ctx, userID)(&err)
customerID, err := accounts.service.db.Customers().GetCustomerID(ctx, userID)
if err != nil {
return payments.Balance{}, Error.Wrap(err)
}
c, err := accounts.service.stripeClient.Customers().Get(customerID, nil)
if err != nil {
return payments.Balance{}, Error.Wrap(err)
}
// add all active coupons amount to balance.
coupons, err := accounts.service.db.Coupons().ListByUserIDAndStatus(ctx, userID, payments.CouponActive)
if err != nil {
return payments.Balance{}, Error.Wrap(err)
}
var couponsAmount int64 = 0
for _, coupon := range coupons {
alreadyUsed, err := accounts.service.db.Coupons().TotalUsage(ctx, coupon.ID)
if err != nil {
return payments.Balance{}, Error.Wrap(err)
}
couponsAmount += coupon.Amount - alreadyUsed
}
accountBalance := payments.Balance{
FreeCredits: couponsAmount,
Coins: -c.Balance,
}
return accountBalance, nil
}
// ProjectCharges returns how much money current user will be charged for each project.
func (accounts *accounts) ProjectCharges(ctx context.Context, userID uuid.UUID, since, before time.Time) (charges []payments.ProjectCharge, err error) {
defer mon.Task()(&ctx, userID, since, before)(&err)
// to return empty slice instead of nil if there are no projects
charges = make([]payments.ProjectCharge, 0)
projects, err := accounts.service.projectsDB.GetOwn(ctx, userID)
if err != nil {
return nil, Error.Wrap(err)
}
for _, project := range projects {
usage, err := accounts.service.usageDB.GetProjectTotal(ctx, project.ID, since, before)
if err != nil {
return charges, Error.Wrap(err)
}
projectPrice := accounts.service.calculateProjectUsagePrice(usage.Egress, usage.Storage, usage.ObjectCount)
charges = append(charges, payments.ProjectCharge{
ProjectUsage: *usage,
ProjectID: project.ID,
Egress: projectPrice.Egress.IntPart(),
ObjectCount: projectPrice.Objects.IntPart(),
StorageGbHrs: projectPrice.Storage.IntPart(),
})
}
return charges, nil
}
// CheckProjectInvoicingStatus returns true if for the given project there are outstanding project records and/or usage
// which have not been applied/invoiced yet (meaning sent over to stripe).
func (accounts *accounts) CheckProjectInvoicingStatus(ctx context.Context, projectID uuid.UUID) (unpaidUsage bool, err error) {
defer mon.Task()(&ctx)(&err)
// we do not want to delete projects that have usage for the current month.
year, month, _ := accounts.service.nowFn().UTC().Date()
firstOfMonth := time.Date(year, month, 1, 0, 0, 0, 0, time.UTC)
currentUsage, err := accounts.service.usageDB.GetProjectTotal(ctx, projectID, firstOfMonth, accounts.service.nowFn())
if err != nil {
return false, err
}
if currentUsage.Storage > 0 || currentUsage.Egress > 0 || currentUsage.ObjectCount > 0 {
return true, errors.New("usage for current month exists")
}
// if usage of last month exist, make sure to look for billing records
lastMonthUsage, err := accounts.service.usageDB.GetProjectTotal(ctx, projectID, firstOfMonth.AddDate(0, -1, 0), firstOfMonth.AddDate(0, 0, -1))
if err != nil {
return false, err
}
if lastMonthUsage.Storage > 0 || lastMonthUsage.Egress > 0 || lastMonthUsage.ObjectCount > 0 {
// time passed into the check function need to be the UTC midnight dates of the first and last day of the month
err = accounts.service.db.ProjectRecords().Check(ctx, projectID, firstOfMonth.AddDate(0, -1, 0), firstOfMonth.Add(-time.Hour*24))
switch err {
case ErrProjectRecordExists:
record, err := accounts.service.db.ProjectRecords().Get(ctx, projectID, firstOfMonth.AddDate(0, -1, 0), firstOfMonth.Add(-time.Hour*24))
if err != nil {
return true, err
}
// state = 0 means unapplied and not invoiced yet.
if record.State == 0 {
return true, errors.New("unapplied project invoice record exist")
}
case nil:
return true, errors.New("usage for last month exist, but is not billed yet")
default:
return true, err
}
}
return false, nil
}
// Charges returns list of all credit card charges related to account.
func (accounts *accounts) Charges(ctx context.Context, userID uuid.UUID) (_ []payments.Charge, err error) {
defer mon.Task()(&ctx, userID)(&err)
customerID, err := accounts.service.db.Customers().GetCustomerID(ctx, userID)
if err != nil {
return nil, Error.Wrap(err)
}
params := &stripe.ChargeListParams{
Customer: stripe.String(customerID),
}
params.Filters.AddFilter("limit", "", "100")
iter := accounts.service.stripeClient.Charges().List(params)
var charges []payments.Charge
for iter.Next() {
charge := iter.Charge()
// ignore all non credit card charges
if charge.PaymentMethodDetails.Type != stripe.ChargePaymentMethodDetailsTypeCard {
continue
}
if charge.PaymentMethodDetails.Card == nil {
continue
}
charges = append(charges, payments.Charge{
ID: charge.ID,
Amount: charge.Amount,
CardInfo: payments.CardInfo{
ID: charge.PaymentMethod,
Brand: string(charge.PaymentMethodDetails.Card.Brand),
LastFour: charge.PaymentMethodDetails.Card.Last4,
},
CreatedAt: time.Unix(charge.Created, 0).UTC(),
})
}
if err = iter.Err(); err != nil {
return nil, Error.Wrap(err)
}
return charges, nil
}
// StorjTokens exposes all storj token related functionality.
func (accounts *accounts) StorjTokens() payments.StorjTokens {
return &storjTokens{service: accounts.service}
}
// Coupons exposes all needed functionality to manage coupons.
func (accounts *accounts) Coupons() payments.Coupons {
return &coupons{service: accounts.service}
}
// PaywallEnabled returns a true if a credit card or account
// balance is required to create projects.
func (accounts *accounts) PaywallEnabled(userID uuid.UUID) bool {
return BytesAreWithinProportion(userID, accounts.service.PaywallProportion)
}
// BytesAreWithinProportion returns true if first byte is less than the normalized proportion [0..1].
func BytesAreWithinProportion(uuidBytes [16]byte, proportion float64) bool {
return int(uuidBytes[0]) < int(proportion*256)
}