stripecoinpayments

package
v0.34.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 26, 2020 License: AGPL-3.0 Imports: 23 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// Error defines stripecoinpayments service error.
	Error = errs.Class("stripecoinpayments service error")
	// ErrNoCouponUsages indicates that there are no coupon usages.
	ErrNoCouponUsages = errs.Class("stripecoinpayments no coupon usages")
)
View Source
var ErrChore = errs.Class("stripecoinpayments chore error")

ErrChore is stripecoinpayments clearing loop chore error class.

View Source
var ErrNoCustomer = Error.New("customer doesn't exist")

ErrNoCustomer is error class defining that there is no customer for user.

View Source
var ErrProjectRecordExists = Error.New("invoice project record already exists")

ErrProjectRecordExists is error class defining that such project record already exists.

View Source
var ErrTransactionConsumed = errs.New("error transaction already consumed")

ErrTransactionConsumed is thrown when trying to consume already consumed transaction.

View Source
var ErrVersion = errs.Class("version service error")

ErrVersion defines version service error.

Functions

This section is empty.

Types

type Chore added in v0.25.0

type Chore struct {
	TransactionCycle    *sync2.Cycle
	AccountBalanceCycle *sync2.Cycle
	// contains filtered or unexported fields
}

Chore runs clearing process of reconciling transactions deposits, customer balance, invoices and usages.

architecture: Chore

func NewChore added in v0.25.0

func NewChore(log *zap.Logger, service *Service, txInterval, accBalanceInterval time.Duration) *Chore

NewChore creates new clearing loop chore. TODO: uncomment new interval when coupons will be finished.

func (*Chore) Close added in v0.25.0

func (chore *Chore) Close() (err error)

Close closes all underlying resources.

func (*Chore) Run added in v0.25.0

func (chore *Chore) Run(ctx context.Context) (err error)

Run runs all clearing related cycles.

type Config

type Config struct {
	StripeSecretKey              string        `help:"stripe API secret key" default:""`
	StripePublicKey              string        `help:"stripe API public key" default:""`
	CoinpaymentsPublicKey        string        `help:"coinpayments API public key" default:""`
	CoinpaymentsPrivateKey       string        `help:"coinpayments API private key key" default:""`
	TransactionUpdateInterval    time.Duration `help:"amount of time we wait before running next transaction update loop" devDefault:"1m" releaseDefault:"30m"`
	AccountBalanceUpdateInterval time.Duration `help:"amount of time we wait before running next account balance update loop" devDefault:"3m" releaseDefault:"1h30m"`
	ConversionRatesCycleInterval time.Duration `help:"amount of time we wait before running next conversion rates update loop" devDefault:"1m" releaseDefault:"10m"`
}

Config stores needed information for payment service initialization.

type CouponUsage added in v0.27.0

type CouponUsage struct {
	CouponID uuid.UUID
	Amount   int64
	Status   CouponUsageStatus
	Period   time.Time
}

CouponUsage stores amount of money that should be charged from coupon for billing period.

type CouponUsagePage added in v0.30.0

type CouponUsagePage struct {
	Usages     []CouponUsage
	Next       bool
	NextOffset int64
}

CouponUsagePage holds coupons usages and indicates if there is more data available and provides next offset.

type CouponUsageStatus added in v0.30.0

type CouponUsageStatus int

CouponUsageStatus indicates the state of the coupon usage.

const (
	// CouponUsageStatusUnapplied is a default coupon usage state.
	CouponUsageStatusUnapplied CouponUsageStatus = 0
	// CouponUsageStatusApplied status indicates that coupon usage was used.
	CouponUsageStatusApplied CouponUsageStatus = 1
)

type CouponsDB added in v0.27.0

