npm package: @kitty-kit/crud-generator
Description: A powerful CLI tool that generates complete CRUD features for React/TypeScript applications from simple configuration files
Author: Your Name
Latest version: 2.0.1

# Frontend CRUD Generator

A powerful CLI tool that generates complete CRUD (Create, Read, Update, Delete) feature folders for React/TypeScript applications from simple configuration files.

## Features

- 🚀 **Config-based generation** - Define your entity once, generate everything
- 📝 **TypeScript-first** - Full type safety with TypeScript and Zod validation
- 🎨 **Consistent patterns** - Follows established patterns from your codebase
- 🔧 **Customizable** - Support for all field types: string, number, boolean, date, enum, relations
- 🎯 **Production-ready** - Generates complete CRUD with forms, tables, modals, and API integration
- ⚡ **Fast development** - Go from config to working CRUD in seconds

## Installation

Install globally via npm:

```bash
npm install -g @kitty-kit/crud-generator
```

> **Note**: After global installation, use the `crud-gen` command directly in your terminal.

## Quick Start

### 1. Initialize a config file

```bash
crud-gen init user
```

This creates a `user.config.ts` file with a sample configuration.

### 2. Customize your config

Edit `crud.config.ts` to define your entity:

```typescript
import { EntityConfig, FieldType } from "@kitty-kit/crud-generator";

const config: EntityConfig = {
  name: "user",
  displayName: "User",
  nameField: "user_name",
  statusField: "user_status",
  fields: [
    {
      name: "user_name",
      type: FieldType.STRING,
      label: "Name",
      required: true,
      showInTable: true,
      showInForm: true,
      placeholder: "Enter user name",
    },
    {
      name: "age",
      type: FieldType.NUMBER,
      label: "Age",
      required: true,
      showInTable: true,
      showInForm: true,
    },
    {
      name: "user_status",
      type: FieldType.ENUM,
      label: "Status",
      required: true,
      enumValues: ["active", "inactive"],
      showInTable: true,
      showInForm: true,
    },
  ],
};

export default config;
```

### 3. Generate CRUD

```bash
crud-gen generate user.config.ts
```

This generates a complete CRUD feature at `examples/src/features/users/` with:

- ✅ TypeScript types and interfaces
- ✅ Zod validation schema
- ✅ API action hooks (create, read, update, delete)
- ✅ Zustand store for state management
- ✅ Table columns with sorting and pagination
- ✅ Add/Edit/Delete modals
- ✅ Form with validation
- ✅ Main page component

## CLI Commands

### `crud-gen generate <config-file>`

Generate CRUD from a configuration file.

```bash
crud-gen generate user.config.ts
crud-gen generate user.config.ts -o src/features
```

Options:

- `-o, --output <dir>` - Output directory (default: `examples/src/features`)

### `crud-gen init [entity-name]`

Create a sample configuration file.

```bash
crud-gen init user
crud-gen init product -o product.config.ts
```

Options:

- `-o, --output <file>` - Output file path (default: `{entity-name}.config.ts`)

### `crud-gen validate <config-file>`

Validate a configuration file without generating.

```bash
crud-gen validate user.config.ts
```

## Configuration Reference

### EntityConfig

| Property       | Type          | Required | Description                                     |
| -------------- | ------------- | -------- | ----------------------------------------------- |
| `name`         | string        | ✅       | Entity name (singular, lowercase, e.g., 'user') |
| `displayName`  | string        | ✅       | Human-readable name (e.g., 'User')              |
| `nameField`    | string        | ✅       | Field to use for display/delete confirmation    |
| `fields`       | FieldConfig[] | ✅       | Array of field configurations                   |
| `pluralName`   | string        | ❌       | Plural name (auto-generated if not provided)    |
| `idField`      | string        | ❌       | Primary key field (default: `{entity}_id`)      |
| `statusField`  | string        | ❌       | Status field for badge select                   |
| `apiEndpoints` | APIEndpoints  | ❌       | Custom API endpoints                            |
| `features`     | Features      | ❌       | Enable/disable features                         |
| `description`  | string        | ❌       | Page header description                         |

### FieldConfig

