order

package
v1.38.0 Latest Latest
Warning

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

Go to latest
Published: Apr 21, 2026 License: MIT Imports: 47 Imported by: 0

Documentation

Overview

Package order provides the Order model with support for the new db.DB interface. This file contains the modernized Order implementation that works with SQLite and PostgreSQL backends through the unified db.DB abstraction.

Package order provides the Order model and repository. This file contains the OrderRepository for querying orders using the db.DB interface.

Package order provides the Order model. This file contains SQL schema definitions for orders when using the structured table approach (vs JSON entity storage).

Index

Constants

View Source
const (
	// Default mode is a simple purchase of product
	DefaultMode Mode = ""

	// Deposit mode is a transfer of funds for platform credit based
	// on subtotal
	DepositMode = "deposit"

	// Contribution mode is a simple transfer of funds
	ContributionMode = "contribution"
)

Variables

View Source
var AlreadyReservedError = errors.New("Product is reserved.")
View Source
var IgnoreFieldMismatch = datastore.IgnoreFieldMismatch
View Source
var Migrations = []Migration{
	{
		Version:     1,
		Description: "Create orders table",
		Up:          Schema.SQLite,
		Down:        "DROP TABLE IF EXISTS orders",
	},
	{
		Version:     2,
		Description: "Add wallet fields",
		Up: `
			ALTER TABLE orders ADD COLUMN wallet_id TEXT;
			ALTER TABLE orders ADD COLUMN wallet_passphrase TEXT;
		`,
		Down: `
			ALTER TABLE orders DROP COLUMN wallet_id;
			ALTER TABLE orders DROP COLUMN wallet_passphrase;
		`,
	},
	{
		Version:     3,
		Description: "Add analytics fields",
		Up: `
			ALTER TABLE orders ADD COLUMN utm_source TEXT;
			ALTER TABLE orders ADD COLUMN utm_medium TEXT;
			ALTER TABLE orders ADD COLUMN utm_campaign TEXT;
			ALTER TABLE orders ADD COLUMN utm_term TEXT;
			ALTER TABLE orders ADD COLUMN utm_content TEXT;
		`,
		Down: `
			ALTER TABLE orders DROP COLUMN utm_source;
			ALTER TABLE orders DROP COLUMN utm_medium;
			ALTER TABLE orders DROP COLUMN utm_campaign;
			ALTER TABLE orders DROP COLUMN utm_term;
			ALTER TABLE orders DROP COLUMN utm_content;
		`,
	},
}

Migrations contains SQL migrations for the orders table

