model

package
v0.0.0-...-8a10f5f Latest Latest
Warning

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

Go to latest
Published: Apr 15, 2024 License: MPL-2.0 Imports: 15 Imported by: 0

Documentation

Overview

Package model provides data that the SKUs service operates on.

Index

Constants

View Source
const (
	MerchID             = "brave.com"
	StripePaymentMethod = "stripe"
	RadomPaymentMethod  = "radom"

	// OrderStatus* represent order statuses at runtime and in db.
	OrderStatusCanceled = "canceled"
	OrderStatusPaid     = "paid"
	OrderStatusPending  = "pending"
)

Variables

This section is empty.

Functions

func EnsureEqualPaymentMethods

func EnsureEqualPaymentMethods(methods, incoming []string) error

EnsureEqualPaymentMethods checks if the methods list equals the incoming list.

This operation may change both slices due to sorting.

Types

type CreateCheckoutSessionResponse

type CreateCheckoutSessionResponse struct {
	SessionID string `json:"checkoutSessionId"`
}

CreateCheckoutSessionResponse represents a checkout session response.

func CreateStripeCheckoutSession

func CreateStripeCheckoutSession(
	oid, email, successURI, cancelURI string,
	trialDays int64,
	items []OrderItem,
) (CreateCheckoutSessionResponse, error)

CreateStripeCheckoutSession creates a Stripe checkout session for the order.

func EmptyCreateCheckoutSessionResponse

func EmptyCreateCheckoutSessionResponse() CreateCheckoutSessionResponse

type CreateOrderRequest

type CreateOrderRequest struct {
	Email string             `json:"email" valid:"-"`
	Items []OrderItemRequest `json:"items" valid:"-"`
}

CreateOrderRequest includes information needed to create an order.

type CreateOrderRequestNew

type CreateOrderRequestNew struct {
	Email          string                `json:"email" validate:"required,email"`
	Currency       string                `json:"currency" validate:"required,iso4217"`
	StripeMetadata *OrderStripeMetadata  `json:"stripe_metadata"`
	PaymentMethods []string              `json:"payment_methods"`
	Items          []OrderItemRequestNew `json:"items" validate:"required,gt=0,dive"`
}

CreateOrderRequestNew includes information needed to create an order.

type CreateOrderWithReceiptResponse

type CreateOrderWithReceiptResponse struct {
	ID string `json:"orderId"`
}

type Error

type Error string
const (
	ErrSomethingWentWrong                     Error = "something went wrong"
	ErrOrderNotFound                          Error = "model: order not found"
	ErrOrderItemNotFound                      Error = "model: order item not found"
	ErrIssuerNotFound                         Error = "model: issuer not found"
	ErrNoRowsChangedOrder                     Error = "model: no rows changed in orders"
	ErrNoRowsChangedOrderPayHistory           Error = "model: no rows changed in order_payment_history"
	ErrExpiredStripeCheckoutSessionIDNotFound Error = "model: expired stripeCheckoutSessionId not found"
	ErrInvalidOrderNoItems                    Error = "model: invalid order: no items"
	ErrInvalidOrderNoSuccessURL               Error = "model: invalid order: no success url"
	ErrInvalidOrderNoCancelURL                Error = "model: invalid order: no cancel url"
	ErrInvalidOrderNoProductID                Error = "model: invalid order: no product id"
	ErrNoStripeCheckoutSessID                 Error = "model: order: no stripe checkout session id"

	ErrNumPerIntervalNotSet  Error = "model: invalid order: numPerInterval must be set"
	ErrNumIntervalsNotSet    Error = "model: invalid order: numIntervals must be set"
	ErrInvalidNumPerInterval Error = "model: invalid order: invalid numPerInterval"
	ErrInvalidNumIntervals   Error = "model: invalid order: invalid numIntervals"
	ErrInvalidMobileProduct  Error = "model: invalid mobile product"
	ErrNoMatchOrderReceipt   Error = "model: order_id does not match receipt order"

	// The text of the following errors is preserved as is, in case anything depends on them.
	ErrInvalidSKU              Error = "Invalid SKU Token provided in request"
	ErrDifferentPaymentMethods Error = "all order items must have the same allowed payment methods"
	ErrInvalidOrderRequest     Error = "model: no items to be created"
	ErrReceiptAlreadyLinked    Error = "model: receipt already linked"
)