type CouponsDB interface {
	// Insert inserts a coupon into the database.
	Insert(ctx context.Context, coupon payments.Coupon) error
	// Update updates coupon in database.
	Update(ctx context.Context, couponID uuid.UUID, status payments.CouponStatus) error
	// Get returns coupon by ID.
	Get(ctx context.Context, couponID uuid.UUID) (payments.Coupon, error)
	// List returns all coupons with specified status.
	List(ctx context.Context, status payments.CouponStatus) ([]payments.Coupon, error)
	// ListByUserID returns all coupons of specified user.
	ListByUserID(ctx context.Context, userID uuid.UUID) ([]payments.Coupon, error)
	// ListByUserIDAndStatus returns all coupons of specified user and status.
	ListByUserIDAndStatus(ctx context.Context, userID uuid.UUID, status payments.CouponStatus) ([]payments.Coupon, error)
	// ListByProjectID returns all active coupons for specified project.
	ListByProjectID(ctx context.Context, projectID uuid.UUID) ([]payments.Coupon, error)
	// ListPending returns paginated list of coupons with specified status.
	ListPaged(ctx context.Context, offset int64, limit int, before time.Time, status payments.CouponStatus) (payments.CouponsPage, error)

	// AddUsage creates new coupon usage record in database.
	AddUsage(ctx context.Context, usage CouponUsage) error
	// TotalUsage gets sum of all usage records for specified coupon.
	TotalUsage(ctx context.Context, couponID uuid.UUID) (int64, error)
	// GetLatest return period_end of latest coupon charge.
	GetLatest(ctx context.Context, couponID uuid.UUID) (time.Time, error)
	// ListUnapplied returns coupon usage page with unapplied coupon usages.
	ListUnapplied(ctx context.Context, offset int64, limit int, before time.Time) (CouponUsagePage, error)
	// ApplyUsage applies coupon usage and updates its status.
	ApplyUsage(ctx context.Context, couponID uuid.UUID, period time.Time) error

	// PopulatePromotionalCoupons is used to populate promotional coupons through all active users who already have a project
	// and do not have a promotional coupon yet. And updates project limits to selected size.
	PopulatePromotionalCoupons(ctx context.Context, users []uuid.UUID, duration int, amount int64, projectLimit memory.Size) error
}

CouponsDB is an interface for managing coupons table.

architecture: Database

type CreateProjectRecord added in v0.25.0

type CreateProjectRecord struct {
	ProjectID uuid.UUID
	Storage   float64
	Egress    int64
	Objects   float64
}

CreateProjectRecord holds info needed for creation new invoice project record.

type CreditsDB added in v0.33.2

type CreditsDB interface {
	// InsertCredit inserts credit to user's credit balance into the database.
	InsertCredit(ctx context.Context, credit payments.Credit) error
	// GetCredit returns credit by transactionID.
	GetCredit(ctx context.Context, transactionID coinpayments.TransactionID) (_ payments.Credit, err error)
	// ListCredits returns all credits of specific user.
	ListCredits(ctx context.Context, userID uuid.UUID) ([]payments.Credit, error)
	// ListCreditsPaged returns all credits of specific user.
	ListCreditsPaged(ctx context.Context, offset int64, limit int, before time.Time, userID uuid.UUID) (payments.CreditsPage, error)

	// InsertCreditsSpending inserts spending to user's spending list into the database.
	InsertCreditsSpending(ctx context.Context, spending CreditsSpending) error
	// ListCreditsSpendings returns spending received for concrete deposit.
	ListCreditsSpendings(ctx context.Context, userID uuid.UUID) ([]CreditsSpending, error)
	// ListCreditsSpendingsPaged returns all spending of specific user.
	ListCreditsSpendingsPaged(ctx context.Context, status int, offset int64, limit int, before time.Time) (CreditsSpendingsPage, error)
	// ApplyCreditsSpending updated spending's status.
	ApplyCreditsSpending(ctx context.Context, spendingID uuid.UUID) (err error)

	// Balance returns difference between all credits and creditsSpendings of specific user.
	Balance(ctx context.Context, userID uuid.UUID) (int64, error)
}

CreditsDB is an interface for managing credits table.

