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
- Variables
- func Query(db *datastore.Datastore) datastore.Query
- type Document
- type EmailNotificationPrefs
- type MailchimpTracking
- type Migration
- type MigrationManager
- type Mode
- type NotificationPrefs
- type Order
- func (o *Order) AddAffiliateFee(pricing *pricing.Fees, fees []*fee.Fee) ([]*fee.Fee, error)
- func (o *Order) AddPartnerFee(partners []pricing.Partner, fees []*fee.Fee) ([]*fee.Fee, error)
- func (o *Order) AddPlatformFee(pricing *pricing.Fees, fees []*fee.Fee) []*fee.Fee
- func (o *Order) BeforeCreate() error
- func (o *Order) CalcCouponDiscount() currency.Cents
- func (o *Order) CalcItemCouponTaxableDiscount() currency.Cents
- func (o *Order) CalcRuleDiscount() (currency.Cents, error)
- func (o *Order) CalculateFees(pricing *pricing.Fees, partners []pricing.Partner) (currency.Cents, []*fee.Fee, error)
- func (o *Order) CancelReservations() error
- func (o *Order) CreateAndTallySubscriptionFromItem(stor *store.Store, item lineitem.LineItem) Subscription
- func (o *Order) CreateSubscriptionsFromItems(stor *store.Store) error
- func (o *Order) DedupeCouponCodes()
- func (o *Order) Defaults()
- func (o Order) Description() string
- func (o Order) DescriptionLong() string
- func (o Order) DisplayCreatedAt() string
- func (o Order) DisplayDiscount() string
- func (o Order) DisplayId() string
- func (o Order) DisplayRefunded() string
- func (o Order) DisplayRemaining() string
- func (o Order) DisplayShipping() string
- func (o Order) DisplaySubtotal() string
- func (o Order) DisplayTax() string
- func (o Order) DisplayTotal() string
- func (o Order) Document() mixin.Document
- func (o *Order) GetCoupons() error
- func (o *Order) GetDiscounts() ([]*discount.Discount, error)
- func (o *Order) GetItemEntities() error
- func (o Order) GetPaymentMethod() (*paymentmethod.PaymentMethod, error)
- func (o Order) GetPayments() ([]*payment.Payment, error)
- func (o Order) HasDiscount() bool
- func (o Order) IntId() int
- func (o Order) ItemsJSON() string
- func (o *Order) Load(ps []datastore.Property) (err error)
- func (o *Order) MakeReservations() error
- func (o Order) NumberFromId() int
- func (o Order) OrderDay() string
- func (o Order) OrderMonthName() string
- func (o Order) OrderYear() string
- func (o *Order) Save() (ps []datastore.Property, err error)
- func (o *Order) SyncItems(stor *store.Store)
- func (o *Order) TallySubtotalWithoutSubscriptions()
- func (o *Order) TallyTotalWithoutSubscriptions()
- func (o *Order) TallyWithoutSubscriptions()
- func (o *Order) UpdateAndTally(stor *store.Store) error
- func (o *Order) UpdateCouponItems() error
- func (o *Order) UpdateEntitiesFromStore(stor *store.Store)
- func (o *Order) UpdateItemsFromEntities()
- func (o *Order) UpdatePaymentStatus()
- func (o *Order) Validator() *val.Validator
- type OrderDB
- func (o *OrderDB) AddEvent(eventType, desc string)
- func (o *OrderDB) AddItem(item lineitem.LineItem)
- func (o *OrderDB) AfterCreate() error
- func (o *OrderDB) ApplyCoupon(c coupon.Coupon) error
- func (o *OrderDB) ApplyDiscount(d *discount.Discount)
- func (o *OrderDB) BeforeCreate() error
- func (o *OrderDB) Cancel(ctx context.Context) error
- func (o *OrderDB) Clone() *OrderDB
- func (o *OrderDB) Complete(ctx context.Context) error
- func (o *OrderDB) Defaults()
- func (o *OrderDB) Description() string
- func (o *OrderDB) DescriptionLong() string
- func (o *OrderDB) DisplayCreatedAt() string
- func (o *OrderDB) DisplayDiscount() string
- func (o *OrderDB) DisplayRefunded() string
- func (o *OrderDB) DisplayRemaining() string
- func (o *OrderDB) DisplayShipping() string
- func (o *OrderDB) DisplaySubtotal() string
- func (o *OrderDB) DisplayTax() string
- func (o *OrderDB) DisplayTotal() string
- func (o *OrderDB) FromJSON(data map[string]interface{}) error
- func (o *OrderDB) HasDiscount() bool
- func (o *OrderDB) ItemsJSON() string
- func (o *OrderDB) Kind() string
- func (o *OrderDB) NumberFromID() int
- func (o *OrderDB) RemoveItem(id string) bool
- func (o *OrderDB) Tally()
- func (o *OrderDB) ToJSON() map[string]interface{}
- func (o *OrderDB) UpdateItemQuantity(id string, quantity int) bool
- func (o *OrderDB) UpdatePaymentStatus(ctx context.Context) error
- func (o *OrderDB) Validate() error
- type OrderRepository
- func (r *OrderRepository) Count(ctx context.Context) (int, error)
- func (r *OrderRepository) CountByStatus(ctx context.Context, status Status) (int, error)
- func (r *OrderRepository) CountByUserID(ctx context.Context, userID string) (int, error)
- func (r *OrderRepository) Create(ctx context.Context, order *OrderDB) error
- func (r *OrderRepository) Delete(ctx context.Context, order *OrderDB) error
- func (r *OrderRepository) DeleteMulti(ctx context.Context, ids []string) error
- func (r *OrderRepository) GetByCampaignID(ctx context.Context, campaignID string, opts *QueryOptions) ([]*OrderDB, error)
- func (r *OrderRepository) GetByDateRange(ctx context.Context, start, end time.Time, opts *QueryOptions) ([]*OrderDB, error)
- func (r *OrderRepository) GetByEmail(ctx context.Context, email string, opts *QueryOptions) ([]*OrderDB, error)
- func (r *OrderRepository) GetByID(ctx context.Context, id string) (*OrderDB, error)
- func (r *OrderRepository) GetByPaymentStatus(ctx context.Context, status payment.Status, opts *QueryOptions) ([]*OrderDB, error)
- func (r *OrderRepository) GetByReferrerID(ctx context.Context, referrerID string, opts *QueryOptions) ([]*OrderDB, error)
- func (r *OrderRepository) GetByStatus(ctx context.Context, status Status, opts *QueryOptions) ([]*OrderDB, error)
- func (r *OrderRepository) GetByStoreID(ctx context.Context, storeID string, opts *QueryOptions) ([]*OrderDB, error)
- func (r *OrderRepository) GetByUserID(ctx context.Context, userID string, opts *QueryOptions) ([]*OrderDB, error)
- func (r *OrderRepository) GetMulti(ctx context.Context, ids []string) ([]*OrderDB, error)
- func (r *OrderRepository) GetPendingOrders(ctx context.Context, opts *QueryOptions) ([]*OrderDB, error)
- func (r *OrderRepository) GetStats(ctx context.Context, opts *QueryOptions) (*OrderStats, error)
- func (r *OrderRepository) GetTestOrders(ctx context.Context, opts *QueryOptions) ([]*OrderDB, error)
- func (r *OrderRepository) RunInTransaction(ctx context.Context, fn func(tx db.Transaction) error) error
- func (r *OrderRepository) Search(ctx context.Context, criteria *SearchCriteria) ([]*OrderDB, error)
- func (r *OrderRepository) Update(ctx context.Context, order *OrderDB) error
- func (r *OrderRepository) UpdateMulti(ctx context.Context, orders []*OrderDB) error
- type OrderStats
- type QueryOptions
- type SMSNotificationPrefs
- type SchemaManager
- type SearchCriteria
- type Status
- type Subscription
- type SubscriptionBillingType
- type SubscriptionStatus
Constants ¶
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 ¶
var AlreadyReservedError = errors.New("Product is reserved.")
var IgnoreFieldMismatch = datastore.IgnoreFieldMismatch
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
var PendingReservationError = errors.New("Product is already being reserved.")
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 ¶
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"`
}
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 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
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 (*Order) AddAffiliateFee ¶
func (*Order) AddPartnerFee ¶
func (*Order) AddPlatformFee ¶
func (*Order) CalcCouponDiscount ¶
func (*Order) CalcItemCouponTaxableDiscount ¶ added in v1.36.4
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 ¶
Discount for this order calculated using applicable discount rules
func (*Order) CalculateFees ¶
func (*Order) CancelReservations ¶
func (*Order) CreateAndTallySubscriptionFromItem ¶
func (*Order) CreateSubscriptionsFromItems ¶
Update order with information from datastore and tally
func (*Order) DedupeCouponCodes ¶
func (o *Order) DedupeCouponCodes()
func (Order) Description ¶
func (Order) DescriptionLong ¶
func (Order) DisplayCreatedAt ¶
func (Order) DisplayDiscount ¶
func (Order) DisplayRefunded ¶
func (Order) DisplayRemaining ¶
func (Order) DisplayShipping ¶
func (Order) DisplaySubtotal ¶
func (Order) DisplayTax ¶
func (Order) DisplayTotal ¶
func (*Order) GetItemEntities ¶
Get line items from datastore
func (Order) GetPaymentMethod ¶
func (o Order) GetPaymentMethod() (*paymentmethod.PaymentMethod, error)
func (*Order) MakeReservations ¶
func (Order) NumberFromId ¶
func (Order) OrderMonthName ¶
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 ¶
Update order with information from datastore and tally
func (*Order) UpdateCouponItems ¶
Update discount using coupon codes/order info. Refactor later when we have more time to think about it
func (*Order) UpdateEntitiesFromStore ¶
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
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 ¶
NewOrderDB creates a new Order using the db.DB interface
func (*OrderDB) AfterCreate ¶
AfterCreate is called after entity creation
func (*OrderDB) ApplyCoupon ¶
ApplyCoupon applies a coupon to the order
func (*OrderDB) ApplyDiscount ¶
ApplyDiscount applies a discount to the order Note: The discount calculation is handled by the discount's Rules/Actions system
func (*OrderDB) BeforeCreate ¶
BeforeCreate is called before entity creation
func (*OrderDB) Defaults ¶
func (o *OrderDB) Defaults()
Defaults sets default values for a new order
func (*OrderDB) Description ¶
Description returns a string description of the order items
func (*OrderDB) DescriptionLong ¶
DescriptionLong returns a detailed description of order items
func (*OrderDB) DisplayCreatedAt ¶
DisplayCreatedAt returns human-readable creation time
func (*OrderDB) DisplayDiscount ¶
DisplayDiscount returns formatted discount
func (*OrderDB) DisplayRefunded ¶
DisplayRefunded returns formatted refunded amount
func (*OrderDB) DisplayRemaining ¶
DisplayRemaining returns formatted remaining balance
func (*OrderDB) DisplayShipping ¶
DisplayShipping returns formatted shipping
func (*OrderDB) DisplaySubtotal ¶
DisplaySubtotal returns formatted subtotal
func (*OrderDB) DisplayTotal ¶
DisplayTotal returns formatted total
func (*OrderDB) HasDiscount ¶
HasDiscount returns true if a discount is applied
func (*OrderDB) NumberFromID ¶
NumberFromID generates an order number from the ID
func (*OrderDB) RemoveItem ¶
RemoveItem removes a line item from the order
func (*OrderDB) UpdateItemQuantity ¶
UpdateItemQuantity updates the quantity of a line item
func (*OrderDB) UpdatePaymentStatus ¶
UpdatePaymentStatus updates the order's payment status based on payments
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 ¶
CountByStatus returns the count of orders with a specific status
func (*OrderRepository) CountByUserID ¶
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) 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) 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 ¶
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 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" )