View Source
var PendingReservationError = errors.New("Product is already being reserved.")
View Source
var Schema = struct {
	SQLite     string
	PostgreSQL string
}{
	SQLite: `
		-- Orders table for SQLite
		CREATE TABLE IF NOT EXISTS orders (
			id TEXT PRIMARY KEY,
			number INTEGER,

			-- References
			store_id TEXT,
			campaign_id TEXT,
			user_id TEXT,
			email TEXT,
			cart_id TEXT,
			referrer_id TEXT,
			referral_id TEXT,

			-- Status
			status TEXT NOT NULL DEFAULT 'open',
			payment_status TEXT NOT NULL DEFAULT 'unpaid',
			preorder INTEGER DEFAULT 0,
			unconfirmed INTEGER DEFAULT 0,

			-- Payment
			currency TEXT NOT NULL DEFAULT 'usd',
			payment_type TEXT,
			payment_method_id TEXT,
			mode TEXT,
			shipping_method TEXT,

			-- Amounts (in cents)
			line_total INTEGER DEFAULT 0,
			taxable_line_total INTEGER DEFAULT 0,
			discount INTEGER DEFAULT 0,
			subtotal INTEGER DEFAULT 0,
			shipping INTEGER DEFAULT 0,
			tax INTEGER DEFAULT 0,
			adjustment INTEGER DEFAULT 0,
			total INTEGER DEFAULT 0,
			balance INTEGER DEFAULT 0,
			paid INTEGER DEFAULT 0,
			refunded INTEGER DEFAULT 0,

			-- Addresses (JSON)
			company TEXT,
			billing_address JSON,
			shipping_address JSON,

			-- Items and Discounts (JSON arrays)
			items JSON,
			adjustments JSON,
			discounts JSON,
			coupons JSON,
			coupon_codes JSON,
			payment_ids JSON,

			-- Dates
			created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
			updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
			cancelled_at DATETIME,

			-- Fulfillment (JSON)
			fulfillment JSON,
			return_ids JSON,

			-- Gift options
			gift INTEGER DEFAULT 0,
			gift_message TEXT,
			gift_email TEXT,

			-- Token sales
			token_sale_id TEXT,

			-- Integrations (JSON)
			mailchimp JSON,
			notifications JSON,
			metadata JSON,
			history JSON,

			-- Flags
			test INTEGER DEFAULT 0,
			deleted INTEGER DEFAULT 0,
			version INTEGER DEFAULT 1,

			-- Subscriptions
			subscriptions JSON,

			-- Form/Template
			form_id TEXT,
			template_id TEXT
		);

		-- Indexes for common queries
		CREATE INDEX IF NOT EXISTS idx_orders_user_id ON orders(user_id);
		CREATE INDEX IF NOT EXISTS idx_orders_email ON orders(email);
		CREATE INDEX IF NOT EXISTS idx_orders_status ON orders(status);
		CREATE INDEX IF NOT EXISTS idx_orders_payment_status ON orders(payment_status);
		CREATE INDEX IF NOT EXISTS idx_orders_store_id ON orders(store_id);
		CREATE INDEX IF NOT EXISTS idx_orders_campaign_id ON orders(campaign_id);
		CREATE INDEX IF NOT EXISTS idx_orders_referrer_id ON orders(referrer_id);
		CREATE INDEX IF NOT EXISTS idx_orders_created_at ON orders(created_at);
		CREATE INDEX IF NOT EXISTS idx_orders_deleted ON orders(deleted);
		CREATE INDEX IF NOT EXISTS idx_orders_test ON orders(test);
		CREATE INDEX IF NOT EXISTS idx_orders_number ON orders(number);
	`,

	PostgreSQL: `
		-- Orders table for PostgreSQL
		CREATE TABLE IF NOT EXISTS orders (
			id TEXT PRIMARY KEY,
			number INTEGER,

			-- References
			store_id TEXT,
			campaign_id TEXT,
			user_id TEXT,
			email TEXT,
			cart_id TEXT,
			referrer_id TEXT,
			referral_id TEXT,

			-- Status
			status TEXT NOT NULL DEFAULT 'open',
			payment_status TEXT NOT NULL DEFAULT 'unpaid',
			preorder BOOLEAN DEFAULT FALSE,
			unconfirmed BOOLEAN DEFAULT FALSE,

			-- Payment
			currency TEXT NOT NULL DEFAULT 'usd',
			payment_type TEXT,
			payment_method_id TEXT,
			mode TEXT,
			shipping_method TEXT,

			-- Amounts (in cents)
			line_total BIGINT DEFAULT 0,
			taxable_line_total BIGINT DEFAULT 0,
			discount BIGINT DEFAULT 0,
			subtotal BIGINT DEFAULT 0,
			shipping BIGINT DEFAULT 0,
			tax BIGINT DEFAULT 0,
			adjustment BIGINT DEFAULT 0,
			total BIGINT DEFAULT 0,
			balance BIGINT DEFAULT 0,
			paid BIGINT DEFAULT 0,
			refunded BIGINT DEFAULT 0,

			-- Addresses
			company TEXT,
			billing_address JSONB,
			shipping_address JSONB,

			-- Items and Discounts
			items JSONB DEFAULT '[]'::JSONB,
			adjustments JSONB DEFAULT '[]'::JSONB,
			discounts JSONB DEFAULT '[]'::JSONB,
			coupons JSONB DEFAULT '[]'::JSONB,
			coupon_codes JSONB DEFAULT '[]'::JSONB,
			payment_ids JSONB DEFAULT '[]'::JSONB,

			-- Dates
			created_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP,
			updated_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP,
			cancelled_at TIMESTAMPTZ,

			-- Fulfillment
			fulfillment JSONB,
			return_ids JSONB DEFAULT '[]'::JSONB,

			-- Gift options
			gift BOOLEAN DEFAULT FALSE,
			gift_message TEXT,
			gift_email TEXT,

			-- Token sales
			token_sale_id TEXT,

			-- Integrations
			mailchimp JSONB,
			notifications JSONB,
			metadata JSONB DEFAULT '{}'::JSONB,
			history JSONB DEFAULT '[]'::JSONB,

			-- Flags
			test BOOLEAN DEFAULT FALSE,
			deleted BOOLEAN DEFAULT FALSE,
			version INTEGER DEFAULT 1,

			-- Subscriptions
			subscriptions JSONB DEFAULT '[]'::JSONB,

			-- Form/Template
			form_id TEXT,
			template_id TEXT
		);

		-- Indexes for common queries
		CREATE INDEX IF NOT EXISTS idx_orders_user_id ON orders(user_id);
		CREATE INDEX IF NOT EXISTS idx_orders_email ON orders(email);
		CREATE INDEX IF NOT EXISTS idx_orders_status ON orders(status);
		CREATE INDEX IF NOT EXISTS idx_orders_payment_status ON orders(payment_status);
		CREATE INDEX IF NOT EXISTS idx_orders_store_id ON orders(store_id);
		CREATE INDEX IF NOT EXISTS idx_orders_campaign_id ON orders(campaign_id);
		CREATE INDEX IF NOT EXISTS idx_orders_referrer_id ON orders(referrer_id);
		CREATE INDEX IF NOT EXISTS idx_orders_created_at ON orders(created_at);
		CREATE INDEX IF NOT EXISTS idx_orders_deleted ON orders(deleted);
		CREATE INDEX IF NOT EXISTS idx_orders_test ON orders(test);
		CREATE INDEX IF NOT EXISTS idx_orders_number ON orders(number);

		-- GIN indexes for JSONB columns
		CREATE INDEX IF NOT EXISTS idx_orders_metadata ON orders USING GIN (metadata);
		CREATE INDEX IF NOT EXISTS idx_orders_items ON orders USING GIN (items);
	`,
}

Schema contains SQL schema for orders supporting both SQLite and PostgreSQL

Functions

func Query

Types

type Document