architecture: Database

type CreditsSpending added in v0.33.2

type CreditsSpending struct {
	ID        uuid.UUID             `json:"id"`
	ProjectID uuid.UUID             `json:"projectId"`
	UserID    uuid.UUID             `json:"userId"`
	Amount    int64                 `json:"amount"`
	Status    CreditsSpendingStatus `json:"status"`
	Created   time.Time             `json:"created"`
}

CreditsSpending is an entity that holds funds been used from Accounts bonus credit balance. Status shows if spending have been used to pay for invoice already or not.

type CreditsSpendingStatus added in v0.33.2

type CreditsSpendingStatus int

CreditsSpendingStatus indicates the state of the creditsSpending.

const (
	// CreditsSpendingStatusUnapplied is a default creditsSpending state.
	CreditsSpendingStatusUnapplied CreditsSpendingStatus = 0
	// CreditsSpendingStatusApplied status indicates that spending was applied.
	CreditsSpendingStatusApplied CreditsSpendingStatus = 1
)

type CreditsSpendingsPage added in v0.33.2

type CreditsSpendingsPage struct {
	Spendings  []CreditsSpending
	Next       bool
	NextOffset int64
}

CreditsSpendingsPage holds set of creditsSpendings and indicates if there are more creditsSpendings to fetch.

type Customer added in v0.25.0

type Customer struct {
	ID     string
	UserID uuid.UUID
}

Customer holds customer id and user id.

type CustomersDB

type CustomersDB interface {
	// Insert inserts a stripe customer into the database.
	Insert(ctx context.Context, userID uuid.UUID, customerID string) error
	// GetCustomerID return stripe customers id.
	GetCustomerID(ctx context.Context, userID uuid.UUID) (string, error)
	// List returns page with customers ids created before specified date.
	List(ctx context.Context, offset int64, limit int, before time.Time) (CustomersPage, error)
}

CustomersDB is interface for working with stripe customers table.

architecture: Database

type CustomersPage added in v0.25.0

type CustomersPage struct {
	Customers  []Customer
	Next       bool
	NextOffset int64
}

CustomersPage holds customers and indicates if there is more data available and provides next offset.

type DB added in v0.25.0

type DB interface {
	// Customers is getter for customers db.
	Customers() CustomersDB
	// Transactions is getter for transactions db.
	Transactions() TransactionsDB
	// ProjectRecords is getter for invoice project records db.
	ProjectRecords() ProjectRecordsDB
	// Coupons is getter for coupons db.
	Coupons() CouponsDB
	// Credits is getter for credits db.
	Credits() CreditsDB
}

DB is stripecoinpayments DB interface.

architecture: Database

type Endpoint added in v0.25.0

type Endpoint struct {
	// contains filtered or unexported fields
}

Endpoint is stripecoinpayments private RPC server payments endpoint.

func NewEndpoint added in v0.25.0

func NewEndpoint(service *Service) *Endpoint

NewEndpoint creates new endpoint.

func (*Endpoint) ApplyInvoiceCoupons added in v0.30.0

func (endpoint *Endpoint) ApplyInvoiceCoupons(ctx context.Context, req *pb.ApplyInvoiceCouponsRequest) (_ *pb.ApplyInvoiceCouponsResponse, err error)

ApplyInvoiceCoupons creates stripe line items for all unapplied coupons.

func (*Endpoint) ApplyInvoiceCredits added in v0.34.1

func (endpoint *Endpoint) ApplyInvoiceCredits(ctx context.Context, req *pb.ApplyInvoiceCreditsRequest) (_ *pb.ApplyInvoiceCreditsResponse, err error)

ApplyInvoiceCredits creates stripe line items for all credits.

func (*Endpoint) ApplyInvoiceRecords added in v0.25.0

func (endpoint *Endpoint) ApplyInvoiceRecords(ctx context.Context, req *pb.ApplyInvoiceRecordsRequest) (_ *pb.ApplyInvoiceRecordsResponse, err error)

