npm package: @shitalgomare/provider-gateway-hotel
Description: Hotel Provider Gateway - NPM Package for hotel search, booking, and management
Author: CTS
Latest version: 1.0.0

# @zentrum/provider-gateway-hotel

A TypeScript npm package for hotel provider gateway functionality, migrated from C# to Node.js.

## Features

- Hotel search with multiple providers
- Rooms and rates retrieval
- Price checking
- Booking management
- Cancellation handling
- Provider currency resolution
- Caching support
- Error handling and validation

## Installation

```bash
npm install @zentrum/provider-gateway-hotel
```

> **Note**: Make sure to load environment variables in your application. You can use packages like `dotenv`:
>
> ```bash
> npm install dotenv
> ```
>
> Then in your main application file:
>
> ```typescript
> import "dotenv/config";
> ```

## Environment Variables

The package uses environment variables for configuration. Copy `env.example` to `.env` and configure the following variables:

### Required Environment Variables

| Variable                                  | Description                        | Default Value                                                        |
| ----------------------------------------- | ---------------------------------- | -------------------------------------------------------------------- |
| `CONFIGURATION_SERVICE_BASE_URL`          | Base URL for configuration service | `http://dev.akbar.zeal-connect.com/api/configuration/configuration/` |
| `CONFIGURATION_SERVICE_PROVIDER_APP_NAME` | Provider application name          | `provider-dev`                                                       |

### Optional Environment Variables

| Variable            | Description             | Default Value            |
| ------------------- | ----------------------- | ------------------------ |
| `REDIS_URL`         | Redis connection URL    | `redis://localhost:6379` |
| `REDIS_HOST`        | Redis host              | `localhost`              |
| `REDIS_PORT`        | Redis port              | `6379`                   |
| `REDIS_PASSWORD`    | Redis password          | (empty)                  |
| `REDIS_DB`          | Redis database number   | `0`                      |
| `CACHE_TTL_SECONDS` | Cache TTL in seconds    | `3600` (60 minutes)      |
| `LOG_LEVEL`         | Logging level           | `info`                   |
| `NODE_ENV`          | Application environment | `development`            |

### Example .env file

```bash
# Copy env.example to .env and modify as needed
cp env.example .env
```

```env
# Redis Configuration
REDIS_URL=redis://localhost:6379
REDIS_HOST=localhost
REDIS_PORT=6379
REDIS_PASSWORD=
REDIS_DB=0

# Configuration Service
CONFIGURATION_SERVICE_BASE_URL=http://dev.akbar.zeal-connect.com/api/configuration/configuration/
CONFIGURATION_SERVICE_PROVIDER_APP_NAME=provider-dev

# Cache Settings
CACHE_TTL_SECONDS=3600

# Logging
LOG_LEVEL=info

# Application
NODE_ENV=development
```

## Usage

### Basic Setup

```typescript
import {
  HotelController,
  SearchManager,
  ProviderCurrencyResolver,
  HotelSearchRequest,
  Logger,
  IHotelProvider,
  createConfigurationProviderWithCache,
} from "@zentrum/provider-gateway-hotel";

// Implement required interfaces
class MyHotelProvider implements IHotelProvider {
  async searchHotels(request: any): Promise<any> {
    // Your provider implementation
    return { hotels: [] };
  }

  async getRoomsAndRates(request: any): Promise<any> {
    return { rooms: [], rates: [] };
  }

  async getPrice(request: any): Promise<any> {
    return { price: 100, currency: "USD" };
  }

  async book(request: any): Promise<any> {
    return { bookingId: "123", status: "confirmed" };
  }

  async cancel(request: any): Promise<any> {
    return { bookingId: "123", status: "cancelled" };
  }
}

// Initialize components with environment variables
const logger = new Logger();
const hotelProvider = new MyHotelProvider();

// Use cached configuration provider (recommended for production)
// This will automatically use environment variables for configuration
const configurationProvider = createConfigurationProviderWithCache();

const currencyResolver = new ProviderCurrencyResolver();

const searchManager = new SearchManager(
  hotelProvider,
  configurationProvider, // Cached configuration provider
  currencyResolver,
  logger
);

const hotelController = new HotelController(searchManager, logger);
```

### Hotel Search