func (Error) Error

func (e Error) Error() string

type Issuer

type Issuer struct {
	ID         uuid.UUID `json:"id" db:"id"`
	MerchantID string    `json:"merchantId" db:"merchant_id"`
	PublicKey  string    `json:"publicKey" db:"public_key"`
	CreatedAt  time.Time `json:"createdAt" db:"created_at"`
}

Issuer represents a credential issuer.

func (*Issuer) Name

func (x *Issuer) Name() string

Name returns the name of the issuer as known by the challenge bypass server.

type IssuerConfig

type IssuerConfig struct {
	Buffer  int
	Overlap int
}

IssuerConfig holds configuration of an issuer.

func (*IssuerConfig) NumIntervals

func (c *IssuerConfig) NumIntervals() int

type IssuerNew

type IssuerNew struct {
	MerchantID string `db:"merchant_id"`
	PublicKey  string `db:"public_key"`
}

IssuerNew is a request to create an issuer in the database.

type ItemStripeMetadata

type ItemStripeMetadata struct {
	ProductID string `json:"product_id"`
	ItemID    string `json:"item_id"`
}

ItemStripeMetadata holds data about the product in Stripe.

func (*ItemStripeMetadata) Metadata

func (m *ItemStripeMetadata) Metadata() map[string]interface{}

Metadata returns the contents of m as a map for datastore.Metadata.

It can be called when m is nil.

type Order

type Order struct {
	ID                    uuid.UUID            `json:"id" db:"id"`
	CreatedAt             time.Time            `json:"createdAt" db:"created_at"`
	Currency              string               `json:"currency" db:"currency"`
	UpdatedAt             time.Time            `json:"updatedAt" db:"updated_at"`
	TotalPrice            decimal.Decimal      `json:"totalPrice" db:"total_price"`
	MerchantID            string               `json:"merchantId" db:"merchant_id"`
	Location              datastore.NullString `json:"location" db:"location"`
	Status                string               `json:"status" db:"status"`
	Items                 []OrderItem          `json:"items"`
	AllowedPaymentMethods pq.StringArray       `json:"allowedPaymentMethods" db:"allowed_payment_methods"`
	Metadata              datastore.Metadata   `json:"metadata" db:"metadata"`
	LastPaidAt            *time.Time           `json:"lastPaidAt" db:"last_paid_at"`
	ExpiresAt             *time.Time           `json:"expiresAt" db:"expires_at"`
	ValidFor              *time.Duration       `json:"validFor" db:"valid_for"`
	TrialDays             *int64               `json:"-" db:"trial_days"`
}

Order represents an individual order.

func (*Order) CreateRadomCheckoutSession

func (o *Order) CreateRadomCheckoutSession(
	ctx context.Context,
	client radomClient,
	sellerAddr string,
) (CreateCheckoutSessionResponse, error)

CreateRadomCheckoutSession creates a Radom checkout session for o.

func (*Order) CreateRadomCheckoutSessionWithTime

func (o *Order) CreateRadomCheckoutSessionWithTime(
	ctx context.Context,
	client radomClient,
	sellerAddr string,
	expiresAt time.Time,
) (CreateCheckoutSessionResponse, error)

CreateRadomCheckoutSessionWithTime creates a Radom checkout session for o.

TODO: This must be refactored before it's usable. Issues with the current implementation: - it assumes one item per order; - most of the logic does not belong in here; - metadata information must be passed explisictly instead of being parsed (it's known prior to this place); And more.