type Document struct {
	mixin.DocumentSaveLoad `datastore:"-" json:"-"`

	// Special Kind Option
	Kind string `search:",facet"`

	Id_           string
	Number        float64
	Email         string
	EmailPartials string
	UserId        string
	StoreId       string
	CampaignId    string
	CartId        string
	ReferrerId    string

	ProductNames string
	ProductIds   string
	ProductSlugs string

	BillingAddressName        string
	BillingAddressLine1       string
	BillingAddressLine2       string
	BillingAddressCity        string
	BillingAddressStateCode   string
	BillingAddressState       string
	BillingAddressCountryCode string
	BillingAddressCountry     string
	BillingAddressPostalCode  string

	ShippingAddressName        string
	ShippingAddressLine1       string
	ShippingAddressLine2       string
	ShippingAddressCity        string
	ShippingAddressStateCode   string
	ShippingAddressState       string
	ShippingAddressCountryCode string
	ShippingAddressCountry     string
	ShippingAddressPostalCode  string

	Discount   float64
	Subtotal   float64
	Shipping   float64
	Tax        float64
	Adjustment float64
	Total      float64
	Paid       float64
	Refunded   float64

	Type string

	CouponCodes string

	Status            string
	PaymentStatus     string
	FulfillmentStatus string

	FulfillmentTracking   string
	FulfillmentExternalId string
	FulfillmentService    string
	FulfillmentCarrier    string

	CreatedAt float64
	UpdatedAt float64

	Test string

	// Facets
	ProductNameOption0 string `search:"productName,facet"`
	ProductNameOption1 string `search:"productName,facet"`
	ProductNameOption2 string `search:"productName,facet"`
	ProductNameOption3 string `search:"productName,facet"`
	ProductNameOption4 string `search:"productName,facet"`
	ProductNameOption5 string `search:"productName,facet"`
	ProductNameOption6 string `search:"productName,facet"`
	ProductNameOption7 string `search:"productName,facet"`
	ProductNameOption8 string `search:"productName,facet"`
	ProductNameOption9 string `search:"productName,facet"`

	BillingAddressCityOption       string `search:"billingAddressCity,facet"`
	BillingAddressStateOption      string `search:"billingAddressState,facet"`
	BillingAddressPostalCodeOption string `search:"billingAddressPostalCode,facet"`
	BillingAddressCountryOption    string `search:"billingAddressCountry,facet"`

	ShippingAddressCityOption       string `search:"shippingAddressCity,facet"`
	ShippingAddressStateOption      string `search:"shippingAddressState,facet"`
	ShippingAddressPostalCodeOption string `search:"shippingAddressPostalCode,facet"`
	ShippingAddressCountryOption    string `search:"shippingAddressCountry,facet"`

	DiscountOption   float64 `search:"discount,facet"`
	SubtotalOption   float64 `search:"subtotal,facet"`
	ShippingOption   float64 `search:"shipping,facet"`
	TaxOption        float64 `search:"tax,facet"`
	AdjustmentOption float64 `search:"adjustment,facet"`
	TotalOption      float64 `search:"total,facet"`
	PaidOption       float64 `search:"paid,facet"`
	RefundedOption   float64 `search:"refunded,facet"`

	TypeOption        string `search:"type,facet"`
	CouponCodeOption0 string `search:"couponCode,facet"`

	StatusOption            string `search:"status,facet"`
	PaymentStatusOption     string `search:"paymentStatus,facet"`
	FulfillmentStatusOption string `search:"fulfillmentStatus,facet"`
	PreorderOption          string `search:"preorder,facet"`
	ConfirmedOption         string `search:"confirmed,facet"`

	FulfillmentTrackingOption0 string `search:"fulfillmentTracking,facet"`
	FulfillmentTrackingOption1 string `search:"fulfillmentTracking,facet"`
	FulfillmentTrackingOption2 string `search:"fulfillmentTracking,facet"`
}

func (*Document) Id

func (d *Document) Id() string

func (*Document) Init

func (d *Document) Init()

type EmailNotificationPrefs

type EmailNotificationPrefs struct {
	Enabled    bool   `json:"enabled"`
	TemplateID string `json:"templateId"`
	ProviderID string `json:"providerId"`
}

EmailNotificationPrefs holds email notification settings

type MailchimpTracking

type MailchimpTracking struct {
	ID           string `json:"id,omitempty"`
	CampaignID   string `json:"campaignId,omitempty"`
	TrackingCode string `json:"trackingCode,omitempty"`
}

MailchimpTracking holds Mailchimp integration data

type Migration

type Migration struct {
	Version     int
	Description string
	Up          string
	Down        string
}

Migration represents a database migration

type MigrationManager

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

MigrationManager handles database migrations

func NewMigrationManager

func NewMigrationManager(database *sql.DB) *MigrationManager

NewMigrationManager creates a new migration manager

func (*MigrationManager) EnsureMigrationTable

func (mm *MigrationManager) EnsureMigrationTable(ctx context.Context) error

EnsureMigrationTable creates the migration tracking table

func (*MigrationManager) GetAppliedVersions

func (mm *MigrationManager) GetAppliedVersions(ctx context.Context) ([]int, error)

GetAppliedVersions returns all applied migration versions

func (*MigrationManager) Migrate

func (mm *MigrationManager) Migrate(ctx context.Context) error

Migrate runs all pending migrations

func (*MigrationManager) Rollback

func (mm *MigrationManager) Rollback(ctx context.Context) error

Rollback rolls back the last migration

type Mode

type Mode string

type NotificationPrefs

type NotificationPrefs struct {
	Email EmailNotificationPrefs `json:"email"`
	SMS   SMSNotificationPrefs   `json:"sms"`
}

NotificationPrefs holds notification settings

type Order