ApplyInvoiceRecords creates stripe line items for all unapplied invoice project records.

func (*Endpoint) CreateInvoices added in v0.25.0

func (endpoint *Endpoint) CreateInvoices(ctx context.Context, req *pb.CreateInvoicesRequest) (_ *pb.CreateInvoicesResponse, err error)

CreateInvoices creates invoice for all user accounts on the satellite.

func (*Endpoint) PrepareInvoiceRecords added in v0.25.0

func (endpoint *Endpoint) PrepareInvoiceRecords(ctx context.Context, req *pb.PrepareInvoiceRecordsRequest) (_ *pb.PrepareInvoiceRecordsResponse, err error)

PrepareInvoiceRecords creates project invoice records for all satellite projects.

type ProjectRecord added in v0.25.0

type ProjectRecord struct {
	ID          uuid.UUID
	ProjectID   uuid.UUID
	Storage     float64
	Egress      int64
	Objects     float64
	PeriodStart time.Time
	PeriodEnd   time.Time
}

ProjectRecord holds project usage particular for billing period.

type ProjectRecordsDB added in v0.25.0

type ProjectRecordsDB interface {
	// Create creates new invoice project record with coupon usages and credits spendings in the DB.
	Create(ctx context.Context, records []CreateProjectRecord, couponUsages []CouponUsage, creditsSpendings []CreditsSpending, start, end time.Time) error
	// Check checks if invoice project record for specified project and billing period exists.
	Check(ctx context.Context, projectID uuid.UUID, start, end time.Time) error
	// Get returns record for specified project and billing period.
	Get(ctx context.Context, projectID uuid.UUID, start, end time.Time) (*ProjectRecord, error)
	// Consume consumes invoice project record.
	Consume(ctx context.Context, id uuid.UUID) error
	// ListUnapplied returns project records page with unapplied project records.
	ListUnapplied(ctx context.Context, offset int64, limit int, before time.Time) (ProjectRecordsPage, error)
}

ProjectRecordsDB is interface for working with invoice project records.

architecture: Database

type ProjectRecordsPage added in v0.25.0

type ProjectRecordsPage struct {
	Records    []ProjectRecord
	Next       bool
	NextOffset int64
}

ProjectRecordsPage holds project records and indicates if there is more data available and provides next offset.

type Service

type Service struct {
	ByteHourCents   decimal.Decimal
	EgressByteCents decimal.Decimal
	ObjectHourCents decimal.Decimal
	// BonusRate amount of percents
	BonusRate int64
	// contains filtered or unexported fields
}

Service is an implementation for payment service via Stripe and Coinpayments.

architecture: Service

func NewService

func NewService(log *zap.Logger, config Config, db DB, projectsDB console.Projects, usageDB accounting.ProjectAccounting, storageTBPrice, egressTBPrice, objectPrice string, bonusRate int64) (*Service, error)

NewService creates a Service instance.

func (*Service) Accounts

func (service *Service) Accounts() payments.Accounts

Accounts exposes all needed functionality to manage payment accounts.

func (*Service) CreateInvoices added in v0.25.0

func (service *Service) CreateInvoices(ctx context.Context) (err error)

CreateInvoices lists through all customers and creates invoices.

func (*Service) GetRate added in v0.26.0

func (service *Service) GetRate(ctx context.Context, curr1, curr2 coinpayments.Currency) (_ *big.Float, err error)

GetRate returns conversion rate for specified currencies.

func (*Service) InvoiceApplyCoupons added in v0.27.0

func (service *Service) InvoiceApplyCoupons(ctx context.Context) (err error)

InvoiceApplyCoupons iterates through unapplied project coupons and creates invoice line items for stripe customer.

func (*Service) InvoiceApplyCredits added in v0.34.1

func (service *Service) InvoiceApplyCredits(ctx context.Context) (err error)

InvoiceApplyCredits iterates through credits with status false of project and creates invoice line items for stripe customer.

