Stacks Commerce
Comprehensive e-commerce module with 13 sub-modules and 20+ models.
Key Paths
- Core package:
storage/framework/core/commerce/src/
- Default functions:
storage/framework/defaults/functions/commerce/
- Default models:
storage/framework/defaults/app/Models/commerce/
Commerce Namespace
import { commerce } from '@stacksjs/commerce'
// 13 sub-modules
commerce.products // Product CRUD
commerce.coupons // Coupon management
commerce.customers // Customer management
commerce.errors // Error tracking
commerce.giftCards // Gift card management
commerce.orders // Order management
commerce.payments // Payment processing
commerce.restaurant // Restaurant features
commerce.shippings // Shipping management
commerce.tax // Tax rate management
commerce.waitlists // Waitlist management
commerce.devices // Print device management
commerce.receipts // Receipt management
Sub-Module Operations
Each sub-module typically provides:
index() — list all
fetch(id) — get one
store(data) — create
update(id, data) — update
destroy(id) — delete
Products Sub-Module
- Products: items, variants, units
- Manufacturers
- Reviews
- Categories
- Product waitlists
Orders Sub-Module
- Order CRUD
- Order items
- Order export
Shipping Sub-Module
- Shipping methods
- Shipping rates (weight-based)
- Shipping zones
- Delivery routes and their stops
- Drivers
- Digital deliveries
- License keys
- Live tracking (
commerce.shippings.tracking) - see below
Commerce Models (20+)
| Model |
Key Fields |
Relationships |
| Product |
name, price, inventoryCount, allergens(JSON) |
belongsTo: Category, Manufacturer; hasMany: Review, ProductUnit, ProductVariant |
| ProductVariant |
SKU, options, pricing |
belongsTo: Product |
| ProductUnit |
unit pricing |
belongsTo: Product |
| Category |
name, slug, isActive, displayOrder |
hasMany: Product |
| Cart |
status, total, currency(USD), expiresAt |
hasMany: CartItem; belongsTo: Customer |
| CartItem |
quantity, unitPrice, totalPrice |
belongsTo: Cart |
| Order |
status, totalAmount, orderType, deliveryAddress |
hasMany: OrderItem, Payment; belongsTo: Customer |
| OrderItem |
quantity, price |
belongsTo: Order, Product |
| Coupon |
code(unique), discountType, discountValue, usageLimit |
hasMany: Order |
| GiftCard |
code(unique), initialBalance, currentBalance, isReloadable |
belongsTo: Customer |
| Customer |
name, email, totalSpent, status |
hasMany: Order, GiftCard, Review, Payment |
| Manufacturer |
manufacturer info |
hasMany: Product |
| Review |
rating(1-5), content, isVerifiedPurchase, helpfulVotes |
belongsTo: Product, Customer |
| ShippingRate |
weightFrom, weightTo, rate |
belongsTo: ShippingMethod, ShippingZone |
| DeliveryRoute |
stops, totalDistance, status(planned/active/completed), startedAt |
belongsTo: Driver; hasMany: DeliveryStop, DriverPing |
| DeliveryStop |
sequence, status, address, latitude, longitude, etaAt, arrivedAt |
belongsTo: DeliveryRoute, Order |
| Driver |
name, phone, vehicleNumber, status, latitude, longitude, heading, lastPingAt |
hasMany: DeliveryRoute, DriverPing |
| DriverPing |
latitude, longitude, heading, speed, accuracy, recordedAt |
belongsTo: Driver, DeliveryRoute |
| TaxRate |
name, rate(0-100), type(VAT/GST/Sales Tax) |
|
| LicenseKey |
key(XXXX-XXXX-XXXX-XXXX-XXXX), template, status |
belongsTo: Customer, Product, Order |
| DigitalDelivery |
downloadLimit, expiryDays, automaticDelivery |
|
| WaitlistProduct |
product waitlist tracking |
|
| Receipt |
receipt records |
|
Live Delivery Tracking
commerce.shippings.tracking is the moving part of shipping: position ingest,
the stop lifecycle, and the fan-out that drives a customer's tracking map.
import { commerce } from '@stacksjs/commerce'
const { tracking } = commerce.shippings
// Put an order on a route, then set the vehicle moving.
const stop = await tracking.assignStop({
deliveryRouteId: route.id,
orderId: order.id,
address: '3821 Grand View Blvd, Los Angeles CA 90066',
latitude: 34.0128,
longitude: -118.4361,
})
await tracking.startRoute(route.id)
await tracking.startStop(stop.id) // order -> OUT_FOR_DELIVERY
// One call per position fix from the driver's device.
await tracking.recordDriverPing({
driverId, latitude, longitude, speed, accuracy,
})
await tracking.completeStop(stop.id) // order -> DELIVERED, route closes itself
What recordDriverPing does
One entry point, so a tracking page never shows a position its ETA disagrees
with. Per fix it: appends to driver_pings, updates the driver's denormalised
present position, recomputes the served stop's ETA, broadcasts the position,
and latches delivery:nearby / delivery:arrived so each fires exactly once.
A fix reporting worse than 250m accuracy is stored but does not move the driver
or trip a threshold.
Two fan-outs, on purpose
| Path |
Carries |
Why |
Realtime channel (@stacksjs/realtime) |
delivery:position, plus every state change |
Fires every few seconds per delivery; only browsers care |
Event bus (@stacksjs/events) |
delivery:assigned, :started, :nearby, :arrived, :completed, :failed |
Where notifications, analytics and fulfilment subscribe |
Position never reaches the event bus. Subscribe to the state changes to send an
SMS without being woken several times a minute per active delivery.
Channels are order.{id} for a customer's page and delivery-route.{id} for a
dispatch map, both private: authorise them in your setWsAuthenticator.
Order status
OUT_FOR_DELIVERY sits between SHIPPED and DELIVERED, reachable from
PROCESSING too (a local kitchen goes straight out on its own van), and falls
back to SHIPPED when a drop fails and the parcel returns to the depot.
canTransition enforces it.
Geodesy
distanceInMeters, bearingInDegrees, estimateSecondsRemaining, isWithin
and hasCoordinates are exported for building dispatch views. The ETA pads
straight-line distance by a detour factor and returns null for a stationary
driver rather than Infinity.
Integration with Payments
Commerce works with @stacksjs/payments for Stripe integration:
import { Payment } from '@stacksjs/payments'
await Payment.charge(customer, order.totalAmount, paymentMethodId)
Dashboard Routes
All commerce models have dashboard views at /dashboard/commerce/*.
Gotchas
- Commerce models are auto-generated — edit definitions, not generated files
- Use
buddy make:migration when changing commerce schemas
- Order
observe: true emits events on create/update/delete
- Products have JSON fields for allergens and nutritionalInfo
- Cart expiry is tracked via
expiresAt field
- Coupon types:
fixed_amount or percentage
- Gift card codes are unique and auto-generated
- License keys follow XXXX-XXXX-XXXX-XXXX-XXXX format
- Product dashboard is highlighted (
dashboard: { highlight: true })
- Default seeder counts: Product(10), Order(20), Review(50), Payment(50)
1---2name: stacks-commerce-43description: Use when building e-commerce features in Stacks — the commerce namespace with 13 sub-modules (products, orders, customers, coupons, payments, shipping, tax, gift cards, waitlists, devices, receipts, restaurant), 20+ commerce models, default commerce functions, or the commerce configuration. Covers @stacksjs/commerce.4license: MIT5compatibility: Bun >= 1.3.0, TypeScript6allowed-tools: Read Edit Write Bash Grep Glob7metadata:8 source: https://skillmd.com/skills/stacksjs/stacks-commerce-49---1011# Stacks Commerce1213Comprehensive e-commerce module with 13 sub-modules and 20+ models.1415## Key Paths16- Core package: `storage/framework/core/commerce/src/`17- Default functions: `storage/framework/defaults/functions/commerce/`18- Default models: `storage/framework/defaults/app/Models/commerce/`1920## Commerce Namespace2122```typescript23import { commerce } from '@stacksjs/commerce'2425// 13 sub-modules26commerce.products // Product CRUD27commerce.coupons // Coupon management28commerce.customers // Customer management29commerce.errors // Error tracking30commerce.giftCards // Gift card management31commerce.orders // Order management32commerce.payments // Payment processing33commerce.restaurant // Restaurant features34commerce.shippings // Shipping management35commerce.tax // Tax rate management36commerce.waitlists // Waitlist management37commerce.devices // Print device management38commerce.receipts // Receipt management39```4041## Sub-Module Operations4243Each sub-module typically provides:44- `index()` — list all45- `fetch(id)` — get one46- `store(data)` — create47- `update(id, data)` — update48- `destroy(id)` — delete4950### Products Sub-Module51- Products: items, variants, units52- Manufacturers53- Reviews54- Categories55- Product waitlists5657### Orders Sub-Module58- Order CRUD59- Order items60- Order export6162### Shipping Sub-Module63- Shipping methods64- Shipping rates (weight-based)65- Shipping zones66- Delivery routes and their stops67- Drivers68- Digital deliveries69- License keys70- **Live tracking** (`commerce.shippings.tracking`) - see below7172## Commerce Models (20+)7374| Model | Key Fields | Relationships |75|-------|-----------|---------------|76| Product | name, price, inventoryCount, allergens(JSON) | belongsTo: Category, Manufacturer; hasMany: Review, ProductUnit, ProductVariant |77| ProductVariant | SKU, options, pricing | belongsTo: Product |78| ProductUnit | unit pricing | belongsTo: Product |79| Category | name, slug, isActive, displayOrder | hasMany: Product |80| Cart | status, total, currency(USD), expiresAt | hasMany: CartItem; belongsTo: Customer |81| CartItem | quantity, unitPrice, totalPrice | belongsTo: Cart |82| Order | status, totalAmount, orderType, deliveryAddress | hasMany: OrderItem, Payment; belongsTo: Customer |83| OrderItem | quantity, price | belongsTo: Order, Product |84| Coupon | code(unique), discountType, discountValue, usageLimit | hasMany: Order |85| GiftCard | code(unique), initialBalance, currentBalance, isReloadable | belongsTo: Customer |86| Customer | name, email, totalSpent, status | hasMany: Order, GiftCard, Review, Payment |87| Manufacturer | manufacturer info | hasMany: Product |88| Review | rating(1-5), content, isVerifiedPurchase, helpfulVotes | belongsTo: Product, Customer |89| ShippingRate | weightFrom, weightTo, rate | belongsTo: ShippingMethod, ShippingZone |90| DeliveryRoute | stops, totalDistance, status(planned/active/completed), startedAt | belongsTo: Driver; hasMany: DeliveryStop, DriverPing |91| DeliveryStop | sequence, status, address, latitude, longitude, etaAt, arrivedAt | belongsTo: DeliveryRoute, Order |92| Driver | name, phone, vehicleNumber, status, latitude, longitude, heading, lastPingAt | hasMany: DeliveryRoute, DriverPing |93| DriverPing | latitude, longitude, heading, speed, accuracy, recordedAt | belongsTo: Driver, DeliveryRoute |94| TaxRate | name, rate(0-100), type(VAT/GST/Sales Tax) | |95| LicenseKey | key(XXXX-XXXX-XXXX-XXXX-XXXX), template, status | belongsTo: Customer, Product, Order |96| DigitalDelivery | downloadLimit, expiryDays, automaticDelivery | |97| WaitlistProduct | product waitlist tracking | |98| Receipt | receipt records | |99100## Live Delivery Tracking101102`commerce.shippings.tracking` is the moving part of shipping: position ingest,103the stop lifecycle, and the fan-out that drives a customer's tracking map.104105```ts106import { commerce } from '@stacksjs/commerce'107108const { tracking } = commerce.shippings109110// Put an order on a route, then set the vehicle moving.111const stop = await tracking.assignStop({112 deliveryRouteId: route.id,113 orderId: order.id,114 address: '3821 Grand View Blvd, Los Angeles CA 90066',115 latitude: 34.0128,116 longitude: -118.4361,117})118await tracking.startRoute(route.id)119await tracking.startStop(stop.id) // order -> OUT_FOR_DELIVERY120121// One call per position fix from the driver's device.122await tracking.recordDriverPing({123 driverId, latitude, longitude, speed, accuracy,124})125126await tracking.completeStop(stop.id) // order -> DELIVERED, route closes itself127```128129### What `recordDriverPing` does130131One entry point, so a tracking page never shows a position its ETA disagrees132with. Per fix it: appends to `driver_pings`, updates the driver's denormalised133present position, recomputes the served stop's ETA, broadcasts the position,134and latches `delivery:nearby` / `delivery:arrived` so each fires exactly once.135136A fix reporting worse than 250m accuracy is stored but does not move the driver137or trip a threshold.138139### Two fan-outs, on purpose140141| Path | Carries | Why |142|---|---|---|143| Realtime channel (`@stacksjs/realtime`) | `delivery:position`, plus every state change | Fires every few seconds per delivery; only browsers care |144| Event bus (`@stacksjs/events`) | `delivery:assigned`, `:started`, `:nearby`, `:arrived`, `:completed`, `:failed` | Where notifications, analytics and fulfilment subscribe |145146Position never reaches the event bus. Subscribe to the state changes to send an147SMS without being woken several times a minute per active delivery.148149Channels are `order.{id}` for a customer's page and `delivery-route.{id}` for a150dispatch map, both private: authorise them in your `setWsAuthenticator`.151152### Order status153154`OUT_FOR_DELIVERY` sits between `SHIPPED` and `DELIVERED`, reachable from155`PROCESSING` too (a local kitchen goes straight out on its own van), and falls156back to `SHIPPED` when a drop fails and the parcel returns to the depot.157`canTransition` enforces it.158159### Geodesy160161`distanceInMeters`, `bearingInDegrees`, `estimateSecondsRemaining`, `isWithin`162and `hasCoordinates` are exported for building dispatch views. The ETA pads163straight-line distance by a detour factor and returns `null` for a stationary164driver rather than `Infinity`.165166## Integration with Payments167Commerce works with `@stacksjs/payments` for Stripe integration:168```typescript169import { Payment } from '@stacksjs/payments'170await Payment.charge(customer, order.totalAmount, paymentMethodId)171```172173## Dashboard Routes174All commerce models have dashboard views at `/dashboard/commerce/*`.175176## Gotchas177- Commerce models are auto-generated — edit definitions, not generated files178- Use `buddy make:migration` when changing commerce schemas179- Order `observe: true` emits events on create/update/delete180- Products have JSON fields for allergens and nutritionalInfo181- Cart expiry is tracked via `expiresAt` field182- Coupon types: `fixed_amount` or `percentage`183- Gift card codes are unique and auto-generated184- License keys follow XXXX-XXXX-XXXX-XXXX-XXXX format185- Product dashboard is highlighted (`dashboard: { highlight: true }`)186- Default seeder counts: Product(10), Order(20), Review(50), Payment(50)