type Order struct {
	mixin.Model[Order]
	mixin.Salesforce `json:"-"`
	wallet.WalletHolder

	Number int `json:"number,omitempty"`

	// Store this was sold from (if any)
	StoreId string `json:"storeId,omitempty"`

	// Associated campaign
	CampaignId string `json:"campaignId,omitempty"`

	// Associated user or buyer.
	UserId string `json:"userId,omitempty"`
	Email  string `json:"email,omitempty"`

	// Associated cart
	CartId string `json:"cartId,omitempty"`

	// Associated referrer
	ReferrerId string `json:"referrerId,omitempty"`
	ReferralId string `json:"referralId,omitempty"`

	// Status
	Status        Status         `json:"status"`
	PaymentStatus payment.Status `json:"paymentStatus"`

	// Whether this was a preorder or not
	Preorder bool `json:"preorder"`

	// Order is unconfirmed if user has not declared (either implicitly or
	// explicitly) precise order variant options.
	Unconfirmed bool `json:"unconfirmed,omitempty"`

	// 3-letter ISO currency code (lowercase).
	Currency currency.Type `json:"currency"`

	// Payment processor type - paypal, stripe, etc
	Type accounts.Type `json:"-"` // type,omitempty"`

	// Payment Method Id
	PaymentMethodId string                      `json:"paymentMethodId,omitempty"`
	PaymentMethod   paymentmethod.PaymentMethod `json:"paymentMethod" datastore:"-"`

	// Payment mode
	Mode Mode `json:"mode,omitempty"`

	// Shipping method
	ShippingMethod string `json:"shippingMethod,omitempty"`

	// Sum of the line item amounts. Amount in cents.
	LineTotal currency.Cents `json:"lineTotal"`

	// Sum of line totals less discount. Amount in cents.
	TaxableLineTotal currency.Cents `json:"taxableLineTotal"`

	// Discount amount applied to the order. Amount in cents.
	Discount currency.Cents `json:"discount"`

	// Sum of line totals less discount. Amount in cents.
	Subtotal currency.Cents `json:"subtotal"`

	// Shipping cost applied. Amount in cents.
	Shipping currency.Cents `json:"shipping"`

	// Sales tax applied. Amount in cents.
	Tax currency.Cents `json:"tax"`

	// Price adjustments applied. Amount in cents.
	Adjustment currency.Cents `json:"-"`

	// Total = subtotal + shipping + taxes + adjustments. Amount in cents.
	Total currency.Cents `json:"total"`

	// Amount owed to the seller. Amount in cents.
	Balance currency.Cents `json:"balance,omitempty"`

	// Gross amount paid to the seller. Amount in cents.
	Paid currency.Cents `json:"paid,omitempty"`

	// integer	Amount refunded by the seller. Amount in cents.
	Refunded currency.Cents `json:"refunded"`

	Company         string  `json:"company,omitempty"`
	BillingAddress  Address `json:"billingAddress"`
	ShippingAddress Address `json:"shippingAddress"`

	// Individual line items
	Items  []lineitem.LineItem `json:"items" datastore:"-"`
	Items_ string              `json:"-" datastore:",noindex"`

	Adjustments []Adjustment `json:"-"`

	Discounts  []*discount.Discount `json:"discounts,omitempty" datastore:"-"`
	Discounts_ string               `json:"-" datastore:",noindex"` // need props

	Coupons     []coupon.Coupon `json:"coupons,omitempty" datastore:",noindex"`
	CouponCodes []string        `json:"couponCodes,omitempty" datastore:",noindex"`

	PaymentIds []string           `json:"payments" datastore:",noindex"`
	Payments   []*payment.Payment `json:"-" datastore:"-"`

	// Date order was cancelled at
	CancelledAt time.Time `json:"cancelledAt,omitempty"`

	// Fulfillment information
	Fulfillment fulfillment.Fulfillment `json:"fulfillment"`

	// Return ids
	ReturnIds []string `json:"returnIds" datastore:",noindex"`

	// Gift options
	Gift        bool   `json:"gift,omitempty"`                             // Is this a gift?
	GiftMessage string `json:"giftMessage,omitempty" datastore:",noindex"` // Message to go on gift
	GiftEmail   string `json:"giftEmail,omitempty"`                        // Email for digital gifts

	// Token sales are processed differently, similar to contribution
	TokenSaleId string `json:"tokenSaleId,omitempty"`

	// Mailchimp tracking information
	Mailchimp struct {
		Id           string `json:"id,omitempty" datastore:",noindex"`
		CampaignId   string `json:"campaignId,omitempty"`
		TrackingCode string `json:"trackingCode,omitempty" datastore:",noindex"`
	} `json:"mailchimp,omitempty"`

	// Notification preferences
	Notifications struct {
		Email struct {
			Enabled    bool   `json:"disable"`
			TemplateId string `json:"templateId"`
			ProviderId string `json:"providerId"`
		} `json:"email"`

		SMS struct {
			Enabled bool `json:"enabled"`
		} `json:"sms"`
	} `json:"notifications"`

	// Arbitrary key/value pairs associated with this order
	Metadata  Map    `json:"metadata,omitempty" datastore:"-"`
	Metadata_ string `json:"-" datastore:",noindex"`

	// Series of events that have occured relevant to this order
	History []Event `json:"-" datastore:",noindex"`

	Test bool `json:"test"` // Whether our internal test flag is active or not

	// Passphrase for the wallet accounts the order controls, never send to the client
	WalletPassphrase string `json:"-"`

	Subscriptions []Subscription `json:"subscriptions,omitempty"`

	FormId string `json:"formId,omitempty"`

	TemplateId string `json:"templateId,omitempty"`
}

func Fake

func Fake(db *datastore.Datastore, lis ...lineitem.LineItem) *Order

func New

func New(db *datastore.Datastore) *Order

func (*Order) AddAffiliateFee

func (o *Order) AddAffiliateFee(pricing *pricing.Fees, fees []*fee.Fee) ([]*fee.Fee, error)

func (*Order) AddPartnerFee

func (o *Order) AddPartnerFee(partners []pricing.Partner, fees []*fee.Fee) ([]*fee.Fee, error)

func (*Order) AddPlatformFee

func (o *Order) AddPlatformFee(pricing *pricing.Fees, fees []*fee.Fee) []*fee.Fee

func (*Order) BeforeCreate

func (o *Order) BeforeCreate() error

Hooks

func (*Order) CalcCouponDiscount

func (o *Order) CalcCouponDiscount() currency.Cents

func (*Order) CalcItemCouponTaxableDiscount added in v1.36.4

