Skip to content

Commerce Module (Products, Cart, Orders)

Overview

The Commerce Module handles the complete e-commerce functionality of the IWM Platform, including product catalog management, shopping cart operations, checkout process, order fulfillment, payment processing, and shipping integration. It integrates with the MLM Module for referral attribution and commission triggering.

Responsibilities

  • Product catalog and category management
  • Inventory tracking and stock management
  • Shopping cart (guest and authenticated)
  • Multi-step checkout process
  • Order lifecycle management
  • Payment processing (Stripe, YooKassa)
  • Shipping integration (CDEK, DHL)
  • Returns and refund handling
  • Referral attribution for orders

Domain Entities

Product

Core product entity for the catalog.

FieldTypeDescription
idUUIDProduct identifier
category_idUUIDCategory reference
skuVARCHAR(50)Stock keeping unit (unique)
nameVARCHAR(200)Product name
slugVARCHAR(200)URL-friendly identifier
short_descriptionVARCHAR(500)Brief description
descriptionTEXTFull description
base_priceDECIMALRegular price
sale_priceDECIMALDiscounted price
cost_priceDECIMALInternal cost
currencyVARCHAR(3)Price currency
statusENUMProduct status
stock_quantityINTAvailable stock
low_stock_thresholdINTAlert threshold
weight_gramsINTProduct weight
dimensionsJSONBLength, width, height
career_points_valueDECIMALMLM points per purchase
is_featuredBOOLEANFeatured flag

Category

Product category with hierarchical structure.

FieldTypeDescription
idUUIDCategory identifier
nameVARCHAR(100)Category name
slugVARCHAR(100)URL-friendly identifier
descriptionTEXTCategory description
parent_idUUIDParent category
pathLTREEMaterialized path for hierarchy
image_urlVARCHAR(500)Category image
sort_orderINTDisplay order
is_activeBOOLEANActive status

Cart

Shopping cart for users and guests.

FieldTypeDescription
idUUIDCart identifier
user_idUUIDUser reference (optional)
session_idVARCHAR(100)Guest session ID
referring_partner_idUUIDMLM attribution
statusENUMCart status
subtotalDECIMALItems total
discount_totalDECIMALApplied discounts
totalDECIMALFinal total
currencyVARCHAR(3)Cart currency
expires_atTIMESTAMPCart expiration

CartItem

Individual items in a cart.

FieldTypeDescription
idUUIDItem identifier
cart_idUUIDCart reference
product_idUUIDProduct reference
quantityINTItem quantity
unit_priceDECIMALPrice per unit
total_priceDECIMALLine total
added_atTIMESTAMPAddition time

Order

Customer order record.

FieldTypeDescription
idUUIDOrder identifier
order_numberVARCHAR(20)Human-readable number
user_idUUIDCustomer reference
statusENUMOrder status
subtotalDECIMALItems total
discount_totalDECIMALApplied discounts
shipping_costDECIMALShipping charge
tax_amountDECIMALApplicable taxes
totalDECIMALFinal total
currencyVARCHAR(3)Order currency
shipping_address_idUUIDDelivery address
billing_address_idUUIDBilling address
shipping_method_idUUIDDelivery method
referring_partner_idUUIDMLM attribution
notesTEXTCustomer notes

OrderItem

Line items in an order (snapshot of product at purchase time).

FieldTypeDescription
idUUIDItem identifier
order_idUUIDOrder reference
product_idUUIDProduct reference
skuVARCHAR(50)SKU snapshot
nameVARCHAR(200)Name snapshot
quantityINTItem quantity
unit_priceDECIMALPrice per unit
total_priceDECIMALLine total
career_points_valueDECIMALMLM points earned

Payment

Payment transaction for an order.

FieldTypeDescription
idUUIDPayment identifier
order_idUUIDOrder reference
amountDECIMALPayment amount
currencyVARCHAR(3)Payment currency
methodENUMCARD, EWALLET, BANK_TRANSFER
providerENUMSTRIPE, YOOKASSA
statusENUMPayment status
provider_referenceVARCHAR(255)External transaction ID
provider_responseJSONBFull provider response
paid_atTIMESTAMPSuccessful payment time
failed_atTIMESTAMPFailure time
refunded_atTIMESTAMPRefund time

Shipment

Shipment tracking for an order.

FieldTypeDescription
idUUIDShipment identifier
order_idUUIDOrder reference
carrierVARCHAR(50)CDEK, DHL, etc.
tracking_numberVARCHAR(100)Carrier tracking number
statusENUMShipment status
shipped_atTIMESTAMPShip date
estimated_deliveryDATEExpected delivery
delivered_atTIMESTAMPActual delivery
tracking_eventsJSONBTracking history

