Documentation
¶
Overview ¶
Package orders is the official commerce order module: first-class orders snapshotted at checkout, a domain-enforced status lifecycle, and guest order tracking. The module never imports the cart, content, or catalog packages — checkout consumes the cart through the CartSource seam and snapshots product titles through the ContentSource seam, with the composition root providing the adapters.
Index ¶
- Constants
- Variables
- func CanTransition(from, to Status) bool
- func ParseOrderNumber(number string) (int64, bool)
- type Address
- type CartSnapshot
- type CartSnapshotLine
- type CartSource
- type CheckoutInput
- type ConsentPolicy
- type ContentSource
- type Inventory
- type InvoiceDocument
- type InvoiceLine
- type InvoiceRenderer
- type InvoiceSettings
- type Mailer
- type Money
- type Order
- type OrderItem
- type OrderStore
- type Service
- func (s *Service) BuildInvoice(ctx context.Context, id int64, settings InvoiceSettings) (*InvoiceDocument, error)
- func (s *Service) Checkout(ctx context.Context, input CheckoutInput) (*Order, error)
- func (s *Service) ConfirmPaid(ctx context.Context, id int64) (*Order, error)
- func (s *Service) ExpireStale(ctx context.Context, before time.Time, limit int) ([]int64, error)
- func (s *Service) Get(ctx context.Context, id int64) (*Order, error)
- func (s *Service) List(ctx context.Context, status *Status, beforeID int64, limit int) ([]Order, error)
- func (s *Service) SetShipping(ctx context.Context, id int64, amount int64) (*Order, error)
- func (s *Service) Tracking(ctx context.Context, number string, email string, token string) (*Order, error)
- func (s *Service) Transition(ctx context.Context, id int64, to Status) (*Order, error)
- type ServiceOption
- type Status
Constants ¶
const ( // CapabilityManage is the permission that gates order admin operations. // The module contributes it to the registry (RoleProvider) and gates // its admin surface to Admin for now, so a role-registry grants // mechanism can widen access later without changing the wire behavior. CapabilityManage = capability.Capability("orders.manage") // OrderNumberPrefix precedes every rendered order number. OrderNumberPrefix = "ORD-" // OrderNumberWidth is the zero-padded digit width of an order number. OrderNumberWidth = 6 // TrackingTokenBytes is the entropy of the per-order tracking secret. // 16 bytes (128 bits) base64url-encoded keeps the token unguessable // even though order numbers themselves are sequential. TrackingTokenBytes = 16 )
const ( // ListLimitDefault applies when a caller passes no explicit list page // size. ListLimitDefault = 50 // ListLimitCeiling bounds the admin list page size. ListLimitCeiling = 100 // FallbackProductTitle fills the item snapshot when the content seam // reports no published title for the product. FallbackProductTitle = "Product" )
const ( // InvoiceNumberPrefix precedes every rendered invoice number, mirroring // the derived order numbers (INV-000042 pays ORD-000042). InvoiceNumberPrefix = "INV-" )
Variables ¶
var ( // ErrOrderNotFound is returned when an order does not exist, an order // number cannot parse, or the tracking email does not match. The // reasons are deliberately indistinguishable so lookup misses never // enumerate orders. ErrOrderNotFound = errOrder("order not found") // ErrInvalidTransition is returned when the lifecycle forbids a status // change. ErrInvalidTransition = errOrder("order transition is not allowed") // ErrInvalidStatus is returned when a status value sits outside the // vocabulary. ErrInvalidStatus = errOrder("status is invalid") // ErrInvalidEmail is returned when the checkout email is missing or // malformed. ErrInvalidEmail = errOrder("email is required and must be valid") // ErrInvalidName is returned when the checkout name is missing. ErrInvalidName = errOrder("name is required") // ErrInvalidAddress is returned when the shipping address misses a // required field. ErrInvalidAddress = errOrder("shipping address is incomplete") // ErrInvalidShipping is returned when the shipping line is negative. ErrInvalidShipping = errOrder("shipping amount must be non-negative") // ErrEmptyCart is returned when the presented cart holds no lines to // check out. ErrEmptyCart = errOrder("cart is empty") // ErrCartGone is returned when the presented cart no longer exists: // unknown tokens and already-consumed carts read the same, which is // exactly what makes consumed carts a natural double-submit guard. ErrCartGone = errOrder("cart is gone") // ErrOutOfStock is returned when a cart line is out of stock at // checkout. Stock is only validated here; decrement happens at // payment. ErrOutOfStock = errOrder("item is out of stock") // to a sellable product or variant. ErrLineUnavailable = errOrder("cart line is no longer available") // ErrInsufficientStock is returned when payment confirmation cannot // cover the sold quantities from the inventory seam. The order stays // pending so the stock can be topped up and the payment path retried. ErrInsufficientStock = errOrder("insufficient stock for the order") // ErrConsentRequired is returned when checkout demands an affirmative // consent act and the request does not carry one. ErrConsentRequired = errOrder("consent is required to place an order") )
Functions ¶
func CanTransition ¶
CanTransition reports whether from may move to to under the order lifecycle. Every legal move appears in the lifecycle map; refusals are domain errors at the call site, not silent no-ops.
func ParseOrderNumber ¶
ParseOrderNumber converts a presented order number back into its order ID, accepting the exact RenderedNumber shape (case-sensitive prefix, decimal digits).
Types ¶
type Address ¶
type Address struct {
Street string `json:"street"`
City string `json:"city"`
Province string `json:"province"`
PostalCode string `json:"postalCode"`
}
Address is the shipping address stored as a JSON snapshot: structured enough for packing labels, never a rates or validation integration.
type CartSnapshot ¶
type CartSnapshot struct {
Lines []CartSnapshotLine
}
CartSnapshot is the priced cart read the CartSource seam resolves at checkout time.
type CartSnapshotLine ¶
type CartSnapshotLine struct {
ProductContentID int
VariantID *int64
SKU string
Quantity int
UnitPrice int64
InStock bool
Available bool
}
CartSnapshotLine is the narrowed cart vocabulary checkout consumes: the line key, its live catalog posture, and the live unit price.
type CartSource ¶
type CartSource interface {
Snapshot(ctx context.Context, token string) (CartSnapshot, error)
Consume(ctx context.Context, token string) error
}
CartSource owns the cart's checkout lifecycle: the read that prices the presented cart and the atomic delete that claims it. The claim runs before the order row is stored, so only the winner of a parallel race on one token ever creates an order — and a failed order storage abandons the claim the customer rebuilds by re-adding lines. Unknown or malformed tokens map to ErrCartGone on both methods (a gone cart aborts the checkout with it); every other failure is a persistence problem that aborts the checkout verbatim.
type CheckoutInput ¶
type CheckoutInput struct {
Token string
Email string
Name string
Phone string
ShipTo Address
ConsentAccepted bool
}
CheckoutInput is the checkout request: the cart token to consume plus the customer contact and shipping address. The order currency comes from the platform configuration, not the client.
type ConsentPolicy ¶
ConsentPolicy is the checkout consent contract resolved once at boot: whether an affirmative act is required and which document revisions that act refers to. A zero policy leaves checkout unchanged.
type ContentSource ¶
ContentSource resolves published product titles for the item snapshot. A miss — deleted or unpublished product — is reported as found=false and falls back to the module's generic title.
type Inventory ¶
type Inventory interface {
// Reserve decrements every line's tracked bucket. A bucket that
// cannot cover its quantity refuses the whole call with
// ErrInsufficientStock — the atomic guard keeps racing moves
// serialized at the row.
Reserve(ctx context.Context, items []OrderItem) error
// Release restocks every line with its full quantity, mirroring a
// strict Reserve or reverting one.
Release(ctx context.Context, items []OrderItem) error
}
Inventory is the stock ledger seam between orders and the catalog: payment confirmation decrements the sold quantities, and symmetric unwinds — a lost flip race, a cancellation or refund before shipment — restock them. The line quantities are exactly what a strict Reserve consumed, so Release always mirrors its counterpart line for line. The adapter maps the catalog's own refused-move sentinel onto ErrInsufficientStock; a failed restock is logged adapter-side and does not rewind the transition that triggered it.
type InvoiceDocument ¶
type InvoiceDocument struct {
Number string
OrderNumber string
IssuedAt time.Time
CustomerName string
CustomerEmail string
CustomerPhone string
ShipTo Address
SellerName string
SellerAddress string
SellerTaxID string
Lines []InvoiceLine
Subtotal Money
Shipping Money
TaxRate float64
Tax Money
Total Money
}
InvoiceDocument is the render-ready invoice: everything the PDF needs, derived on demand from the stored order — nothing is persisted, so the document always reflects the current record.
type InvoiceLine ¶
InvoiceLine is one billed row: the frozen snapshot values, never live pricing.
type InvoiceRenderer ¶
type InvoiceRenderer interface {
// Render builds the invoice PDF for one document.
Render(ctx context.Context, doc *InvoiceDocument) ([]byte, error)
}
InvoiceRenderer turns a document into PDF bytes. The maroto implementation lives in modules/orders/pdf; tests use fakes.
type InvoiceSettings ¶
type InvoiceSettings struct {
SellerName string
SellerAddress string
SellerTaxID string
TaxRate float64
}
InvoiceSettings carries the [invoice] block into the document build: seller identity and the PPN rate. The rate is percent (12 = twelve percent); the computed tax is a display-only breakdown — the order total stays the money truth and never moves.
type Mailer ¶
type Mailer interface {
SendOrderConfirmationEmail(ctx context.Context, order *Order) error
SendOrderStatusEmail(ctx context.Context, order *Order, from Status) error
}
Mailer delivers the customer-facing order emails. Delivery is best-effort by contract: the order record is authoritative, so a failed send never fails the checkout or a transition, and the adapter logs its own failures.
type Money ¶
Money is one monetary amount in minor units paired with its currency code: the domain's value representation of money. The ledger stores integers — never floats — and every rendered amount comes from Format, so an amount can never drift from the currency it is quoted in.
type Order ¶
type Order struct {
ID int64
Status Status
Items []OrderItem
ItemCount int
CustomerEmail string
CustomerName string
CustomerPhone string
ShipTo Address
Currency string
Subtotal int64
ShippingMinor int64
// TrackingTokenHash is the SHA-256 of the per-order tracking secret.
// It is written at checkout and compared on guest lookups; it is
// never selected back into API payloads. An empty hash marks an order
// from before the token existed — such orders are untrackable through
// the guest gate (the email-only gate was the vulnerability).
TrackingTokenHash string
// TrackingToken carries the freshly minted raw secret across checkout
// only: it reaches the checkout response and the confirmation email
// and is never persisted or returned again.
TrackingToken string
// Consent is the GDPR evidence captured at checkout: when the buyer
// affirmed the terms and which document revisions the affirmation
// referred to. Nil for orders placed before consent was enforced and
// for stores that do not ask for it.
Consent *legal.Consent
CreatedAt time.Time
UpdatedAt time.Time
}
Order is the read shape of one order: the checkout snapshot plus the lifecycle state. Items are loaded on detail reads; list reads leave them nil and carry the read-time ItemCount aggregate instead.
func (*Order) DisplayNumber ¶
DisplayNumber renders the human-readable order number: the zero-padded order ID. Numbers are derived, never stored — there is nothing to keep in sync.
func (*Order) TotalMinor ¶
TotalMinor renders the payable total: the frozen subtotal plus the shipping line. Shipping is admin-set while the order is pending and never stored anywhere else — one field, one truth.
type OrderItem ¶
type OrderItem struct {
ID int64
OrderID int64
ProductContentID int
VariantID *int64
SKU string
Title string
UnitPrice int64
Quantity int
}
OrderItem is one snapshotted purchase line. SKU, title, and price freeze at checkout so order history survives price edits, content edits, and deletion. Lines are immutable after creation — the total derives from unit price and quantity, so no extended total is stored.
type OrderStore ¶
type OrderStore interface {
// CreateOrder persists the order and its item snapshot in one
// transaction and returns the generated order ID.
CreateOrder(ctx context.Context, order *Order) (int64, error)
// FindByID returns the order with its items, or ErrOrderNotFound.
FindByID(ctx context.Context, id int64) (*Order, error)
// FindByNumberAndEmailAndToken returns the order with its items when
// the order ID, the customer email, and the tracking-token hash all
// match, or ErrOrderNotFound. The three factors are the guest gate:
// sequential numbers and knowable emails alone must never open an
// order.
FindByNumberAndEmailAndToken(ctx context.Context, id int64, email string, tokenHash string) (*Order, error)
// List returns the newest orders carrying the given status (nil is
// any), strictly after none — beforeID is the exclusive, upper keyset
// boundary (0 means from the newest), at most limit rows. Items are
// not loaded.
List(ctx context.Context, status *Status, beforeID int64, limit int) ([]Order, error)
// SetStatus replaces the lifecycle status of the order.
SetStatus(ctx context.Context, id int64, status Status) error
// SetShipping replaces the shipping line of a pending order and
// reports whether this call did the write. The pending guard lives
// in the statement, so a status flip racing the write loses it.
SetShipping(ctx context.Context, id int64, amount int64) (bool, error)
// MarkPaid flips a pending order to paid and reports whether this
// call did the flip. The pending guard lives in the statement, so the
// loser of a racing confirm, webhook retry, or expiry sweep reads
// false.
MarkPaid(ctx context.Context, id int64) (bool, error)
// ExpirePending flips up to limit pending orders created before the
// boundary to expired and returns the flipped IDs; every flip keeps
// the pending guard.
ExpirePending(ctx context.Context, before time.Time, limit int) ([]int64, error)
}
OrderStore is the persistence seam the service is built over. The single-source store satisfies it; tests use mocks.
type Service ¶
type Service struct {
// contains filtered or unexported fields
}
Service is the order domain service: checkout snapshotting over the cart and content seams, guest tracking, and the admin lifecycle operations over the persistence, mail, and inventory seams.
func NewService ¶
func NewService( store OrderStore, cart CartSource, content ContentSource, mail Mailer, inventory Inventory, currency string, opts ...ServiceOption, ) *Service
NewService builds the service over the persistence, cart, content, mail, and inventory seams, stamping the adopted platform currency into every checkout snapshot.
func (*Service) BuildInvoice ¶
func (s *Service) BuildInvoice(ctx context.Context, id int64, settings InvoiceSettings) (*InvoiceDocument, error)
BuildInvoice derives the render-ready invoice for one order: the frozen lines, the shipping line, and the display-only tax breakdown at the configured PPN rate. The document is derived on demand — nothing is persisted — so it always reflects the current record. Unknown orders read as not found.
func (*Service) Checkout ¶
Checkout validates the request, claims the presented cart, and stores it as a pending order, then emails the confirmation (best-effort). Every line must resolve and be in stock: stock is validated here and only decremented later, at payment. The order numbers snapshot live cart prices at the moment of purchase, so later catalog edits never rewrite history.
func (*Service) ConfirmPaid ¶
ConfirmPaid flips a pending order to paid on a confirmed payment and decrements its stock first. Reserve and the conditional flip together arbitrate racing confirms, retried webhooks, and the expiry sweep: only one caller wins the flip, and whoever loses releases the stock it claimed so the winner's decrement stands alone. A stock shortfall leaves the order pending for fulfillment to top up before the payment path retries.
func (*Service) ExpireStale ¶
ExpireStale flips up to limit pending orders created before the boundary to expired and emails each flipped order's customer (best-effort), returning the flipped IDs. Items load with each read; their quantities are irrelevant here because expiry never touched stock.
func (*Service) List ¶
func (s *Service) List( ctx context.Context, status *Status, beforeID int64, limit int, ) ([]Order, error)
List returns the newest orders for the admin surface: newest first, the status filter optional, keyed exclusively on the cursor the next page starts from. Items are not loaded — lists render summaries.
func (*Service) SetShipping ¶
SetShipping replaces the shipping line of a pending order and returns the refreshed order. Shipping is admin-set bookkeeping for the manual flow — weigh the parcel, then charge it — and only a pending order can carry it: once paid the amount is settled, and correction rides reject and resubmit. No email rides the write: the customer learns the full total when the proof records it.
func (*Service) Tracking ¶
func (s *Service) Tracking(ctx context.Context, number string, email string, token string) (*Order, error)
Tracking resolves one order for its customer. The order number, the email, and the per-order tracking token must all match; every other combination — unknown number, wrong address, missing or wrong token, malformed input — reads as not found so lookups can never enumerate orders. The token is what makes the gate strong: numbers are sequential and emails are guessable, the 128-bit secret is neither.
func (*Service) Transition ¶
Transition moves an order along the lifecycle after validating the target status and the transition legality, emails the customer (best-effort), and returns the refreshed order. The paid target is refused here by contract: payment confirmation is the only path into paid, through ConfirmPaid — an order surface can never mint a payment.
type ServiceOption ¶
type ServiceOption func(*Service)
ServiceOption configures a Service. Options carry the boot-time contracts the composition root resolves once (consent requirements), keeping the service free of per-request legal lookups.
func WithConsentPolicy ¶
func WithConsentPolicy(policy ConsentPolicy) ServiceOption
WithConsentPolicy adopts the checkout consent contract: when required, checkout rejects orders without an affirmative act and records the resolved document revisions on every stored order.
type Status ¶
type Status string
Status is an order lifecycle state: a snapshot of what the fulfillment pipeline has done with the order. Payment confirmation moves pending to paid; fulfillment walks paid through packed, shipped, and delivered. Cancelled, refunded, and expired are terminal.
const ( // StatusPending is a placed order awaiting payment confirmation. StatusPending Status = "pending" // StatusPaid is a payment-confirmed order awaiting preparation. StatusPaid Status = "paid" // StatusPacked is a packaged order awaiting shipment. StatusPacked Status = "packed" // StatusShipped is an order handed to the carrier. StatusShipped Status = "shipped" // StatusDelivered is an order received by the customer. StatusDelivered Status = "delivered" // StatusCancelled is an order withdrawn before shipment. StatusCancelled Status = "cancelled" // StatusRefunded is an order whose payment was returned to the // customer. StatusRefunded Status = "refunded" // StatusExpired is a pending order never confirmed in time. StatusExpired Status = "expired" )
func ParseStatus ¶
ParseStatus converts a wire status value into the vocabulary, reporting whether the value is a known state.