# Cart Management

**Author**: Josh S. Sakweli, Backend Lead Team  
**Last Updated**: 2025-09-23  
**Version**: v1.0

**Short Description**: The Cart Management API provides comprehensive shopping cart functionality for the NextGate e-commerce platform. It supports adding products to cart, updating quantities, removing items, real-time price calculations, stock validation, and automatic cart management with user authentication.

**Hints**: 
- All cart operations require user authentication via Bearer token
- Cart is automatically created for each user upon first interaction
- Each user has one persistent cart that maintains state across sessions  
- Real-time stock validation prevents overselling
- Supports adding existing products with quantity updates
- Real-time price calculations include discounts and promotions
- Cart items are linked to active products only (ACTIVE status)
- Automatic cart cleanup when products become unavailable
- Optimized for concurrent access and inventory management
- Cart items show shop information for multi-vendor marketplace support
- Stock availability is validated on every cart operation
- Cart persistence survives user logout/login cycles

---

## Endpoints

## 1. Initialize Cart
**Purpose**: Creates or ensures cart exists for the authenticated user

**Endpoint**: <span style="background-color: #28a745; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">POST</span> `/api/v1/cart/initialize`

**Access Level**: 🔒 Protected (Requires authentication)

**Authentication**: Bearer Token

**Request Headers**:
| Header | Type | Required | Description |
|--------|------|----------|-------------|
| Authorization | string | Yes | Bearer token for authentication |

**Response JSON Sample**:
```json
{
  "success": true,
  "message": "Shopping cart initialized successfully",
  "data": null
}
```

**Business Logic**:
- Creates new cart if user doesn't have one
- Returns success if cart already exists
- Automatic cart creation on first use

**Error Responses**:
- `401 Unauthorized`: Authentication required or invalid token
- `500 Internal Server Error`: Server error during cart creation

---

## 2. Add Product to Cart
**Purpose**: Adds a product to the user's cart or updates quantity if already exists

**Endpoint**: <span style="background-color: #28a745; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">POST</span> `/api/v1/cart/add`

**Access Level**: 🔒 Protected (Requires authentication)

**Authentication**: Bearer Token

**Request Headers**:
| Header | Type | Required | Description |
|--------|------|----------|-------------|
| Authorization | string | Yes | Bearer token for authentication |
| Content-Type | string | Yes | application/json |

**Request JSON Sample**:
```json
{
  "productId": "456e7890-e89b-12d3-a456-426614174001",
  "quantity": 2
}
```

**Request Body Parameters**:
| Parameter | Type | Required | Description | Validation |
|-----------|------|----------|-------------|------------|
| productId | UUID | Yes | ID of the product to add | Valid UUID, product must exist and be active |
| quantity | integer | Yes | Quantity to add to cart | Min: 1, must not exceed available stock |

**Response JSON Sample (New Item)**:
```json
{
  "success": true,
  "message": "Product added to cart successfully",
  "data": null
}
```

**Response JSON Sample (Updated Existing)**:
```json
{
  "success": true,
  "message": "Product quantity updated in cart successfully",
  "data": null
}
```

**Business Logic**:
- Creates cart automatically if doesn't exist
- If product already in cart, adds to existing quantity
- Validates total quantity doesn't exceed available stock
- Only allows active products to be added
- Real-time stock validation

**Stock Validation**:
- Checks product current stock before adding
- For existing items: validates (current cart quantity + new quantity) ≤ stock
- Prevents overselling with detailed error messages

**Error Responses**:
- `400 Bad Request`: Invalid productId or quantity validation error
- `401 Unauthorized`: Authentication required
- `404 Not Found`: Product not found or not active
- `422 Unprocessable Entity`: Insufficient stock available

**Error Examples**:
```json
{
  "success": false,
  "message": "Insufficient stock for 'iPhone 15 Pro'. Only 3 units available",
  "data": null
}
```

```json
{
  "success": false,
  "message": "Cannot add more items. Total quantity (8) would exceed available stock (5) for 'MacBook Pro'",
  "data": null
}
```

---

## 3. Get Shopping Cart
**Purpose**: Retrieves the complete shopping cart with all items, pricing, and calculations

**Endpoint**: <span style="background-color: #007bff; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">GET</span> `/api/v1/cart`