func (*Service) InvoiceApplyProjectRecords added in v0.25.0

func (service *Service) InvoiceApplyProjectRecords(ctx context.Context) (err error)

InvoiceApplyProjectRecords iterates through unapplied invoice project records and creates invoice line items for stripe customer.

func (*Service) PrepareInvoiceProjectRecords added in v0.25.0

func (service *Service) PrepareInvoiceProjectRecords(ctx context.Context, period time.Time) (err error)

PrepareInvoiceProjectRecords iterates through all projects and creates invoice records if none exists.

func (*Service) UpdateRates added in v0.26.0

func (service *Service) UpdateRates(ctx context.Context) (err error)

UpdateRates fetches new rates and updates service rate cache.

type Transaction

type Transaction struct {
	ID        coinpayments.TransactionID
	AccountID uuid.UUID
	Address   string
	Amount    big.Float
	Received  big.Float
	Status    coinpayments.Status
	Key       string
	Timeout   time.Duration
	CreatedAt time.Time
}

Transaction defines coinpayments transaction info that is stored in the DB.

type TransactionAndUserList added in v0.31.4

type TransactionAndUserList map[coinpayments.TransactionID]uuid.UUID

TransactionAndUserList is a composite type for storing userID and txID

func (TransactionAndUserList) IDList added in v0.31.4

IDList returns transaction id list.

type TransactionUpdate

type TransactionUpdate struct {
	TransactionID coinpayments.TransactionID
	Status        coinpayments.Status
	Received      big.Float
}

TransactionUpdate holds transaction update info.

type TransactionsDB

type TransactionsDB interface {
	// Insert inserts new coinpayments transaction into DB.
	Insert(ctx context.Context, tx Transaction) (*Transaction, error)
	// Update updates status and received for set of transactions.
	Update(ctx context.Context, updates []TransactionUpdate, applies coinpayments.TransactionIDList) error
	// Consume marks transaction as consumed, so it won't participate in apply account balance loop.
	Consume(ctx context.Context, id coinpayments.TransactionID) error
	// LockRate locks conversion rate for transaction.
	LockRate(ctx context.Context, id coinpayments.TransactionID, rate *big.Float) error
	// GetLockedRate returns locked conversion rate for transaction or error if non exists.
	GetLockedRate(ctx context.Context, id coinpayments.TransactionID) (*big.Float, error)
	// ListAccount returns all transaction for specific user.
	ListAccount(ctx context.Context, userID uuid.UUID) ([]Transaction, error)
	// ListPending returns TransactionsPage with pending transactions.
	ListPending(ctx context.Context, offset int64, limit int, before time.Time) (TransactionsPage, error)
	// List Unapplied returns TransactionsPage with completed transaction that should be applied to account balance.
	ListUnapplied(ctx context.Context, offset int64, limit int, before time.Time) (TransactionsPage, error)
}

TransactionsDB is an interface which defines functionality of DB which stores coinpayments transactions.

architecture: Database

type TransactionsPage

type TransactionsPage struct {
	Transactions []Transaction
	Next         bool
	NextOffset   int64
}

TransactionsPage holds set of transaction and indicates if there are more transactions to fetch.

func (*TransactionsPage) IDList

IDList returns transaction id list of page's transactions.

type VersionService added in v0.26.0

type VersionService struct {
	Cycle sync2.Cycle
	// contains filtered or unexported fields
}

VersionService updates conversion rates in a loop.

architecture: Service

func NewVersionService added in v0.26.0

func NewVersionService(log *zap.Logger, service *Service, interval time.Duration) *VersionService

NewVersionService creates new instance of VersionService.

func (*VersionService) Close added in v0.26.0

func (version *VersionService) Close() (err error)

Close closes underlying cycle.

func (*VersionService) Run added in v0.26.0

func (version *VersionService) Run(ctx context.Context) (err error)

Run runs loop which updates conversion rates for service.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL