# @panoptic-it-solutions/itglue-client

A comprehensive TypeScript/Node.js client for the IT Glue API with full type safety and complete resource coverage. This client provides access to **ALL** IT Glue API endpoints with consistent patterns, excellent documentation, and robust error handling.

## 🚀 Quick Start

### Installation
```bash
npm install @panoptic-it-solutions/itglue-client
# or
pnpm add @panoptic-it-solutions/itglue-client
# or
yarn add @panoptic-it-solutions/itglue-client
```

### Authentication & Client Initialization
```typescript
import { ITGlueClient } from '@panoptic-it-solutions/itglue-client';

const client = new ITGlueClient('your-api-key', {
  baseURL: 'https://api.itglue.com', // optional, defaults to IT Glue API
  timeout: 30000, // optional, request timeout in ms
  retries: 3 // optional, number of retries on failure
});
```

### Basic Usage
```typescript
// List organizations
const organizations = await client.organizations.list();

// Get a specific organization
const org = await client.organizations.get('123');

// Create a new organization
const newOrg = await client.organizations.create({
  data: {
    type: 'organizations',
    attributes: {
      name: 'Acme Corp',
      organization_type_name: 'Client'
    }
  }
});
```

## 🌟 Features

- 🔒 **Full Type Safety** - Complete TypeScript definitions for all IT Glue API resources
- 🌐 **Complete Resource Coverage** - ALL 28 IT Glue API resources with appropriate operations
- 📄 **Pagination Made Easy** - Built-in pagination utilities for handling large datasets
- 🔍 **Advanced Filtering & Sorting** - Robust query building with type-safe filters
- 📚 **Excellent Documentation** - JSDoc comments and generated API documentation
- ✅ **Well Tested** - Comprehensive test suite with extensive coverage
- 🎯 **JSON:API Compliant** - Proper JSON:API format handling
- 🚀 **Production Ready** - Error handling, retries, and rate limiting

## 📋 Complete Resource List

### Organization & Contact Management
- **Organizations** - `client.organizations` (list, get, create, update, delete)
- **Organization Types** - `client.organizationTypes` (list, get, create, update, delete)
- **Organization Statuses** - `client.organizationStatuses` (list, get, create, update, delete)
- **Contacts** - `client.contacts` (list, get, create, update, delete)
- **Contact Types** - `client.contactTypes` (list, get, create, update, delete)
- **Locations** - `client.locations` (list, get, create, update, delete)

### Asset & Configuration Management
- **Configurations** - `client.configurations` (list, get, create, update, delete)
- **Configuration Types** - `client.configurationTypes` (list, get, create, update, delete)
- **Configuration Statuses** - `client.configurationStatuses` (list, get, create, update, delete)
- **Configuration Interfaces** - `client.configurationInterfaces` (list, get, create, update, delete)
- **Flexible Assets** - `client.flexibleAssets` (list, get, create, update, delete)
- **Flexible Asset Types** - `client.flexibleAssetTypes` (list, get, create, update, delete)
- **Flexible Asset Fields** - `client.flexibleAssetFields` (list, get, create, update, delete, bulkUpdate)

### Security & Documentation
- **Passwords** - `client.passwords` (list, get, create, update, delete)
- **Password Categories** - `client.passwordCategories` (list, get, create, update, delete)
- **Documents** - `client.documents` (list, get, create, update, delete)
- **Attachments** - `client.attachments` (list, get, create, update, delete)

### Reference Data & Metadata
- **Manufacturers** - `client.manufacturers` (list, get, create, update, delete)
- **Models** - `client.models` (list, get, create, update, delete)
- **Operating Systems** - `client.operatingSystems` (list, get, create, update, delete)
- **Platforms** - `client.platforms` (list, get) *read-only*
- **Countries** - `client.countries` (list, get, listRegions, getRegion) *read-only*
- **Regions** - `client.regions` (list, get) *read-only*
- **Domains** - `client.domains` (list) *read-only*

