> 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/order-management/api.md).

# API Documentation

## Overview

The Order Management API provides comprehensive functionality for managing orders within the Bee O'clock panel service. This module handles the complete order lifecycle, including creation, updates, status management, and deletion of orders containing services and products.

## 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

### Base URL

```
/api/v1/order
```

## Endpoints

### 1. Get Paginated Orders

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

**Description:** Retrieves a paginated list of orders 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 order content
  start?: string;          // Start date filter (ISO string)
  end?: string;            // End date filter (ISO string)
  customerId?: string;     // Filter by customer ID
  statuses?: OrderStatusEnum[]; // Filter by order statuses
  memberIds?: string[];    // Filter by assigned member IDs
}
```

**Response:**

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

**Example Request:**

```bash
GET /api/v1/order/paged?page=1&size=10&statuses[]=inProgress&statuses[]=confirmed&start=2024-01-01T00:00:00.000Z&end=2024-12-31T23:59:59.999Z
Authorization: Bearer <token>
x-business-tenant-id: <tenant_id>
```

**Example Response:**

```json
{
  "items": [
    {
      "_id": "64fa1c71b19d6d001c88a91f",
      "status": "confirmed",
      "services": [
        {
          "_id": "64fa1c71b19d6d001c88a920",
          "orderId": "64fa1c71b19d6d001c88a91f",
          "serviceSnapshot": {
            "_id": "64fa1c71b19d6d001c88a921",
            "languageVersions": [
              {
                "language": "en",
                "title": "Premium Massage Therapy",
                "description": "Relaxing therapeutic massage"
              }
            ]
          },
          "orderAppointmentDetails": {
            "start": "2024-07-26T10:00:00.000Z",
            "end": "2024-07-26T11:00:00.000Z",
            "specialists": [
              {
                "_id": "64fa1c71b19d6d001c88a922",
                "profile": {
                  "firstName": "John",
                  "lastName": "Doe"
                }
              }
            ]
          },
          "status": "confirmed",
          "paymentStatus": "pending"
        }
      ],
      "products": [],
      "paymentStatus": "pending",
      "businessNote": "VIP customer",
      "customer": {
        "_id": "64fa1c71b19d6d001c88a923",
        "firstName": "Jane",
        "lastName": "Smith",
        "email": "jane.smith@example.com"
      },
      "createdAt": "2024-07-26T08:00:00.000Z",
      "updatedAt": "2024-07-26T08:30:00.000Z"
    }
  ],
  "totalSize": 25
}
```

### 2. Get Order by ID

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

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

**Path Parameters:**

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

**Response:** `OrderDto`

**Example Request:**

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

**Example Response:**

```json
{
  "_id": "64fa1c71b19d6d001c88a91f",
  "status": "confirmed",
  "services": [
    {
      "_id": "64fa1c71b19d6d001c88a920",
      "orderId": "64fa1c71b19d6d001c88a91f",
      "serviceSnapshot": {
        "_id": "64fa1c71b19d6d001c88a921",
        "languageVersions": [
          {
            "language": "en",
            "title": "Premium Massage Therapy",
            "description": "Relaxing therapeutic massage with aromatherapy"
          }
        ],
        "durationVersions": [
          {
            "durationInSeconds": 3600,
            "breakInSeconds": 300,
            "prices": [
              {
                "price": 80.00,
                "currency": "USD",
                "preferredLanguages": ["en"]
              }
            ]
          }
        ]
      },
      "orderAppointmentDetails": {
        "start": "2024-07-26T10:00:00.000Z",
        "end": "2024-07-26T11:00:00.000Z",
        "type": "service",
        "languageCodes": ["en"],
        "specialists": [
          {
            "_id": "64fa1c71b19d6d001c88a922",
            "profile": {
              "firstName": "John",
              "lastName": "Doe",
              "email": "john.doe@example.com"
            }
          }
        ],
        "attendants": [
          {
            "customer": {
              "_id": "64fa1c71b19d6d001c88a923",
              "firstName": "Jane",
              "lastName": "Smith",
              "email": "jane.smith@example.com"
            },
            "firstTime": true
          }
        ],
        "location": {
          "address": "123 Wellness Street, Health City",
          "coordinates": {
            "latitude": 40.7128,
            "longitude": -74.0060
          }
        }
      },
      "status": "confirmed",
      "customerNote": "Please use lavender oil for aromatherapy",
      "paymentStatus": "pending",
      "meta": {
        "source": "panel",
        "createdBy": "64fa1c71b19d6d001c88a924"
      },
      "createdAt": "2024-07-26T08:00:00.000Z",
      "updatedAt": "2024-07-26T08:30:00.000Z"
    }
  ],
  "products": [
    {
      "_id": "64fa1c71b19d6d001c88a925",
      "orderId": "64fa1c71b19d6d001c88a91f",
      "orderServiceId": "64fa1c71b19d6d001c88a920",
      "productSnapshot": {
        "_id": "64fa1c71b19d6d001c88a926",
        "title": "Aromatherapy Oil Set",
        "description": "Premium essential oils for massage therapy",
        "price": 25.00,
        "currency": "USD"
      },
      "quantity": 1,
      "paymentStatus": "pending",
      "meta": {
        "addedBy": "64fa1c71b19d6d001c88a924"
      }
    }
  ],
  "paymentStatus": "pending",
  "businessNote": "VIP customer - extra attention required",
  "notificationSettings": {
    "emailNotifications": true,
    "smsNotifications": false,
    "pushNotifications": true
  },
  "customer": {
    "_id": "64fa1c71b19d6d001c88a923",
    "firstName": "Jane",
    "lastName": "Smith",
    "email": "jane.smith@example.com",
    "phone": "+1-555-123-4567"
  },
  "meta": {
    "source": "panel",
    "createdBy": "64fa1c71b19d6d001c88a924",
    "lastModifiedBy": "64fa1c71b19d6d001c88a924"
  },
  "createdAt": "2024-07-26T08:00:00.000Z",
  "updatedAt": "2024-07-26T08:30:00.000Z"
}
```

### 3. Create Order

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

**Description:** Creates a new order with services and products through a saga pattern with validation and rollback capabilities.

**Request Body:** `OrderDto`

**Response:** `OrderDto`

**Example Request:**

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

{
  "services": [
    {
      "serviceSnapshot": {
        "_id": "64fa1c71b19d6d001c88a921",
        "languageVersions": [
          {
            "language": "en",
            "title": "Premium Massage Therapy",
            "description": "Relaxing therapeutic massage with aromatherapy"
          }
        ],
        "durationVersions": [
          {
            "durationInSeconds": 3600,
            "breakInSeconds": 300,
            "prices": [
              {
                "price": 80.00,
                "currency": "USD",
                "preferredLanguages": ["en"]
              }
            ]
          }
        ]
      },
      "orderAppointmentDetails": {
        "start": "2024-07-26T10:00:00.000Z",
        "end": "2024-07-26T11:00:00.000Z",
        "type": "service",
        "languageCodes": ["en"],
        "specialists": [
          {
            "_id": "64fa1c71b19d6d001c88a922"
          }
        ],
        "attendants": [
          {
            "customer": {
              "_id": "64fa1c71b19d6d001c88a923"
            },
            "firstTime": true
          }
        ],
        "location": {
          "address": "123 Wellness Street, Health City",
          "coordinates": {
            "latitude": 40.7128,
            "longitude": -74.0060
          }
        }
      },
      "customerNote": "Please use lavender oil for aromatherapy",
      "status": "requested"
    }
  ],
  "products": [
    {
      "productSnapshot": {
        "_id": "64fa1c71b19d6d001c88a926",
        "title": "Aromatherapy Oil Set",
        "description": "Premium essential oils for massage therapy",
        "price": 25.00,
        "currency": "USD"
      },
      "quantity": 1
    }
  ],
  "businessNote": "VIP customer - extra attention required",
  "notificationSettings": {
    "emailNotifications": true,
    "smsNotifications": false,
    "pushNotifications": true
  },
  "customer": {
    "_id": "64fa1c71b19d6d001c88a923"
  }
}
```