func (*Order) CreateStripeCheckoutSession deprecated

func (o *Order) CreateStripeCheckoutSession(
	email, successURI, cancelURI string,
	freeTrialDays int64,
) (CreateCheckoutSessionResponse, error)

CreateStripeCheckoutSession creates a Stripe checkout session for the order.

Deprecated: Use CreateStripeCheckoutSession function instead of this method.

func (*Order) GetTrialDays

func (o *Order) GetTrialDays() int64

func (*Order) HasItem

func (o *Order) HasItem(id uuid.UUID) (*OrderItem, bool)

HasItem returns the item if found.

It exposes a comma, ok API similar to a map. Today items are stored in a slice, but it might change to a map in the future.

func (*Order) IsAndroid

func (o *Order) IsAndroid() bool

func (*Order) IsIOS

func (o *Order) IsIOS() bool

func (*Order) IsPaid

func (o *Order) IsPaid() bool

IsPaid returns true if the order is paid.

func (*Order) IsRadomPayable

func (o *Order) IsRadomPayable() bool

IsRadomPayable indicates whether the order is payable by Radom.

func (*Order) IsStripePayable

func (o *Order) IsStripePayable() bool

IsStripePayable returns true if every item is payable by Stripe.

func (*Order) NumIntervals

func (o *Order) NumIntervals() (int, error)

func (*Order) NumPerInterval

func (o *Order) NumPerInterval() (int, error)

func (*Order) PaymentProc

func (o *Order) PaymentProc() (string, bool)

func (*Order) ShouldSetTrialDays

func (o *Order) ShouldSetTrialDays() bool

func (*Order) StripeSubID

func (o *Order) StripeSubID() (string, bool)

func (*Order) Vendor

func (o *Order) Vendor() (Vendor, bool)

type OrderItem

type OrderItem struct {
	ID                        uuid.UUID            `json:"id" db:"id"`
	OrderID                   uuid.UUID            `json:"orderId" db:"order_id"`
	SKU                       string               `json:"sku" db:"sku"`
	CreatedAt                 *time.Time           `json:"createdAt" db:"created_at"`
	UpdatedAt                 *time.Time           `json:"updatedAt" db:"updated_at"`
	Currency                  string               `json:"currency" db:"currency"`
	Quantity                  int                  `json:"quantity" db:"quantity"`
	Price                     decimal.Decimal      `json:"price" db:"price"`
	Subtotal                  decimal.Decimal      `json:"subtotal" db:"subtotal"`
	Location                  datastore.NullString `json:"location" db:"location"`
	Description               datastore.NullString `json:"description" db:"description"`
	CredentialType            string               `json:"credentialType" db:"credential_type"`
	ValidFor                  *time.Duration       `json:"validFor" db:"valid_for"`
	ValidForISO               *string              `json:"validForIso" db:"valid_for_iso"`
	EachCredentialValidForISO *string              `json:"-" db:"each_credential_valid_for_iso"`
	Metadata                  datastore.Metadata   `json:"metadata" db:"metadata"`
	IssuanceIntervalISO       *string              `json:"issuanceInterval" db:"issuance_interval"`

	// TODO: Remove this when products & issuers have been reworked.
	// The issuer for a product must be created when the product is created.
	IssuerConfig *IssuerConfig `json:"-" db:"-"`
}

OrderItem represents a particular order item.

func (*OrderItem) IsLeo

func (x *OrderItem) IsLeo() bool

type OrderItemList

type OrderItemList []OrderItem

func (OrderItemList) SetOrderID

func (l OrderItemList) SetOrderID(orderID uuid.UUID)

func (OrderItemList) TotalCost

func (l OrderItemList) TotalCost() decimal.Decimal

type OrderItemRequest

type OrderItemRequest struct {
	SKU      string `json:"sku" valid:"-"`
	Quantity int    `json:"quantity" valid:"int"`
}

OrderItemRequest represents an item in a order request.

type OrderItemRequestNew