### System & Audit
- **Users** - `client.users` (list, get, update) *no create/delete*
- **User Metrics** - `client.userMetrics` (list, get)
- **Groups** - `client.groups` (list, get, create, update, delete)
- **Tags** - `client.tags` (list, get, create, update, delete)
- **Logs** - `client.logs` (list) *audit trail, read-only*
- **Expirations** - `client.expirations` (list, get) *read-only*

### Data Management
- **Exports** - `client.exports` (list, get, create, destroy)
- **Related Items** - `client.relatedItems` (create, update, bulkDestroy)

## 🔧 Operation Patterns

### Standard CRUD Operations
Most resources follow this pattern:

```typescript
// List with pagination and filtering
const results = await client.organizations.list({
  filter: { name: 'Acme' },
  sort: '-created_at',
  page: { number: 1, size: 50 }
});

// Get single resource
const item = await client.organizations.get('123');

// Create new resource
const created = await client.organizations.create({
  data: {
    type: 'organizations',
    attributes: {
      name: 'New Company',
      organization_type_name: 'Client'
    }
  }
});

// Update existing resource
const updated = await client.organizations.update('123', {
  data: {
    type: 'organizations',
    attributes: {
      name: 'Updated Company Name'
    }
  }
});

// Delete resource
await client.organizations.destroy('123');
```

### Read-Only Resources
Some resources are read-only reference data:

```typescript
// Countries (with nested regions)
const countries = await client.countries.list();
const country = await client.countries.get('1');
const regions = await client.countries.listRegions('1');
const region = await client.countries.getRegion('1', '2');

// Platforms (OS platforms)
const platforms = await client.platforms.list();
const platform = await client.platforms.get('1');

// Domains (read-only)
const domains = await client.domains.list();

// Logs (audit trail)
const logs = await client.logs.list({
  filter: { user_id: '123' },
  sort: '-created_at'
});
```

### Special Operations
Some resources have unique operations:

```typescript
// Flexible Asset Fields - bulk update
await client.flexibleAssetFields.bulkUpdate({
  data: [
    {
      type: 'flexible_asset_fields',
      id: '1',
      attributes: { name: 'Updated Field 1' }
    },
    {
      type: 'flexible_asset_fields',
      id: '2', 
      attributes: { name: 'Updated Field 2' }
    }
  ]
});

// Related Items - bulk destroy
await client.relatedItems.bulkDestroy({
  data: [
    { type: 'related_items', id: '1' },
    { type: 'related_items', id: '2' }
  ]
});

// Users - limited operations (no create/delete)
const users = await client.users.list();
const user = await client.users.get('123');
const updated = await client.users.update('123', {
  data: {
    type: 'users',
    attributes: {
      first_name: 'Updated Name'
    }
  }
});
```

## 📄 Pagination Support

### Automatic Pagination
```typescript
// Fetch single page (default)
const page1 = await client.organizations.list({
  page: { number: 1, size: 50 }
});

// Fetch all pages automatically
const allResults = await client.organizations.list({}, true);
console.log(`Total results: ${allResults.data.length}`);
```

### Manual Pagination
```typescript
let page = 1;
let hasMore = true;

while (hasMore) {
  const results = await client.organizations.list({
    page: { number: page, size: 100 }
  });
  
  // Process results.data
  console.log(`Page ${page}: ${results.data.length} items`);
  
  hasMore = results.meta?.pagination?.next_page !== null;
  page++;
}
```

## 🔍 Filtering and Sorting

### Basic Filtering
```typescript
const filtered = await client.organizations.list({
  filter: {
    name: 'Acme Corp',
    organization_type_name: 'Client'
  }
});
```

### Advanced Filtering
```typescript
const advanced = await client.configurations.list({
  filter: {
    organization_id: '123',
    configuration_type_id: '456',
    'meta.serial_number': 'ABC123'
  }
});
```