func (o *Order) CalcItemCouponTaxableDiscount() currency.Cents

CalcItemCouponTaxableDiscount returns the taxable discount from item-specific coupons only. Order-wide coupons (no ProductId/VariantId) do not reduce the taxable base.

func (*Order) CalcRuleDiscount

func (o *Order) CalcRuleDiscount() (currency.Cents, error)

Discount for this order calculated using applicable discount rules

func (*Order) CalculateFees

func (o *Order) CalculateFees(pricing *pricing.Fees, partners []pricing.Partner) (currency.Cents, []*fee.Fee, error)

func (*Order) CancelReservations

func (o *Order) CancelReservations() error

func (*Order) CreateAndTallySubscriptionFromItem

func (o *Order) CreateAndTallySubscriptionFromItem(stor *store.Store, item lineitem.LineItem) Subscription

func (*Order) CreateSubscriptionsFromItems

func (o *Order) CreateSubscriptionsFromItems(stor *store.Store) error

Update order with information from datastore and tally

func (*Order) DedupeCouponCodes

func (o *Order) DedupeCouponCodes()

func (*Order) Defaults

func (o *Order) Defaults()

func (Order) Description

func (o Order) Description() string

func (Order) DescriptionLong

func (o Order) DescriptionLong() string

func (Order) DisplayCreatedAt

func (o Order) DisplayCreatedAt() string

func (Order) DisplayDiscount

func (o Order) DisplayDiscount() string

func (Order) DisplayId

func (o Order) DisplayId() string

func (Order) DisplayRefunded

func (o Order) DisplayRefunded() string

func (Order) DisplayRemaining

func (o Order) DisplayRemaining() string

func (Order) DisplayShipping

func (o Order) DisplayShipping() string

func (Order) DisplaySubtotal

func (o Order) DisplaySubtotal() string

func (Order) DisplayTax

func (o Order) DisplayTax() string

func (Order) DisplayTotal

func (o Order) DisplayTotal() string

func (Order) Document

func (o Order) Document() mixin.Document

func (*Order) GetCoupons

func (o *Order) GetCoupons() error

Get line items from datastore

func (*Order) GetDiscounts

func (o *Order) GetDiscounts() ([]*discount.Discount, error)

func (*Order) GetItemEntities

func (o *Order) GetItemEntities() error

Get line items from datastore

func (Order) GetPaymentMethod

func (o Order) GetPaymentMethod() (*paymentmethod.PaymentMethod, error)

func (Order) GetPayments

func (o Order) GetPayments() ([]*payment.Payment, error)

func (Order) HasDiscount

func (o Order) HasDiscount() bool

Check if there is a discount

func (Order) IntId

func (o Order) IntId() int

func (Order) ItemsJSON

func (o Order) ItemsJSON() string

func (*Order) Load

func (o *Order) Load(ps []datastore.Property) (err error)

func (*Order) MakeReservations

func (o *Order) MakeReservations() error

func (Order) NumberFromId

func (o Order) NumberFromId() int

func (Order) OrderDay

func (o Order) OrderDay() string

func (Order) OrderMonthName

func (o Order) OrderMonthName() string

func (Order) OrderYear

func (o Order) OrderYear() string

func (*Order) Save

func (o *Order) Save() (ps []datastore.Property, err error)

func (*Order) SyncItems

func (o *Order) SyncItems(stor *store.Store)

func (*Order) TallySubtotalWithoutSubscriptions

func (o *Order) TallySubtotalWithoutSubscriptions()

func (*Order) TallyTotalWithoutSubscriptions

func (o *Order) TallyTotalWithoutSubscriptions()

func (*Order) TallyWithoutSubscriptions

func (o *Order) TallyWithoutSubscriptions()

Calculates order totals

func (*Order) UpdateAndTally

func (o *Order) UpdateAndTally(stor *store.Store) error

Update order with information from datastore and tally

func (*Order) UpdateCouponItems

func (o *Order) UpdateCouponItems() error

Update discount using coupon codes/order info. Refactor later when we have more time to think about it

func (*Order) UpdateEntitiesFromStore

func (o *Order) UpdateEntitiesFromStore(stor *store.Store)

Update underlying line item entities using store listings

func (*Order) UpdateItemsFromEntities

func (o *Order) UpdateItemsFromEntities()

Update line items from underlying entities

func (*Order) UpdatePaymentStatus

func (o *Order) UpdatePaymentStatus()

Update order's payment status based on payments

func (*Order) Validator

func (o *Order) Validator() *val.Validator

type OrderDB

