> For the complete documentation index, see [llms.txt](https://docs.beeoclock.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.beeoclock.com/services/product-management/api.md).

# API Documentation

## Overview

The Product Management API provides comprehensive functionality for managing products and product tags within the Bee O'clock panel service. This module handles the complete product lifecycle, including creation, updates, status management, deletion, and image management for products and their associated tags.

## Base Configuration

### Authentication

All endpoints require Bearer token authentication.

### Headers

* `Authorization: Bearer <token>` - Required for all endpoints
* `x-business-tenant-id: <tenant_id>` - Required for multi-tenancy support
* `Content-Type: application/json` - For POST/PUT requests
* `Content-Type: multipart/form-data` - For image upload requests

### Base URLs

```
/api/v1/product          # Product management
/api/v1/product-tag      # Product tag management
/api/v1/product-media    # Product image management
```

## Product Endpoints

### 1. Get Paginated Products

**Endpoint:** `GET /api/v1/product/paged`

**Description:** Retrieves a paginated list of products with advanced filtering capabilities.

**Query Parameters:**

```typescript
{
  page?: number;           // Page number (default: 1)
  size?: number;           // Items per page (default: 10)
  phrase?: string;         // Search phrase for product title/description
  tags?: string[];         // Filter by product tags
}
```

**Response:**

```typescript
{
  items: ProductDto[];
  totalSize: number;
}
```

**Example Request:**

```bash
GET /api/v1/product/paged?page=1&size=10&phrase=massage&tags[]=wellness&tags[]=therapy
Authorization: Bearer <token>
x-business-tenant-id: <tenant_id>
```

**Example Response:**

```json
{
  "items": [
    {
      "_id": "64fa1c71b19d6d001c88a91f",
      "object": "ProductDto",
      "sku": "WELLNESS-001",
      "languageVersions": [
        {
          "language": "en",
          "title": "Premium Aromatherapy Oil Set",
          "description": "Organic essential oils perfect for therapeutic massage and relaxation"
        },
        {
          "language": "es", 
          "title": "Set de Aceites de Aromaterapia Premium",
          "description": "Aceites esenciales orgánicos perfectos para masajes terapéuticos y relajación"
        }
      ],
      "price": {
        "object": "ProductPriceDto",
        "value": 49.99,
        "currency": "USD"
      },
      "tags": ["wellness", "therapy", "aromatherapy", "organic"],
      "images": [
        {
          "_id": "64fa1c71b19d6d001c88a920",
          "url": "https://cdn.beeoclock.com/products/aromatherapy-set-main.jpg",
          "type": "image",
          "mimeType": "image/jpeg",
          "size": 256000,
          "alt": "Premium Aromatherapy Oil Set"
        }
      ],
      "order": 1,
      "createdAt": "2024-07-26T08:00:00.000Z",
      "updatedAt": "2024-07-26T08:30:00.000Z"
    }
  ],
  "totalSize": 25
}
```

### 2. Get Product by ID

**Endpoint:** `GET /api/v1/product/{id}`

**Description:** Retrieves a specific product by its ID with permission validation.

**Path Parameters:**

* `id` (string, required) - Product ID

**Response:** `ProductDto`

**Example Request:**

```bash
GET /api/v1/product/64fa1c71b19d6d001c88a91f
Authorization: Bearer <token>
x-business-tenant-id: <tenant_id>
```

**Example Response:**

```json
{
  "_id": "64fa1c71b19d6d001c88a91f",
  "object": "ProductDto",
  "sku": "WELLNESS-001",
  "languageVersions": [
    {
      "language": "en",
      "title": "Premium Aromatherapy Oil Set",
      "description": "Organic essential oils perfect for therapeutic massage and relaxation. Each bottle contains 10ml of pure essential oil extracted using traditional methods."
    },
    {
      "language": "es",
      "title": "Set de Aceites de Aromaterapia Premium", 
      "description": "Aceites esenciales orgánicos perfectos para masajes terapéuticos y relajación. Cada botella contiene 10ml de aceite esencial puro extraído usando métodos tradicionales."
    }
  ],
  "price": {
    "object": "ProductPriceDto",
    "value": 49.99,
    "currency": "USD"
  },
  "tags": ["wellness", "therapy", "aromatherapy", "organic"],
  "images": [
    {
      "_id": "64fa1c71b19d6d001c88a920",
      "url": "https://cdn.beeoclock.com/products/aromatherapy-set-main.jpg",
      "type": "image",
      "mimeType": "image/jpeg",
      "size": 256000,
      "alt": "Premium Aromatherapy Oil Set - Main Image"
    },
    {
      "_id": "64fa1c71b19d6d001c88a921",
      "url": "https://cdn.beeoclock.com/products/aromatherapy-set-detail.jpg",
      "type": "image", 
      "mimeType": "image/jpeg",
      "size": 198000,
      "alt": "Premium Aromatherapy Oil Set - Detail View"
    }
  ],
  "order": 1,
  "createdAt": "2024-07-26T08:00:00.000Z",
  "updatedAt": "2024-07-26T08:30:00.000Z"
}
```

### 3. Create Product

**Endpoint:** `POST /api/v1/product`

**Description:** Creates a new product with validation and permission checks.

**Request Body:** `ProductDto`

**Response:** `ProductDto`

**Example Request:**

```bash
POST /api/v1/product
Authorization: Bearer <token>
x-business-tenant-id: <tenant_id>
Content-Type: application/json

{
  "sku": "WELLNESS-002",
  "languageVersions": [
    {
      "language": "en",
      "title": "Himalayan Salt Scrub",
      "description": "Exfoliating body scrub made with pure Himalayan pink salt and organic oils"
    },
    {
      "language": "es",
      "title": "Exfoliante de Sal del Himalaya",
      "description": "Exfoliante corporal hecho con sal rosa pura del Himalaya y aceites orgánicos"
    }
  ],
  "price": {
    "value": 29.99,
    "currency": "USD"
  },
  "tags": ["exfoliation", "himalayan", "organic", "spa"],
  "order": 2
}
```

**Example Response:**

```json
{
  "_id": "64fa1c71b19d6d001c88a922",
  "object": "ProductDto",
  "sku": "WELLNESS-002",
  "languageVersions": [
    {
      "language": "en",
      "title": "Himalayan Salt Scrub",
      "description": "Exfoliating body scrub made with pure Himalayan pink salt and organic oils"
    },
    {
      "language": "es",
      "title": "Exfoliante de Sal del Himalaya",
      "description": "Exfoliante corporal hecho con sal rosa pura del Himalaya y aceites orgánicos"
    }
  ],
  "price": {
    "object": "ProductPriceDto",
    "value": 29.99,
    "currency": "USD"
  },
  "tags": ["exfoliation", "himalayan", "organic", "spa"],
  "images": [],
  "order": 2,
  "createdAt": "2024-07-26T09:00:00.000Z",
  "updatedAt": "2024-07-26T09:00:00.000Z"
}
```

### 4. Update Product

**Endpoint:** `PUT /api/v1/product/{id}`

**Description:** Updates an existing product with validation and permission checks.

**Path Parameters:**

* `id` (string, required) - Product ID

**Request Body:** `ProductDto`

**Response:** `ProductDto`

**Example Request:**

```bash
PUT /api/v1/product/64fa1c71b19d6d001c88a922
Authorization: Bearer <token>
x-business-tenant-id: <tenant_id>
Content-Type: application/json

{
  "_id": "64fa1c71b19d6d001c88a922",
  "sku": "WELLNESS-002",
  "languageVersions": [
    {
      "language": "en",
      "title": "Premium Himalayan Salt Scrub",
      "description": "Luxury exfoliating body scrub made with pure Himalayan pink salt, organic oils, and vitamin E"
    },
    {
      "language": "es",
      "title": "Exfoliante Premium de Sal del Himalaya",
      "description": "Exfoliante corporal de lujo hecho con sal rosa pura del Himalaya, aceites orgánicos y vitamina E"
    }
  ],
  "price": {
    "value": 39.99,
    "currency": "USD"
  },
  "tags": ["exfoliation", "himalayan", "organic", "spa", "premium", "vitamin-e"],
  "order": 2
}
```

### 5. Delete Product

**Endpoint:** `DELETE /api/v1/product/{id}`

**Description:** Soft deletes a product with permission validation and dependency checking.

**Path Parameters:**

* `id` (string, required) - Product ID

**Response:** `void` (204 No Content)

**Example Request:**

```bash
DELETE /api/v1/product/64fa1c71b19d6d001c88a922
Authorization: Bearer <token>
x-business-tenant-id: <tenant_id>
```

## Product Tag Endpoints

### 1. Get Paginated Product Tags

**Endpoint:** `GET /api/v1/product-tag/paged`

**Description:** Retrieves a paginated list of product tags with filtering capabilities.

**Query Parameters:**

```typescript
{
  page?: number;           // Page number (default: 1)
  size?: number;           // Items per page (default: 10)
  phrase?: string;         // Search phrase for tag names
}
```

**Response:**

```typescript
{
  items: TagDto[];
  totalSize: number;
}
```

**Example Request:**

```bash
GET /api/v1/product-tag/paged?page=1&size=10&phrase=therapy
Authorization: Bearer <token>
x-business-tenant-id: <tenant_id>
```

**Example Response:**

```json
{
  "items": [
    {
      "_id": "64fa1c71b19d6d001c88a923",
      "object": "ProductTagDto",
      "name": "aromatherapy",
      "createdAt": "2024-07-26T08:00:00.000Z",
      "updatedAt": "2024-07-26T08:00:00.000Z"
    },
    {
      "_id": "64fa1c71b19d6d001c88a924",
      "object": "ProductTagDto",
      "name": "therapy",
      "createdAt": "2024-07-26T08:05:00.000Z",
      "updatedAt": "2024-07-26T08:05:00.000Z"
    }
  ],
  "totalSize": 8
}
```

### 2. Get Product Tag by ID

**Endpoint:** `GET /api/v1/product-tag/{id}`

**Description:** Retrieves a specific product tag by its ID.

**Path Parameters:**

* `id` (string, required) - Tag ID

**Response:** `TagDto`

**Example Request:**

```bash
GET /api/v1/product-tag/64fa1c71b19d6d001c88a923
Authorization: Bearer <token>
x-business-tenant-id: <tenant_id>
```

**Example Response:**

```json
{
  "_id": "64fa1c71b19d6d001c88a923",
  "object": "ProductTagDto",
  "name": "aromatherapy",
  "createdAt": "2024-07-26T08:00:00.000Z",
  "updatedAt": "2024-07-26T08:00:00.000Z"
}
```

### 3. Create Product Tag

**Endpoint:** `POST /api/v1/product-tag`

**Description:** Creates a new product tag with validation.

**Request Body:** `TagDto`

**Response:** `TagDto`

**Example Request:**

```bash
POST /api/v1/product-tag
Authorization: Bearer <token>
x-business-tenant-id: <tenant_id>
Content-Type: application/json

{
  "name": "luxury"
}
```

**Example Response:**

```json
{
  "_id": "64fa1c71b19d6d001c88a925",
  "object": "ProductTagDto",
  "name": "luxury",
  "createdAt": "2024-07-26T09:00:00.000Z",
  "updatedAt": "2024-07-26T09:00:00.000Z"
}
```

### 4. Update Product Tag

**Endpoint:** `PUT /api/v1/product-tag/{id}`

**Description:** Updates an existing product tag.

**Path Parameters:**

* `id` (string, required) - Tag ID

**Request Body:** `TagDto`

**Response:** `TagDto`

**Example Request:**

```bash
PUT /api/v1/product-tag/64fa1c71b19d6d001c88a925
Authorization: Bearer <token>
x-business-tenant-id: <tenant_id>
Content-Type: application/json

{
  "_id": "64fa1c71b19d6d001c88a925",
  "name": "premium-luxury"
}
```

### 5. Delete Product Tag

**Endpoint:** `DELETE /api/v1/product-tag/{id}`

**Description:** Deletes a product tag with dependency validation.

**Path Parameters:**

* `id` (string, required) - Tag ID

**Response:** `void` (204 No Content)

**Example Request:**

```bash
DELETE /api/v1/product-tag/64fa1c71b19d6d001c88a925
Authorization: Bearer <token>
x-business-tenant-id: <tenant_id>
```

## Product Media Endpoints

### 1. Upload/Update Product Image

**Endpoint:** `PATCH /api/v1/product-media/{productId}/images`

**Description:** Uploads a new image or updates an existing image for a product.

**Path Parameters:**

* `productId` (string, required) - Product ID

**Request Body:** `multipart/form-data`

* `file` (File, required) - Image file to upload
* Additional media metadata fields

**Response:** `MediaDto`

**Example Request:**

```bash
PATCH /api/v1/product-media/64fa1c71b19d6d001c88a91f/images
Authorization: Bearer <token>
x-business-tenant-id: <tenant_id>
Content-Type: multipart/form-data

--boundary123
Content-Disposition: form-data; name="file"; filename="aromatherapy-oils.jpg"
Content-Type: image/jpeg

[binary image data]
--boundary123
Content-Disposition: form-data; name="alt"

Premium Aromatherapy Oil Set - Updated Image
--boundary123--
```

**Example Response:**

```json
{
  "_id": "64fa1c71b19d6d001c88a926",
  "url": "https://cdn.beeoclock.com/products/aromatherapy-oils-updated.jpg",
  "type": "image",
  "mimeType": "image/jpeg",
  "size": 312000,
  "alt": "Premium Aromatherapy Oil Set - Updated Image",
  "createdAt": "2024-07-26T09:30:00.000Z",
  "updatedAt": "2024-07-26T09:30:00.000Z"
}
```

### 2. Delete Product Image

**Endpoint:** `DELETE /api/v1/product-media/{productId}/{id}`

**Description:** Deletes a specific image from a product.

**Path Parameters:**

* `productId` (string, required) - Product ID
* `id` (string, required) - Image ID

**Response:** `void` (204 No Content)

**Example Request:**

```bash
DELETE /api/v1/product-media/64fa1c71b19d6d001c88a91f/64fa1c71b19d6d001c88a926
Authorization: Bearer <token>
x-business-tenant-id: <tenant_id>
```

## Data Models

### ProductDto

```typescript
{
  _id?: string;                              // Product ID
  object?: 'ProductDto';                     // Object type identifier
  sku?: string;                              // Product SKU/identifier
  languageVersions: LanguageVersionDto[];    // Multi-language content
  price: ProductPriceDto;                    // Product pricing information
  tags?: string[];                           // Product tags for categorization
  images?: MediaDto[];                       // Product images
  order?: number;                            // Display order priority
  createdAt?: string;                        // Creation timestamp
  updatedAt?: string;                        // Last update timestamp
}
```

### ProductPriceDto

```typescript
{
  object?: 'ProductPriceDto';                // Object type identifier
  value: number;                             // Price value
  currency: CurrencyCodeEnum;                // Currency code (USD, EUR, etc.)
}
```

### ProductPaginationDto

```typescript
{
  page?: number;                             // Page number (default: 1)
  size?: number;                             // Items per page (default: 10)
  phrase?: string;                           // Search phrase for title/description
  tags?: string[];                           // Filter by product tags
}
```

### TagDto

```typescript
{
  _id?: string;                              // Tag ID
  object?: 'ProductTagDto';                  // Object type identifier
  name?: string;                             // Tag name
  createdAt?: string;                        // Creation timestamp
  updatedAt?: string;                        // Last update timestamp
}
```

### TagPaginationDto

```typescript
{
  page?: number;                             // Page number (default: 1)
  size?: number;                             // Items per page (default: 10)
  phrase?: string;                           // Search phrase for tag names
}
```

### LanguageVersionDto

```typescript
{
  language: string;                          // Language code (en, es, fr, etc.)
  title: string;                             // Product title in specified language
  description?: string;                      // Product description in specified language
}
```

### MediaDto

```typescript
{
  _id: string;                               // Media ID
  url: string;                               // CDN URL for the image
  type: string;                              // Media type (image, video, etc.)
  mimeType: string;                          // MIME type (image/jpeg, image/png, etc.)
  size: number;                              // File size in bytes
  alt?: string;                              // Alternative text for accessibility
  createdAt: string;                         // Creation timestamp
  updatedAt: string;                         // Last update timestamp
}
```

## Enums

### CurrencyCodeEnum

```typescript
enum CurrencyCodeEnum {
  USD = 'USD',                               // US Dollar
  EUR = 'EUR',                               // Euro
  GBP = 'GBP',                               // British Pound
  CAD = 'CAD',                               // Canadian Dollar
  AUD = 'AUD',                               // Australian Dollar
  JPY = 'JPY',                               // Japanese Yen
  CHF = 'CHF',                               // Swiss Franc
  CNY = 'CNY',                               // Chinese Yuan
  INR = 'INR',                               // Indian Rupee
  BRL = 'BRL',                               // Brazilian Real
  MXN = 'MXN',                               // Mexican Peso
  ZAR = 'ZAR',                               // South African Rand
}
```

## Error Handling

### Common Error Responses

#### 400 Bad Request

```json
{
  "statusCode": 400,
  "message": "Validation failed",
  "error": "Bad Request",
  "details": [
    {
      "field": "price.value",
      "message": "Price must be a positive number"
    },
    {
      "field": "languageVersions",
      "message": "At least one language version is required"
    }
  ]
}
```

#### 401 Unauthorized

```json
{
  "statusCode": 401,
  "message": "Unauthorized",
  "error": "Authentication required"
}
```

#### 403 Forbidden

```json
{
  "statusCode": 403,
  "message": "Access denied",
  "error": "Insufficient permissions to access product management"
}
```

#### 404 Not Found

```json
{
  "statusCode": 404,
  "message": "Product not found",
  "error": "Product with ID 64fa1c71b19d6d001c88a91f does not exist"
}
```

#### 409 Conflict

```json
{
  "statusCode": 409,
  "message": "Product creation conflict",
  "error": "Product with SKU 'WELLNESS-001' already exists"
}
```

#### 413 Payload Too Large

```json
{
  "statusCode": 413,
  "message": "File too large",
  "error": "Image file size exceeds maximum limit of 5MB"
}
```

#### 415 Unsupported Media Type

```json
{
  "statusCode": 415,
  "message": "Unsupported file type",
  "error": "Only JPEG, PNG, and WebP images are supported"
}
```

#### 422 Unprocessable Entity

```json
{
  "statusCode": 422,
  "message": "Business validation failed",
  "error": "Cannot delete product that is currently used in active orders"
}
```

## Business Rules

### Product Creation

1. **SKU Uniqueness**: Each product must have a unique SKU within the tenant
2. **Language Validation**: At least one language version is required
3. **Price Validation**: Price value must be positive and currency must be valid
4. **Tag Validation**: All tags must exist in the product tag collection
5. **Image Constraints**: Maximum 10 images per product, each under 5MB

### Product Updates

1. **SKU Immutability**: SKU cannot be changed after product creation
2. **Language Preservation**: Cannot remove all language versions
3. **Price History**: Price changes are tracked for audit purposes
4. **Tag Management**: Tags are managed separately and referenced by name
5. **Image Management**: Images can be added, updated, or removed independently

### Product Deletion

1. **Soft Delete**: Products are marked as deleted rather than physically removed
2. **Order Dependency**: Cannot delete products that are used in active orders
3. **History Preservation**: All historical data is maintained for audit purposes
4. **Cascade Rules**: Associated images are also soft deleted

### Tag Management

1. **Name Uniqueness**: Tag names must be unique within the tenant
2. **Case Sensitivity**: Tag names are case-insensitive
3. **Usage Tracking**: Cannot delete tags that are currently used by products
4. **Bulk Operations**: Support for bulk tag creation and management

### Permission Requirements

1. **Product Operations**:
   * `READ_PRODUCT` (11001) - View products
   * `CREATE_PRODUCT` (11002) - Create new products
   * `EDIT_PRODUCT` (11003) - Update existing products
   * `DELETE_PRODUCT` (11004) - Delete products
   * `CRUD_PRODUCT` (11000) - All product operations
2. **Tag Operations**:
   * `READ_PRODUCT_TAG` (12001) - View product tags
   * `CREATE_PRODUCT_TAG` (12002) - Create new tags
   * `EDIT_PRODUCT_TAG` (12003) - Update existing tags
   * `DELETE_PRODUCT_TAG` (12004) - Delete tags
   * `CRUD_PRODUCT_TAG` (12000) - All tag operations

### Image Management

1. **File Types**: Only JPEG, PNG, and WebP formats are supported
2. **File Size**: Maximum 5MB per image
3. **Image Count**: Maximum 10 images per product
4. **Resolution**: Recommended minimum 800x600 pixels
5. **Optimization**: Images are automatically optimized and resized

## Performance Considerations

### Pagination

* Default page size: 10 items
* Maximum page size: 100 items
* Use pagination for large product catalogs

### Filtering and Search

* Text search is optimized with MongoDB text indexes
* Tag filtering uses indexed arrays for fast queries
* Multi-language search supports all language versions

### Caching

* Product data is cached for frequently accessed items
* Image CDN caching with long expiration times
* Tag data is heavily cached due to infrequent changes

### Database Optimization

* Compound indexes on commonly filtered fields
* Text indexes for search functionality
* Optimized queries with proper field projection

## Rate Limiting

* **Read Operations**: 100 requests per minute per user
* **Write Operations**: 30 requests per minute per user
* **Image Upload**: 10 requests per minute per user
* **Bulk Operations**: 5 requests per minute per user

## File Upload Specifications

### Supported Image Formats

* **JPEG** (.jpg, .jpeg) - Recommended for photographs
* **PNG** (.png) - Recommended for graphics with transparency
* **WebP** (.webp) - Modern format with excellent compression

### Image Processing

* **Automatic Optimization**: Images are automatically compressed and optimized
* **Multiple Sizes**: Thumbnails and preview sizes are generated automatically
* **CDN Distribution**: Images are distributed via CDN for fast global access
* **Format Conversion**: Images may be converted to WebP for better performance

### Upload Constraints

* **Maximum File Size**: 5MB per image
* **Maximum Dimensions**: 4000x4000 pixels
* **Minimum Dimensions**: 200x200 pixels (recommended)
* **Image Count**: Maximum 10 images per product

## Monitoring and Logging

### Request Logging

All API requests are logged with:

* Request ID for tracing
* User context and permissions
* Performance metrics
* Error details and stack traces

### Business Event Logging

* Product creation, updates, and deletions
* Tag management operations
* Image upload and management activities
* Permission validation events

### Performance Monitoring

* Response time tracking for all endpoints
* Database query performance analysis
* Cache hit rates and effectiveness
* Image processing and upload metrics
* Error rate monitoring and alerting

## Security Considerations

### Input Validation

* Comprehensive validation of all input data
* SQL injection prevention through parameterized queries
* XSS prevention through output encoding
* File upload security with type and size validation

### Access Control

* Role-based permission system
* Tenant-based data isolation
* API rate limiting and abuse prevention
* Audit logging for all sensitive operations

### Image Security

* Virus scanning for uploaded files
* Content type validation
* File size and dimension limits
* Secure file storage with access controls

## Integration Examples

### Creating a Product with Multiple Languages

```typescript
const newProduct = {
  sku: "SPA-ESSENTIALS-001",
  languageVersions: [
    {
      language: "en",
      title: "Essential Oils Starter Kit",
      description: "Complete starter kit with 6 essential oils and diffuser"
    },
    {
      language: "es",
      title: "Kit Iniciador de Aceites Esenciales",
      description: "Kit iniciador completo con 6 aceites esenciales y difusor"
    },
    {
      language: "fr",
      title: "Kit de Démarrage aux Huiles Essentielles",
      description: "Kit de démarrage complet avec 6 huiles essentielles et diffuseur"
    }
  ],
  price: {
    value: 89.99,
    currency: "USD"
  },
  tags: ["essential-oils", "starter-kit", "diffuser", "aromatherapy"],
  order: 1
};
```

### Advanced Product Search

```typescript
// Search for wellness products with specific tags
GET /api/v1/product/paged?
  phrase=wellness&
  tags[]=organic&
  tags[]=therapy&
  page=1&
  size=20
```

### Bulk Image Upload Workflow

```typescript
// 1. Create product
const product = await createProduct(productData);

// 2. Upload multiple images
const images = [];
for (const imageFile of imageFiles) {
  const uploadedImage = await uploadProductImage(product._id, imageFile);
  images.push(uploadedImage);
}

// 3. Update product with image references
await updateProduct(product._id, { ...product, images });
```