type OrderItemRequestNew struct {
	Quantity                    int                 `json:"quantity" validate:"required,gte=1"`
	IssuerTokenBuffer           int                 `json:"issuer_token_buffer"`
	IssuerTokenOverlap          int                 `json:"issuer_token_overlap"`
	SKU                         string              `json:"sku" validate:"required"`
	Location                    string              `json:"location" validate:"required"`
	Description                 string              `json:"description" validate:"required"`
	CredentialType              string              `json:"credential_type" validate:"required"`
	CredentialValidDuration     string              `json:"credential_valid_duration" validate:"required"`
	Price                       decimal.Decimal     `json:"price"`
	CredentialValidDurationEach *string             `json:"each_credential_valid_duration"`
	IssuanceInterval            *string             `json:"issuance_interval"`
	StripeMetadata              *ItemStripeMetadata `json:"stripe_metadata"`
}

OrderItemRequestNew represents an item in an order request.

func (*OrderItemRequestNew) TokenBufferOrDefault

func (r *OrderItemRequestNew) TokenBufferOrDefault() int

func (*OrderItemRequestNew) TokenOverlapOrDefault

func (r *OrderItemRequestNew) TokenOverlapOrDefault() int

type OrderNew

type OrderNew struct {
	MerchantID            string          `db:"merchant_id"`
	Currency              string          `db:"currency"`
	Status                string          `db:"status"`
	Location              sql.NullString  `db:"location"`
	TotalPrice            decimal.Decimal `db:"total_price"`
	AllowedPaymentMethods pq.StringArray  `db:"allowed_payment_methods"`
	ValidFor              *time.Duration  `db:"valid_for"`
}

OrderNew represents a request to create an order in the database.

type OrderStripeMetadata

type OrderStripeMetadata struct {
	SuccessURI string `json:"success_uri" validate:"http_url"`
	CancelURI  string `json:"cancel_uri" validate:"http_url"`
}

OrderStripeMetadata holds data relevant to the order in Stripe.

func (*OrderStripeMetadata) CancelURL

func (m *OrderStripeMetadata) CancelURL(oid string) (string, error)

func (*OrderStripeMetadata) SuccessURL

func (m *OrderStripeMetadata) SuccessURL(oid string) (string, error)

type OrderTimeBounds

type OrderTimeBounds struct {
	ValidFor *time.Duration `db:"valid_for"`
	LastPaid sql.NullTime   `db:"last_paid_at"`
}

func EmptyOrderTimeBounds

func EmptyOrderTimeBounds() OrderTimeBounds

func (*OrderTimeBounds) ExpiresAt

func (x *OrderTimeBounds) ExpiresAt() time.Time

ExpiresAt computes expiry time, and uses now if last paid was not set before.

func (*OrderTimeBounds) ExpiresAtWithFallback

func (x *OrderTimeBounds) ExpiresAtWithFallback(fallback time.Time) time.Time

ExpiresAtWithFallback computes expiry time, and uses fallback for last paid, if it was not set before.

type ReceiptRequest

type ReceiptRequest struct {
	Type           Vendor `json:"type" validate:"required,oneof=ios android"`
	Blob           string `json:"raw_receipt" validate:"required"`
	Package        string `json:"package" validate:"-"`
	SubscriptionID string `json:"subscription_id" validate:"-"`
}

ReceiptRequest represents a receipt submitted by a mobile or web client.

type Slice

type Slice[T comparable] []T

func (Slice[T]) Contains

func (s Slice[T]) Contains(target T) bool

func (Slice[T]) Equal

func (s Slice[T]) Equal(target []T) bool

type Vendor

type Vendor string

Vendor represents an app store vendor.

const (
	VendorUnknown Vendor = "unknown"
	VendorApple   Vendor = "ios"
	VendorGoogle  Vendor = "android"
)

func (Vendor) String

func (v Vendor) String() string

Jump to

Keyboard shortcuts

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