type OrderDB struct {
	db.Model

	Number int `json:"number,omitempty"`

	// Store this was sold from (if any)
	StoreID string `json:"storeId,omitempty"`

	// Associated campaign
	CampaignID string `json:"campaignId,omitempty"`

	// Associated user or buyer
	UserID string `json:"userId,omitempty"`
	Email  string `json:"email,omitempty"`

	// Associated cart
	CartID string `json:"cartId,omitempty"`

	// Associated referrer
	ReferrerID string `json:"referrerId,omitempty"`
	ReferralID string `json:"referralId,omitempty"`

	// Status
	Status        Status         `json:"status"`
	PaymentStatus payment.Status `json:"paymentStatus"`

	// Whether this was a preorder
	Preorder bool `json:"preorder"`

	// Order is unconfirmed if user has not declared variant options
	Unconfirmed bool `json:"unconfirmed,omitempty"`

	// 3-letter ISO currency code (lowercase)
	Currency currency.Type `json:"currency"`

	// Payment processor type - paypal, stripe, etc
	Type accounts.Type `json:"type,omitempty"`

	// Payment Method
	PaymentMethodID string                      `json:"paymentMethodId,omitempty"`
	PaymentMethod   paymentmethod.PaymentMethod `json:"-"`

	// Payment mode
	Mode Mode `json:"mode,omitempty"`

	// Shipping method
	ShippingMethod string `json:"shippingMethod,omitempty"`

	// Sum of the line item amounts (cents)
	LineTotal currency.Cents `json:"lineTotal"`

	// Sum of line totals less discount (cents)
	TaxableLineTotal currency.Cents `json:"taxableLineTotal"`

	// Discount amount applied (cents)
	Discount currency.Cents `json:"discount"`

	// Sum of line totals less discount (cents)
	Subtotal currency.Cents `json:"subtotal"`

	// Shipping cost applied (cents)
	Shipping currency.Cents `json:"shipping"`

	// Sales tax applied (cents)
	Tax currency.Cents `json:"tax"`

	// Price adjustments (cents)
	Adjustment currency.Cents `json:"-"`

	// Total = subtotal + shipping + taxes + adjustments (cents)
	Total currency.Cents `json:"total"`

	// Amount owed to the seller (cents)
	Balance currency.Cents `json:"balance,omitempty"`

	// Gross amount paid (cents)
	Paid currency.Cents `json:"paid,omitempty"`

	// Amount refunded (cents)
	Refunded currency.Cents `json:"refunded"`

	// Address information
	Company         string  `json:"company,omitempty"`
	BillingAddress  Address `json:"billingAddress"`
	ShippingAddress Address `json:"shippingAddress"`

	// Line items - stored as JSON
	Items []lineitem.LineItem `json:"items"`

	// Adjustments
	Adjustments []Adjustment `json:"adjustments,omitempty"`

	// Discounts - stored as JSON
	Discounts []*discount.Discount `json:"discounts,omitempty"`

	// Coupons - stored as JSON
	Coupons     []coupon.Coupon `json:"coupons,omitempty"`
	CouponCodes []string        `json:"couponCodes,omitempty"`

	// Payment references
	PaymentIDs []string           `json:"payments"`
	Payments   []*payment.Payment `json:"-"`

	// Date order was cancelled
	CancelledAt time.Time `json:"cancelledAt,omitempty"`

	// Fulfillment information
	Fulfillment fulfillment.Fulfillment `json:"fulfillment"`

	// Return IDs
	ReturnIDs []string `json:"returnIds"`

	// Gift options
	Gift        bool   `json:"gift,omitempty"`
	GiftMessage string `json:"giftMessage,omitempty"`
	GiftEmail   string `json:"giftEmail,omitempty"`

	// Token sales
	TokenSaleID string `json:"tokenSaleId,omitempty"`

	// Mailchimp tracking
	Mailchimp MailchimpTracking `json:"mailchimp,omitempty"`

	// Notification preferences
	Notifications NotificationPrefs `json:"notifications"`

	// Arbitrary key/value pairs
	Metadata Map `json:"metadata,omitempty"`

	// Event history
	History []Event `json:"history,omitempty"`

	// Test flag
	Test bool `json:"test"`

	// Wallet passphrase (never sent to client)
	WalletPassphrase string `json:"-"`

	// Subscriptions
	Subscriptions []Subscription `json:"subscriptions,omitempty"`

	// Form ID
	FormID string `json:"formId,omitempty"`

	// Template ID
	TemplateID string `json:"templateId,omitempty"`
}

OrderDB is the modernized Order model using the new db.DB interface. It provides full compatibility with SQLite and PostgreSQL backends.

func NewOrderDB

func NewOrderDB(database db.DB) *OrderDB

NewOrderDB creates a new Order using the db.DB interface

func (*OrderDB) AddEvent

func (o *OrderDB) AddEvent(eventType, desc string)

AddEvent adds an event to the order history

func (*OrderDB) AddItem

func (o *OrderDB) AddItem(item lineitem.LineItem)

AddItem adds a line item to the order

func (*OrderDB) AfterCreate

func (o *OrderDB) AfterCreate() error

AfterCreate is called after entity creation

func (*OrderDB) ApplyCoupon

func (o *OrderDB) ApplyCoupon(c coupon.Coupon) error

ApplyCoupon applies a coupon to the order

func (*OrderDB) ApplyDiscount

func (o *OrderDB) ApplyDiscount(d *discount.Discount)

ApplyDiscount applies a discount to the order Note: The discount calculation is handled by the discount's Rules/Actions system

func (*OrderDB) BeforeCreate

func (o *OrderDB) BeforeCreate() error

BeforeCreate is called before entity creation

func (*OrderDB) Cancel

func (o *OrderDB) Cancel(ctx context.Context) error

Cancel cancels the order

func (*OrderDB) Clone

func (o *OrderDB) Clone() *OrderDB

Clone creates a copy of the order

func (*OrderDB) Complete

func (o *OrderDB) Complete(ctx context.Context) error

Complete marks the order as completed

func (*OrderDB) Defaults

func (o *OrderDB) Defaults()

Defaults sets default values for a new order

func (*OrderDB) Description

func (o *OrderDB) Description() string

Description returns a string description of the order items

func (*OrderDB) DescriptionLong

func (o *OrderDB) DescriptionLong() string

DescriptionLong returns a detailed description of order items

func (*OrderDB) DisplayCreatedAt

func (o *OrderDB) DisplayCreatedAt() string

DisplayCreatedAt returns human-readable creation time

func (*OrderDB) DisplayDiscount

func (o *OrderDB) DisplayDiscount() string

DisplayDiscount returns formatted discount

func (*OrderDB) DisplayRefunded

func (o *OrderDB) DisplayRefunded() string

DisplayRefunded returns formatted refunded amount

func (*OrderDB) DisplayRemaining