Address

Customer addresses for shipping/billing.

FieldTypeDescription
idUUIDAddress identifier
user_idUUIDUser reference
typeENUMSHIPPING, BILLING
first_nameVARCHAR(100)Recipient first name
last_nameVARCHAR(100)Recipient last name
companyVARCHAR(200)Company name
address_line1VARCHAR(255)Street address
address_line2VARCHAR(255)Apt, suite, etc.
cityVARCHAR(100)City
stateVARCHAR(100)State/province
postal_codeVARCHAR(20)Postal/ZIP code
countryVARCHAR(3)ISO 3166-1 alpha-3
phoneVARCHAR(20)Contact phone
is_defaultBOOLEANDefault address flag

Product Catalog

Category Hierarchy (LTREE)

Categories use PostgreSQL LTREE for efficient hierarchical queries:

Key LTREE Queries:

sql
-- Get all products in "Health" and subcategories
SELECT p.* FROM products p
JOIN categories c ON p.category_id = c.id
WHERE c.path <@ 'health';

-- Get direct children of a category
SELECT * FROM categories
WHERE path ~ 'health.*{1}';

-- Get all ancestors of a category
SELECT * FROM categories
WHERE 'health.vitamins.multivitamins' <@ path;

Product Attributes

Products support dynamic attributes via JSONB:

json
{
  "color": "Blue",
  "size": "Large",
  "material": "Organic Cotton",
  "weight_net": "500g",
  "ingredients": ["Vitamin C", "Zinc", "Elderberry"]
}

Product Images

Multiple images per product with ordering:

FieldDescription
urlCDN URL to image
alt_textAccessibility text
sort_orderDisplay order
is_primaryMain product image

Inventory Management

Stock Tracking

Stock Operations

OperationTriggerEffect
ReserveAdd to cartTemporarily holds stock
ReleaseCart expires, item removedReturns reserved stock
CommitOrder confirmedPermanently allocates stock
DeductOrder shippedRemoves from inventory
RestoreOrder cancelled/refundedReturns committed stock

Low Stock Alerts

When stock_quantity <= low_stock_threshold:

  1. Admin notification sent
  2. Product marked for reorder
  3. Optional: Auto-hide if stock = 0

Stock Reservation Rules

  • Cart reservation: 30 minutes
  • Checkout reservation: 15 minutes
  • Order confirmation: Permanent until shipped/cancelled
  • Failed payment: Stock released after 1 hour

Cart System

Guest vs User Carts

Guest Carts

  • Identified by session_id (UUID stored in cookie)
  • Expire after 7 days of inactivity
  • Referral attribution stored on cart

User Carts

  • Linked to user_id
  • Persist indefinitely
  • Auto-restore on login

Cart Merge on Login

When a guest with items logs in:

  1. Find existing user cart (if any)
  2. For each guest cart item:
    • If product exists in user cart: Update quantity
    • If product not in user cart: Add item
  3. Recalculate totals
  4. Delete guest cart
  5. Preserve referral attribution (most recent wins)

Cart Expiry


Checkout Process

Multi-Step Checkout

Step 1: Cart Validation

  • Verify all items still in stock
  • Check product availability (not discontinued)
  • Recalculate prices (may have changed)
  • Apply any automatic discounts

Step 2: Shipping Selection

  • User selects/adds shipping address
  • Available shipping methods calculated
  • Shipping cost displayed
  • Estimated delivery dates shown

Step 3: Payment

  • Select payment method
  • Enter payment details
  • Apply promo codes
  • Calculate final total with taxes

Step 4: Confirmation

  • Order summary review
  • Terms acceptance
  • Final order placement
  • Payment processing

Order State Machine

State Diagram

Valid Transitions

FromToTriggerConditions
PENDINGCONFIRMEDpayment_successPayment completed
PENDINGCANCELLEDcancelPayment failed or user cancels
CONFIRMEDPROCESSINGstart_processingFulfillment begins
CONFIRMEDCANCELLEDcancelBefore shipping only
PROCESSINGSHIPPEDshipTracking number assigned
PROCESSINGCANCELLEDcancelStock unavailable
SHIPPEDDELIVEREDdeliverCarrier confirmation
DELIVEREDREFUNDEDrefundWithin 14-day window

Order Timestamps

StatusTimestamp Field
CONFIRMEDconfirmed_at
SHIPPEDshipped_at
DELIVEREDdelivered_at
CANCELLEDcancelled_at
REFUNDEDrefunded_at

Payment Integration

Supported Providers

ProviderMarketsMethods
StripeInternationalCard, Apple Pay, Google Pay
YooKassaRussia/CISCard, SberPay, YooMoney

Payment Flow