**Access Level**: 🔒 Protected (Requires authentication)

**Authentication**: Bearer Token

**Request Headers**:
| Header | Type | Required | Description |
|--------|------|----------|-------------|
| Authorization | string | Yes | Bearer token for authentication |

**Response JSON Sample**:
```json
{
  "success": true,
  "message": "Shopping cart retrieved successfully",
  "data": {
    "user": {
      "userId": "111e2222-e89b-12d3-a456-426614174003",
      "userName": "john.doe",
      "name": "John Doe"
    },
    "cartSummary": {
      "totalItems": 3,
      "totalQuantity": 7,
      "subtotal": 2497.00,
      "totalDiscount": 200.00,
      "totalAmount": 2297.00
    },
    "cartItems": [
      {
        "itemId": "cart001-e89b-12d3-a456-426614174004",
        "productId": "456e7890-e89b-12d3-a456-426614174001",
        "productName": "iPhone 15 Pro Max 512GB",
        "productSlug": "iphone-15-pro-max-512gb",
        "productImage": "https://example.com/images/iphone15-pro-max.jpg",
        "unitPrice": 1199.00,
        "discountAmount": 100.00,
        "quantity": 2,
        "itemSubtotal": 2398.00,
        "itemDiscount": 200.00,
        "totalPrice": 2198.00,
        "shop": {
          "shopId": "123e4567-e89b-12d3-a456-426614174000",
          "shopName": "TechStore Pro",
          "shopSlug": "techstore-pro",
          "logoUrl": "https://example.com/logos/techstore-pro.png"
        },
        "availability": {
          "inStock": true,
          "stockQuantity": 25
        },
        "addedAt": "2025-09-23T10:30:00Z"
      },
      {
        "itemId": "cart002-e89b-12d3-a456-426614174005",
        "productId": "567e8901-e89b-12d3-a456-426614174002",
        "productName": "MacBook Air M3",
        "productSlug": "macbook-air-m3",
        "productImage": "https://example.com/images/macbook-air-m3.jpg",
        "unitPrice": 999.00,
        "discountAmount": 0.00,
        "quantity": 1,
        "itemSubtotal": 999.00,
        "itemDiscount": 0.00,
        "totalPrice": 999.00,
        "shop": {
          "shopId": "123e4567-e89b-12d3-a456-426614174000",
          "shopName": "TechStore Pro",
          "shopSlug": "techstore-pro",
          "logoUrl": "https://example.com/logos/techstore-pro.png"
        },
        "availability": {
          "inStock": true,
          "stockQuantity": 8
        },
        "addedAt": "2025-09-23T11:15:00Z"
      }
    ],
    "updatedAt": "2025-09-23T14:20:00Z"
  }
}
```

**Response Structure**:

### User Summary
| Field | Description |
|-------|-------------|
| userId | Unique identifier of the cart owner |
| userName | User's login username |
| name | User's full name (firstName + lastName) |

### Cart Summary
| Field | Description |
|-------|-------------|
| totalItems | Number of distinct products in cart |
| totalQuantity | Total quantity of all items combined |
| subtotal | Total price before discounts |
| totalDiscount | Total discount amount applied |
| totalAmount | Final amount after discounts |

### Cart Item Details
| Field | Description |
|-------|-------------|
| itemId | Unique identifier for the cart item |
| productId | Product identifier |
| productName | Current product name |
| productSlug | URL-friendly product identifier |
| productImage | Primary product image URL |
| unitPrice | Current product price per unit |
| discountAmount | Discount per unit (if product on sale) |
| quantity | Quantity of this product in cart |
| itemSubtotal | unitPrice × quantity |
| itemDiscount | discountAmount × quantity |
| totalPrice | itemSubtotal - itemDiscount |
| shop | Shop information (id, name, slug, logo) |
| availability | Real-time stock information |
| addedAt | When item was first added to cart |

**Real-time Calculations**:
- Prices reflect current product pricing
- Discounts applied automatically for sale items
- Stock quantities show real-time availability
- Calculations updated on each cart retrieval

**Error Responses**:
- `401 Unauthorized`: Authentication required
- `404 Not Found`: User not found

---

## 4. Update Cart Item Quantity
**Purpose**: Updates the quantity of a specific item in the cart

