# Subtask: Order Workflow Engine **Parent Task**: Decomp/004 **Subtask ID**: Decomp/004-05 **Dependencies**: Decomp-004-01 (Database Schema), Decomp-004-03 (Inventory Reservation), Decomp-004-04 (Payment Integration) ## Description Implement order workflow engine managing the complete order lifecycle from cart creation to delivery. Handle state transitions, inventory coordination, payment processing, and order fulfillment. ## Requirements - Complete order lifecycle management - State machine for order statuses - Cart to order conversion - Payment processing integration - Inventory reservation coordination - Order status transitions with validation - Event-driven order updates - Support for order modifications ## Technical Specifications **Order status enum and transitions**: ```python from enum import Enum from typing import Dict, Set, List, Optional from dataclasses import dataclass from datetime import datetime, timezone from decimal import Decimal import logging logger = logging.getLogger(__name__) class OrderStatus(Enum): """Order status values.""" PENDING = "pending" # Initial state, awaiting payment PROCESSING = "processing" # Payment received, preparing PAID = "paid" # Payment confirmed SHIPPED = "shipped" # Shipped to customer DELIVERED = "delivered" # Delivered to customer CANCELLED = "cancelled" # Cancelled by customer/system REFUNDED = "refunded" # Refunded # Valid status transitions VALID_TRANSITIONS: Dict[OrderStatus, Set[OrderStatus]] = { OrderStatus.PENDING: { OrderStatus.PROCESSING, # Payment initiated OrderStatus.PAID, # Payment confirmed OrderStatus.CANCELLED, # Cancelled before payment }, OrderStatus.PROCESSING: { OrderStatus.PAID, # Payment completed OrderStatus.CANCELLED, # Payment failed/customer cancelled }, OrderStatus.PAID: { OrderStatus.SHIPPED, # Shipped OrderStatus.REFUNDED, # Refunded OrderStatus.CANCELLED, # Cancelled before shipping }, OrderStatus.SHIPPED: { OrderStatus.DELIVERED, # Delivered OrderStatus.REFUNDED, # Return/refund }, OrderStatus.DELIVERED: { OrderStatus.REFUNDED, # Return/refund }, OrderStatus.CANCELLED: set(), # Terminal state OrderStatus.REFUNDED: set(), # Terminal state } @dataclass class OrderItem: """Item in an order.""" product_id: int sku: str name: str quantity: int unit_price: Decimal @dataclass class Order: """Order domain object.""" id: int order_number: str customer_id: int status: OrderStatus items: List[OrderItem] subtotal: Decimal tax_amount: Decimal shipping_amount: Decimal total_amount: Decimal billing_address: dict shipping_address: dict created_at: datetime updated_at: datetime paid_at: Optional[datetime] = None shipped_at: Optional[datetime] = None delivered_at: Optional[datetime] = None cancelled_at: Optional[datetime] = None ``` **Order workflow service**: ```python class OrderWorkflowService: """Service for managing order workflow and state transitions.""" def __init__( self, db, inventory_service, payment_service, notification_service ): self.db = db self.inventory = inventory_service self.payment = payment_service self.notifications = notification_service async def create_order_from_cart( self, cart_id: int, customer_id: int, billing_address: dict, shipping_address: dict, shipping_method: str = "standard" ) -> Order: """Create an order from shopping cart.""" async with self.db.acquire() as conn: async with conn.transaction(): # Load cart with items cart = await self._load_cart(conn, cart_id) if not cart or not cart["items"]: raise ValueError("Cannot create order from empty cart") # Calculate totals subtotal = sum( Decimal(str(item["unit_price"])) * item["quantity"] for item in cart["items"] ) tax_amount = Decimal("0") # Calculate based on address shipping_amount = await self._calculate_shipping( cart["items"], shipping_address, shipping_method ) total_amount = subtotal + tax_amount + shipping_amount # Create order order = await conn.fetchrow( """INSERT INTO orders (customer_id, status, subtotal, tax_amount, shipping_amount, total_amount, billing_address, shipping_address, shipping_method, payment_method) VALUES ($1, 'pending', $2, $3, $4, $5, $6, $7, $8, 'card') RETURNING *""", customer_id, subtotal, tax_amount, shipping_amount, total_amount, json.dumps(billing_address), json.dumps(shipping_address), shipping_method ) order_id = order["id"] order_number = order["order_number"] # Copy cart items to order items for item in cart["items"]: await conn.execute( """INSERT INTO order_items (order_id, product_id, sku, product_name, quantity, unit_price, total_amount, product_snapshot) VALUES ($1, $2, $3, $4, $5, $6, $7, $8)""", order_id, item["product_id"], item["sku"], item["name"], item["quantity"], item["unit_price"], Decimal(str(item["unit_price"])) * item["quantity"], item.get("product_snapshot", {}) ) # Reserve inventory reservation_result = await self.inventory.reserve_inventory( order_id, [ {"product_id": item["product_id"], "quantity": item["quantity"]} for item in cart["items"] ] ) if not reservation_result.success: raise ValueError( f"Insufficient inventory: {reservation_result.failed_items}" ) # Clear cart await conn.execute("DELETE FROM shopping_carts WHERE id = $1", cart_id) logger.info(f"Created order {order_number} for customer {customer_id}") # Send order confirmation await self.notifications.send_order_confirmation(order_id) return await self._load_order(conn, order_id) async def transition_status( self, order_id: int, new_status: OrderStatus, reason: str = None, changed_by: str = None ) -> Order: """Transition order to new status with validation.""" async with self.db.acquire() as conn: # Get current order order = await conn.fetchrow( "SELECT * FROM orders WHERE id = $1", order_id ) if not order: raise ValueError(f"Order not found: {order_id}") current_status = OrderStatus(order["status"]) # Validate transition if new_status not in VALID_TRANSITIONS.get(current_status, set()): raise ValueError( f"Invalid status transition: {current_status.value} -> {new_status.value}" ) # Execute transition-specific logic await self._execute_status_transition( conn, order, current_status, new_status, reason, changed_by ) # Log status change await conn.execute( """INSERT INTO order_status_history (order_id, from_status, to_status, reason, changed_by) VALUES ($1, $2, $3, $4, $5)""", order_id, current_status.value, new_status.value, reason, changed_by ) logger.info( f"Order {order['order_number']}: {current_status.value} -> {new_status.value}" ) return await self._load_order(conn, order_id) async def _execute_status_transition( self, conn, order: dict, current_status: OrderStatus, new_status: OrderStatus, reason: str, changed_by: str ): """Execute logic specific to status transition.""" # Handle payment confirmation if new_status == OrderStatus.PAID: await self._handle_payment_confirmed(conn, order) # Handle shipping elif new_status == OrderStatus.SHIPPED: await self._handle_order_shipped(conn, order) # Handle delivery elif new_status == OrderStatus.DELIVERED: await self._handle_order_delivered(conn, order) # Handle cancellation elif new_status == OrderStatus.CANCELLED: await self._handle_order_cancelled(conn, order, reason) # Handle refund elif new_status == OrderStatus.REFUNDED: await self._handle_order_refunded(conn, order, reason) async def _handle_payment_confirmed(self, conn, order: dict): """Handle successful payment.""" # Commit inventory reservations await self.inventory.commit_reservations(order["id"]) # Update order await conn.execute( """UPDATE orders SET status = 'paid', paid_at = NOW(), paid_amount = total_amount WHERE id = $1""", order["id"] ) # Send payment confirmation await self.notifications.send_payment_confirmation(order["id"]) async def _handle_order_shipped(self, conn, order: dict): """Handle order shipment.""" await conn.execute( """UPDATE orders SET status = 'shipped', shipped_at = NOW() WHERE id = $1""", order["id"] ) # Send shipping notification await self.notifications.send_shipping_notification(order["id"]) async def _handle_order_delivered(self, conn, order: dict): """Handle order delivery.""" await conn.execute( """UPDATE orders SET status = 'delivered', actual_delivery_at = NOW() WHERE id = $1""", order["id"] ) # Send delivery notification await self.notifications.send_delivery_notification(order["id"]) async def _handle_order_cancelled(self, conn, order: dict, reason: str): """Handle order cancellation.""" # Release inventory reservations await self.inventory.release_reservations(order["id"]) # Update order await conn.execute( """UPDATE orders SET status = 'cancelled', cancelled_at = NOW(), cancelled_reason = $1 WHERE id = $2""", reason or "Customer request", order["id"] ) # Send cancellation notification await self.notifications.send_cancellation_notification(order["id"]) async def _handle_order_refunded(self, conn, order: dict, reason: str): """Handle order refund.""" await conn.execute( """UPDATE orders SET status = 'refunded' WHERE id = $1""", order["id"] ) # Send refund notification await self.notifications.send_refund_notification(order["id"]) async def process_payment( self, order_id: int, payment_method: str, payment_method_type: str ) -> dict: """Process payment for an order.""" async with self.db.acquire() as conn: order = await conn.fetchrow( "SELECT * FROM orders WHERE id = $1", order_id ) if not order: raise ValueError(f"Order not found: {order_id}") if order["status"] not in ("pending", "processing"): raise ValueError( f"Cannot process payment for order in status: {order['status']}" ) # Update to processing await conn.execute( "UPDATE orders SET status = 'processing' WHERE id = $1", order_id ) # Process payment result = await self.payment.create_payment( order_id=order_id, amount=Decimal(str(order["total_amount"])), currency=order["currency"], payment_method=payment_method, payment_method_type=PaymentMethod(payment_method_type), customer_id=order["customer_id"] ) if result.success: # Transition to paid await self.transition_status( order_id, OrderStatus.PAID, changed_by="payment_system" ) else: # Payment failed, release inventory await self.inventory.release_reservations(order_id) await self.transition_status( order_id, OrderStatus.CANCELLED, reason=f"Payment failed: {result.failure_reason}", changed_by="payment_system" ) return { "success": result.success, "transaction_id": result.transaction_id, "failure_reason": result.failure_reason, "requires_action": result.requires_action, "next_action": result.next_action } async def get_order(self, order_id: int) -> Optional[Order]: """Get order by ID.""" async with self.db.acquire() as conn: return await self._load_order(conn, order_id) async def get_customer_orders( self, customer_id: int, limit: int = 50, offset: int = 0 ) -> List[Order]: """Get orders for a customer.""" async with self.db.acquire() as conn: rows = await conn.fetch( """SELECT * FROM orders WHERE customer_id = $1 ORDER BY created_at DESC LIMIT $2 OFFSET $3""", customer_id, limit, offset ) return [await self._load_order(conn, row["id"]) for row in rows] async def _load_order(self, conn, order_id: int) -> Order: """Load order with items.""" order = await conn.fetchrow( "SELECT * FROM orders WHERE id = $1", order_id ) if not order: return None items = await conn.fetch( "SELECT * FROM order_items WHERE order_id = $1", order_id ) return Order( id=order["id"], order_number=order["order_number"], customer_id=order["customer_id"], status=OrderStatus(order["status"]), items=[ OrderItem( product_id=item["product_id"], sku=item["sku"], name=item["product_name"], quantity=item["quantity"], unit_price=Decimal(str(item["unit_price"])) ) for item in items ], subtotal=Decimal(str(order["subtotal"])), tax_amount=Decimal(str(order["tax_amount"])), shipping_amount=Decimal(str(order["shipping_amount"])), total_amount=Decimal(str(order["total_amount"])), billing_address=order["billing_address"], shipping_address=order["shipping_address"], created_at=order["created_at"], updated_at=order["updated_at"], paid_at=order.get("paid_at"), shipped_at=order.get("shipped_at"), delivered_at=order.get("actual_delivery_at"), cancelled_at=order.get("cancelled_at") ) async def _load_cart(self, conn, cart_id: int) -> Optional[dict]: """Load cart with items.""" cart = await conn.fetchrow( "SELECT * FROM shopping_carts WHERE id = $1", cart_id ) if not cart: return None items = await conn.fetch( """SELECT ci.*, p.sku, p.name FROM cart_items ci JOIN products p ON p.id = ci.product_id WHERE ci.cart_id = $1""", cart_id ) return { **dict(cart), "items": [dict(item) for item in items] } async def _calculate_shipping( self, items: list, address: dict, method: str ) -> Decimal: """Calculate shipping cost.""" # Simple flat rate logic rates = { "standard": Decimal("9.99"), "express": Decimal("19.99"), "overnight": Decimal("39.99") } return rates.get(method, rates["standard"]) ``` ## Acceptance Criteria - [ ] Orders can be created from carts - [ ] Status transitions are validated - [ ] Inventory is reserved on order creation - [ ] Inventory is committed on payment - [ ] Inventory is released on cancellation - [ ] Payment processing integrates correctly - [ ] Notifications are sent on status changes ## Notes **Trade-offs**: - Immediate vs eventual consistency: Strong consistency for order states - Centralized vs distributed workflow: Centralized for simplicity **Performance**: - Use message queue for async notifications - Cache order status for frequent checks **Alternatives considered**: - Event sourcing: Overkill for this use case - External workflow engine: Added complexity