### Date Range Filtering
```typescript
const recent = await client.logs.list({
  filter: {
    created_at: '2024-01-01..2024-12-31'
  }
});
```

### Sorting
```typescript
const sorted = await client.organizations.list({
  sort: ['-created_at', 'name'], // DESC by created_at, then ASC by name
});
```

### Including Related Data
```typescript
const withRelated = await client.organizations.list({
  include: ['contacts', 'locations']
});
```

## 🛠️ Utility Classes

### PaginationUtil
```typescript
// Access pagination utilities
const paginator = client.pagination;

// Custom pagination logic
const results = await paginator.paginate('/organizations', {
  filter: { name: 'test' }
}, true); // allPages = true
```

### QueryUtil
```typescript
// Build query parameters
const params = client.query.buildQueryParams({
  filter: { name: 'test' },
  sort: ['-created_at'],
  page: { number: 1, size: 50 }
});
```

## 🎯 JSON:API Format

All create/update operations use JSON:API format:

```typescript
// Single resource
const payload = {
  data: {
    type: 'organizations',
    attributes: {
      name: 'Company Name',
      description: 'Company description'
    },
    relationships: {
      organization_type: {
        data: { type: 'organization_types', id: '1' }
      }
    }
  }
};

// Multiple resources (bulk operations)
const bulkPayload = {
  data: [
    {
      type: 'flexible_asset_fields',
      id: '1',
      attributes: { name: 'Field 1' }
    },
    {
      type: 'flexible_asset_fields',
      id: '2', 
      attributes: { name: 'Field 2' }
    }
  ]
};
```

## 🚨 Error Handling

```typescript
try {
  const result = await client.organizations.get('invalid-id');
} catch (error) {
  if (error.response?.status === 404) {
    console.log('Organization not found');
  } else if (error.response?.status === 429) {
    console.log('Rate limit exceeded');
  } else {
    console.error('API Error:', error.message);
  }
}
```

## 🔄 Configuration Updates

```typescript
// Update API key at runtime
client.setApiKey('new-api-key');

// Update configuration options
client.setOptions({
  baseURL: 'https://custom-api.itglue.com',
  timeout: 60000
});
```

## 📖 API Documentation

- **Generated API Docs**: Run `npm run docs` to generate TypeDoc documentation
- **JSDoc Comments**: All methods include comprehensive JSDoc with examples
- **Type Definitions**: Full TypeScript definitions for all operations
- **Examples**: Practical examples for each resource and operation

## 🤖 AI Integration Guidelines

This client is designed to be AI-friendly:

1. **Consistent Patterns**: All resources follow the same operation patterns
2. **Comprehensive Types**: Full TypeScript support for auto-completion
3. **Clear Documentation**: JSDoc comments with practical examples
4. **Error Context**: Descriptive error messages with status codes
5. **Resource Discovery**: All resources are properties on the main client
6. **Operation Discovery**: Standard CRUD methods with clear names

### AI Usage Example
```typescript
// AI can determine available resources from client properties
const availableResources = Object.keys(client).filter(key => 
  typeof client[key] === 'object' && 
  client[key].list !== undefined
);

// AI can discover operations on each resource
const organizationOps = Object.getOwnPropertyNames(
  Object.getPrototypeOf(client.organizations)
).filter(name => name !== 'constructor');
```

## 📝 License

MIT License - see LICENSE file for details.

## 🤝 Contributing

Contributions are welcome! Please read our contributing guidelines and submit pull requests to our GitHub repository.

## 🔗 Links

- [Complete API Reference Index](./API_REFERENCE.md) - Comprehensive resource categorization and method reference
- [Generated TypeDoc Documentation](./docs/index.html) - Detailed API documentation with examples
- [IT Glue API Documentation](https://api.itglue.com/developer/) - Official IT Glue API documentation
- [GitHub Repository](https://github.com/panoptic-it-solutions/itglue-client)