**Endpoint**: <span style="background-color: #ffc107; color: black; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">PUT</span> `/api/v1/cart/items/{itemId}`

**Access Level**: 🔒 Protected (Requires authentication)

**Authentication**: Bearer Token

**Request Headers**:
| Header | Type | Required | Description |
|--------|------|----------|-------------|
| Authorization | string | Yes | Bearer token for authentication |
| Content-Type | string | Yes | application/json |

**Path Parameters**:
| Parameter | Type | Required | Description | Validation |
|-----------|------|----------|-------------|------------|
| itemId | UUID | Yes | ID of the cart item to update | Valid UUID, must belong to user's cart |

**Request JSON Sample**:
```json
{
  "quantity": 3
}
```

**Request Body Parameters**:
| Parameter | Type | Required | Description | Validation |
|-----------|------|----------|-------------|------------|
| quantity | integer | Yes | New quantity for the cart item | Min: 1, must not exceed available stock |

**Response JSON Sample**:
```json
{
  "success": true,
  "message": "Product quantity updated successfully",
  "data": null
}
```

**Business Logic**:
- Updates quantity to exact specified value (not additive)
- Validates new quantity doesn't exceed current stock
- Only allows updating user's own cart items

**Stock Validation**:
- Checks current product stock before updating
- Prevents quantity exceeding available inventory
- Provides detailed error message if stock insufficient

**Error Responses**:
- `400 Bad Request`: Invalid quantity value
- `401 Unauthorized`: Authentication required
- `404 Not Found`: Cart item not found in user's cart
- `422 Unprocessable Entity`: Insufficient stock for requested quantity

**Error Example**:
```json
{
  "success": false,
  "message": "Insufficient stock for 'iPhone 15 Pro'. Only 2 units available",
  "data": null
}
```

---

## 5. Remove Cart Item
**Purpose**: Removes a specific item completely from the cart

**Endpoint**: <span style="background-color: #dc3545; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">DELETE</span> `/api/v1/cart/items/{itemId}`

**Access Level**: 🔒 Protected (Requires authentication)

**Authentication**: Bearer Token

**Request Headers**:
| Header | Type | Required | Description |
|--------|------|----------|-------------|
| Authorization | string | Yes | Bearer token for authentication |

**Path Parameters**:
| Parameter | Type | Required | Description | Validation |
|-----------|------|----------|-------------|------------|
| itemId | UUID | Yes | ID of the cart item to remove | Valid UUID, must belong to user's cart |

**Response JSON Sample**:
```json
{
  "success": true,
  "message": "Product removed from cart successfully",
  "data": null
}
```

**Business Logic**:
- Completely removes the cart item and all its quantity
- Only allows removing user's own cart items
- Cart item is permanently deleted from database

**Error Responses**:
- `401 Unauthorized`: Authentication required
- `404 Not Found`: Cart item not found in user's cart

---

## 6. Clear Shopping Cart
**Purpose**: Removes all items from the user's cart

**Endpoint**: <span style="background-color: #dc3545; color: white; padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 12px; font-weight: bold;">DELETE</span> `/api/v1/cart/clear`

**Access Level**: 🔒 Protected (Requires authentication)

**Authentication**: Bearer Token

**Request Headers**:
| Header | Type | Required | Description |
|--------|------|----------|-------------|
| Authorization | string | Yes | Bearer token for authentication |

**Response JSON Sample**:
```json
{
  "success": true,
  "message": "Shopping cart cleared successfully",
  "data": null
}
```

**Business Logic**:
- Removes all cart items for the authenticated user
- Cart entity remains but becomes empty
- Cannot be undone - permanent deletion of all items

**Use Cases**:
- User wants to start fresh with empty cart
- Clear cart after successful order completion
- Administrative cart cleanup

**Error Responses**:
- `401 Unauthorized`: Authentication required
- `404 Not Found`: User not found

---

## Quick Reference Guide

### Common HTTP Status Codes
- `200 OK`: Successful GET/PUT/DELETE request
- `201 Created`: Successful POST request (cart initialization)
- `400 Bad Request`: Invalid request data or validation errors
- `401 Unauthorized`: Authentication required or invalid token
- `404 Not Found`: Cart item, product, or user not found
- `422 Unprocessable Entity`: Stock validation errors
- `500 Internal Server Error`: Server error during processing