**Example Response:**

```json
{
  "_id": "64fa1c71b19d6d001c88a91f",
  "status": "requested",
  "services": [...],
  "products": [...],
  "paymentStatus": "pending",
  "businessNote": "VIP customer - extra attention required",
  "customer": {...},
  "createdAt": "2024-07-26T08:00:00.000Z",
  "updatedAt": "2024-07-26T08:00:00.000Z"
}
```

### 4. Update Order

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

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

**Path Parameters:**

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

**Request Body:** `OrderDto`

**Response:** `OrderDto`

**Example Request:**

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

{
  "_id": "64fa1c71b19d6d001c88a91f",
  "status": "confirmed",
  "services": [
    {
      "_id": "64fa1c71b19d6d001c88a920",
      "status": "confirmed",
      "customerNote": "Updated note: Please use eucalyptus oil instead"
    }
  ],
  "businessNote": "Updated: VIP customer confirmed for premium service"
}
```

### 5. Delete Order

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

**Description:** Soft deletes an order with permission validation and dependency checking.

**Path Parameters:**

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

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

**Example Request:**

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

## Data Models

### OrderDto

```typescript
{
  _id?: string;                              // Order ID
  status?: OrderStatusEnum;                  // Order status
  meta?: MetaDto;                           // Metadata information
  products?: OrderProductDto[];              // Order products
  services?: OrderServiceDto[];              // Order services
  paymentStatus?: PaymentStatusEnum;         // Payment status
  businessNote?: string;                     // Internal business note
  notificationSettings?: OrderNotificationSettingsDto; // Notification preferences
  customer?: CustomerDto;                    // Customer information
  createdAt?: string;                        // Creation timestamp
  updatedAt?: string;                        // Last update timestamp
}
```

### OrderServiceDto

```typescript
{
  _id?: string;                              // Service ID
  orderId?: string;                          // Parent order ID
  serviceSnapshot?: ServiceDto;              // Service configuration snapshot
  orderAppointmentDetails?: OrderAppointmentDetailsDto; // Appointment details
  status: OrderServiceStatusEnum;            // Service status
  customerNote?: string;                     // Customer note for service
  meta?: MetaDto;                           // Service metadata
  paymentStatus?: PaymentStatusEnum;         // Service payment status
  createdAt?: string;                        // Creation timestamp
  updatedAt?: string;                        // Last update timestamp
}
```

### OrderProductDto

```typescript
{
  _id?: string;                              // Product ID
  orderId?: string;                          // Parent order ID
  orderServiceId?: string;                   // Associated service ID
  productSnapshot: ProductDto;               // Product configuration snapshot
  quantity: number;                          // Product quantity
  meta?: MetaDto;                           // Product metadata
  paymentStatus?: PaymentStatusEnum;         // Product payment status
  createdAt?: string;                        // Creation timestamp
  updatedAt?: string;                        // Last update timestamp
}
```

### OrderAppointmentDetailsDto

```typescript
{
  start: string;                             // Appointment start time (ISO string)
  end: string;                               // Appointment end time (ISO string)
  type?: ReservationTypeEnum;                // Reservation type
  languageCodes?: LanguageCodeEnum[];        // Preferred languages
  specialists: SpecialistDto[];              // Assigned specialists
  attendants?: AttendantDto[];               // Service attendants
  location?: LocationDto;                    // Service location
  attachments?: AttachmentDto[];             // Additional attachments
}
```

### OrderPaginationDto

```typescript
{
  page?: number;                             // Page number
  size?: number;                             // Items per page
  phrase?: string;                           // Search phrase
  start?: string;                            // Start date filter
  end?: string;                              // End date filter
  customerId?: string;                       // Customer ID filter
  statuses?: OrderStatusEnum[];              // Status filters
  memberIds?: string[];                      // Member ID filters
}
```

## Enums

### OrderStatusEnum

```typescript
enum OrderStatusEnum {
  draft = 'draft',                           // Order in draft state
  deleted = 'deleted',                       // Order deleted
  requested = 'requested',                   // Order requested
  confirmed = 'confirmed',                   // Order confirmed
  inProgress = 'inProgress',                 // Order in progress
  done = 'done',                            // Order completed
  cancelled = 'cancelled',                   // Order cancelled
  rejected = 'rejected',                     // Order rejected
  waitingForPayment = 'waitingForPayment'    // Awaiting payment
}
```

### OrderServiceStatusEnum

```typescript
enum OrderServiceStatusEnum {
  requested = 'requested',                   // Service requested
  accepted = 'accepted',                     // Service accepted
  ready = 'ready',                          // Service ready
  inProgress = 'inProgress',                 // Service in progress
  done = 'done',                            // Service completed
  rejected = 'rejected',                     // Service rejected
  cancelled = 'cancelled',                   // Service cancelled
  deleted = 'deleted'                        // Service deleted
}
```

### ReservationTypeEnum

```typescript
enum ReservationTypeEnum {
  service = 'service',                       // Service reservation
  event = 'event',                          // Event reservation
  consultation = 'consultation'              // Consultation reservation
}
```

### PaymentStatusEnum

```typescript
enum PaymentStatusEnum {
  pending = 'pending',                       // Payment pending
  processing = 'processing',                 // Payment processing
  completed = 'completed',                   // Payment completed
  failed = 'failed',                        // Payment failed
  refunded = 'refunded',                    // Payment refunded
  cancelled = 'cancelled'                    // Payment cancelled
}
```

## Error Handling

### Common Error Responses

#### 400 Bad Request

```json
{
  "statusCode": 400,
  "message": "Validation failed",
  "error": "Bad Request",
  "details": [
    {
      "field": "services[0].orderAppointmentDetails.start",
      "message": "Start time must be a valid ISO string"
    }
  ]
}
```

#### 401 Unauthorized

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

#### 403 Forbidden

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

#### 404 Not Found

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

#### 409 Conflict

```json
{
  "statusCode": 409,
  "message": "Order creation conflict",
  "error": "Specialist is not available during the requested time slot"
}
```

#### 422 Unprocessable Entity

```json
{
  "statusCode": 422,
  "message": "Business validation failed",
  "error": "Cannot cancel order with confirmed payment"
}
```

## Business Rules

### Order Creation

1. **Service Validation**: All services must be valid and available
2. **Time Slot Validation**: Appointment times must not conflict with existing bookings
3. **Specialist Availability**: Assigned specialists must be available during requested times
4. **Customer Validation**: Customer must exist and be valid
5. **Product Validation**: All products must be available in inventory

### Order Updates

1. **Status Transitions**: Updates must follow valid status transition rules
2. **Service Modification**: Changes to services require specialist availability validation
3. **Payment Constraints**: Cannot modify orders with completed payments
4. **Time Constraints**: Cannot modify past appointments
5. **Permission Validation**: User must have appropriate permissions for the scope of changes

### Order Deletion

1. **Soft Delete**: Orders are marked as deleted rather than physically removed
2. **Payment Check**: Cannot delete orders with active or completed payments
3. **Dependency Validation**: Cannot delete orders with dependent records
4. **History Preservation**: All historical data is maintained for audit purposes

### Permission Scopes

1. **OWN**: Users can only access orders assigned to them
2. **TEAM**: Users can access orders within their team
3. **BUSINESS**: Users can access all orders within the business
4. **ADMIN**: Full access to all order operations

## Performance Considerations

### Pagination

* Default page size: 10 items
* Maximum page size: 100 items
* Use pagination for large datasets to maintain performance

### Filtering

* Date range filters are optimized with database indexes
* Status filtering uses enum indexes for fast queries
* Member ID filtering supports array-based queries

### Caching

* Order data is cached for frequently accessed items
* Cache invalidation occurs on order updates
* Cache warming for dashboard queries

### Database Optimization

* Compound indexes on status, dates, and member IDs
* Separate collections for order services and products
* Optimized queries with projection for large orders

## Rate Limiting

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

## 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

* Order status changes
* Payment status updates
* Service assignments and modifications
* Customer interactions and notes

### Performance Monitoring

* Response time tracking
* Database query performance
* Cache hit rates
* Error rate monitoring