| Property       | Type      | Required | Description                                                |
| -------------- | --------- | -------- | ---------------------------------------------------------- |
| `name`         | string    | ✅       | Field name (e.g., 'user_name')                             |
| `type`         | FieldType | ✅       | Field type (string, number, boolean, date, enum, relation) |
| `label`        | string    | ✅       | Display label for forms                                    |
| `required`     | boolean   | ✅       | Whether the field is required                              |
| `showInTable`  | boolean   | ✅       | Display in table list                                      |
| `showInForm`   | boolean   | ✅       | Include in add/edit forms                                  |
| `validation`   | string    | ❌       | Zod validation rules (e.g., '.min(3).max(50)')             |
| `enumValues`   | string[]  | ❌       | For enum types: possible values                            |
| `relationTo`   | string    | ❌       | For relation types: entity name                            |
| `placeholder`  | string    | ❌       | Placeholder text for inputs                                |
| `defaultValue` | any       | ❌       | Default value                                              |
| `columnWidth`  | string    | ❌       | Table column width (e.g., 'w-[20%]')                       |

### Field Types

- **string** - Text input
- **number** - Number input
- **boolean** - Checkbox
- **date** - Date picker (stored as ISO string)
- **enum** - Select dropdown with predefined values
- **relation** - Foreign key to another entity (select dropdown)

## Example Configurations

### Simple Entity

```typescript
const config: EntityConfig = {
  name: "category",
  displayName: "Category",
  nameField: "category_name",
  fields: [
    {
      name: "category_name",
      type: FieldType.STRING,
      label: "Category Name",
      required: true,
      showInTable: true,
      showInForm: true,
    },
  ],
};
```

### Entity with Relations

```typescript
const config: EntityConfig = {
  name: "product",
  displayName: "Product",
  nameField: "product_name",
  fields: [
    {
      name: "product_name",
      type: FieldType.STRING,
      label: "Product Name",
      required: true,
      showInTable: true,
      showInForm: true,
    },
    {
      name: "category_id",
      type: FieldType.RELATION,
      label: "Category",
      required: true,
      relationTo: "category",
      showInTable: true,
      showInForm: true,
    },
    {
      name: "price",
      type: FieldType.NUMBER,
      label: "Price",
      required: true,
      showInTable: true,
      showInForm: true,
      validation: ".min(0)",
    },
  ],
};
```

### Entity with Custom API Endpoints

```typescript
const config: EntityConfig = {
  name: 'user',
  displayName: 'User',
  nameField: 'user_name',
  apiEndpoints: {
    list: 'users/all',
    add: 'users/create',
    update: 'users/modify',
    delete: 'users/remove'
  },
  fields: [...]
}
```

## Generated Structure

For an entity named `user`, the generator creates:

```
examples/src/features/users/
├── actions/
│   └── users.action.ts          # API hooks (CRUD operations)
├── components/
│   ├── list/
│   │   ├── user-list-columns.tsx    # Table column definitions
│   │   └── user-list-actions.tsx    # Edit/Delete buttons
│   └── mutate/
│       ├── mutate-user-modal.tsx    # Modal controller
│       └── mutate-user-form.tsx     # Add/Edit form
├── hooks/
│   └── use-user-mutations.ts    # Mutation logic
├── schema/
│   └── user.schema.ts           # Zod validation
├── store/
│   └── user.store.ts            # Zustand store
├── types/
│   └── index.ts                 # TypeScript types
└── index.tsx                    # Main page component
```

## API Configuration

The generator automatically updates `examples/src/config/api/api.ts` with new endpoints:

```typescript
users: {
  list: 'user/list',
  add: 'user/create-user',
  update: 'user/update',
  delete: 'user',
}
```

## Next Steps After Generation

1. **Add Route** - Add the generated page to your router:

   ```typescript
   import UsersPage from '@/features/users'

   // In your routes
   { path: '/users', element: <UsersPage /> }
   ```

2. **Verify API Endpoints** - Ensure the API endpoints match your backend

3. **Test CRUD Operations** - Test create, read, update, and delete functionality

4. **Customize** - Modify generated files as needed for your specific requirements

## Troubleshooting

### Config validation fails

- Ensure all required fields are present
- Check field names follow lowercase_snake_case convention
- Verify enum fields have enumValues array
- Verify relation fields have relationTo property

### Generated code has TypeScript errors

- Run `npm install` in the examples directory
- Ensure all dependencies are installed
- Check that related entities exist for relation fields

### API endpoints not working

- Verify the API config file path is correct
- Check that backend endpoints match the generated configuration
- Ensure API base URL is configured correctly

## License

MIT