/
service.go
1324 lines (1131 loc) · 42.9 KB
/
service.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
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (C) 2019 Storj Labs, Inc.
// See LICENSE for copying information.
package stripe
import (
"context"
"encoding/json"
"errors"
"fmt"
"math"
"sort"
"strconv"
"strings"
"sync"
"time"
"github.com/shopspring/decimal"
"github.com/spacemonkeygo/monkit/v3"
"github.com/stripe/stripe-go/v75"
"github.com/zeebo/errs"
"go.uber.org/zap"
"storj.io/common/currency"
"storj.io/common/sync2"
"storj.io/common/uuid"
"storj.io/storj/satellite/accounting"
"storj.io/storj/satellite/analytics"
"storj.io/storj/satellite/console"
"storj.io/storj/satellite/payments"
"storj.io/storj/satellite/payments/billing"
"storj.io/storj/satellite/payments/storjscan"
)
var (
// Error defines stripecoinpayments service error.
Error = errs.Class("stripecoinpayments service")
mon = monkit.Package()
)
// hoursPerMonth is the number of months in a billing month. For the purpose of billing, the billing month is always 30 days.
const hoursPerMonth = 24 * 30
// Config stores needed information for payment service initialization.
type Config struct {
StripeSecretKey string `help:"stripe API secret key" default:""`
StripePublicKey string `help:"stripe API public key" default:""`
StripeFreeTierCouponID string `help:"stripe free tier coupon ID" default:""`
AutoAdvance bool `help:"toggle autoadvance feature for invoice creation" default:"false"`
ListingLimit int `help:"sets the maximum amount of items before we start paging on requests" default:"100" hidden:"true"`
SkipEmptyInvoices bool `help:"if set, skips the creation of empty invoices for customers with zero usage for the billing period" default:"true"`
MaxParallelCalls int `help:"the maximum number of concurrent Stripe API calls in invoicing methods" default:"10"`
RemoveExpiredCredit bool `help:"whether to remove expired package credit or not" default:"true"`
Retries RetryConfig
}
// Service is an implementation for payment service via Stripe and Coinpayments.
//
// architecture: Service
type Service struct {
log *zap.Logger
db DB
walletsDB storjscan.WalletsDB
billingDB billing.TransactionsDB
projectsDB console.Projects
usersDB console.Users
usageDB accounting.ProjectAccounting
stripeClient Client
analytics *analytics.Service
usagePrices payments.ProjectUsagePriceModel
usagePriceOverrides map[string]payments.ProjectUsagePriceModel
packagePlans map[string]payments.PackagePlan
partnerNames []string
// BonusRate amount of percents
BonusRate int64
// Coupon Values
StripeFreeTierCouponID string
// Stripe Extended Features
AutoAdvance bool
listingLimit int
skipEmptyInvoices bool
maxParallelCalls int
removeExpiredCredit bool
nowFn func() time.Time
}
// NewService creates a Service instance.
func NewService(log *zap.Logger, stripeClient Client, config Config, db DB, walletsDB storjscan.WalletsDB, billingDB billing.TransactionsDB, projectsDB console.Projects, usersDB console.Users, usageDB accounting.ProjectAccounting, usagePrices payments.ProjectUsagePriceModel, usagePriceOverrides map[string]payments.ProjectUsagePriceModel, packagePlans map[string]payments.PackagePlan, bonusRate int64, analyticsService *analytics.Service) (*Service, error) {
var partners []string
for partner := range usagePriceOverrides {
partners = append(partners, partner)
}
return &Service{
log: log,
db: db,
walletsDB: walletsDB,
billingDB: billingDB,
projectsDB: projectsDB,
usersDB: usersDB,
usageDB: usageDB,
stripeClient: stripeClient,
analytics: analyticsService,
usagePrices: usagePrices,
usagePriceOverrides: usagePriceOverrides,
packagePlans: packagePlans,
partnerNames: partners,
BonusRate: bonusRate,
StripeFreeTierCouponID: config.StripeFreeTierCouponID,
AutoAdvance: config.AutoAdvance,
listingLimit: config.ListingLimit,
skipEmptyInvoices: config.SkipEmptyInvoices,
maxParallelCalls: config.MaxParallelCalls,
removeExpiredCredit: config.RemoveExpiredCredit,
nowFn: time.Now,
}, nil
}
// Accounts exposes all needed functionality to manage payment accounts.
func (service *Service) Accounts() payments.Accounts {
return &accounts{service: service}
}
// PrepareInvoiceProjectRecords iterates through all projects and creates invoice records if none exist.
func (service *Service) PrepareInvoiceProjectRecords(ctx context.Context, period time.Time) (err error) {
defer mon.Task()(&ctx)(&err)
now := service.nowFn().UTC()
utc := period.UTC()
start := time.Date(utc.Year(), utc.Month(), 1, 0, 0, 0, 0, time.UTC)
end := time.Date(utc.Year(), utc.Month()+1, 1, 0, 0, 0, 0, time.UTC)
if end.After(now) {
return Error.New("allowed for past periods only")
}
var numberOfCustomers, numberOfRecords int
customersPage := CustomersPage{
Next: true,
}
for customersPage.Next {
if err = ctx.Err(); err != nil {
return Error.Wrap(err)
}
customersPage, err = service.db.Customers().List(ctx, customersPage.Cursor, service.listingLimit, end)
if err != nil {
return Error.Wrap(err)
}
numberOfCustomers += len(customersPage.Customers)
records, err := service.processCustomers(ctx, customersPage.Customers, start, end)
if err != nil {
return Error.Wrap(err)
}
numberOfRecords += records
}
service.log.Info("Number of processed entries.", zap.Int("Customers", numberOfCustomers), zap.Int("Projects", numberOfRecords))
return nil
}
func (service *Service) processCustomers(ctx context.Context, customers []Customer, start, end time.Time) (int, error) {
var allRecords []CreateProjectRecord
for _, customer := range customers {
if inactive, err := service.isUserInactive(ctx, customer.UserID); err != nil {
return 0, err
} else if inactive {
continue
}
projects, err := service.projectsDB.GetOwn(ctx, customer.UserID)
if err != nil {
return 0, err
}
records, err := service.createProjectRecords(ctx, customer.ID, projects, start, end)
if err != nil {
return 0, err
}
allRecords = append(allRecords, records...)
}
return len(allRecords), service.db.ProjectRecords().Create(ctx, allRecords, start, end)
}
// createProjectRecords creates invoice project record if none exists.
func (service *Service) createProjectRecords(ctx context.Context, customerID string, projects []console.Project, start, end time.Time) (_ []CreateProjectRecord, err error) {
defer mon.Task()(&ctx)(&err)
var records []CreateProjectRecord
for _, project := range projects {
if err = ctx.Err(); err != nil {
return nil, err
}
if err = service.db.ProjectRecords().Check(ctx, project.ID, start, end); err != nil {
if errors.Is(err, ErrProjectRecordExists) {
service.log.Warn("Record for this project already exists.", zap.String("Customer ID", customerID), zap.String("Project ID", project.ID.String()))
continue
}
return nil, err
}
usage, err := service.usageDB.GetProjectTotal(ctx, project.ID, start, end)
if err != nil {
return nil, err
}
// TODO: account for usage data.
records = append(records,
CreateProjectRecord{
ProjectID: project.ID,
Storage: usage.Storage,
Egress: usage.Egress,
Segments: usage.SegmentCount,
},
)
}
return records, nil
}
// InvoiceApplyProjectRecords iterates through unapplied invoice project records and creates invoice line items
// for stripe customer.
func (service *Service) InvoiceApplyProjectRecords(ctx context.Context, period time.Time) (err error) {
defer mon.Task()(&ctx)(&err)
now := service.nowFn().UTC()
utc := period.UTC()
start := time.Date(utc.Year(), utc.Month(), 1, 0, 0, 0, 0, time.UTC)
end := time.Date(utc.Year(), utc.Month()+1, 1, 0, 0, 0, 0, time.UTC)
if end.After(now) {
return Error.New("allowed for past periods only")
}
var totalRecords int
var totalSkipped int
for {
if err = ctx.Err(); err != nil {
return Error.Wrap(err)
}
// we are always starting from offset 0 because applyProjectRecords is changing project record state to applied
recordsPage, err := service.db.ProjectRecords().ListUnapplied(ctx, uuid.UUID{}, service.listingLimit, start, end)
if err != nil {
return Error.Wrap(err)
}
totalRecords += len(recordsPage.Records)
skipped, err := service.applyProjectRecords(ctx, recordsPage.Records)
if err != nil {
return Error.Wrap(err)
}
totalSkipped += skipped
if !recordsPage.Next {
break
}
}
service.log.Info("Processed project records.",
zap.Int("Total", totalRecords),
zap.Int("Skipped", totalSkipped))
return nil
}
// InvoiceApplyTokenBalance iterates through customer storjscan wallets and creates invoice credit notes
// for stripe customers with invoices on or after the given date.
func (service *Service) InvoiceApplyTokenBalance(ctx context.Context, createdOnAfter time.Time) (err error) {
defer mon.Task()(&ctx)(&err)
// get all wallet entries
wallets, err := service.walletsDB.GetAll(ctx)
if err != nil {
return Error.New("unable to get users in the wallets table")
}
var errGrp errs.Group
for _, wallet := range wallets {
// get the stripe customer invoice balance
customerID, err := service.db.Customers().GetCustomerID(ctx, wallet.UserID)
if err != nil {
errGrp.Add(Error.New("unable to get stripe customer ID for user ID %s", wallet.UserID.String()))
continue
}
customerInvoices, err := service.getInvoices(ctx, customerID, createdOnAfter)
if err != nil {
errGrp.Add(Error.New("unable to get invoice balance for stripe customer ID %s", customerID))
continue
}
err = service.payInvoicesWithTokenBalance(ctx, customerID, wallet, customerInvoices)
if err != nil {
errGrp.Add(Error.New("unable to pay invoices for stripe customer ID %s", customerID))
continue
}
}
return errGrp.Err()
}
// InvoiceApplyCustomerTokenBalance creates invoice credit notes for the customers token payments to open invoices.
func (service *Service) InvoiceApplyCustomerTokenBalance(ctx context.Context, customerID string) (err error) {
defer mon.Task()(&ctx)(&err)
userID, err := service.db.Customers().GetUserID(ctx, customerID)
if err != nil {
return Error.New("unable to get user ID for stripe customer ID %s", customerID)
}
customerInvoices, err := service.getInvoices(ctx, customerID, time.Unix(0, 0))
if err != nil {
return Error.New("error getting invoices for stripe customer %s", customerID)
}
return service.PayInvoicesWithTokenBalance(ctx, userID, customerID, customerInvoices)
}
// getInvoices returns the stripe customer's open finalized invoices created on or after the given date.
func (service *Service) getInvoices(ctx context.Context, cusID string, createdOnAfter time.Time) (_ []stripe.Invoice, err error) {
defer mon.Task()(&ctx)(&err)
params := &stripe.InvoiceListParams{
ListParams: stripe.ListParams{Context: ctx},
Customer: stripe.String(cusID),
Status: stripe.String(string(stripe.InvoiceStatusOpen)),
}
params.Filters.AddFilter("created", "gte", strconv.FormatInt(createdOnAfter.Unix(), 10))
invoicesIterator := service.stripeClient.Invoices().List(params)
var stripeInvoices []stripe.Invoice
for invoicesIterator.Next() {
stripeInvoice := invoicesIterator.Invoice()
if stripeInvoice != nil {
stripeInvoices = append(stripeInvoices, *stripeInvoice)
}
}
if err = invoicesIterator.Err(); err != nil {
return stripeInvoices, Error.Wrap(err)
}
return stripeInvoices, nil
}
// addCreditNoteToInvoice creates a credit note for the user token payment.
func (service *Service) addCreditNoteToInvoice(ctx context.Context, invoiceID, cusID, wallet string, amount, txID int64) (_ string, err error) {
defer mon.Task()(&ctx)(&err)
var lineParams []*stripe.CreditNoteLineParams
lineParam := stripe.CreditNoteLineParams{
Description: stripe.String("Storjscan Token payment"),
Type: stripe.String("custom_line_item"),
UnitAmount: stripe.Int64(amount),
Quantity: stripe.Int64(1),
}
lineParams = append(lineParams, &lineParam)
params := &stripe.CreditNoteParams{
Params: stripe.Params{Context: ctx},
Invoice: stripe.String(invoiceID),
Lines: lineParams,
Memo: stripe.String("Storjscan Token Payment - Wallet: " + wallet),
}
params.AddMetadata("txID", strconv.FormatInt(txID, 10))
params.AddMetadata("wallet address", wallet)
creditNote, err := service.stripeClient.CreditNotes().New(params)
if err != nil {
service.log.Warn("unable to add credit note for stripe customer", zap.String("Customer ID", cusID))
return "", Error.Wrap(err)
}
return creditNote.ID, nil
}
// createTokenPaymentBillingTransaction creates a billing DB entry for the user token payment.
func (service *Service) createTokenPaymentBillingTransaction(ctx context.Context, userID uuid.UUID, invoiceID, wallet string, amount int64) (_ int64, err error) {
defer mon.Task()(&ctx)(&err)
metadata, err := json.Marshal(map[string]interface{}{
"InvoiceID": invoiceID,
"Wallet": wallet,
})
transaction := billing.Transaction{
UserID: userID,
Amount: currency.AmountFromBaseUnits(amount, currency.USDollars),
Description: "Paid Stripe Invoice",
Source: billing.StripeSource,
Status: billing.TransactionStatusPending,
Type: billing.TransactionTypeDebit,
Metadata: metadata,
Timestamp: time.Now(),
}
txIDs, err := service.billingDB.Insert(ctx, transaction)
if err != nil {
service.log.Warn("unable to add transaction to billing DB for user", zap.String("User ID", userID.String()))
return 0, Error.Wrap(err)
}
return txIDs[0], nil
}
// applyProjectRecords applies invoice intents as invoice line items to stripe customer.
func (service *Service) applyProjectRecords(ctx context.Context, records []ProjectRecord) (skipCount int, err error) {
defer mon.Task()(&ctx)(&err)
var mu sync.Mutex
var errGrp errs.Group
limiter := sync2.NewLimiter(service.maxParallelCalls)
ctx, cancel := context.WithCancel(ctx)
defer func() {
cancel()
limiter.Wait()
}()
for _, record := range records {
if err = ctx.Err(); err != nil {
return 0, errs.Wrap(err)
}
proj, err := service.projectsDB.Get(ctx, record.ProjectID)
if err != nil {
// This should never happen, but be sure to log info to further troubleshoot before exiting.
service.log.Error("project ID for corresponding project record not found", zap.Stringer("Record ID", record.ID), zap.Stringer("Project ID", record.ProjectID))
return 0, errs.Wrap(err)
}
if inactive, err := service.isUserInactive(ctx, proj.OwnerID); err != nil {
return 0, errs.Wrap(err)
} else if inactive {
mu.Lock()
skipCount++
mu.Unlock()
continue
}
cusID, err := service.db.Customers().GetCustomerID(ctx, proj.OwnerID)
if err != nil {
if errors.Is(err, ErrNoCustomer) {
service.log.Warn("Stripe customer does not exist for project owner.", zap.Stringer("Owner ID", proj.OwnerID), zap.Stringer("Project ID", proj.ID))
continue
}
return 0, errs.Wrap(err)
}
record := record
limiter.Go(ctx, func() {
skipped, err := service.createInvoiceItems(ctx, cusID, proj.Name, record)
if err != nil {
mu.Lock()
errGrp.Add(errs.Wrap(err))
mu.Unlock()
return
}
if skipped {
mu.Lock()
skipCount++
mu.Unlock()
}
})
}
limiter.Wait()
return skipCount, errGrp.Err()
}
// createInvoiceItems creates invoice line items for stripe customer.
func (service *Service) createInvoiceItems(ctx context.Context, cusID, projName string, record ProjectRecord) (skipped bool, err error) {
defer mon.Task()(&ctx)(&err)
if err = service.db.ProjectRecords().Consume(ctx, record.ID); err != nil {
return false, err
}
if service.skipEmptyInvoices && doesProjectRecordHaveNoUsage(record) {
return true, nil
}
usages, err := service.usageDB.GetProjectTotalByPartner(ctx, record.ProjectID, service.partnerNames, record.PeriodStart, record.PeriodEnd)
if err != nil {
return false, err
}
items := service.InvoiceItemsFromProjectUsage(projName, usages)
for _, item := range items {
item.Params = stripe.Params{Context: ctx}
item.Currency = stripe.String(string(stripe.CurrencyUSD))
item.Customer = stripe.String(cusID)
item.AddMetadata("projectID", record.ProjectID.String())
_, err = service.stripeClient.InvoiceItems().New(item)
if err != nil {
return false, err
}
}
return false, nil
}
// InvoiceItemsFromProjectUsage calculates Stripe invoice item from project usage.
func (service *Service) InvoiceItemsFromProjectUsage(projName string, partnerUsages map[string]accounting.ProjectUsage) (result []*stripe.InvoiceItemParams) {
var partners []string
if len(partnerUsages) == 0 {
partners = []string{""}
partnerUsages = map[string]accounting.ProjectUsage{"": {}}
} else {
for partner := range partnerUsages {
partners = append(partners, partner)
}
sort.Strings(partners)
}
for _, partner := range partners {
priceModel := service.Accounts().GetProjectUsagePriceModel(partner)
usage := partnerUsages[partner]
usage.Egress = applyEgressDiscount(usage, priceModel)
prefix := "Project " + projName
if partner != "" {
prefix += " (" + partner + ")"
}
projectItem := &stripe.InvoiceItemParams{}
projectItem.Description = stripe.String(prefix + " - Segment Storage (MB-Month)")
projectItem.Quantity = stripe.Int64(storageMBMonthDecimal(usage.Storage).IntPart())
storagePrice, _ := priceModel.StorageMBMonthCents.Float64()
projectItem.UnitAmountDecimal = stripe.Float64(storagePrice)
result = append(result, projectItem)
projectItem = &stripe.InvoiceItemParams{}
projectItem.Description = stripe.String(prefix + " - Egress Bandwidth (MB)")
projectItem.Quantity = stripe.Int64(egressMBDecimal(usage.Egress).IntPart())
egressPrice, _ := priceModel.EgressMBCents.Float64()
projectItem.UnitAmountDecimal = stripe.Float64(egressPrice)
result = append(result, projectItem)
projectItem = &stripe.InvoiceItemParams{}
projectItem.Description = stripe.String(prefix + " - Segment Fee (Segment-Month)")
projectItem.Quantity = stripe.Int64(segmentMonthDecimal(usage.SegmentCount).IntPart())
segmentPrice, _ := priceModel.SegmentMonthCents.Float64()
projectItem.UnitAmountDecimal = stripe.Float64(segmentPrice)
result = append(result, projectItem)
}
service.log.Info("invoice items", zap.Any("result", result))
return result
}
// RemoveExpiredPackageCredit removes a user's package plan credit, or sends an analytics event, if it has expired.
// If the user has never received credit from anything other than the package, and it is expired, the remaining package
// credit is removed. If the user has received credit from another source, we send an analytics event instead of removing
// the remaining credit so someone can remove it manually. `sentEvent` indicates whether this analytics event was sent.
func (service *Service) RemoveExpiredPackageCredit(ctx context.Context, customer Customer) (sentEvent bool, err error) {
defer mon.Task()(&ctx)(&err)
// TODO: store the package expiration somewhere
if customer.PackagePlan == nil || customer.PackagePurchasedAt == nil ||
customer.PackagePurchasedAt.After(service.nowFn().AddDate(-1, -1, 0)) {
return false, nil
}
list := service.stripeClient.CustomerBalanceTransactions().List(&stripe.CustomerBalanceTransactionListParams{
Customer: stripe.String(customer.ID),
})
var balance int64
var gotBalance, foundOtherCredit bool
var tx *stripe.CustomerBalanceTransaction
for list.Next() {
tx = list.CustomerBalanceTransaction()
if !gotBalance {
// Stripe returns list ordered by most recent, so ending balance of the first item is current balance.
balance = tx.EndingBalance
gotBalance = true
// if user doesn't have credit, we're done.
if balance >= 0 {
break
}
}
// negative amount means credit
if tx.Amount < 0 {
if tx.Description != *customer.PackagePlan {
foundOtherCredit = true
}
}
}
// send analytics event to notify someone to handle removing credit if credit other than package exists.
if foundOtherCredit {
if service.analytics != nil {
service.analytics.TrackExpiredCreditNeedsRemoval(customer.UserID, customer.ID, *customer.PackagePlan)
}
return true, nil
}
// If no other credit found, we can set the balance to zero.
if balance < 0 {
_, err = service.stripeClient.CustomerBalanceTransactions().New(&stripe.CustomerBalanceTransactionParams{
Customer: stripe.String(customer.ID),
Amount: stripe.Int64(-balance),
Currency: stripe.String(string(stripe.CurrencyUSD)),
Description: stripe.String(fmt.Sprintf("%s expired", *customer.PackagePlan)),
})
if err != nil {
return false, Error.Wrap(err)
}
if service.analytics != nil {
service.analytics.TrackExpiredCreditRemoved(customer.UserID, customer.ID, *customer.PackagePlan)
}
}
err = service.Accounts().UpdatePackage(ctx, customer.UserID, nil, nil)
return false, Error.Wrap(err)
}
// ApplyFreeTierCoupons iterates through all customers in Stripe. For each customer,
// if that customer does not currently have a Stripe coupon, the free tier Stripe coupon
// is applied.
func (service *Service) ApplyFreeTierCoupons(ctx context.Context) (err error) {
defer mon.Task()(&ctx)(&err)
customers := service.db.Customers()
limiter := sync2.NewLimiter(service.maxParallelCalls)
ctx, cancel := context.WithCancel(ctx)
defer func() {
cancel()
limiter.Wait()
}()
var mu sync.Mutex
var appliedCoupons int
failedUsers := []string{}
morePages := true
var nextCursor uuid.UUID
listingLimit := 100
end := time.Now()
for morePages {
customersPage, err := customers.List(ctx, nextCursor, listingLimit, end)
if err != nil {
return err
}
morePages = customersPage.Next
nextCursor = customersPage.Cursor
for _, c := range customersPage.Customers {
cusID := c.ID
limiter.Go(ctx, func() {
if inactive, err := service.isUserInactive(ctx, c.UserID); err != nil {
mu.Lock()
failedUsers = append(failedUsers, cusID)
mu.Unlock()
return
} else if inactive {
return
}
applied, err := service.applyFreeTierCoupon(ctx, cusID)
if err != nil {
mu.Lock()
failedUsers = append(failedUsers, cusID)
mu.Unlock()
return
}
if applied {
mu.Lock()
appliedCoupons++
mu.Unlock()
}
})
}
}
limiter.Wait()
if len(failedUsers) > 0 {
service.log.Warn("Failed to get or apply free tier coupon to some customers:", zap.String("idlist", strings.Join(failedUsers, ", ")))
}
service.log.Info("Finished", zap.Int("number of coupons applied", appliedCoupons))
return nil
}
// applyFreeTierCoupon applies the free tier Stripe coupon to a customer if it doesn't already have a coupon.
func (service *Service) applyFreeTierCoupon(ctx context.Context, cusID string) (applied bool, err error) {
defer mon.Task()(&ctx)(&err)
params := &stripe.CustomerParams{Params: stripe.Params{Context: ctx}}
stripeCust, err := service.stripeClient.Customers().Get(cusID, params)
if err != nil {
service.log.Error("Failed to get customer", zap.Error(err))
return false, err
}
// if customer has a coupon, don't apply the free tier coupon
if stripeCust.Discount != nil && stripeCust.Discount.Coupon != nil {
return false, nil
}
params = &stripe.CustomerParams{
Params: stripe.Params{Context: ctx},
Coupon: stripe.String(service.StripeFreeTierCouponID),
}
_, err = service.stripeClient.Customers().Update(cusID, params)
if err != nil {
service.log.Error("Failed to update customer with free tier coupon", zap.Error(err))
return false, err
}
return true, nil
}
// CreateInvoices lists through all customers, removes expired credit if applicable, and creates invoices.
func (service *Service) CreateInvoices(ctx context.Context, period time.Time) (err error) {
defer mon.Task()(&ctx)(&err)
now := service.nowFn().UTC()
utc := period.UTC()
start := time.Date(utc.Year(), utc.Month(), 1, 0, 0, 0, 0, time.UTC)
end := time.Date(utc.Year(), utc.Month()+1, 1, 0, 0, 0, 0, time.UTC)
if end.After(now) {
return Error.New("allowed for past periods only")
}
var nextCursor uuid.UUID
var totalDraft, totalScheduled int
for {
cusPage, err := service.db.Customers().List(ctx, nextCursor, service.listingLimit, end)
if err != nil {
return Error.Wrap(err)
}
if service.removeExpiredCredit {
for _, c := range cusPage.Customers {
if c.PackagePlan != nil {
if _, err := service.RemoveExpiredPackageCredit(ctx, c); err != nil {
return Error.Wrap(err)
}
}
}
}
scheduled, draft, err := service.createInvoices(ctx, cusPage.Customers, start)
if err != nil {
return Error.Wrap(err)
}
totalScheduled += scheduled
totalDraft += draft
if !cusPage.Next {
break
}
nextCursor = cusPage.Cursor
}
service.log.Info("Number of created invoices", zap.Int("Draft", totalDraft), zap.Int("Scheduled", totalScheduled))
return nil
}
// createInvoice creates invoice for Stripe customer.
func (service *Service) createInvoice(ctx context.Context, cusID string, period time.Time) (stripeInvoice *stripe.Invoice, err error) {
defer mon.Task()(&ctx)(&err)
itemsIter := service.stripeClient.InvoiceItems().List(&stripe.InvoiceItemListParams{
Customer: &cusID,
Pending: stripe.Bool(true),
ListParams: stripe.ListParams{
Context: ctx,
Limit: stripe.Int64(1),
},
})
hasItems := itemsIter.Next()
if err = itemsIter.Err(); err != nil {
return nil, err
}
if !hasItems {
return nil, nil
}
description := fmt.Sprintf("Storj DCS Cloud Storage for %s %d", period.Month(), period.Year())
stripeInvoice, err = service.stripeClient.Invoices().New(
&stripe.InvoiceParams{
Params: stripe.Params{Context: ctx},
Customer: stripe.String(cusID),
AutoAdvance: stripe.Bool(service.AutoAdvance),
Description: stripe.String(description),
PendingInvoiceItemsBehavior: stripe.String("include"),
},
)
if err != nil {
return nil, err
}
// auto advance the invoice if nothing is due from the customer
if !stripeInvoice.AutoAdvance && stripeInvoice.AmountDue == 0 {
params := &stripe.InvoiceParams{
Params: stripe.Params{Context: ctx},
AutoAdvance: stripe.Bool(true),
}
stripeInvoice, err = service.stripeClient.Invoices().Update(stripeInvoice.ID, params)
if err != nil {
return nil, err
}
}
return stripeInvoice, nil
}
// createInvoices creates invoices for Stripe customers.
func (service *Service) createInvoices(ctx context.Context, customers []Customer, period time.Time) (scheduled, draft int, err error) {
defer mon.Task()(&ctx)(&err)
limiter := sync2.NewLimiter(service.maxParallelCalls)
var errGrp errs.Group
var mu sync.Mutex
for _, cus := range customers {
cusID := cus.ID
limiter.Go(ctx, func() {
if inactive, err := service.isUserInactive(ctx, cus.UserID); err != nil {
mu.Lock()
errGrp.Add(err)
mu.Unlock()
return
} else if inactive {
return
}
inv, err := service.createInvoice(ctx, cusID, period)
if err != nil {
mu.Lock()
errGrp.Add(err)
mu.Unlock()
return
}
if inv != nil {
mu.Lock()
if inv.AutoAdvance {
scheduled++
} else {
draft++
}
mu.Unlock()
}
})
}
limiter.Wait()
return scheduled, draft, errGrp.Err()
}
// SetInvoiceStatus will set all open invoices within the specified date range to the requested status.
func (service *Service) SetInvoiceStatus(ctx context.Context, startPeriod, endPeriod time.Time, status string, dryRun bool) (err error) {
defer mon.Task()(&ctx)(&err)
switch stripe.InvoiceStatus(strings.ToLower(status)) {
case stripe.InvoiceStatusUncollectible:
err = service.iterateInvoicesInTimeRange(ctx, startPeriod, endPeriod, func(invoiceId string) error {
service.log.Info("updating invoice status to uncollectible", zap.String("invoiceId", invoiceId))
if !dryRun {
_, err := service.stripeClient.Invoices().MarkUncollectible(invoiceId, &stripe.InvoiceMarkUncollectibleParams{})
if err != nil {
return Error.Wrap(err)
}
}
return nil
})
case stripe.InvoiceStatusVoid:
err = service.iterateInvoicesInTimeRange(ctx, startPeriod, endPeriod, func(invoiceId string) error {
service.log.Info("updating invoice status to void", zap.String("invoiceId", invoiceId))
if !dryRun {
_, err = service.stripeClient.Invoices().VoidInvoice(invoiceId, &stripe.InvoiceVoidInvoiceParams{})
if err != nil {
return Error.Wrap(err)
}
}
return nil
})
case stripe.InvoiceStatusPaid:
err = service.iterateInvoicesInTimeRange(ctx, startPeriod, endPeriod, func(invoiceId string) error {
service.log.Info("updating invoice status to paid", zap.String("invoiceId", invoiceId))
if !dryRun {
payParams := &stripe.InvoicePayParams{
Params: stripe.Params{Context: ctx},
PaidOutOfBand: stripe.Bool(true),
}
_, err = service.stripeClient.Invoices().Pay(invoiceId, payParams)
if err != nil {
return Error.Wrap(err)
}
}
return nil
})
default:
// unknown
service.log.Error("Unknown status provided. Valid options are uncollectible, void, or paid.", zap.String("status", status))
return Error.New("unknown status provided")
}
return err
}
func (service *Service) iterateInvoicesInTimeRange(ctx context.Context, startPeriod, endPeriod time.Time, updateStatus func(string) error) (err error) {
defer mon.Task()(&ctx)(&err)
params := &stripe.InvoiceListParams{
ListParams: stripe.ListParams{
Context: ctx,
Limit: stripe.Int64(100),
},
Status: stripe.String("open"),
CreatedRange: &stripe.RangeQueryParams{
GreaterThanOrEqual: startPeriod.Unix(),
LesserThanOrEqual: endPeriod.Unix(),
},
}
numInvoices := 0
invoicesIterator := service.stripeClient.Invoices().List(params)
for invoicesIterator.Next() {
numInvoices++
stripeInvoice := invoicesIterator.Invoice()
err := updateStatus(stripeInvoice.ID)
if err != nil {
return Error.Wrap(err)
}
}
service.log.Info("found " + strconv.Itoa(numInvoices) + " total invoices")
return Error.Wrap(invoicesIterator.Err())
}
// CreateBalanceInvoiceItems will find users with a stripe balance, create an invoice
// item with the charges due, and zero out the stripe balance.
func (service *Service) CreateBalanceInvoiceItems(ctx context.Context) (err error) {
defer mon.Task()(&ctx)(&err)
custListParams := &stripe.CustomerListParams{
ListParams: stripe.ListParams{
Context: ctx,
Limit: stripe.Int64(100),
},
}
var errGrp errs.Group
itr := service.stripeClient.Customers().List(custListParams)
for itr.Next() {
if itr.Customer().Balance <= 0 {
continue
}
userID, err := service.db.Customers().GetUserID(ctx, itr.Customer().ID)
if err != nil {
return err
}
if inactive, err := service.isUserInactive(ctx, userID); err != nil {
return err
} else if inactive {
continue
}
service.log.Info("Creating invoice item for customer prior balance", zap.String("CustomerID", itr.Customer().ID))
itemParams := &stripe.InvoiceItemParams{
Params: stripe.Params{
Context: ctx,
},
Currency: stripe.String(string(stripe.CurrencyUSD)),
Customer: stripe.String(itr.Customer().ID),
Description: stripe.String("Prior Stripe Customer Balance"),
Quantity: stripe.Int64(1),
UnitAmount: stripe.Int64(itr.Customer().Balance),
}
invoiceItem, err := service.stripeClient.InvoiceItems().New(itemParams)
if err != nil {
service.log.Error("Failed to add invoice item for customer prior balance", zap.Error(err))
errGrp.Add(err)
continue
}