> ## Documentation Index
> Fetch the complete documentation index at: https://docs.jethings.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Item Variants API

> Retrieve paginated item variants with search capabilities by barcode or name for optical store inventory management

# Item Variants API Documentation

This document describes the item variants endpoint for retrieving paginated lists of item variants in the optical store system. Item variants represent specific configurations of items (e.g., different lens prescriptions, treatments, or colors) and can be searched by barcode or name.

## Endpoint Details

**Base URL:** `https://joptic.jethings.com`

### Required Headers

```
x-store-id: <store_id>
Authorization: Bearer <token>
```

***

## Authentication

All endpoints require user authentication. The user ID is extracted from the JWT token (`req.user.sub`), and store access is validated via the `@StoreId()` decorator. Only item variants belonging to products in the authenticated user's store are returned.

***

## Get All Item Variants

Retrieve a paginated list of item variants for the current store. Supports searching by barcode or item variant name.

**Endpoint:** `GET /item-variants`

### Query Parameters

| Parameter | Type     | Required | Default | Description                                           |
| --------- | -------- | -------- | ------- | ----------------------------------------------------- |
| `search`  | `string` | No       | —       | Search term to filter by barcode or item variant name |
| `page`    | `number` | No       | `1`     | Page number (min: 1)                                  |
| `limit`   | `number` | No       | `10`    | Items per page (min: 1, max: 100)                     |

### Search Functionality

The search parameter performs a case-insensitive search across:

* **Barcodes**: Searches in the barcode table and returns item variants associated with matching barcodes
* **Item Variant Names**: Searches directly in item variant names

<Note>
  When searching, the system searches both barcodes and item variant names in parallel for optimal performance. Results are combined and deduplicated. If no matches are found, an empty array is returned with pagination metadata.
</Note>

### Success Response

```json theme={null}
{
  "data": [
    {
      "id": "variant_123",
      "name": "1.50 PhGy BB +0.00 +0.25",
      "description": "Standard lens with anti-reflective coating",
      "isActive": true,
      "createdAt": "2024-01-15T10:30:00.000Z",
      "updatedAt": "2024-01-15T10:30:00.000Z"
    },
    {
      "id": "variant_124",
      "name": "1.67 Clear AR -2.00 -0.50",
      "description": "High-index lens with blue light filter",
      "isActive": true,
      "createdAt": "2024-01-14T09:20:00.000Z",
      "updatedAt": "2024-01-14T09:20:00.000Z"
    }
  ],
  "pagination": {
    "page": 1,
    "limit": 10,
    "total": 25,
    "totalPages": 3,
    "hasNext": true,
    "hasPrev": false
  }
}
```

### Response Fields

* `id` (string) - Unique identifier for the item variant
* `name` (string | null) - Name of the item variant (e.g., "1.50 PhGy BB +0.00 +0.25")
* `description` (string | null) - Optional description of the item variant
* `isActive` (boolean) - Whether the item variant is currently active
* `createdAt` (Date) - Timestamp when the item variant was created
* `updatedAt` (Date) - Timestamp when the item variant was last updated

### Pagination Fields

* `page` (number) - Current page number
* `limit` (number) - Number of items per page
* `total` (number) - Total number of item variants matching the criteria
* `totalPages` (number) - Total number of pages available
* `hasNext` (boolean) - Whether a next page exists
* `hasPrev` (boolean) - Whether a previous page exists

<Note>
  Results are paginated for performance. Default sorting is by creation date (newest first). Only non-deleted item variants (`deletedAt IS NULL`) belonging to products in the authenticated user's store are returned.
</Note>

### Example Request