Webhook Handling

Idempotency

  • Each payment has unique idempotency_key
  • Prevents duplicate charges on retry
  • Key format: order_{orderId}_{timestamp}

Payment Statuses

StatusDescription
PENDINGPayment initiated
PROCESSINGBeing processed by provider
COMPLETEDSuccessfully charged
FAILEDPayment failed
REFUNDEDFully refunded

Shipping Integration

Supported Carriers

CarrierCoverageFeatures
CDEKRussia, CISDoor-to-door, pickup points
DHLInternationalExpress, standard

Shipping Flow

Shipment Statuses

StatusDescription
PREPARINGOrder being packed
SHIPPEDHanded to carrier
IN_TRANSITWith carrier, moving
OUT_FOR_DELIVERYLast mile
DELIVEREDSuccessfully delivered
RETURNEDReturned to sender

Tracking Events

Stored as JSONB array:

json
[
  {
    "timestamp": "2024-01-15T10:30:00Z",
    "status": "SHIPPED",
    "location": "Moscow, Russia",
    "description": "Shipment picked up"
  },
  {
    "timestamp": "2024-01-16T14:20:00Z",
    "status": "IN_TRANSIT",
    "location": "Novosibirsk, Russia",
    "description": "In transit to destination"
  }
]

Returns and Refunds

Refund Window

  • Standard: 14 days from delivery
  • Extended (VIP): 30 days
  • No refund: Digital products, opened supplements

Refund Flow

Partial Refunds

  • Supported for multi-item orders
  • Individual items can be refunded
  • Shipping cost refund optional
  • Pro-rata discount adjustment

Refund Impact on MLM

When an order is refunded:

  1. Related commissions are reversed
  2. If commissions were paid, clawback created
  3. Career points deducted
  4. Partner balances adjusted

Events Published

EventTriggerPayload
ProductCreatedNew product addedproductId, sku, categoryId
ProductUpdatedProduct modifiedproductId, changedFields
ProductStatusChangedStatus transitionproductId, fromStatus, toStatus
StockLevelChangedInventory changeproductId, previousQty, newQty
LowStockAlertBelow thresholdproductId, currentQty, threshold
CartCreatedNew cartcartId, userId/sessionId
CartItemAddedItem added to cartcartId, productId, quantity
CartItemRemovedItem removed from cartcartId, productId
CartAbandonedCart expiredcartId, userId, items
OrderCreatedOrder placedorderId, userId, total
OrderConfirmedPayment successfulorderId, paymentId
OrderStatusChangedStatus transitionorderId, fromStatus, toStatus
OrderCancelledOrder cancelledorderId, reason
OrderShippedShipment createdorderId, trackingNumber
OrderDeliveredDelivery confirmedorderId, deliveredAt
PaymentReceivedPayment successfulpaymentId, orderId, amount
PaymentFailedPayment failedpaymentId, orderId, reason
RefundInitiatedRefund startedorderId, amount, reason
RefundCompletedRefund processedorderId, refundId, amount
ShipmentUpdatedTracking updateshipmentId, status, location

Events Consumed

EventSourceHandler
UserRegisteredCoreMerge guest cart if exists
UserLoggedInCoreRestore/merge user cart
ReferralAttributedMLMStore attribution on cart

Business Rules and Invariants

Product Rules

  1. SKU must be unique across all products
  2. Sale price cannot exceed base price
  3. Stock quantity cannot be negative
  4. Discontinued products cannot be added to cart
  5. Products with 0 stock shown as "Out of Stock"

Cart Rules

  1. Maximum 50 unique items per cart
  2. Maximum quantity per item: 99
  3. Cart total cannot exceed platform limits
  4. Guest carts expire after 7 days
  5. Referral attribution preserved through checkout

Order Rules

  1. Order number format: IWM-{YYYYMMDD}-
  2. Status transitions must follow state machine
  3. Cannot cancel after shipping
  4. Refund window: 14 days from delivery
  5. Minimum order value may apply

Payment Rules

  1. Single successful payment per order
  2. Idempotency key prevents duplicate charges
  3. Webhook signature must be verified
  4. Failed payments retry up to 3 times

Inventory Rules

  1. Stock reserved on cart add
  2. Reserved stock released on cart expiry
  3. Stock committed on order confirmation
  4. Stock restored on order cancellation

Integration Points

Provides to Other Modules

InterfaceConsumersPurpose
IOrderServiceMLMGet order details for commission
IProductServiceMLMGet product career points value

Consumes from Other Modules

InterfaceProviderPurpose
IUserLookupServiceCoreGet customer details
IPartnerLookupServiceMLMValidate referral attribution
IAttributionServiceMLMGet referral partner for order