# order3000 Node.js SDK

A TypeScript-first Node.js SDK for integrating with the order3000 restaurant management platform. This SDK provides a simple, type-safe interface for managing orders, reservations, and other restaurant operations through the order3000 API.

## Overview

order3000 is a comprehensive restaurant management platform that handles orders, reservations, customer management, and more. This SDK allows external applications and websites to integrate seamlessly with order3000 through a clean, promise-based API.

### Key Features

- 🔐 **OAuth2 Authentication** - Secure client credentials flow with automatic token management
- 🏢 **Multi-Tenant Support** - Built for multi-restaurant/tenant operations
- 📝 **TypeScript Support** - Full TypeScript support with auto-generated types from OpenAPI spec
- 🔄 **Auto Token Refresh** - Automatic token renewal with 5-minute buffer before expiration
- 🎯 **Type-Safe API** - OpenAPI-generated types ensure type safety across all operations
- ⚡ **Modern Architecture** - Built with ES modules and CommonJS dual support

## Installation

```bash
npm install order3000
# or
yarn add order3000
# or
pnpm add order3000
```

## Quick Start

```typescript
import { O3KClient } from 'order3000'

// Initialize the client
const client = new O3KClient({
  clientId: 'your-client-id',
  clientSecret: 'your-client-secret',
  tenantId: 'your-tenant-id', // Optional - will use default from token if not provided
  baseUrl: 'https://api.order3000.com', // Optional - defaults to production
})

// Place an order
const order = await client.orders.place({
  tenantId: 'restaurant-123',
  basketId: 'basket-456',
  status: 'PENDING',
  paymentMethod: 'CARD',
  taxAmount: '2.50',
  totalAmount: '25.00',
  currency: 'USD',
  orderedBy: 'customer@example.com',
})

console.log('Order placed:', order.id)
```

## Type naming convention

Every exported name in this SDK carries an **`O3K`** prefix
(`O3KClient`, `O3KFetchTeamOrderResponse`, `O3KMenuItem`,
`O3KPaymentMethodEnum`, …). The prefix namespaces the SDK surface so
consumer code never has to alias imports to disambiguate them from local
domain types:

```typescript
// no `as SDKFoo` aliasing needed — the name is already namespaced
import type { O3KFetchTeamOrderResponse } from 'order3000'
```

## Architecture

### Authentication Flow

The SDK uses OAuth2 client credentials flow for authentication:

1. **Initial Authentication**: On first use, the SDK requests an access token using your client credentials
2. **Token Storage**: The access token is stored in memory with its expiration time
3. **Automatic Refresh**: Tokens are automatically refreshed 5 minutes before expiration
4. **Tenant Resolution**: If no tenant ID is provided, the SDK extracts the default tenant from the JWT token

### Project Structure

```
order3000-nodejs/
├── src/
│   ├── client.ts           # Main client class and initialization
│   ├── token-manager.ts    # OAuth2 token management and refresh logic
│   ├── resources/
│   │   ├── index.ts        # Base resource class for API calls
│   │   └── orders.ts       # Orders resource implementation
│   └── types/
│       ├── index.ts        # Type exports
│       └── generated.d.ts  # Auto-generated types from OpenAPI spec
├── scripts/
│   ├── dev.sh             # Development script with Vault integration
│   └── vaultcar.sh        # HashiCorp Vault integration for secrets
└── package.json
```

## Configuration

### Client Options

```typescript
interface O3KClientConfig {
  clientId: string // OAuth2 client ID (required)
  clientSecret: string // OAuth2 client secret (required)
  tenantId?: string // Specific tenant ID (optional)
  baseUrl?: string // Base URL for API requests (default: https://order3000.com/api)
  tokenUrl?: string // OAuth2 token endpoint (default: ${baseUrl}/auth/token)
}
```

### Environment Variables

For development, you can use environment variables:

```bash
ORDER3000_CLIENT_ID=your-client-id
ORDER3000_CLIENT_SECRET=your-client-secret
ORDER3000_BASE_URL=https://api.order3000.com
```

## API Documentation

For complete API documentation including all available endpoints, request/response schemas, and interactive examples, visit:

- **Development**: http://localhost:3000/developers/reference
- **Staging**: https://staging.order3000.com/developers/reference
- **Production**: https://order3000.com/developers/reference

The API documentation is powered by Scalar and provides a comprehensive view of all available endpoints, schemas, and integration examples.