func (o *OrderDB) DisplayRemaining() string

DisplayRemaining returns formatted remaining balance

func (*OrderDB) DisplayShipping

func (o *OrderDB) DisplayShipping() string

DisplayShipping returns formatted shipping

func (*OrderDB) DisplaySubtotal

func (o *OrderDB) DisplaySubtotal() string

DisplaySubtotal returns formatted subtotal

func (*OrderDB) DisplayTax

func (o *OrderDB) DisplayTax() string

DisplayTax returns formatted tax

func (*OrderDB) DisplayTotal

func (o *OrderDB) DisplayTotal() string

DisplayTotal returns formatted total

func (*OrderDB) FromJSON

func (o *OrderDB) FromJSON(data map[string]interface{}) error

FromJSON populates the order from a JSON map

func (*OrderDB) HasDiscount

func (o *OrderDB) HasDiscount() bool

HasDiscount returns true if a discount is applied

func (*OrderDB) ItemsJSON

func (o *OrderDB) ItemsJSON() string

ItemsJSON returns items as JSON string

func (*OrderDB) Kind

func (o *OrderDB) Kind() string

Kind returns the entity kind/table name

func (*OrderDB) NumberFromID

func (o *OrderDB) NumberFromID() int

NumberFromID generates an order number from the ID

func (*OrderDB) RemoveItem

func (o *OrderDB) RemoveItem(id string) bool

RemoveItem removes a line item from the order

func (*OrderDB) Tally

func (o *OrderDB) Tally()

Tally calculates all order totals

func (*OrderDB) ToJSON

func (o *OrderDB) ToJSON() map[string]interface{}

ToJSON returns the order as a JSON map

func (*OrderDB) UpdateItemQuantity

func (o *OrderDB) UpdateItemQuantity(id string, quantity int) bool

UpdateItemQuantity updates the quantity of a line item

func (*OrderDB) UpdatePaymentStatus

func (o *OrderDB) UpdatePaymentStatus(ctx context.Context) error

UpdatePaymentStatus updates the order's payment status based on payments

func (*OrderDB) Validate

func (o *OrderDB) Validate() error

Validate validates the order before saving

type OrderRepository

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

OrderRepository provides methods for querying and managing orders. It uses the db.DB interface to support both SQLite and PostgreSQL backends.

func NewRepository

func NewRepository(database db.DB) *OrderRepository

NewRepository creates a new OrderRepository

func (*OrderRepository) Count

func (r *OrderRepository) Count(ctx context.Context) (int, error)

Count returns the total number of orders

func (*OrderRepository) CountByStatus

func (r *OrderRepository) CountByStatus(ctx context.Context, status Status) (int, error)

CountByStatus returns the count of orders with a specific status

func (*OrderRepository) CountByUserID

func (r *OrderRepository) CountByUserID(ctx context.Context, userID string) (int, error)

CountByUserID returns the count of orders for a user

func (*OrderRepository) Create

func (r *OrderRepository) Create(ctx context.Context, order *OrderDB) error

Create creates a new order

func (*OrderRepository) Delete

func (r *OrderRepository) Delete(ctx context.Context, order *OrderDB) error

Delete soft-deletes an order

func (*OrderRepository) DeleteMulti

func (r *OrderRepository) DeleteMulti(ctx context.Context, ids []string) error

DeleteMulti soft-deletes multiple orders

func (*OrderRepository) GetByCampaignID

func (r *OrderRepository) GetByCampaignID(ctx context.Context, campaignID string, opts *QueryOptions) ([]*OrderDB, error)

GetByCampaignID retrieves orders for a campaign

func (*OrderRepository) GetByDateRange

func (r *OrderRepository) GetByDateRange(ctx context.Context, start, end time.Time, opts *QueryOptions) ([]*OrderDB, error)

GetByDateRange retrieves orders within a date range

func (*OrderRepository) GetByEmail

func (r *OrderRepository) GetByEmail(ctx context.Context, email string, opts *QueryOptions) ([]*OrderDB, error)

GetByEmail retrieves all orders for an email

func (*OrderRepository) GetByID

func (r *OrderRepository) GetByID(ctx context.Context, id string) (*OrderDB, error)

GetByID retrieves an order by its ID

func (*OrderRepository) GetByPaymentStatus

func (r *OrderRepository) GetByPaymentStatus(ctx context.Context, status payment.Status, opts *QueryOptions) ([]*OrderDB, error)

GetByPaymentStatus retrieves orders by payment status

func (*OrderRepository) GetByReferrerID

func (r *OrderRepository) GetByReferrerID(ctx context.Context, referrerID string, opts *QueryOptions) ([]*OrderDB, error)

GetByReferrerID retrieves orders for a referrer

func (*OrderRepository) GetByStatus

func (r *OrderRepository) GetByStatus(ctx context.Context, status Status, opts *QueryOptions) ([]*OrderDB, error)

GetByStatus retrieves orders by status

func (*OrderRepository) GetByStoreID

func (r *OrderRepository) GetByStoreID(ctx context.Context, storeID string, opts *QueryOptions) ([]*OrderDB, error)

GetByStoreID retrieves orders for a store

func (*OrderRepository) GetByUserID

func (r *OrderRepository) GetByUserID(ctx context.Context, userID string, opts *QueryOptions) ([]*OrderDB, error)

GetByUserID retrieves all orders for a user

func (*OrderRepository) GetMulti

func (r *OrderRepository) GetMulti(ctx context.Context, ids []string) ([]*OrderDB, error)

GetMulti retrieves multiple orders by IDs

func (*OrderRepository) GetPendingOrders

func (r *OrderRepository) GetPendingOrders(ctx context.Context, opts *QueryOptions) ([]*OrderDB, error)