```typescript
const searchRequest: HotelSearchRequest = {
  token: "your-token",
  providerIds: ["provider1", "provider2"],
  checkIn: new Date("2024-01-15"),
  checkOut: new Date("2024-01-20"),
  occupancies: [{ numOfAdults: 2 }],
  channelId: "channel1",
  accountId: "account1",
};

const hotelMappings = new Map();

hotelController.searchHotelsAsync(
  searchRequest,
  hotelMappings,
  (response, error) => {
    if (error) {
      console.error("Search error:", error);
    } else {
      console.log("Found hotels:", response?.hotels);
    }
  }
);
```

### Rooms and Rates

```typescript
const roomsRequest: RoomsAndRatesRequest = {
  token: "your-token",
  hotelId: "hotel123",
  accountId: "account1",
  channelId: "channel1",
  providerIds: ["provider1"],
  checkIn: new Date("2024-01-15"),
  checkOut: new Date("2024-01-20"),
  occupancies: [{ numOfAdults: 2 }],
};

hotelController.getRoomsAndRatesAsync(roomsRequest, (response, error) => {
  if (error) {
    console.error("Rooms and rates error:", error);
  } else {
    console.log("Rooms and rates:", response);
  }
});
```

### Price Check

```typescript
const priceRequest: PriceRequest = {
  hotelId: "hotel123",
  providerId: "provider1",
  rateKey: "rate123",
};

const priceResponse = await hotelController.getPriceAsync(priceRequest);
console.log("Price:", priceResponse);
```

### Booking

```typescript
const bookRequest: BookRequest = {
  hotelId: "hotel123",
  providerId: "provider1",
  rateKey: "rate123",
  guestInfo: {
    // Guest information
  },
};

const bookResponse = await hotelController.bookAsync(bookRequest);
console.log("Booking:", bookResponse);
```

### Cancellation

```typescript
const cancelRequest: CancelRequest = {
  bookingId: "booking123",
  providerId: "provider1",
};

const cancelResponse = await hotelController.cancelAsync(cancelRequest);
console.log("Cancellation:", cancelResponse);
```

## Configuration Caching

The package includes a caching layer for configuration providers that matches the C# implementation pattern. This ensures that provider configurations are cached to improve performance and reduce external service calls.

### Using Cached Configuration

```typescript
import { createConfigurationProviderWithCache } from "@zentrum/provider-gateway-hotel";

// Use cached configuration provider (automatically uses environment variables)
const configurationProvider = createConfigurationProviderWithCache();

// Or specify custom settings
const customConfigurationProvider = createConfigurationProviderWithCache(
  {
    baseUrl: "https://custom-config-service.com/api/",
    providerApplicationName: "custom-provider",
  },
  "redis://custom-redis:6379"
);
```

### Cache Behavior

- **Cache Duration**: Configurable via `CACHE_TTL_SECONDS` (default: 60 minutes)
- **Cache Key Format**: `${baseUrl}${accountId}/${applicationName}/${groupName}`
- **Fallback**: If cache miss, calls configuration service
- **Error Handling**: Logs errors but doesn't rethrow (matches C# behavior)

For more details, see [CONFIGURATION_CACHING.md](./CONFIGURATION_CACHING.md).

## API Reference

### Core Classes

- `HotelController` - Main controller for hotel operations
- `SearchManager` - Manages search operations and provider coordination
- `ProviderCurrencyResolver` - Handles currency conversion between providers

### Interfaces

- `IHotelController` - Main controller interface
- `ISearchManager` - Search manager interface
- `IHotelProvider` - Hotel provider interface
- `IConfigurationProvider` - Configuration provider interface
- `IContentProvider` - Content provider interface
- `ILogger` - Logger interface

### Models

- `HotelSearchRequest` - Hotel search request model
- `HotelSearchResponse` - Hotel search response model
- `RoomsAndRatesRequest` - Rooms and rates request model
- `RoomsAndRatesResponse` - Rooms and rates response model
- `PriceRequest` - Price request model
- `PriceResponse` - Price response model
- `BookRequest` - Booking request model
- `BookResponse` - Booking response model
- `CancelRequest` - Cancellation request model
- `CancelResponse` - Cancellation response model

## Development

### Building

```bash
npm run build
```

### Testing

```bash
npm test
```

### Linting

```bash
npm run lint
```

### Formatting

```bash
npm run format
```

## License

MIT

## Support

For support and questions, please contact the development team.