# Subtask: Order Cancellation and Refunds **Parent Task**: Decomp/004 **Subtask ID**: Decomp-004-07 **Dependencies**: Decomp-004-03 (Inventory Reservation), Decomp-004-04 (Payment Integration), Decomp-004-05 (Order Workflow Engine) ## Description Implement order cancellation and refund handling. Support cancellation at different order stages, automatic refund processing, return management, and partial refunds. ## Requirements - Cancel orders at different stages - Release inventory on cancellation - Process refunds via payment provider - Handle partial refunds - Support returns and exchanges - Track refund status - Cancellation restrictions based on order status - Refund reason tracking ## Technical Specifications **Cancellation policy**: ```python from enum import Enum from typing import Optional, List from dataclasses import dataclass from decimal import Decimal from datetime import datetime, timezone class CancellationEligibility(Enum): """Can order be cancelled?""" ELIGIBLE = "eligible" ALREADY_SHIPPED = "already_shipped" ALREADY_DELIVERED = "already_delivered" ALREADY_CANCELLED = "already_cancelled" ALREADY_REFUNDED = "already_refunded" TOO_LATE = "too_late" # e.g., >24 hours after placement @dataclass class CancellationResult: """Result of cancellation attempt.""" success: bool eligibility: CancellationEligibility message: str refund_status: Optional[str] = None refund_amount: Optional[Decimal] = None @dataclass class RefundRequest: """Refund request details.""" order_id: int amount: Optional[Decimal] = None # None = full refund reason: str = None item_ids: Optional[List[int]] = None # For partial refunds restock_items: bool = True ``` **Cancellation service**: ```python class CancellationService: """Service for handling order cancellations.""" def __init__( self, db, inventory_service, payment_service, order_workflow ): self.db = db self.inventory = inventory_service self.payment = payment_service self.workflow = order_workflow async def check_cancellation_eligibility( self, order_id: int ) -> CancellationEligibility: """Check if order can be cancelled.""" 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}") status = order["status"] # Already in terminal state if status == "cancelled": return CancellationEligibility.ALREADY_CANCELLED if status == "refunded": return CancellationEligibility.ALREADY_REFUNDED if status == "shipped": return CancellationEligibility.ALREADY_SHIPPED if status == "delivered": return CancellationEligibility.ALREADY_DELIVERED # Check time limit (e.g., 24 hours for paid orders) if status in ("paid", "processing"): hours_since_paid = ( datetime.now(timezone.utc) - order.get("paid_at", order["created_at"]) ).total_seconds() / 3600 if hours_since_paid > 24: return CancellationEligibility.TOO_LATE return CancellationEligibility.ELIGIBLE async def cancel_order( self, order_id: int, customer_id: int, reason: str = None, refund: bool = True ) -> CancellationResult: """ Cancel an order. Args: order_id: Order to cancel customer_id: Customer requesting cancellation (for verification) reason: Reason for cancellation refund: Whether to process refund Returns: CancellationResult with details """ # Verify ownership async with self.db.acquire() as conn: order = await conn.fetchrow( """SELECT * FROM orders WHERE id = $1""", order_id ) if not order: return CancellationResult( success=False, eligibility=CancellationEligibility.ELIGIBLE, message="Order not found" ) if order["customer_id"] != customer_id: return CancellationResult( success=False, eligibility=CancellationEligibility.ELIGIBLE, message="Not authorized to cancel this order" ) # Check eligibility eligibility = await self.check_cancellation_eligibility(order_id) if eligibility != CancellationEligibility.ELIGIBLE: return CancellationResult( success=False, eligibility=eligibility, message=f"Cannot cancel: {eligibility.value}" ) # Process cancellation try: # Release inventory await self.inventory.release_reservations(order_id) # Cancel shipping label if created await self._cancel_shipping_label(order_id) # Process refund if requested and payment was made refund_status = None refund_amount = None if refund and order.get("paid_amount", 0) > 0: refund_result = await self._refund_order(order_id, reason) refund_status = refund_result.get("status") refund_amount = refund_result.get("amount") else: # Just cancel without refund await self.workflow.transition_status( order_id, OrderStatus.CANCELLED, reason=reason or "Customer request", changed_by="customer" ) return CancellationResult( success=True, eligibility=CancellationEligibility.ELIGIBLE, message="Order cancelled successfully", refund_status=refund_status, refund_amount=refund_amount ) except Exception as e: logger.error(f"Error cancelling order {order_id}: {e}") return CancellationResult( success=False, eligibility=CancellationEligibility.ELIGIBLE, message=f"Cancellation failed: {str(e)}" ) async def _refund_order( self, order_id: int, reason: str = None ) -> dict: """Process refund for order.""" async with self.db.acquire() as conn: # Get payment transaction transaction = await conn.fetchrow( """SELECT * FROM payment_transactions WHERE order_id = $1 AND status = 'succeeded' ORDER BY created_at DESC LIMIT 1""", order_id ) if not transaction: return {"status": "no_payment_to_refund", "amount": None} # Get order order = await conn.fetchrow( "SELECT * FROM orders WHERE id = $1", order_id ) # Calculate refund amount (total - already refunded) refund_amount = Decimal(str(order["total_amount"])) - Decimal(str(order.get("refunded_amount", 0))) if refund_amount <= 0: return {"status": "already_refunded", "amount": None} # Process refund via payment service try: refund_result = await self.payment.refund_payment( transaction_id=transaction["transaction_id"], amount=refund_amount, reason=reason or "Customer cancellation" ) if refund_result.success: # Update order status await conn.execute( """UPDATE orders SET status = 'refunded', refunded_amount = refunded_amount + $1 WHERE id = $2""", refund_result.amount, order_id ) # Log status change await conn.execute( """INSERT INTO order_status_history (order_id, from_status, to_status, reason, changed_by) VALUES ($1, $2, 'refunded', $3, 'system')""", order_id, order["status"], reason ) return { "status": "succeeded", "amount": refund_result.amount } else: return { "status": "failed", "amount": None, "error": refund_result.failure_reason } except Exception as e: logger.error(f"Refund failed for order {order_id}: {e}") return { "status": "failed", "amount": None, "error": str(e) } async def _cancel_shipping_label(self, order_id: int): """Cancel shipping label if created.""" async with self.db.acquire() as conn: label = await conn.fetchrow( """SELECT * FROM shipping_labels WHERE order_id = $1 AND status = 'created'""", order_id ) if label: # Call carrier to cancel # This would use the shipping service await conn.execute( """UPDATE shipping_labels SET status = 'cancelled' WHERE id = $1""", label["id"] ) logger.info(f"Cancelled shipping label {label['label_id']}") ``` **Return and refund service**: ```python class ReturnService: """Service for handling returns and exchanges.""" def __init__(self, db, inventory_service, payment_service): self.db = db self.inventory = inventory_service self.payment = payment_service async def create_return_request( self, order_id: int, item_ids: List[int], reason: str, return_type: str = "refund" # refund, exchange ) -> int: """Create a return request.""" async with self.db.acquire() as conn: # Validate items belong to order items = await conn.fetch( """SELECT oi.*, p.name FROM order_items oi JOIN products p ON p.id = oi.product_id WHERE oi.id = ANY($1) AND oi.order_id = $2""", item_ids, order_id ) if len(items) != len(item_ids): raise ValueError("Some items don't belong to this order") # Calculate return amount return_amount = sum(Decimal(str(item["total_amount"])) for item in items) # Create return record return_id = await conn.fetchval( """INSERT INTO returns (order_id, items, reason, return_type, return_amount, status) VALUES ($1, $2, $3, $4, $5, 'pending') RETURNING id""", order_id, json.dumps([dict(item) for item in items]), reason, return_type, return_amount ) logger.info(f"Created return request {return_id} for order {order_id}") return return_id async def process_return( self, return_id: int, approved: bool, notes: str = None ) -> dict: """Process a return request.""" async with self.db.acquire() as conn: return_request = await conn.fetchrow( """SELECT * FROM returns WHERE id = $1""", return_id ) if not return_request: raise ValueError(f"Return request not found: {return_id}") if return_request["status"] != "pending": raise ValueError(f"Return already processed: {return_request['status']}") if approved: # Update return status await conn.execute( """UPDATE returns SET status = 'approved', processed_at = NOW(), notes = COALESCE(notes || '; ', '') || $1 WHERE id = $2""", notes or "", return_id ) items = json.loads(return_request["items"]) if return_request["return_type"] == "refund": # Process refund order_id = return_request["order_id"] transaction = await conn.fetchrow( """SELECT pt.* FROM payment_transactions pt JOIN orders o ON o.id = pt.order_id WHERE o.id = $1 AND pt.status = 'succeeded' ORDER BY pt.created_at DESC LIMIT 1""", order_id ) if transaction: refund_result = await self.payment.refund_payment( transaction_id=transaction["transaction_id"], amount=Decimal(str(return_request["return_amount"])), reason=f"Return: {return_request['reason']}" ) if refund_result.success: # Restock items for item in items: await self.inventory.restock( product_id=item["product_id"], quantity=item["quantity"], location_id=1 # Default location ) return { "success": True, "refund_amount": refund_result.amount, "message": "Return processed and refund initiated" } else: return { "success": False, "message": f"Refund failed: {refund_result.failure_reason}" } else: # exchange # Create exchange order await conn.execute( """UPDATE returns SET status = 'exchanged', exchange_order_id = NULL WHERE id = $1""", return_id ) return { "success": True, "message": "Exchange request processed" } else: # Reject return await conn.execute( """UPDATE returns SET status = 'rejected', processed_at = NOW(), notes = COALESCE(notes || '; ', '') || $1 WHERE id = $2""", notes or "Return request denied", return_id ) return { "success": False, "message": "Return request rejected" } async def get_return_requests( self, order_id: int = None, status: str = None ) -> List[dict]: """Get return requests.""" async with self.db.acquire() as conn: query = "SELECT * FROM returns WHERE 1=1" params = [] if order_id: query += " AND order_id = $1" params.append(order_id) if status: query += f" AND status = ${len(params) + 1}" params.append(status) query += " ORDER BY created_at DESC" rows = await conn.fetch(query, *params) return [dict(row) for row in rows] ``` **Database extension for returns**: ```sql -- Returns table CREATE TABLE returns ( id BIGSERIAL PRIMARY KEY, order_id BIGINT NOT NULL REFERENCES orders(id), items JSONB NOT NULL, -- Array of order items being returned reason TEXT NOT NULL, return_type VARCHAR(20) NOT NULL, -- 'refund' or 'exchange' return_amount DECIMAL(10, 2) NOT NULL, status VARCHAR(20) NOT NULL DEFAULT 'pending', -- pending, approved, rejected, exchanged, refunded notes TEXT, processed_at TIMESTAMP, created_at TIMESTAMP NOT NULL DEFAULT NOW(), exchange_order_id BIGINT REFERENCES orders(id), refund_id BIGINT REFERENCES refunds(id), metadata JSONB DEFAULT '{}'::jsonb ); CREATE INDEX idx_returns_order ON returns(order_id); CREATE INDEX idx_returns_status ON returns(status); ``` **Admin API for cancellations**: ```python from fastapi import APIRouter, Depends, HTTPException router = APIRouter(prefix="/admin/orders", tags=["admin-orders"]) @router.post("/{order_id}/cancel") async def admin_cancel_order( order_id: int, reason: str = None, force: bool = False, refund: bool = True ): """Admin endpoint to cancel an order.""" cancellation_service = get_cancellation_service() if force: # Force cancel even if normally ineligible # Still releases inventory and processes refund async with cancellation_service.db.acquire() as conn: order = await conn.fetchrow( "SELECT * FROM orders WHERE id = $1", order_id ) if not order: raise HTTPException(status_code=404, detail="Order not found") # Release inventory await cancellation_service.inventory.release_reservations(order_id) # Process refund if needed if refund and order.get("paid_amount", 0) > 0: refund_result = await cancellation_service._refund_order(order_id, reason) else: await cancellation_service.workflow.transition_status( order_id, OrderStatus.CANCELLED, reason=reason or "Cancelled by admin", changed_by="admin" ) refund_result = None return { "success": True, "order_id": order_id, "refund": refund_result } else: # Normal cancellation flow result = await cancellation_service.cancel_order( order_id, customer_id=None, # Admin can cancel any order reason=reason or "Cancelled by admin", refund=refund ) if not result.success: raise HTTPException(status_code=400, detail=result.message) return { "success": True, "order_id": order_id, "cancellation": result } @router.get("/returns/pending") async def get_pending_returns(): """Get pending return requests.""" return_service = get_return_service() returns = await return_service.get_return_requests(status="pending") return {"returns": returns} @router.post("/returns/{return_id}/process") async def process_return_request( return_id: int, approved: bool, notes: str = None ): """Process a return request.""" return_service = get_return_service() result = await return_service.process_return(return_id, approved, notes) return result ``` ## Acceptance Criteria - [ ] Orders can be cancelled when eligible - [ ] Cancellation eligibility is enforced - [ ] Inventory is released on cancellation - [ ] Refunds process correctly - [ ] Return requests can be created - [ ] Returns can be approved/rejected - [ ] Admin can force cancel orders ## Notes **Trade-offs**: - Strict vs lenient cancellation policy: Configurable via settings - Immediate vs scheduled refund: Immediate for customer satisfaction **Performance**: - Queue refund processing for high volume - Cache cancellation rules **Alternatives considered**: - Third-party returns service (Returnly): Overkill for MVP - RMA system complexity: Keep simple for now