npm package: @kodeme-io/next-core-codegen
Description: TypeScript code generation utilities for next-core framework with React Query hooks and API client generation
Latest version: 0.8.4

# @kodeme-io/next-core-codegen

TypeScript code generation utilities for next-core framework, specifically designed to generate type-safe interfaces from Odoo models.

## Features

- 🚀 **Automatic Type Generation** - Generate TypeScript interfaces from any Odoo model
- 🔍 **Native Odoo Integration** - Uses Odoo's built-in `fields_get()` API
- 📝 **Zero Configuration** - Works out of the box with sensible defaults
- 🎯 **Type Safety** - Prevents runtime errors through compile-time checking
- 🔄 **Regenerate Anytime** - Types stay in sync with your Odoo schema
- 📦 **Framework Agnostic** - Works with any Odoo project using next-core

## Quick Start

### Installation

```bash
npm install -D @kodeme-io/next-core-codegen
```

### Configuration

Create a `.next-core.json` file in your project root:

```json
{
  "odoo": {
    "url": "${ODOO_URL}",
    "db": "${ODOO_DB}",
    "username": "${ODOO_USERNAME}",
    "password": "${ODOO_PASSWORD}"
  },
  "models": [
    "res.partner",
    "res.users",
    "product.product",
    "sale.order",
    "sfa.visit"
  ],
  "output": "src/types/odoo.ts",
  "exclude": [
    "ir.*",
    "mail.*",
    "base.*"
  ]
}
```

### Generate Types

```bash
# Generate types from configured models
npx next-core-codegen types

# Or use the shorter command
npx next-core-codegen

# Discover and generate all available models
npx next-core-codegen types --discover

# Generate specific models
npx next-core-codegen types --models res.partner,sale.order

# Custom output file
npx next-core-codegen types --output src/types/models.ts
```

### Usage in Code

```typescript
// Import generated types
import type { ResPartner, SaleOrder, SfaVisit } from './types/odoo'

// Use with full type safety
const partners: ResPartner[] = await odoo.searchRead('res.partner', [], ['name', 'email'])

const order: SaleOrder = {
  name: 'SO001',
  partner_id: [1, 'ABC Company'],
  state: 'draft', // TypeScript will validate this is a valid state
  amount_total: 1000.00
}
```

## Generated Output Example

The generator creates clean, documented TypeScript interfaces:

```typescript
/**
 * Auto-generated TypeScript types from Odoo models
 * Generated: 2025-10-07T10:30:00.000Z
 *
 * DO NOT EDIT MANUALLY!
 * Regenerate with: npx next-core-codegen types
 */

// Odoo-specific types
export type Many2one<T = any> = [number, string] | false
export type One2many = number[]
export type Many2many = number[]

/**
 * Partner
 * Odoo Model: res.partner
 */
export interface ResPartner {
  /** Auto-generated identifier*/
  id?: number
  /** Name*/
  name?: string
  /** Email Address*/
  email?: string
  /** Phone*/
  phone?: string
  /** Is a Company*/
  is_company?: boolean
  /** Related Company*/
  parent_id?: Many2one
  /** Tags*/
  category_id?: Many2many
  /** Active*/
  active?: boolean
}

/**
 * Sales Order
 * Odoo Model: sale.order
 */
export interface SaleOrder {
  /** Order Reference*/
  name?: string
  /** Customer*/
  partner_id?: Many2one
  /** Status*/
  state?: 'draft' | 'sent' | 'sale' | 'done' | 'cancel'
  /** Total Amount*/
  amount_total?: number
  /** Order Date*/
  date_order?: string
}
```

## CLI Reference

### Commands

```bash
next-core-codegen types [options]
```

### Options

| Option | Description | Default |
|--------|-------------|---------|
| `--config, -c` | Configuration file path | `.next-core.json` |
| `--models, -m` | Comma-separated model names | From config |
| `--output, -o` | Output file path | From config |
| `--discover, -d` | Discover all available models | `false` |
| `--exclude, -e` | Exclude patterns (comma-separated) | From config |
| `--help, -h` | Show help | |
| `--version, -v` | Show version | |

## Configuration

### Configuration File Formats

The codegen tool supports multiple configuration file formats:

#### JSON (.next-core.json)
```json
{
  "odoo": {
    "url": "${ODOO_URL}",
    "db": "${ODOO_DB}",
    "username": "${ODOO_USERNAME}",
    "password": "${ODOO_PASSWORD}"
  },
  "models": ["res.partner", "sale.order"],
  "output": "src/types/odoo.ts",
  "exclude": ["ir.*"]
}
```