GetPendingOrders retrieves orders that need attention

func (*OrderRepository) GetStats

func (r *OrderRepository) GetStats(ctx context.Context, opts *QueryOptions) (*OrderStats, error)

GetStats calculates order statistics

func (*OrderRepository) GetTestOrders

func (r *OrderRepository) GetTestOrders(ctx context.Context, opts *QueryOptions) ([]*OrderDB, error)

GetTestOrders retrieves test orders

func (*OrderRepository) RunInTransaction

func (r *OrderRepository) RunInTransaction(ctx context.Context, fn func(tx db.Transaction) error) error

RunInTransaction executes operations within a transaction

func (*OrderRepository) Search

func (r *OrderRepository) Search(ctx context.Context, criteria *SearchCriteria) ([]*OrderDB, error)

Search searches orders by various criteria

func (*OrderRepository) Update

func (r *OrderRepository) Update(ctx context.Context, order *OrderDB) error

Update updates an existing order

func (*OrderRepository) UpdateMulti

func (r *OrderRepository) UpdateMulti(ctx context.Context, orders []*OrderDB) error

UpdateMulti updates multiple orders

type OrderStats

type OrderStats struct {
	TotalOrders    int            `json:"totalOrders"`
	TotalRevenue   int64          `json:"totalRevenue"`
	AverageOrder   float64        `json:"averageOrder"`
	OrdersByStatus map[Status]int `json:"ordersByStatus"`
}

OrderStats holds order statistics

type QueryOptions

type QueryOptions struct {
	Limit  int
	Offset int
	Cursor db.Cursor
}

QueryOptions provides options for query pagination and filtering

type SMSNotificationPrefs

type SMSNotificationPrefs struct {
	Enabled bool `json:"enabled"`
}

SMSNotificationPrefs holds SMS notification settings

type SchemaManager

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

SchemaManager provides methods for managing order schema

func NewSchemaManager

func NewSchemaManager(database *sql.DB) *SchemaManager

NewSchemaManager creates a new schema manager

func (*SchemaManager) CreateSchema

func (sm *SchemaManager) CreateSchema(ctx context.Context, dialect string) error

CreateSchema creates the orders table and indexes

func (*SchemaManager) DropSchema

func (sm *SchemaManager) DropSchema(ctx context.Context) error

DropSchema drops the orders table

type SearchCriteria

type SearchCriteria struct {
	UserID        string
	Email         string
	Status        Status
	PaymentStatus payment.Status
	StoreID       string
	CampaignID    string
	StartDate     time.Time
	EndDate       time.Time
	MinTotal      int
	MaxTotal      int
	Test          *bool
	SortBy        string
	SortDesc      bool
	Limit         int
	Offset        int
}

SearchCriteria provides criteria for searching orders

type Status

type Status string
const (
	Cancelled Status = "cancelled"
	Completed Status = "completed"
	Locked    Status = "locked"
	OnHold    Status = "on-hold"
	Open      Status = "open"
)

type Subscription

type Subscription struct {
	productcachedvalues.ProductCachedValues

	Subtotal currency.Cents `json:"subtotal"`

	// Discount amount applied to the order. Amount in cents.
	Discount currency.Cents `json:"discount"`

	// Shipping cost applied. Amount in cents.
	Shipping currency.Cents `json:"shipping"`

	// Sales tax applied. Amount in cents.
	Tax currency.Cents `json:"tax"`

	// Price adjustments applied. Amount in cents.
	Adjustment currency.Cents `json:"-"`

	// Total = subtotal + shipping + taxes + adjustments. Amount in cents.
	Total currency.Cents `json:"total"`

	Number int `json:"number,omitempty" datastore:"-"`

	// Immutable buyer data from time of payment, may or may not be associated
	// with a user.
	Buyer Buyer `json:"buyer"`

	Type SubscriptionBillingType `json:"billingType"`

	PlanId    string `json:"planId"`
	UserId    string `json:"userId"`
	ProductId string `json:"productId"`

	FeePercent float64 `json:"applicationFeePercent"`
	EndCancel  bool    `json:"cancelAtPeriodEnd"`

	PeriodStart time.Time `json:"currentPeriodStart"`
	PeriodEnd   time.Time `json:"currentPeriodEnd"`

	Start      time.Time `json:"start"`
	Ended      time.Time `json:"endedAt"`
	Canceled   bool      `json:"canceled"`
	CanceledAt time.Time `json:"canceledAt"`

	TrialStart time.Time `json:"trialStart"`
	TrialEnd   time.Time `json:"trialEnd"`

	Status SubscriptionStatus `json:"status"`

	Account accounts.Account  `json:"account,omitempty"`
	Ref     refs.EcommerceRef `json:"ref,omitempty"`
}

func FakeSubscription

func FakeSubscription(db *datastore.Datastore) *Subscription

func (Subscription) PeriodsRemaining

func (s Subscription) PeriodsRemaining() int

func (Subscription) TrialPeriodsRemaining

func (s Subscription) TrialPeriodsRemaining() int

type SubscriptionBillingType

type SubscriptionBillingType string
const (
	Charge  SubscriptionBillingType = "charge_automatically"
	Invoice SubscriptionBillingType = "send_invoice"
)

type SubscriptionStatus

type SubscriptionStatus string
const (
	TrialingSubscriptionStatus  SubscriptionStatus = "trialing"
	ActiveSubscriptionStatus    SubscriptionStatus = "active"
	PastDueSubscriptionStatus   SubscriptionStatus = "past_due"
	CancelledSubscriptionStatus SubscriptionStatus = "cancelled"
	UnpaidSubscriptionStatus    SubscriptionStatus = "unpaid"
)

Jump to

Keyboard shortcuts

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