### Authentication Requirements
- **Bearer Token**: Include `Authorization: Bearer your_token` in headers
- **All endpoints require authentication** - no public cart operations
- **User-specific carts** - each user has their own isolated cart

### Data Format Standards
- **Dates**: Use ISO 8601 format (2025-09-23T14:30:00Z)
- **Prices**: Decimal with 2 decimal places (999.00)
- **UUIDs**: Standard UUID format (123e4567-e89b-12d3-a456-426614174000)
- **Quantities**: Positive integers only (minimum 1)

### Cart Business Rules

#### Stock Management
- **Real-time Validation**: Stock checked on every cart operation
- **Prevent Overselling**: Cannot add more than available inventory
- **Active Products Only**: Only products with ACTIVE status can be added
- **Stock Updates**: Cart shows current stock, not stock at time of adding

#### Quantity Management
- **Minimum Quantity**: All quantities must be at least 1
- **Additive Adding**: Adding existing product increases quantity
- **Absolute Updates**: Update operations set exact quantity (not additive)
- **Stock Limits**: Cannot exceed available inventory at any time

#### Cart Persistence
- **User-Specific**: Each authenticated user has one persistent cart
- **Session Independent**: Cart survives logout/login cycles
- **Automatic Creation**: Cart created automatically on first interaction
- **Cleanup**: No automatic expiration (persists indefinitely)

### Price Calculation Logic

#### Item-Level Calculations
```
Item Subtotal = Unit Price × Quantity
Item Discount = Discount Amount × Quantity (if product on sale)
Item Total = Item Subtotal - Item Discount
```

#### Cart-Level Calculations
```
Total Items = Count of distinct products
Total Quantity = Sum of all item quantities
Subtotal = Sum of all item subtotals
Total Discount = Sum of all item discounts  
Total Amount = Subtotal - Total Discount
```

#### Real-time Price Updates
- Prices reflect current product pricing on each cart retrieval
- Discounts applied automatically for products on sale
- No price locking - prices may change between cart operations

### Error Handling Patterns

#### Stock Validation Errors
```json
{
  "success": false,
  "message": "Insufficient stock for '{productName}'. Only {available} units available"
}
```

#### Cart Item Not Found
```json
{
  "success": false,  
  "message": "Cart item not found"
}
```

#### Authentication Errors  
```json
{
  "success": false,
  "message": "User not authenticated"
}
```

### Best Practices for Cart Management

#### For Frontend Applications
1. **Check stock before adding** - validate availability client-side when possible
2. **Handle stock errors gracefully** - show clear messages about availability
3. **Refresh cart regularly** - prices and stock change in real-time
4. **Implement quantity controls** - prevent users from entering invalid quantities
5. **Show loading states** - cart operations may take time due to validation
6. **Cache cart data briefly** - but refresh before checkout
7. **Handle authentication errors** - redirect to login when tokens expire
8. **Display shop information** - help users understand multi-vendor items
9. **Show stock warnings** - alert users about low stock items
10. **Implement optimistic updates** - with fallback for failures

#### For Backend Integration
1. **Always authenticate users** before cart operations
2. **Validate stock in real-time** - inventory changes frequently
3. **Handle concurrent access** - multiple devices may access same cart
4. **Log cart operations** - for debugging and analytics
5. **Monitor stock levels** - prevent overselling scenarios
6. **Implement rate limiting** - prevent cart abuse
7. **Clean up orphaned items** - when products become inactive
8. **Validate product availability** - ensure products are still active
9. **Handle shop changes** - when products move between shops
10. **Implement cart recovery** - for interrupted operations

### Common Use Cases
- **Add to Cart**: POST /api/v1/cart/add with productId and quantity
- **View Cart**: GET /api/v1/cart for complete cart with calculations
- **Update Quantity**: PUT /api/v1/cart/items/{itemId} with new quantity
- **Remove Item**: DELETE /api/v1/cart/items/{itemId}
- **Clear Cart**: DELETE /api/v1/cart/clear

### Validation Summary
- All endpoints require authentication
- Stock validation on add/update operations
- Only active products can be added to cart
- Quantities must be positive integers (minimum 1)
- Real-time price calculations on cart retrieval