# Cart Management

**Author**: Josh S. Sakweli, Backend Lead Team
**Last Updated**: 2025-09-23
**Version**: v1.0

**Short Description**: The Cart Management API provides shopping cart functionality for the NextGate e-commerce platform. It supports adding products to cart, updating quantities, removing items, and real-time stock validation.

**Base URL**: `api/v1/e-commerce/cart`

**Hints**:
- All cart operations require user authentication via Bearer token
- Each user has one persistent cart that maintains state across sessions
- Real-time stock validation prevents overselling
- Adding an existing product updates its quantity (additive)
- Cart persistence survives user logout/login cycles

---

## Endpoints

## 1. 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> `{base}/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 | Not null, product must exist and be active |
| quantity | integer | Yes | Quantity to add to cart | Min: 1 |

**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 one 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

**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
}
```

---

## 2. Get Shopping Cart
**Purpose**: Retrieves the complete shopping cart with all items and pricing

**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> `{base}`

**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": 2,
      "totalQuantity": 3,
      "subtotal": 2198.00,
      "totalDiscount": 0.00,
      "totalAmount": 2198.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",
        "productPrimaryMedia": {
          "fileId": "9c1a2b3d-4e5f-6789-abcd-ef0123456789",
          "mediaType": "IMAGE",
          "status": "READY",
          "thumbUrl": "https://example.com/products/iphone15-pro-max/thumb.webp",
          "mimeType": "image/webp"
        },
        "productType": "PHYSICAL",
        "unitPrice": 1199.00,
        "quantity": 2,
        "itemSubtotal": 2398.00,
        "totalPrice": 2398.00,
        "shop": {
          "shopId": "123e4567-e89b-12d3-a456-426614174000",
          "shopName": "TechStore Pro",
          "shopSlug": "techstore-pro",
          "shopLogoMedia": {
            "fileId": "1d2e3f4a-5b6c-7890-defa-bc1234567890",
            "status": "READY",
            "thumbUrl": "https://example.com/shops/techstore-pro/thumb.webp",
            "mimeType": "image/png"
          }
        },
        "availability": {
          "inStock": true,
          "availableQuantity": 25,
          "maxPerCustomer": 5
        },
        "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",
        "productPrimaryMedia": {
          "fileId": "2a3b4c5d-6e7f-8901-bcde-f01234567890",
          "mediaType": "IMAGE",
          "status": "READY",
          "thumbUrl": "https://example.com/products/macbook-air-m3/thumb.webp",
          "mimeType": "image/webp"
        },
        "productType": "PHYSICAL",
        "unitPrice": 999.00,
        "quantity": 1,
        "itemSubtotal": 999.00,
        "totalPrice": 999.00,
        "shop": {
          "shopId": "123e4567-e89b-12d3-a456-426614174000",
          "shopName": "TechStore Pro",
          "shopSlug": "techstore-pro",
          "shopLogoMedia": {
            "fileId": "1d2e3f4a-5b6c-7890-defa-bc1234567890",
            "status": "READY",
            "thumbUrl": "https://example.com/shops/techstore-pro/thumb.webp",
            "mimeType": "image/png"
          }
        },
        "availability": {
          "inStock": true,
          "availableQuantity": 8,
          "maxPerCustomer": null
        },
        "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 |
| productPrimaryMedia | Resolved primary media of the product — `{fileId, mediaType, status, thumbUrl, mimeType}`. `null` if the product has no media yet |
| productType | PHYSICAL or DIGITAL |
| unitPrice | Current product price per unit |
| quantity | Quantity of this product in cart |
| itemSubtotal | unitPrice × quantity |
| totalPrice | itemSubtotal after discounts |
| shop | Shop information — `{shopId, shopName, shopSlug, shopLogoMedia}`, where `shopLogoMedia` is `{fileId, status, thumbUrl, mimeType}` or `null` if the shop has no logo |
| availability | Real-time stock information |
| addedAt | When item was first added to cart |

### Product Availability
| Field | Description |
|-------|-------------|
| inStock | Whether the product is currently in stock |
| availableQuantity | Current available inventory |
| maxPerCustomer | Maximum quantity a single customer can purchase (null if no limit) |

**Error Responses**:
- `401 Unauthorized`: Authentication required
- `404 Not Found`: User not found

---

## 3. 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> `{base}/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 |
|-----------|------|----------|-------------|
| itemId | UUID | Yes | ID of the cart item to update |

**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 |

**Response JSON Sample**:
```json
{
  "success": true,
  "message": "Product quantity updated successfully",
  "data": null
}
```

**Business Logic**:
- Updates quantity to the exact specified value (not additive)
- Validates new quantity doesn't exceed current stock
- Only allows updating items in the authenticated user's own cart

**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
}
```

---

## 4. 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> `{base}/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 |
|-----------|------|----------|-------------|
| itemId | UUID | Yes | ID of the cart item to remove |

**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 items from the authenticated user's own cart

**Error Responses**:
- `401 Unauthorized`: Authentication required
- `404 Not Found`: Cart item not found in user's cart

---

## 5. 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> `{base}/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

**Error Responses**:
- `401 Unauthorized`: Authentication required
- `404 Not Found`: User not foundrl at