#### JavaScript (.next-core.js)
```javascript
module.exports = {
  odoo: {
    url: process.env.ODOO_URL,
    db: process.env.ODOO_DB,
    username: process.env.ODOO_USERNAME,
    password: process.env.ODOO_PASSWORD
  },
  models: ['res.partner', 'sale.order'],
  output: 'src/types/odoo.ts',
  exclude: ['ir.*']
}
```

### Environment Variables

Environment variables are automatically substituted in configuration:

```bash
# .env file
ODOO_URL=https://your-odoo.com
ODOO_DB=your_database
ODOO_USERNAME=your_username
ODOO_PASSWORD=your_password
```

## Field Type Mapping

The generator maps Odoo field types to TypeScript types:

| Odoo Type | TypeScript Type | Example |
|-----------|----------------|---------|
| `char` | `string` | `name: string` |
| `text` | `string` | `description: string` |
| `html` | `string` | `content: string` |
| `integer` | `number` | `quantity: number` |
| `float` | `number` | `price: number` |
| `monetary` | `number` | `amount: number` |
| `boolean` | `boolean` | `active: boolean` |
| `date` | `string` | `date_order: string` |
| `datetime` | `string` | `create_date: string` |
| `binary` | `string` | `image: string` |
| `many2one` | `Many2one` | `partner_id: Many2one` |
| `one2many` | `One2many` | `order_ids: One2many` |
| `many2many` | `Many2many` | `tag_ids: Many2many` |
| `selection` | Union Type | `state: 'draft' \| 'done'` |

## Advanced Usage

### Model Discovery

Discover all available models in your Odoo instance:

```bash
npx next-core-codegen types --discover
```

This will:
1. Connect to Odoo
2. List all non-transient models
3. Generate types for all discovered models

### Pattern Filtering

Include or exclude models using patterns:

```json
{
  "models": ["res.*", "sale.*", "sfa.*"],
  "exclude": ["ir.*", "mail.*", "base.*"]
}
```

### Custom Field Exclusion

By default, the generator excludes internal Odoo fields:
- `__*` (private fields)
- `create_uid`, `write_uid`
- `create_date`, `write_date`

You can customize this in your configuration.

## Integration with Next.js

Add to your `package.json` scripts:

```json
{
  "scripts": {
    "types:generate": "next-core-codegen types",
    "dev": "npm run types:generate && next dev",
    "build": "npm run types:generate && next build",
    "type-check": "tsc --noEmit"
  }
}
```

## API Usage

You can also use the codegen utilities programmatically:

```typescript
import { OdooIntrospector, TypeScriptGenerator } from '@kodeme-io/next-core-codegen'
import { OdooClient } from '@kodeme-io/next-core-odoo-api'

// Connect to Odoo
const odoo = new OdooClient({
  url: 'https://your-odoo.com',
  db: 'your_database',
  username: 'your_username',
  password: 'your_password'
})

await odoo.connect()

// Introspect models
const introspector = new OdooIntrospector(odoo)
const schemas = await introspector.introspectModels(['res.partner', 'sale.order'])

// Generate TypeScript
const generator = new TypeScriptGenerator()
const typescript = generator.generate(schemas)

// Save to file
import fs from 'fs'
fs.writeFileSync('src/types/odoo.ts', typescript)
```

## Troubleshooting

### Common Issues

1. **Authentication Failed**
   - Check your Odoo credentials
   - Ensure the user has access to the models
   - Verify the database name

2. **Network Error**
   - Check the Odoo URL
   - Verify network connectivity
   - Check firewall/proxy settings

3. **Permission Denied**
   - Ensure the Odoo user has read access to the models
   - Check `ir.model.access` permissions in Odoo

4. **Types Not Found**
   - Verify the output path is correct
   - Check that models exist in Odoo
   - Ensure proper TypeScript configuration

### Debug Mode

Enable debug logging:

```bash
DEBUG=next-core:* npx next-core-codegen types
```

## Contributing

1. Fork the repository
2. Create a feature branch
3. Make your changes
4. Add tests
5. Submit a pull request

## License

MIT License - see LICENSE file for details.

## Support

- 📖 [Documentation](https://github.com/abc-food/next-core/docs)
- 🐛 [Issues](https://github.com/abc-food/next-core/issues)
- 💬 [Discussions](https://github.com/abc-food/next-core/discussions)