<CodeGroup>
  ```bash cURL theme={null}
  curl -X GET "https://joptic.jethings.com/item-variants?search=1.50&page=1&limit=20" \
    -H "x-store-id: your-store-id" \
    -H "Authorization: Bearer <token>"
  ```

  ```javascript JavaScript theme={null}
  const params = new URLSearchParams({
    search: "1.50",
    page: "1",
    limit: "20"
  })

  const response = await fetch(`https://joptic.jethings.com/item-variants?${params}`, {
    method: "GET",
    headers: {
      "x-store-id": "your-store-id",
      Authorization: "Bearer <token>",
    },
  })

  const result = await response.json()
  ```

  ```python Python theme={null}
  import requests

  url = "https://joptic.jethings.com/item-variants"

  params = {
      "search": "1.50",
      "page": 1,
      "limit": 20
  }

  response = requests.get(
      url,
      headers={
          "x-store-id": "your-store-id",
          "Authorization": "Bearer <token>"
      },
      params=params
  )

  print(response.json())
  ```
</CodeGroup>

### Example: Search by Barcode

<CodeGroup>
  ```bash cURL theme={null}
  curl -X GET "https://joptic.jethings.com/item-variants?search=1234567890123&page=1&limit=10" \
    -H "x-store-id: your-store-id" \
    -H "Authorization: Bearer <token>"
  ```
</CodeGroup>

### Example: Search by Name

<CodeGroup>
  ```bash cURL theme={null}
  curl -X GET "https://joptic.jethings.com/item-variants?search=PhGy&page=1&limit=10" \
    -H "x-store-id: your-store-id" \
    -H "Authorization: Bearer <token>"
  ```
</CodeGroup>

### Example: Get All Variants (No Search)

<CodeGroup>
  ```bash cURL theme={null}
  curl -X GET "https://joptic.jethings.com/item-variants?page=1&limit=10" \
    -H "x-store-id: your-store-id" \
    -H "Authorization: Bearer <token>"
  ```
</CodeGroup>

### Possible Errors

* `401 Unauthorized` - Missing or invalid authentication token
* `403 Forbidden` - User does not have access to the store
* `500 Internal Server Error` - Server error

***

## Business Logic

### Item Variant Retrieval Process

<AccordionGroup>
  <Accordion title="Store Filtering" icon="store">
    **Store Filtering**

    The system automatically filters item variants by:

    1. Joining item variants with items and products
    2. Filtering products by the authenticated user's store ID
    3. Ensuring only variants from accessible stores are returned

    This prevents unauthorized access to item variants from other stores.
  </Accordion>

  <Accordion title="Search Implementation" icon="search">
    **Search Implementation**

    When a search term is provided, the system:

    1. Searches barcodes in parallel with item variant names
    2. Finds matching barcodes and retrieves associated item variant IDs
    3. Finds matching item variant names directly
    4. Combines and deduplicates results
    5. Filters the final results by store and deletion status

    This dual-search approach allows finding variants by either their barcode or name.
  </Accordion>

  <Accordion title="Soft Delete Handling" icon="trash">
    **Soft Delete Handling**

    The system automatically excludes deleted item variants:

    * Only variants where `deletedAt IS NULL` are returned
    * Deleted variants are permanently excluded from results
    * This ensures data integrity and prevents access to archived items
  </Accordion>

  <Accordion title="Pagination" icon="list">
    **Pagination**

    Pagination is enforced with:

    * Minimum page: 1
    * Minimum limit: 1
    * Maximum limit: 100
    * Default values: page=1, limit=10
    * Results are ordered by creation date (newest first)

    This ensures efficient data retrieval and prevents performance issues.
  </Accordion>

  <Accordion title="Barcode Association" icon="barcode">
    **Barcode Association**

    When searching by barcode:

    1. The system finds matching barcodes in the barcode table
    2. Retrieves item variant IDs from the barcode-item association table
    3. Only active barcode associations (`isActive = true`) are considered
    4. Results are combined with name-based search results

    This allows finding item variants by scanning or entering barcodes.
  </Accordion>
</AccordionGroup>

### Item Variant States

<CardGroup cols={2}>
  <Card title="Active Variants" icon="check-circle">
    **Active** (`isActive: true`)

    <br />

    Variant is currently available for use in inventory and sales
  </Card>

  <Card title="Inactive Variants" icon="x-circle">
    **Inactive** (`isActive: false`)

    <br />

    Variant exists but is not currently available
  </Card>

  <Card title="Deleted Variants" icon="trash">
    **Deleted** (`deletedAt IS NOT NULL`)

    <br />

    Soft-deleted variants are excluded from all queries
  </Card>

  <Card title="Barcode Linked" icon="barcode">
    **Barcode Association**

    <br />

    Variants can be found by searching associated barcodes
  </Card>
</CardGroup>

***

## Error Responses

All endpoints may return standard HTTP error codes:

* `401 Unauthorized` - Missing or invalid authentication token
* `403 Forbidden` - User does not have access to the store
* `500 Internal Server Error` - Server error

### Error Response Format

```json theme={null}
{
  "statusCode": 403,
  "message": "You do not have access to this store",
  "error": "Forbidden"
}
```

### Common Error Scenarios

**403 Forbidden - Store Access**

```json theme={null}
{
  "statusCode": 403,
  "message": "You do not have access to this store"
}
```

Occurs when the user doesn't have access to the specified store.

**400 Bad Request - Invalid Pagination**

```json theme={null}
{
  "statusCode": 400,
  "message": ["page must be a positive number", "limit must be between 1 and 100"],
  "error": "Bad Request"
}
```

Occurs when pagination parameters are invalid.

***

## Usage Examples

### Example 1: Get all item variants with default pagination

<CodeGroup>
  ```bash cURL theme={null}
  curl -X GET "https://joptic.jethings.com/item-variants" \
    -H "x-store-id: your-store-id" \
    -H "Authorization: Bearer <token>"
  ```
</CodeGroup>

### Example 2: Search by barcode

<CodeGroup>
  ```bash cURL theme={null}
  curl -X GET "https://joptic.jethings.com/item-variants?search=1234567890123" \
    -H "x-store-id: your-store-id" \
    -H "Authorization: Bearer <token>"
  ```
</CodeGroup>

### Example 3: Search by item variant name

<CodeGroup>
  ```bash cURL theme={null}
  curl -X GET "https://joptic.jethings.com/item-variants?search=PhGy&page=1&limit=20" \
    -H "x-store-id: your-store-id" \
    -H "Authorization: Bearer <token>"
  ```
</CodeGroup>

### Example 4: Get second page with custom limit

<CodeGroup>
  ```bash cURL theme={null}
  curl -X GET "https://joptic.jethings.com/item-variants?page=2&limit=50" \
    -H "x-store-id: your-store-id" \
    -H "Authorization: Bearer <token>"
  ```
</CodeGroup>

### Example 5: Search with pagination

<CodeGroup>
  ```bash cURL theme={null}
  curl -X GET "https://joptic.jethings.com/item-variants?search=1.67&page=1&limit=10" \
    -H "x-store-id: your-store-id" \
    -H "Authorization: Bearer <token>"
  ```
</CodeGroup>

***

## Best Practices

<AccordionGroup>
  <Accordion title="Search Optimization">
    * Use specific search terms for better performance
    * Barcode searches are faster than name searches
    * Combine search with pagination for large result sets
    * Use appropriate limit values (10-50 for most cases)
  </Accordion>

  <Accordion title="Pagination">
    * Use default pagination (page=1, limit=10) for most use cases
    * Increase limit (max 100) only when necessary
    * Always check `hasNext` and `hasPrev` for navigation
    * Implement proper error handling for invalid page numbers
  </Accordion>

  <Accordion title="Barcode Usage">
    * Use barcode search for point-of-sale scenarios
    * Ensure barcodes are properly associated with item variants
    * Handle cases where barcode might not be found
    * Consider implementing barcode scanning in your application
  </Accordion>

  <Accordion title="Error Handling">
    * Always check for 403 errors when accessing store data
    * Handle empty search results gracefully
    * Implement retry logic for 500 errors with exponential backoff
    * Validate pagination parameters before making requests
  </Accordion>

  <Accordion title="Performance">
    * Cache frequently accessed item variants when possible
    * Use search filters to reduce result set size
    * Avoid fetching all variants without pagination
    * Consider implementing client-side filtering for small datasets
  </Accordion>

  <Accordion title="Data Consistency">
    * Be aware that deleted variants are automatically excluded
    * Check `isActive` status for availability
    * Handle null values for `name` and `description` fields
    * Verify store access before displaying results to users
  </Accordion>
</AccordionGroup>

***

## Related Endpoints

Item variants work in conjunction with other inventory management endpoints:

* **Item API** (`/items`) - Create and manage items that contain variants
* **Item CRUD API** (`/items`) - Update item variants and their properties
* **Stock Reconciliation API** (`/stock-reconciliation`) - Reconcile inventory for specific item variants
* **Price List API** (`/price-lists`) - Set prices for item variants

<Info>
  Item variants are automatically created when items are created. Use the Item API to create new items with variants, and use this endpoint to search and retrieve existing variants.
</Info>

***

## Summary

| Endpoint         | Method | Description                                                   |
| ---------------- | ------ | ------------------------------------------------------------- |
| `/item-variants` | `GET`  | Retrieve paginated list of item variants with optional search |

### Key Features

* **Search by Barcode**: Find item variants by scanning or entering barcodes
* **Search by Name**: Find item variants by name (case-insensitive)
* **Pagination**: Efficient data retrieval with configurable page size
* **Store Filtering**: Automatic filtering by authenticated user's store
* **Soft Delete**: Deleted variants are automatically excluded

***

<CardGroup cols={2}>
  <Card title="Item API" icon="package" href="/j-optic/item-api">
    Create and manage optical items
  </Card>

  <Card title="Item CRUD API" icon="edit" href="/j-optic/item-crud">
    Update items and variants
  </Card>

  <Card title="Stock Reconciliation API" icon="clipboard-check" href="/j-optic/stock-reconciliation-api">
    Reconcile inventory for item variants
  </Card>

  <Card title="Price List API" icon="tag" href="/j-optic/price-list-api">
    Manage prices for item variants
  </Card>
</CardGroup>
