2019-10-10 18:12:23 +01:00
// Copyright (C) 2019 Storj Labs, Inc.
// See LICENSE for copying information.
package stripecoinpayments
import (
2019-10-23 13:04:54 +01:00
"context"
2022-05-10 20:19:53 +01:00
"encoding/json"
2020-07-14 14:04:38 +01:00
"errors"
2019-11-05 13:16:02 +00:00
"fmt"
2020-05-28 12:31:02 +01:00
"strconv"
2021-07-30 23:11:36 +01:00
"strings"
2019-11-15 14:59:39 +00:00
"sync"
2019-10-23 13:04:54 +01:00
"time"
2020-01-28 23:36:54 +00:00
"github.com/shopspring/decimal"
2019-11-08 20:40:39 +00:00
"github.com/spacemonkeygo/monkit/v3"
2021-06-22 01:09:56 +01:00
"github.com/stripe/stripe-go/v72"
2019-10-10 18:12:23 +01:00
"github.com/zeebo/errs"
2019-10-23 13:04:54 +01:00
"go.uber.org/zap"
2019-10-15 12:23:54 +01:00
2022-09-06 13:43:09 +01:00
"storj.io/common/currency"
2022-05-10 20:19:53 +01:00
"storj.io/common/uuid"
2019-11-15 14:27:44 +00:00
"storj.io/storj/satellite/accounting"
2019-11-05 13:16:02 +00:00
"storj.io/storj/satellite/console"
2019-10-15 12:23:54 +01:00
"storj.io/storj/satellite/payments"
2022-05-10 20:19:53 +01:00
"storj.io/storj/satellite/payments/billing"
2019-10-17 15:04:50 +01:00
"storj.io/storj/satellite/payments/coinpayments"
2022-05-10 20:19:53 +01:00
"storj.io/storj/satellite/payments/storjscan"
2019-10-10 18:12:23 +01:00
)
2019-11-04 10:54:25 +00:00
var (
// Error defines stripecoinpayments service error.
2021-04-28 09:06:17 +01:00
Error = errs . Class ( "stripecoinpayments service" )
2019-10-10 18:12:23 +01:00
2019-11-04 10:54:25 +00:00
mon = monkit . Package ( )
)
2019-10-10 18:12:23 +01:00
2020-05-26 12:00:14 +01:00
// 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
2019-10-17 15:04:50 +01:00
// Config stores needed information for payment service initialization.
2019-10-15 12:23:54 +01:00
type Config struct {
2019-10-29 16:04:34 +00:00
StripeSecretKey string ` help:"stripe API secret key" default:"" `
2019-11-18 11:38:43 +00:00
StripePublicKey string ` help:"stripe API public key" default:"" `
2021-05-10 18:12:05 +01:00
StripeFreeTierCouponID string ` help:"stripe free tier coupon ID" default:"" `
2019-10-29 16:04:34 +00:00
CoinpaymentsPublicKey string ` help:"coinpayments API public key" default:"" `
2019-10-31 16:56:54 +00:00
CoinpaymentsPrivateKey string ` help:"coinpayments API private key key" default:"" `
testplanet/satellite: reduce the number of places default values need to be configured
Satellites set their configuration values to default values using
cfgstruct, however, it turns out our tests don't test these values
at all! Instead, they have a completely separate definition system
that is easy to forget about.
As is to be expected, these values have drifted, and it appears
in a few cases test planet is testing unreasonable values that we
won't see in production, or perhaps worse, features enabled in
production were missed and weren't enabled in testplanet.
This change makes it so all values are configured the same,
systematic way, so it's easy to see when test values are different
than dev values or release values, and it's less hard to forget
to enable features in testplanet.
In terms of reviewing, this change should be actually fairly
easy to review, considering private/testplanet/satellite.go keeps
the current config system and the new one and confirms that they
result in identical configurations, so you can be certain that
nothing was missed and the config is all correct.
You can also check the config lock to see what actual config
values changed.
Change-Id: I6715d0794887f577e21742afcf56fd2b9d12170e
2021-05-31 22:15:00 +01:00
TransactionUpdateInterval time . Duration ` help:"amount of time we wait before running next transaction update loop" default:"2m" testDefault:"$TESTINTERVAL" `
AccountBalanceUpdateInterval time . Duration ` help:"amount of time we wait before running next account balance update loop" default:"2m" testDefault:"$TESTINTERVAL" `
ConversionRatesCycleInterval time . Duration ` help:"amount of time we wait before running next conversion rates update loop" default:"10m" testDefault:"$TESTINTERVAL" `
2020-03-13 16:07:39 +00:00
AutoAdvance bool ` help:"toogle autoadvance feature for invoice creation" default:"false" `
2020-05-19 08:42:07 +01:00
ListingLimit int ` help:"sets the maximum amount of items before we start paging on requests" default:"100" hidden:"true" `
2019-10-10 18:12:23 +01:00
}
2019-10-15 12:23:54 +01:00
// Service is an implementation for payment service via Stripe and Coinpayments.
2019-11-04 12:30:07 +00:00
//
// architecture: Service
2019-10-15 12:23:54 +01:00
type Service struct {
2022-05-10 20:19:53 +01:00
log * zap . Logger
db DB
walletsDB storjscan . WalletsDB
billingDB billing . TransactionsDB
2019-11-15 14:59:39 +00:00
projectsDB console . Projects
usageDB accounting . ProjectAccounting
2020-05-15 09:46:41 +01:00
stripeClient StripeClient
2019-11-15 14:59:39 +00:00
coinPayments * coinpayments . Client
2020-05-26 12:00:14 +01:00
StorageMBMonthPriceCents decimal . Decimal
EgressMBPriceCents decimal . Decimal
2021-10-20 23:54:34 +01:00
SegmentMonthPriceCents decimal . Decimal
2020-01-24 13:38:53 +00:00
// BonusRate amount of percents
BonusRate int64
2020-03-16 19:34:15 +00:00
// Coupon Values
2021-05-10 18:12:05 +01:00
StripeFreeTierCouponID string
2019-11-15 14:59:39 +00:00
2020-10-13 13:47:55 +01:00
// Stripe Extended Features
2020-03-13 16:07:39 +00:00
AutoAdvance bool
2019-11-15 14:59:39 +00:00
mu sync . Mutex
rates coinpayments . CurrencyRateInfos
ratesErr error
2020-05-19 08:42:07 +01:00
2021-06-28 23:57:41 +01:00
listingLimit int
nowFn func ( ) time . Time
2019-10-10 18:12:23 +01:00
}
2019-10-15 12:23:54 +01:00
// NewService creates a Service instance.
2022-05-10 20:19:53 +01:00
func NewService ( log * zap . Logger , stripeClient StripeClient , config Config , db DB , walletsDB storjscan . WalletsDB , billingDB billing . TransactionsDB , projectsDB console . Projects , usageDB accounting . ProjectAccounting , storageTBPrice , egressTBPrice , segmentPrice string , bonusRate int64 ) ( * Service , error ) {
2019-10-23 13:04:54 +01:00
coinPaymentsClient := coinpayments . NewClient (
2019-10-17 15:04:50 +01:00
coinpayments . Credentials {
PublicKey : config . CoinpaymentsPublicKey ,
PrivateKey : config . CoinpaymentsPrivateKey ,
} ,
)
2019-10-10 18:12:23 +01:00
2020-05-26 12:00:14 +01:00
storageTBMonthDollars , err := decimal . NewFromString ( storageTBPrice )
2020-01-28 23:36:54 +00:00
if err != nil {
return nil , err
}
2020-01-29 05:06:01 +00:00
egressTBDollars , err := decimal . NewFromString ( egressTBPrice )
2020-01-28 23:36:54 +00:00
if err != nil {
return nil , err
}
2021-10-20 23:54:34 +01:00
segmentMonthDollars , err := decimal . NewFromString ( segmentPrice )
2020-01-28 23:36:54 +00:00
if err != nil {
return nil , err
2019-10-10 18:12:23 +01:00
}
2020-01-28 23:36:54 +00:00
2020-05-26 12:00:14 +01:00
// change the precision from TB dollars to MB cents
storageMBMonthPriceCents := storageTBMonthDollars . Shift ( - 6 ) . Shift ( 2 )
egressMBPriceCents := egressTBDollars . Shift ( - 6 ) . Shift ( 2 )
2021-10-20 23:54:34 +01:00
segmentMonthPriceCents := segmentMonthDollars . Shift ( 2 )
2020-01-28 23:36:54 +00:00
return & Service {
2020-05-26 12:00:14 +01:00
log : log ,
db : db ,
2022-05-10 20:19:53 +01:00
walletsDB : walletsDB ,
billingDB : billingDB ,
2020-05-26 12:00:14 +01:00
projectsDB : projectsDB ,
usageDB : usageDB ,
stripeClient : stripeClient ,
coinPayments : coinPaymentsClient ,
StorageMBMonthPriceCents : storageMBMonthPriceCents ,
EgressMBPriceCents : egressMBPriceCents ,
2021-10-20 23:54:34 +01:00
SegmentMonthPriceCents : segmentMonthPriceCents ,
2020-05-26 12:00:14 +01:00
BonusRate : bonusRate ,
2021-05-10 18:12:05 +01:00
StripeFreeTierCouponID : config . StripeFreeTierCouponID ,
2020-05-26 12:00:14 +01:00
AutoAdvance : config . AutoAdvance ,
listingLimit : config . ListingLimit ,
nowFn : time . Now ,
2020-01-28 23:36:54 +00:00
} , nil
2019-10-10 18:12:23 +01:00
}
2019-10-11 16:00:35 +01:00
2019-10-15 12:23:54 +01:00
// Accounts exposes all needed functionality to manage payment accounts.
2019-10-17 15:42:18 +01:00
func ( service * Service ) Accounts ( ) payments . Accounts {
2019-10-15 12:23:54 +01:00
return & accounts { service : service }
2019-10-11 16:00:35 +01:00
}
2019-10-23 13:04:54 +01:00
// updateTransactionsLoop updates all pending transactions in a loop.
func ( service * Service ) updateTransactionsLoop ( ctx context . Context ) ( err error ) {
defer mon . Task ( ) ( & ctx ) ( & err )
2020-05-19 08:42:07 +01:00
before := service . nowFn ( )
2019-10-23 13:04:54 +01:00
2020-05-19 08:42:07 +01:00
txsPage , err := service . db . Transactions ( ) . ListPending ( ctx , 0 , service . listingLimit , before )
2019-10-23 13:04:54 +01:00
if err != nil {
return err
}
2020-06-25 22:16:39 +01:00
if err := service . updateTransactions ( ctx , txsPage . IDList ( ) , txsPage . CreationTimes ( ) ) ; err != nil {
2019-10-23 13:04:54 +01:00
return err
}
for txsPage . Next {
2019-10-29 16:04:34 +00:00
if err = ctx . Err ( ) ; err != nil {
return err
2019-10-23 13:04:54 +01:00
}
2020-05-19 08:42:07 +01:00
txsPage , err = service . db . Transactions ( ) . ListPending ( ctx , txsPage . NextOffset , service . listingLimit , before )
2019-10-23 13:04:54 +01:00
if err != nil {
return err
}
2020-06-25 22:16:39 +01:00
if err := service . updateTransactions ( ctx , txsPage . IDList ( ) , txsPage . CreationTimes ( ) ) ; err != nil {
2019-10-23 13:04:54 +01:00
return err
}
}
return nil
}
// updateTransactions updates statuses and received amount for given transactions.
2020-06-25 22:16:39 +01:00
func ( service * Service ) updateTransactions ( ctx context . Context , ids TransactionAndUserList , creationTimes map [ coinpayments . TransactionID ] time . Time ) ( err error ) {
2019-10-23 13:04:54 +01:00
defer mon . Task ( ) ( & ctx , ids ) ( & err )
if len ( ids ) == 0 {
service . log . Debug ( "no transactions found, skipping update" )
return nil
}
2020-01-29 00:57:15 +00:00
infos , err := service . coinPayments . Transactions ( ) . ListInfos ( ctx , ids . IDList ( ) )
2019-10-23 13:04:54 +01:00
if err != nil {
return err
}
var updates [ ] TransactionUpdate
2019-10-29 16:04:34 +00:00
var applies coinpayments . TransactionIDList
2019-10-23 13:04:54 +01:00
for id , info := range infos {
2020-06-25 22:16:39 +01:00
service . log . Debug ( "Coinpayments results: " , zap . String ( "status" , info . Status . String ( ) ) , zap . String ( "id" , id . String ( ) ) )
2019-10-23 13:04:54 +01:00
updates = append ( updates ,
TransactionUpdate {
TransactionID : id ,
Status : info . Status ,
2022-09-06 13:43:09 +01:00
Received : currency . AmountFromDecimal ( info . Received , currency . StorjToken ) ,
2019-10-23 13:04:54 +01:00
} ,
)
2020-07-01 16:26:23 +01:00
// moment of CoinPayments receives funds, not when STORJ does
// this was a business decision to not wait until StatusCompleted
if info . Status >= coinpayments . StatusReceived {
2020-10-13 13:47:55 +01:00
// monkit currently does not have a DurationVal
2020-06-25 22:16:39 +01:00
mon . IntVal ( "coinpayment_duration" ) . Observe ( int64 ( time . Since ( creationTimes [ id ] ) ) )
2019-10-29 16:04:34 +00:00
applies = append ( applies , id )
}
}
2019-11-05 13:16:02 +00:00
return service . db . Transactions ( ) . Update ( ctx , updates , applies )
2019-10-29 16:04:34 +00:00
}
// applyAccountBalanceLoop fetches all unapplied transaction in a loop, applying transaction
// received amount to stripe customer balance.
func ( service * Service ) updateAccountBalanceLoop ( ctx context . Context ) ( err error ) {
defer mon . Task ( ) ( & ctx ) ( & err )
2020-05-19 08:42:07 +01:00
before := service . nowFn ( )
2019-10-29 16:04:34 +00:00
2020-05-19 08:42:07 +01:00
txsPage , err := service . db . Transactions ( ) . ListUnapplied ( ctx , 0 , service . listingLimit , before )
2019-10-29 16:04:34 +00:00
if err != nil {
return err
}
for _ , tx := range txsPage . Transactions {
if err = ctx . Err ( ) ; err != nil {
return err
}
if err = service . applyTransactionBalance ( ctx , tx ) ; err != nil {
return err
}
}
for txsPage . Next {
if err = ctx . Err ( ) ; err != nil {
return err
}
2020-05-19 08:42:07 +01:00
txsPage , err = service . db . Transactions ( ) . ListUnapplied ( ctx , txsPage . NextOffset , service . listingLimit , before )
2019-10-29 16:04:34 +00:00
if err != nil {
return err
}
for _ , tx := range txsPage . Transactions {
if err = ctx . Err ( ) ; err != nil {
return err
}
if err = service . applyTransactionBalance ( ctx , tx ) ; err != nil {
return err
}
}
2019-10-23 13:04:54 +01:00
}
2019-10-29 16:04:34 +00:00
return nil
}
// applyTransactionBalance applies transaction received amount to stripe customer balance.
func ( service * Service ) applyTransactionBalance ( ctx context . Context , tx Transaction ) ( err error ) {
defer mon . Task ( ) ( & ctx ) ( & err )
2019-11-05 13:16:02 +00:00
cusID , err := service . db . Customers ( ) . GetCustomerID ( ctx , tx . AccountID )
2019-10-29 16:04:34 +00:00
if err != nil {
return err
}
2019-11-15 14:59:39 +00:00
rate , err := service . db . Transactions ( ) . GetLockedRate ( ctx , tx . ID )
if err != nil {
return err
}
satellite/payments: specialized type for monetary amounts
Why: big.Float is not an ideal type for dealing with monetary amounts,
because no matter how high the precision, some non-integer decimal
values can not be represented exactly in base-2 floating point. Also,
storing gob-encoded big.Float values in the database makes it very hard
to use those values in meaningful queries, making it difficult to do
any sort of analysis on billing.
For better accuracy, then, we can just represent monetary values as
integers (in whatever base units are appropriate for the currency). For
example, STORJ tokens or Bitcoins can not be split into pieces smaller
than 10^-8, so we can store amounts of STORJ or BTC with precision
simply by moving the decimal point 8 digits to the right. For USD values
(assuming we don't want to deal with fractional cents), we can move the
decimal point 2 digits to the right.
To make it easier and less error-prone to deal with the math involved, I
introduce here a new type, monetary.Amount, instances of which have an
associated value _and_ a currency.
Change-Id: I03395d52f0e2473cf301361f6033722b54640265
2021-08-10 23:29:50 +01:00
cents := convertToCents ( rate , tx . Received )
2019-10-29 16:04:34 +00:00
2020-05-28 12:31:02 +01:00
if cents <= 0 {
service . log . Warn ( "Trying to deposit non-positive amount." ,
zap . Int64 ( "USD cents" , cents ) ,
zap . Stringer ( "Transaction ID" , tx . ID ) ,
zap . Stringer ( "User ID" , tx . AccountID ) ,
)
return service . db . Transactions ( ) . Consume ( ctx , tx . ID )
2019-10-29 16:04:34 +00:00
}
2020-05-28 12:31:02 +01:00
// Check for balance transactions created from previous failed attempt
var depositDone , bonusDone bool
it := service . stripeClient . CustomerBalanceTransactions ( ) . List ( & stripe . CustomerBalanceTransactionListParams { Customer : stripe . String ( cusID ) } )
for it . Next ( ) {
cbt := it . CustomerBalanceTransaction ( )
2019-10-29 16:04:34 +00:00
2020-05-28 12:31:02 +01:00
if cbt . Type != stripe . CustomerBalanceTransactionTypeAdjustment {
continue
}
txID , ok := cbt . Metadata [ "txID" ]
if ! ok {
continue
}
if txID != tx . ID . String ( ) {
continue
}
switch cbt . Description {
case StripeDepositTransactionDescription :
depositDone = true
case StripeDepositBonusTransactionDescription :
bonusDone = true
}
}
// The first balance transaction is for the actual deposit
if ! depositDone {
params := & stripe . CustomerBalanceTransactionParams {
Amount : stripe . Int64 ( - cents ) ,
Customer : stripe . String ( cusID ) ,
Currency : stripe . String ( string ( stripe . CurrencyUSD ) ) ,
Description : stripe . String ( StripeDepositTransactionDescription ) ,
}
params . AddMetadata ( "txID" , tx . ID . String ( ) )
satellite/payments: specialized type for monetary amounts
Why: big.Float is not an ideal type for dealing with monetary amounts,
because no matter how high the precision, some non-integer decimal
values can not be represented exactly in base-2 floating point. Also,
storing gob-encoded big.Float values in the database makes it very hard
to use those values in meaningful queries, making it difficult to do
any sort of analysis on billing.
For better accuracy, then, we can just represent monetary values as
integers (in whatever base units are appropriate for the currency). For
example, STORJ tokens or Bitcoins can not be split into pieces smaller
than 10^-8, so we can store amounts of STORJ or BTC with precision
simply by moving the decimal point 8 digits to the right. For USD values
(assuming we don't want to deal with fractional cents), we can move the
decimal point 2 digits to the right.
To make it easier and less error-prone to deal with the math involved, I
introduce here a new type, monetary.Amount, instances of which have an
associated value _and_ a currency.
Change-Id: I03395d52f0e2473cf301361f6033722b54640265
2021-08-10 23:29:50 +01:00
params . AddMetadata ( "storj_amount" , tx . Amount . AsDecimal ( ) . String ( ) )
2020-07-17 16:17:21 +01:00
params . AddMetadata ( "storj_usd_rate" , rate . String ( ) )
2020-05-28 12:31:02 +01:00
_ , err = service . stripeClient . CustomerBalanceTransactions ( ) . New ( params )
if err != nil {
return err
}
2020-01-24 13:38:53 +00:00
}
2020-05-28 12:31:02 +01:00
// The second balance transaction for the bonus
if ! bonusDone {
params := & stripe . CustomerBalanceTransactionParams {
Amount : stripe . Int64 ( - cents * service . BonusRate / 100 ) ,
Customer : stripe . String ( cusID ) ,
Currency : stripe . String ( string ( stripe . CurrencyUSD ) ) ,
Description : stripe . String ( StripeDepositBonusTransactionDescription ) ,
}
params . AddMetadata ( "txID" , tx . ID . String ( ) )
params . AddMetadata ( "percentage" , strconv . Itoa ( int ( service . BonusRate ) ) )
_ , err = service . stripeClient . CustomerBalanceTransactions ( ) . New ( params )
if err != nil {
return err
}
2020-01-24 13:38:53 +00:00
}
2020-05-28 12:31:02 +01:00
return service . db . Transactions ( ) . Consume ( ctx , tx . ID )
2019-10-23 13:04:54 +01:00
}
2019-11-05 13:16:02 +00:00
2019-11-15 14:59:39 +00:00
// UpdateRates fetches new rates and updates service rate cache.
func ( service * Service ) UpdateRates ( ctx context . Context ) ( err error ) {
defer mon . Task ( ) ( & ctx ) ( & err )
rates , err := service . coinPayments . ConversionRates ( ) . Get ( ctx )
2020-05-22 11:42:17 +01:00
if coinpayments . ErrMissingPublicKey . Has ( err ) {
rates = coinpayments . CurrencyRateInfos { }
err = nil
service . log . Info ( "Coinpayment client is missing public key" )
}
2019-11-15 14:59:39 +00:00
service . mu . Lock ( )
defer service . mu . Unlock ( )
service . rates = rates
service . ratesErr = err
return err
}
// GetRate returns conversion rate for specified currencies.
2022-09-06 13:43:09 +01:00
func ( service * Service ) GetRate ( ctx context . Context , curr1 , curr2 * currency . Currency ) ( _ decimal . Decimal , err error ) {
2019-11-15 14:59:39 +00:00
defer mon . Task ( ) ( & ctx ) ( & err )
service . mu . Lock ( )
defer service . mu . Unlock ( )
if service . ratesErr != nil {
satellite/payments: specialized type for monetary amounts
Why: big.Float is not an ideal type for dealing with monetary amounts,
because no matter how high the precision, some non-integer decimal
values can not be represented exactly in base-2 floating point. Also,
storing gob-encoded big.Float values in the database makes it very hard
to use those values in meaningful queries, making it difficult to do
any sort of analysis on billing.
For better accuracy, then, we can just represent monetary values as
integers (in whatever base units are appropriate for the currency). For
example, STORJ tokens or Bitcoins can not be split into pieces smaller
than 10^-8, so we can store amounts of STORJ or BTC with precision
simply by moving the decimal point 8 digits to the right. For USD values
(assuming we don't want to deal with fractional cents), we can move the
decimal point 2 digits to the right.
To make it easier and less error-prone to deal with the math involved, I
introduce here a new type, monetary.Amount, instances of which have an
associated value _and_ a currency.
Change-Id: I03395d52f0e2473cf301361f6033722b54640265
2021-08-10 23:29:50 +01:00
return decimal . Decimal { } , Error . Wrap ( err )
2019-11-15 14:59:39 +00:00
}
2021-09-30 17:20:52 +01:00
info1 , ok := service . rates . ForCurrency ( curr1 )
2019-11-15 14:59:39 +00:00
if ! ok {
satellite/payments: specialized type for monetary amounts
Why: big.Float is not an ideal type for dealing with monetary amounts,
because no matter how high the precision, some non-integer decimal
values can not be represented exactly in base-2 floating point. Also,
storing gob-encoded big.Float values in the database makes it very hard
to use those values in meaningful queries, making it difficult to do
any sort of analysis on billing.
For better accuracy, then, we can just represent monetary values as
integers (in whatever base units are appropriate for the currency). For
example, STORJ tokens or Bitcoins can not be split into pieces smaller
than 10^-8, so we can store amounts of STORJ or BTC with precision
simply by moving the decimal point 8 digits to the right. For USD values
(assuming we don't want to deal with fractional cents), we can move the
decimal point 2 digits to the right.
To make it easier and less error-prone to deal with the math involved, I
introduce here a new type, monetary.Amount, instances of which have an
associated value _and_ a currency.
Change-Id: I03395d52f0e2473cf301361f6033722b54640265
2021-08-10 23:29:50 +01:00
return decimal . Decimal { } , Error . New ( "no rate for currency %s" , curr1 . Name ( ) )
2019-11-15 14:59:39 +00:00
}
2021-09-30 17:20:52 +01:00
info2 , ok := service . rates . ForCurrency ( curr2 )
2019-11-15 14:59:39 +00:00
if ! ok {
satellite/payments: specialized type for monetary amounts
Why: big.Float is not an ideal type for dealing with monetary amounts,
because no matter how high the precision, some non-integer decimal
values can not be represented exactly in base-2 floating point. Also,
storing gob-encoded big.Float values in the database makes it very hard
to use those values in meaningful queries, making it difficult to do
any sort of analysis on billing.
For better accuracy, then, we can just represent monetary values as
integers (in whatever base units are appropriate for the currency). For
example, STORJ tokens or Bitcoins can not be split into pieces smaller
than 10^-8, so we can store amounts of STORJ or BTC with precision
simply by moving the decimal point 8 digits to the right. For USD values
(assuming we don't want to deal with fractional cents), we can move the
decimal point 2 digits to the right.
To make it easier and less error-prone to deal with the math involved, I
introduce here a new type, monetary.Amount, instances of which have an
associated value _and_ a currency.
Change-Id: I03395d52f0e2473cf301361f6033722b54640265
2021-08-10 23:29:50 +01:00
return decimal . Decimal { } , Error . New ( "no rate for currency %s" , curr2 . Name ( ) )
2019-11-15 14:59:39 +00:00
}
satellite/payments: specialized type for monetary amounts
Why: big.Float is not an ideal type for dealing with monetary amounts,
because no matter how high the precision, some non-integer decimal
values can not be represented exactly in base-2 floating point. Also,
storing gob-encoded big.Float values in the database makes it very hard
to use those values in meaningful queries, making it difficult to do
any sort of analysis on billing.
For better accuracy, then, we can just represent monetary values as
integers (in whatever base units are appropriate for the currency). For
example, STORJ tokens or Bitcoins can not be split into pieces smaller
than 10^-8, so we can store amounts of STORJ or BTC with precision
simply by moving the decimal point 8 digits to the right. For USD values
(assuming we don't want to deal with fractional cents), we can move the
decimal point 2 digits to the right.
To make it easier and less error-prone to deal with the math involved, I
introduce here a new type, monetary.Amount, instances of which have an
associated value _and_ a currency.
Change-Id: I03395d52f0e2473cf301361f6033722b54640265
2021-08-10 23:29:50 +01:00
return info1 . RateBTC . Div ( info2 . RateBTC ) , nil
2019-11-15 14:59:39 +00:00
}
2021-08-27 01:51:26 +01:00
// PrepareInvoiceProjectRecords iterates through all projects and creates invoice records if none exist.
2019-11-05 13:16:02 +00:00
func ( service * Service ) PrepareInvoiceProjectRecords ( ctx context . Context , period time . Time ) ( err error ) {
defer mon . Task ( ) ( & ctx ) ( & err )
2020-05-19 08:42:07 +01:00
now := service . nowFn ( ) . UTC ( )
2019-11-05 13:16:02 +00:00
utc := period . UTC ( )
start := time . Date ( utc . Year ( ) , utc . Month ( ) , 1 , 0 , 0 , 0 , 0 , time . UTC )
2021-08-25 20:35:57 +01:00
end := time . Date ( utc . Year ( ) , utc . Month ( ) + 1 , 1 , 0 , 0 , 0 , 0 , time . UTC )
2019-11-05 13:16:02 +00:00
if end . After ( now ) {
2020-05-12 09:46:48 +01:00
return Error . New ( "allowed for past periods only" )
2019-11-05 13:16:02 +00:00
}
2021-08-27 01:51:26 +01:00
var numberOfCustomers , numberOfRecords int
2020-05-29 11:29:03 +01:00
customersPage , err := service . db . Customers ( ) . List ( ctx , 0 , service . listingLimit , end )
2019-11-05 13:16:02 +00:00
if err != nil {
return Error . Wrap ( err )
}
2020-06-03 10:50:53 +01:00
numberOfCustomers += len ( customersPage . Customers )
2019-11-05 13:16:02 +00:00
2021-08-27 01:51:26 +01:00
records , err := service . processCustomers ( ctx , customersPage . Customers , start , end )
2020-06-03 10:50:53 +01:00
if err != nil {
2019-11-05 13:16:02 +00:00
return Error . Wrap ( err )
}
2020-06-03 10:50:53 +01:00
numberOfRecords += records
2019-11-05 13:16:02 +00:00
2020-05-29 11:29:03 +01:00
for customersPage . Next {
2019-11-05 13:16:02 +00:00
if err = ctx . Err ( ) ; err != nil {
return Error . Wrap ( err )
}
2020-05-29 11:29:03 +01:00
customersPage , err = service . db . Customers ( ) . List ( ctx , customersPage . NextOffset , service . listingLimit , end )
2019-11-05 13:16:02 +00:00
if err != nil {
return Error . Wrap ( err )
}
2021-08-27 01:51:26 +01:00
records , err := service . processCustomers ( ctx , customersPage . Customers , start , end )
2020-06-03 10:50:53 +01:00
if err != nil {
2019-11-05 13:16:02 +00:00
return Error . Wrap ( err )
}
2020-06-03 10:50:53 +01:00
numberOfRecords += records
2019-11-05 13:16:02 +00:00
}
2021-08-27 01:51:26 +01:00
service . log . Info ( "Number of processed entries." , zap . Int ( "Customers" , numberOfCustomers ) , zap . Int ( "Projects" , numberOfRecords ) )
2019-11-05 13:16:02 +00:00
return nil
}
2021-08-27 01:51:26 +01:00
func ( service * Service ) processCustomers ( ctx context . Context , customers [ ] Customer , start , end time . Time ) ( int , error ) {
2020-05-29 11:29:03 +01:00
var allRecords [ ] CreateProjectRecord
for _ , customer := range customers {
2020-06-03 18:01:54 +01:00
projects , err := service . projectsDB . GetOwn ( ctx , customer . UserID )
2020-01-07 10:41:19 +00:00
if err != nil {
2021-08-27 01:51:26 +01:00
return 0 , err
2020-01-07 10:41:19 +00:00
}
2021-08-27 01:51:26 +01:00
records , err := service . createProjectRecords ( ctx , customer . ID , projects , start , end )
2020-05-08 17:04:04 +01:00
if err != nil {
2021-08-27 01:51:26 +01:00
return 0 , err
2020-05-08 17:04:04 +01:00
}
2020-01-24 13:38:53 +00:00
2020-05-29 11:29:03 +01:00
allRecords = append ( allRecords , records ... )
2019-11-05 13:16:02 +00:00
}
2021-08-27 01:51:26 +01:00
return len ( allRecords ) , service . db . ProjectRecords ( ) . Create ( ctx , allRecords , start , end )
2020-05-29 11:29:03 +01:00
}
// createProjectRecords creates invoice project record if none exists.
2021-08-27 01:51:26 +01:00
func ( service * Service ) createProjectRecords ( ctx context . Context , customerID string , projects [ ] console . Project , start , end time . Time ) ( _ [ ] CreateProjectRecord , err error ) {
2020-05-29 11:29:03 +01:00
defer mon . Task ( ) ( & ctx ) ( & err )
var records [ ] CreateProjectRecord
for _ , project := range projects {
if err = ctx . Err ( ) ; err != nil {
2021-08-27 01:51:26 +01:00
return nil , err
2020-05-29 11:29:03 +01:00
}
if err = service . db . ProjectRecords ( ) . Check ( ctx , project . ID , start , end ) ; err != nil {
2020-07-14 14:04:38 +01:00
if errors . Is ( err , ErrProjectRecordExists ) {
2020-06-03 10:50:53 +01:00
service . log . Warn ( "Record for this project already exists." , zap . String ( "Customer ID" , customerID ) , zap . String ( "Project ID" , project . ID . String ( ) ) )
2020-05-29 11:29:03 +01:00
continue
}
2021-08-27 01:51:26 +01:00
return nil , err
2020-05-29 11:29:03 +01:00
}
usage , err := service . usageDB . GetProjectTotal ( ctx , project . ID , start , end )
if err != nil {
2021-08-27 01:51:26 +01:00
return nil , err
2020-05-29 11:29:03 +01:00
}
// TODO: account for usage data.
records = append ( records ,
CreateProjectRecord {
ProjectID : project . ID ,
Storage : usage . Storage ,
Egress : usage . Egress ,
2021-10-20 23:54:34 +01:00
Segments : usage . SegmentCount ,
2020-05-29 11:29:03 +01:00
} ,
)
}
2021-08-27 01:51:26 +01:00
return records , nil
2019-11-05 13:16:02 +00:00
}
// InvoiceApplyProjectRecords iterates through unapplied invoice project records and creates invoice line items
// for stripe customer.
2020-05-12 09:46:48 +01:00
func ( service * Service ) InvoiceApplyProjectRecords ( ctx context . Context , period time . Time ) ( err error ) {
2019-11-05 13:16:02 +00:00
defer mon . Task ( ) ( & ctx ) ( & err )
2020-05-19 08:42:07 +01:00
now := service . nowFn ( ) . UTC ( )
2020-05-12 09:46:48 +01:00
utc := period . UTC ( )
start := time . Date ( utc . Year ( ) , utc . Month ( ) , 1 , 0 , 0 , 0 , 0 , time . UTC )
2021-08-25 20:35:57 +01:00
end := time . Date ( utc . Year ( ) , utc . Month ( ) + 1 , 1 , 0 , 0 , 0 , 0 , time . UTC )
2019-11-05 13:16:02 +00:00
2020-05-12 09:46:48 +01:00
if end . After ( now ) {
return Error . New ( "allowed for past periods only" )
}
2020-06-09 14:07:06 +01:00
projectRecords := 0
2020-05-19 08:42:07 +01:00
recordsPage , err := service . db . ProjectRecords ( ) . ListUnapplied ( ctx , 0 , service . listingLimit , start , end )
2019-11-05 13:16:02 +00:00
if err != nil {
return Error . Wrap ( err )
}
if err = service . applyProjectRecords ( ctx , recordsPage . Records ) ; err != nil {
return Error . Wrap ( err )
}
2020-06-09 14:07:06 +01:00
projectRecords += len ( recordsPage . Records )
2019-11-05 13:16:02 +00:00
for recordsPage . Next {
if err = ctx . Err ( ) ; err != nil {
return Error . Wrap ( err )
}
2020-05-18 14:01:26 +01:00
// we are always starting from offset 0 because applyProjectRecords is changing project record state to applied
2020-05-19 08:42:07 +01:00
recordsPage , err = service . db . ProjectRecords ( ) . ListUnapplied ( ctx , 0 , service . listingLimit , start , end )
2019-11-05 13:16:02 +00:00
if err != nil {
return Error . Wrap ( err )
}
if err = service . applyProjectRecords ( ctx , recordsPage . Records ) ; err != nil {
return Error . Wrap ( err )
}
2020-06-09 14:07:06 +01:00
projectRecords += len ( recordsPage . Records )
2019-11-05 13:16:02 +00:00
}
2020-06-09 14:07:06 +01:00
service . log . Info ( "Number of processed project records." , zap . Int ( "Project Records" , projectRecords ) )
2019-11-05 13:16:02 +00:00
return nil
}
2022-05-10 20:19:53 +01:00
// InvoiceApplyTokenBalance iterates through customer storjscan wallets and creates invoice line items
// for stripe customer.
func ( service * Service ) InvoiceApplyTokenBalance ( ctx context . Context ) ( 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 user token balance, if it's not > 0, don't bother with the rest
2022-08-27 00:08:03 +01:00
monetaryTokenBalance , err := service . billingDB . GetBalance ( ctx , wallet . UserID )
// truncate here since stripe only has cent level precision for invoices.
// The users account balance will still maintain the full precision monetary value!
2022-09-06 13:43:09 +01:00
tokenBalance := currency . AmountFromDecimal ( monetaryTokenBalance . AsDecimal ( ) . Truncate ( 2 ) , currency . USDollars )
2022-05-10 20:19:53 +01:00
if err != nil {
errGrp . Add ( Error . New ( "unable to compute balance for user ID %s" , wallet . UserID . String ( ) ) )
continue
}
2022-08-27 00:08:03 +01:00
if tokenBalance . BaseUnits ( ) <= 0 {
2022-05-10 20:19:53 +01:00
continue
}
// get the stripe customer invoice balance
cusID , 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
}
invoices , err := service . getInvoices ( ctx , cusID )
if err != nil {
errGrp . Add ( Error . New ( "unable to get invoice balance for stripe customer ID %s" , cusID ) )
continue
}
for _ , invoice := range invoices {
// if no balance due, do nothing
2022-09-13 00:16:17 +01:00
if invoice . AmountRemaining <= 0 {
2022-05-10 20:19:53 +01:00
continue
}
var tokenCreditAmount int64
2022-09-13 00:16:17 +01:00
if invoice . AmountRemaining >= tokenBalance . BaseUnits ( ) {
tokenCreditAmount = tokenBalance . BaseUnits ( )
2022-05-10 20:19:53 +01:00
} else {
2022-09-13 00:16:17 +01:00
tokenCreditAmount = invoice . AmountRemaining
2022-05-10 20:19:53 +01:00
}
2022-09-13 00:16:17 +01:00
txID , err := service . createTokenPaymentBillingTransaction ( ctx , wallet . UserID , invoice . ID , wallet . Address . Hex ( ) , - tokenCreditAmount )
2022-05-10 20:19:53 +01:00
if err != nil {
errGrp . Add ( Error . New ( "unable to create token payment billing transaction for user %s" , wallet . UserID . String ( ) ) )
continue
}
2022-09-13 00:16:17 +01:00
creditNoteID , err := service . addCreditNoteToInvoice ( ctx , invoice . ID , cusID , wallet . Address . Hex ( ) , tokenCreditAmount , txID )
2022-05-10 20:19:53 +01:00
if err != nil {
2022-09-13 00:16:17 +01:00
errGrp . Add ( Error . New ( "unable to create token payment credit note for user %s" , wallet . UserID . String ( ) ) )
2022-05-10 20:19:53 +01:00
continue
}
metadata , err := json . Marshal ( map [ string ] interface { } {
2022-09-13 00:16:17 +01:00
"Credit Note ID" : creditNoteID ,
2022-05-10 20:19:53 +01:00
} )
if err != nil {
2022-09-13 00:16:17 +01:00
errGrp . Add ( Error . New ( "unable to marshall credit note ID %s" , creditNoteID ) )
2022-05-10 20:19:53 +01:00
continue
}
err = service . billingDB . UpdateMetadata ( ctx , txID , metadata )
if err != nil {
2022-09-13 00:16:17 +01:00
errGrp . Add ( Error . New ( "unable to add credit note ID to billing transaction for user %s" , wallet . UserID . String ( ) ) )
continue
}
err = service . billingDB . UpdateStatus ( ctx , txID , billing . TransactionStatusCompleted )
if err != nil {
errGrp . Add ( Error . New ( "unable to update status for billing transaction for user %s" , wallet . UserID . String ( ) ) )
2022-05-10 20:19:53 +01:00
continue
}
}
}
return errGrp . Err ( )
}
2022-09-13 00:16:17 +01:00
// getInvoices returns the stripe customer's open finalized invoices.
2022-05-10 20:19:53 +01:00
func ( service * Service ) getInvoices ( ctx context . Context , cusID string ) ( _ [ ] stripe . Invoice , err error ) {
defer mon . Task ( ) ( & ctx ) ( & err )
params := & stripe . InvoiceListParams {
Customer : stripe . String ( cusID ) ,
2022-09-13 00:16:17 +01:00
Status : stripe . String ( string ( stripe . InvoiceStatusOpen ) ) ,
2022-05-10 20:19:53 +01:00
}
invoicesIterator := service . stripeClient . Invoices ( ) . List ( params )
var stripeInvoices [ ] stripe . Invoice
for invoicesIterator . Next ( ) {
stripeInvoice := invoicesIterator . Invoice ( )
if stripeInvoice != nil {
stripeInvoices = append ( stripeInvoices , * stripeInvoice )
}
}
return stripeInvoices , nil
}
2022-09-13 00:16:17 +01:00
// 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 ) {
2022-05-10 20:19:53 +01:00
defer mon . Task ( ) ( & ctx ) ( & err )
2022-09-13 00:16:17 +01:00
var lineParams [ ] * stripe . CreditNoteLineParams
lineParam := stripe . CreditNoteLineParams {
Description : stripe . String ( "Storjscan Token payment" ) ,
Type : stripe . String ( "custom_line_item" ) ,
2022-05-10 20:19:53 +01:00
UnitAmount : stripe . Int64 ( amount ) ,
2022-09-13 00:16:17 +01:00
Quantity : stripe . Int64 ( 1 ) ,
2022-05-10 20:19:53 +01:00
}
2022-09-13 00:16:17 +01:00
lineParams = append ( lineParams , & lineParam )
params := & stripe . CreditNoteParams {
Invoice : stripe . String ( invoiceID ) ,
Lines : lineParams ,
Memo : stripe . String ( "Storjscan Token Payment - Wallet: 0x" + wallet ) ,
}
params . AddMetadata ( "txID" , "0x" + strconv . FormatInt ( txID , 10 ) )
params . AddMetadata ( "wallet address" , wallet )
creditNote , err := service . stripeClient . CreditNotes ( ) . New ( params )
2022-05-10 20:19:53 +01:00
if err != nil {
2022-09-13 00:16:17 +01:00
service . log . Warn ( "unable to add credit note for stripe customer" , zap . String ( "Customer ID" , cusID ) )
return "" , Error . Wrap ( err )
2022-05-10 20:19:53 +01:00
}
2022-09-13 00:16:17 +01:00
return creditNote . ID , nil
2022-05-10 20:19:53 +01:00
}
// 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 ,
2022-09-06 13:43:09 +01:00
Amount : currency . AmountFromBaseUnits ( amount , currency . USDollars ) ,
2022-05-10 20:19:53 +01:00
Description : "Paid Stripe Invoice" ,
Source : "stripe" ,
Status : billing . TransactionStatusPending ,
Type : billing . TransactionTypeDebit ,
Metadata : metadata ,
Timestamp : time . Now ( ) ,
}
txID , 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 txID , nil
}
2019-11-05 13:16:02 +00:00
// applyProjectRecords applies invoice intents as invoice line items to stripe customer.
func ( service * Service ) applyProjectRecords ( ctx context . Context , records [ ] ProjectRecord ) ( err error ) {
defer mon . Task ( ) ( & ctx ) ( & err )
for _ , record := range records {
if err = ctx . Err ( ) ; err != nil {
2022-02-04 17:31:24 +00:00
return errs . Wrap ( err )
2019-11-05 13:16:02 +00:00
}
proj , err := service . projectsDB . Get ( ctx , record . ProjectID )
if err != nil {
2022-02-04 17:31:24 +00:00
// 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 errs . Wrap ( err )
2019-11-05 13:16:02 +00:00
}
cusID , err := service . db . Customers ( ) . GetCustomerID ( ctx , proj . OwnerID )
if err != nil {
2020-07-14 14:04:38 +01:00
if errors . Is ( err , ErrNoCustomer ) {
2020-06-03 10:50:53 +01:00
service . log . Warn ( "Stripe customer does not exist for project owner." , zap . Stringer ( "Owner ID" , proj . OwnerID ) , zap . Stringer ( "Project ID" , proj . ID ) )
2019-11-05 13:16:02 +00:00
continue
}
2022-02-04 17:31:24 +00:00
return errs . Wrap ( err )
2019-11-05 13:16:02 +00:00
}
if err = service . createInvoiceItems ( ctx , cusID , proj . Name , record ) ; err != nil {
2022-02-04 17:31:24 +00:00
return errs . Wrap ( err )
2019-11-05 13:16:02 +00:00
}
}
return nil
}
// createInvoiceItems consumes invoice project record and creates invoice line items for stripe customer.
func ( service * Service ) createInvoiceItems ( ctx context . Context , cusID , projName string , record ProjectRecord ) ( err error ) {
defer mon . Task ( ) ( & ctx ) ( & err )
if err = service . db . ProjectRecords ( ) . Consume ( ctx , record . ID ) ; err != nil {
return err
}
2020-05-27 13:08:37 +01:00
items := service . InvoiceItemsFromProjectRecord ( projName , record )
for _ , item := range items {
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 err
}
2019-11-05 13:16:02 +00:00
}
2020-05-27 13:08:37 +01:00
return nil
}
// InvoiceItemsFromProjectRecord calculates Stripe invoice item from project record.
func ( service * Service ) InvoiceItemsFromProjectRecord ( projName string , record ProjectRecord ) ( result [ ] * stripe . InvoiceItemParams ) {
projectItem := & stripe . InvoiceItemParams { }
2021-10-20 23:54:34 +01:00
projectItem . Description = stripe . String ( fmt . Sprintf ( "Project %s - Segment Storage (MB-Month)" , projName ) )
2020-05-26 12:00:14 +01:00
projectItem . Quantity = stripe . Int64 ( storageMBMonthDecimal ( record . Storage ) . IntPart ( ) )
storagePrice , _ := service . StorageMBMonthPriceCents . Float64 ( )
projectItem . UnitAmountDecimal = stripe . Float64 ( storagePrice )
2020-05-27 13:08:37 +01:00
result = append ( result , projectItem )
2020-03-13 16:07:39 +00:00
2020-05-27 13:08:37 +01:00
projectItem = & stripe . InvoiceItemParams { }
2020-05-26 12:00:14 +01:00
projectItem . Description = stripe . String ( fmt . Sprintf ( "Project %s - Egress Bandwidth (MB)" , projName ) )
projectItem . Quantity = stripe . Int64 ( egressMBDecimal ( record . Egress ) . IntPart ( ) )
egressPrice , _ := service . EgressMBPriceCents . Float64 ( )
projectItem . UnitAmountDecimal = stripe . Float64 ( egressPrice )
2020-05-27 13:08:37 +01:00
result = append ( result , projectItem )
2020-03-13 16:07:39 +00:00
2020-05-27 13:08:37 +01:00
projectItem = & stripe . InvoiceItemParams { }
2021-10-20 23:54:34 +01:00
projectItem . Description = stripe . String ( fmt . Sprintf ( "Project %s - Segment Fee (Segment-Month)" , projName ) )
projectItem . Quantity = stripe . Int64 ( segmentMonthDecimal ( record . Segments ) . IntPart ( ) )
segmentPrice , _ := service . SegmentMonthPriceCents . Float64 ( )
projectItem . UnitAmountDecimal = stripe . Float64 ( segmentPrice )
2020-05-27 13:08:37 +01:00
result = append ( result , projectItem )
2021-10-20 23:54:34 +01:00
service . log . Info ( "invoice items" , zap . Any ( "result" , result ) )
2020-05-27 13:08:37 +01:00
return result
2019-11-05 13:16:02 +00:00
}
2021-07-30 23:11:36 +01:00
// 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 ( )
appliedCoupons := 0
failedUsers := [ ] string { }
morePages := true
nextOffset := int64 ( 0 )
listingLimit := 100
end := time . Now ( )
for morePages {
customersPage , err := customers . List ( ctx , nextOffset , listingLimit , end )
if err != nil {
return err
}
morePages = customersPage . Next
nextOffset = customersPage . NextOffset
for _ , c := range customersPage . Customers {
stripeCust , err := service . stripeClient . Customers ( ) . Get ( c . ID , nil )
if err != nil {
service . log . Error ( "Failed to get customer" , zap . Error ( err ) )
failedUsers = append ( failedUsers , c . ID )
continue
}
// if customer does not have a coupon, apply the free tier coupon
if stripeCust . Discount == nil || stripeCust . Discount . Coupon == nil {
params := & stripe . CustomerParams {
Coupon : stripe . String ( service . StripeFreeTierCouponID ) ,
}
_ , err := service . stripeClient . Customers ( ) . Update ( c . ID , params )
if err != nil {
service . log . Error ( "Failed to update customer with free tier coupon" , zap . Error ( err ) )
failedUsers = append ( failedUsers , c . ID )
continue
}
appliedCoupons ++
}
}
}
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
}
2019-11-05 13:16:02 +00:00
// CreateInvoices lists through all customers and creates invoices.
2020-05-12 09:46:48 +01:00
func ( service * Service ) CreateInvoices ( ctx context . Context , period time . Time ) ( err error ) {
2019-11-05 13:16:02 +00:00
defer mon . Task ( ) ( & ctx ) ( & err )
2020-05-19 08:42:07 +01:00
now := service . nowFn ( ) . UTC ( )
2020-05-12 09:46:48 +01:00
utc := period . UTC ( )
start := time . Date ( utc . Year ( ) , utc . Month ( ) , 1 , 0 , 0 , 0 , 0 , time . UTC )
2021-08-25 20:35:57 +01:00
end := time . Date ( utc . Year ( ) , utc . Month ( ) + 1 , 1 , 0 , 0 , 0 , 0 , time . UTC )
2020-05-12 09:46:48 +01:00
if end . After ( now ) {
return Error . New ( "allowed for past periods only" )
}
2019-11-05 13:16:02 +00:00
2022-09-26 19:00:07 +01:00
var nextOffset int64
var draft , scheduled int
for {
cusPage , err := service . db . Customers ( ) . List ( ctx , nextOffset , service . listingLimit , end )
2019-11-05 13:16:02 +00:00
if err != nil {
return Error . Wrap ( err )
}
for _ , cus := range cusPage . Customers {
if err = ctx . Err ( ) ; err != nil {
return Error . Wrap ( err )
}
2022-09-26 19:00:07 +01:00
stripeInvoice , err := service . createInvoice ( ctx , cus . ID , start )
if err != nil {
2019-11-05 13:16:02 +00:00
return Error . Wrap ( err )
}
2022-09-26 19:00:07 +01:00
if stripeInvoice . AutoAdvance {
scheduled ++
} else {
draft ++
}
2019-11-05 13:16:02 +00:00
}
2020-06-09 14:07:06 +01:00
2022-09-26 19:00:07 +01:00
if ! cusPage . Next {
break
}
nextOffset = cusPage . NextOffset
2019-11-05 13:16:02 +00:00
}
2022-09-26 19:00:07 +01:00
service . log . Info ( "Number of created invoices" , zap . Int ( "Draft" , draft ) , zap . Int ( "Scheduled" , scheduled ) )
2019-11-05 13:16:02 +00:00
return nil
}
// createInvoice creates invoice for stripe customer. Returns nil error if there are no
// pending invoice line items for customer.
2022-09-26 19:00:07 +01:00
func ( service * Service ) createInvoice ( ctx context . Context , cusID string , period time . Time ) ( stripeInvoice * stripe . Invoice , err error ) {
2019-11-05 13:16:02 +00:00
defer mon . Task ( ) ( & ctx ) ( & err )
2021-04-15 14:57:34 +01:00
description := fmt . Sprintf ( "Storj DCS Cloud Storage for %s %d" , period . Month ( ) , period . Year ( ) )
2020-03-13 16:07:39 +00:00
2022-09-26 19:00:07 +01:00
stripeInvoice , err = service . stripeClient . Invoices ( ) . New (
2019-11-05 13:16:02 +00:00
& stripe . InvoiceParams {
Customer : stripe . String ( cusID ) ,
2020-03-13 16:07:39 +00:00
AutoAdvance : stripe . Bool ( service . AutoAdvance ) ,
Description : stripe . String ( description ) ,
2019-11-05 13:16:02 +00:00
} ,
)
if err != nil {
2021-05-14 16:05:42 +01:00
var stripErr * stripe . Error
if errors . As ( err , & stripErr ) {
if stripErr . Code == stripe . ErrorCodeInvoiceNoCustomerLineItems {
2022-09-26 19:00:07 +01:00
return nil , nil
2019-11-05 13:16:02 +00:00
}
}
2022-09-26 19:00:07 +01:00
return nil , err
2019-11-05 13:16:02 +00:00
}
2022-09-26 19:00:07 +01:00
// auto advance the invoice if nothing is due from the customer
if ! stripeInvoice . AutoAdvance && stripeInvoice . AmountDue == 0 {
stripeInvoice , err = service . stripeClient . Invoices ( ) . Update (
stripeInvoice . ID ,
& stripe . InvoiceParams { AutoAdvance : stripe . Bool ( true ) } ,
)
if err != nil {
return nil , err
}
}
return stripeInvoice , nil
2019-11-05 13:16:02 +00:00
}
2020-01-28 23:36:54 +00:00
2022-09-27 09:48:38 +01:00
// GenerateInvoices performs all tasks necessary to generate Stripe invoices.
// This is equivalent to invoking ApplyFreeTierCoupons, PrepareInvoiceProjectRecords,
// InvoiceApplyProjectRecords, and CreateInvoices in order.
func ( service * Service ) GenerateInvoices ( ctx context . Context , period time . Time ) ( err error ) {
defer mon . Task ( ) ( & ctx ) ( & err )
for _ , subFn := range [ ] struct {
Description string
Exec func ( context . Context , time . Time ) error
} {
{ "Applying free tier coupons" , func ( ctx context . Context , _ time . Time ) error {
return service . ApplyFreeTierCoupons ( ctx )
} } ,
{ "Preparing invoice project records" , service . PrepareInvoiceProjectRecords } ,
{ "Applying invoice project records" , service . InvoiceApplyProjectRecords } ,
{ "Creating invoices" , service . CreateInvoices } ,
} {
service . log . Info ( subFn . Description )
if err := subFn . Exec ( ctx , period ) ; err != nil {
return err
}
}
return nil
}
2022-09-13 00:16:17 +01:00
// FinalizeInvoices transitions all draft invoices to open finalized invoices in stripe. No payment is to be collected yet.
2020-06-09 16:18:36 +01:00
func ( service * Service ) FinalizeInvoices ( ctx context . Context ) ( err error ) {
defer mon . Task ( ) ( & ctx ) ( & err )
params := & stripe . InvoiceListParams {
Status : stripe . String ( "draft" ) ,
}
invoicesIterator := service . stripeClient . Invoices ( ) . List ( params )
for invoicesIterator . Next ( ) {
stripeInvoice := invoicesIterator . Invoice ( )
2022-09-26 19:00:07 +01:00
if stripeInvoice . AutoAdvance {
continue
}
2020-06-09 16:18:36 +01:00
err := service . finalizeInvoice ( ctx , stripeInvoice . ID )
if err != nil {
return Error . Wrap ( err )
}
}
return Error . Wrap ( invoicesIterator . Err ( ) )
}
func ( service * Service ) finalizeInvoice ( ctx context . Context , invoiceID string ) ( err error ) {
defer mon . Task ( ) ( & ctx ) ( & err )
2022-09-13 00:16:17 +01:00
params := & stripe . InvoiceFinalizeParams { AutoAdvance : stripe . Bool ( false ) }
2020-06-09 16:18:36 +01:00
_ , err = service . stripeClient . Invoices ( ) . FinalizeInvoice ( invoiceID , params )
return err
}
2022-09-13 00:16:17 +01:00
// PayInvoices attempts to transition all open finalized invoices to "paid" by charging the customer according to subscriptions settings.
func ( service * Service ) PayInvoices ( ctx context . Context ) ( err error ) {
defer mon . Task ( ) ( & ctx ) ( & err )
params := & stripe . InvoiceListParams {
Status : stripe . String ( "open" ) ,
}
var errGrp errs . Group
invoicesIterator := service . stripeClient . Invoices ( ) . List ( params )
for invoicesIterator . Next ( ) {
stripeInvoice := invoicesIterator . Invoice ( )
params := & stripe . InvoicePayParams { }
_ , err = service . stripeClient . Invoices ( ) . Pay ( stripeInvoice . ID , params )
if err != nil {
errGrp . Add ( Error . New ( "unable to pay invoice %s" , stripeInvoice . ID ) )
continue
}
}
return errGrp . Err ( )
}
2020-01-28 23:36:54 +00:00
// projectUsagePrice represents pricing for project usage.
type projectUsagePrice struct {
2021-10-20 23:54:34 +01:00
Storage decimal . Decimal
Egress decimal . Decimal
Segments decimal . Decimal
2020-01-28 23:36:54 +00:00
}
// Total returns project usage price total.
func ( price projectUsagePrice ) Total ( ) decimal . Decimal {
2021-10-20 23:54:34 +01:00
return price . Storage . Add ( price . Egress ) . Add ( price . Segments )
2020-01-28 23:36:54 +00:00
}
// Total returns project usage price total.
func ( price projectUsagePrice ) TotalInt64 ( ) int64 {
2021-10-20 23:54:34 +01:00
return price . Storage . Add ( price . Egress ) . Add ( price . Segments ) . IntPart ( )
2020-01-28 23:36:54 +00:00
}
// calculateProjectUsagePrice calculate project usage price.
2021-10-20 23:54:34 +01:00
func ( service * Service ) calculateProjectUsagePrice ( egress int64 , storage , segments float64 ) projectUsagePrice {
2020-01-28 23:36:54 +00:00
return projectUsagePrice {
2021-10-20 23:54:34 +01:00
Storage : service . StorageMBMonthPriceCents . Mul ( storageMBMonthDecimal ( storage ) ) . Round ( 0 ) ,
Egress : service . EgressMBPriceCents . Mul ( egressMBDecimal ( egress ) ) . Round ( 0 ) ,
Segments : service . SegmentMonthPriceCents . Mul ( segmentMonthDecimal ( segments ) ) . Round ( 0 ) ,
2020-01-28 23:36:54 +00:00
}
}
2020-05-08 17:04:04 +01:00
2020-05-19 08:42:07 +01:00
// SetNow allows tests to have the Service act as if the current time is whatever
// they want. This avoids races and sleeping, making tests more reliable and efficient.
func ( service * Service ) SetNow ( now func ( ) time . Time ) {
service . nowFn = now
}
2020-05-26 12:00:14 +01:00
// storageMBMonthDecimal converts storage usage from Byte-Hours to Megabyte-Months.
// The result is rounded to the nearest whole number, but returned as Decimal for convenience.
func storageMBMonthDecimal ( storage float64 ) decimal . Decimal {
return decimal . NewFromFloat ( storage ) . Shift ( - 6 ) . Div ( decimal . NewFromInt ( hoursPerMonth ) ) . Round ( 0 )
}
// egressMBDecimal converts egress usage from bytes to Megabytes
// The result is rounded to the nearest whole number, but returned as Decimal for convenience.
func egressMBDecimal ( egress int64 ) decimal . Decimal {
return decimal . NewFromInt ( egress ) . Shift ( - 6 ) . Round ( 0 )
}
2021-10-20 23:54:34 +01:00
// segmentMonthDecimal converts segments usage from Segment-Hours to Segment-Months.
2020-05-26 12:00:14 +01:00
// The result is rounded to the nearest whole number, but returned as Decimal for convenience.
2021-10-20 23:54:34 +01:00
func segmentMonthDecimal ( segments float64 ) decimal . Decimal {
return decimal . NewFromFloat ( segments ) . Div ( decimal . NewFromInt ( hoursPerMonth ) ) . Round ( 0 )
2020-05-26 12:00:14 +01:00
}