## SDK Development Workflow

### Adding New API Endpoints

When new endpoints are added or modified in the order3000 platform, follow this workflow to update the SDK:

1. **Define API Contracts**: Create or update TypeScript contracts that define the API structure
   - Add/modify contracts in `/apps/order3000/src/app/api/openapi/contracts/`
   - Use `@ts-rest/core` to define type-safe contracts
   - Export contracts from `/apps/order3000/src/app/api/openapi/contract.ts`
   - Generate OpenAPI spec to preview changes: `npx nx run order3000:generate-openapi`
   - View updated docs at http://localhost:3000/developers/reference

2. **Implement API Endpoints**: Create the actual endpoint logic in the order3000 application
   - Implement handlers in `/apps/order3000/src/app/api/` following the contract definitions
   - Ensure endpoints match the contracts exactly

3. **Update SDK Resources**: Integrate the new endpoints into the SDK
   - Create or update resource classes in `/apps/order3000-nodejs/src/resources/`
   - Follow the existing pattern extending from `BaseResource`
   - Export new resources from the main `O3KClient` class
   - Note: Type generation (`npm run build:types`) is handled automatically by CI/CD

4. **Create Changeset**: Document the changes

   ```bash
   pnpm changeset
   ```

   - Select `order3000` package
   - Choose version bump type (patch/minor/major)
   - Describe the new endpoints or changes added

5. **CI/CD Pipeline**: The automated pipeline handles the rest
   - Generates types from OpenAPI spec automatically
   - Builds the SDK package with `pkgroll`
   - Runs tests and type checking
   - Publishes to npm registry as `order3000` package
   - Updates version numbers based on changeset

### Local Development

```bash
# Generate types from OpenAPI spec
npm run build:types

# Build the package locally
npm run build

# Test SDK in development mode
npm run dev
```

### Development with Vault

The SDK includes HashiCorp Vault integration for secure credential management:

```bash
# Run with Vault integration
npm run dev
```

Credentials are fetched from:

- `secret/kolaveri/thamarai/ORDER3000_CLIENT_ID`
- `secret/kolaveri/thamarai/ORDER3000_CLIENT_SECRET`
- `secret/kolaveri/thamarai/ORDER3000_BASE_URL`

## Security Considerations

1. **Never commit credentials** - Always use environment variables or secret management systems
2. **Token Security** - Access tokens are stored in memory only, never persisted to disk
3. **HTTPS Only** - All API calls are made over HTTPS
4. **Automatic Token Rotation** - Tokens are refreshed automatically before expiration

## Error Handling

```typescript
try {
  const order = await client.orders.place({
    // ... order details
  })
} catch (error) {
  if (error.response?.statusCode === 401) {
    console.error('Authentication failed - check credentials')
  } else if (error.response?.statusCode === 400) {
    console.error('Invalid order data:', error.response.body)
  } else {
    console.error('Unexpected error:', error)
  }
}
```

## Platform Integration

### Multi-Tenant Architecture

order3000 supports multi-tenant operations where each restaurant or location is a separate tenant:

- **Automatic Tenant Resolution**: If no tenant ID is provided, the SDK uses the default tenant from the authentication token
- **Explicit Tenant Selection**: You can specify a tenant ID in the client configuration or per-request
- **Tenant Isolation**: All operations are scoped to the specified tenant

### Related Components

The order3000 platform includes:

- **Reservations System**: Complete table reservation management with flexible contact preferences
- **Customer Management**: Customer profiles with order history and preferences
- **Order Management**: Full order lifecycle from placement to fulfillment
- **Payment Integration**: Support for multiple payment methods

## Roadmap

Planned features for future releases:

- [ ] Reservations API support
- [ ] Customer management endpoints
- [ ] Webhook support for real-time updates
- [ ] Batch operations
- [ ] Analytics and reporting APIs
- [ ] Menu management
- [ ] Table management

## Contributing

This SDK is part of the Kolaveri monorepo. Development follows the monorepo conventions:

1. Use CVA for styling in library packages
2. Follow TypeScript strict mode
3. Run linting before commits: `npx nx lint order3000-nodejs`
4. Generate types from OpenAPI spec when API changes

## License

Part of the Kolaveri platform - see root repository for license information.

## Support

For issues, questions, or feature requests related to this SDK, please contact the order3000 development team or open an issue in the main repository.
