# Diagramers CLI

A powerful command-line interface for managing Diagramers projects, generating modules, and extending functionality with a comprehensive template system.

## 🚀 Features

### Core Capabilities
- **Project Initialization** - Create new projects from templates
- **Module Generation** - Generate complete modules with CRUD operations
- **Table Generation** - Add database tables to existing modules
- **Endpoint Generation** - Add custom endpoints to existing modules
- **Relation Management** - Generate database relations within modules
- **Feature Extension** - Add features to existing projects
- **Template Management** - Download and update project templates

### Supported Templates
- **API Projects** - Full-featured Node.js API with TypeScript
- **Admin Projects** - Modern admin dashboard with React/Vue/Angular support
- **Custom Templates** - Extensible template system

### Database Support
- **MongoDB** - Primary database with Mongoose schemas
- **SQL Databases** - MySQL, PostgreSQL, SQLite support
- **Schema Generation** - Automatic schema and relation creation

## 📦 Installation

### Global Installation
```bash
npm install -g @diagramers/cli
```

### Local Installation
```bash
npm install @diagramers/cli
npx diagramers --help
```

## 🚀 Quick Start

```bash
# Install the CLI globally
npm install -g @diagramers/cli

# Create a new API project
diagramers init api my-new-api

# Navigate to the project
cd my-new-api

# Set up environment variables
cp .env.example .env

# Install dependencies
npm install

# Start development
npm start
```

## 📋 Commands

### Project Management

#### Initialize New Project
```bash
diagramers init <template-type> <project-name> [options]
```

**Options:**
- `-v, --version <version>` - Specific version of the template to use (e.g., 1.1.17, latest)
- `-t, --template <template>` - Template version to use (deprecated, use --version)
- `-y, --yes` - Skip prompts and use defaults

**Examples:**
```bash
# Create API project with latest version
diagramers init api my-api-project

# Create API project with specific version
diagramers init api my-api-project -v 1.1.17

# Create admin project with specific version
diagramers admin init react-typescript my-admin-dashboard -v 1.0.0
```

#### Update Project

Update an existing project with the latest template features:

```bash
diagramers update [options]
```

**Options:**
- `-v, --version <version>` - Specific version to update to (e.g., 1.1.27, latest)
- `-f, --force` - Force update even if conflicts detected
- `-b, --backup` - Create backup before updating

**Examples:**
```bash
# Update to latest version
diagramers update

# Update to specific version
diagramers update -v 1.1.27

# Force update (overwrite conflicts)
diagramers update --force

# Create backup before updating
diagramers update --backup

# Combine options
diagramers update -v 1.1.27 --backup --force
```

#### What Gets Updated

The update command intelligently updates the following:

- **Core Files**: `src/core/`, `src/shared/`, `src/plugins/`
- **Configuration**: `config/` folder, `webpack.config.js`, `tsconfig.json`
- **Scripts**: `scripts/` folder with utility scripts
- **Documentation**: `README.md`, `DEVELOPER_GUIDE.md`
- **Environment**: `.env.example` template
- **Package.json**: Updates dependencies and scripts while preserving project-specific fields

#### Version Management

- **Automatic Version Sync**: Project version is updated to match template version
- **Project Preservation**: Project-specific fields (name, description, repository, etc.) are preserved
- **Conflict Detection**: Detects conflicts and allows force overwrite
- **Backup Support**: Creates timestamped backups before updating

#### Update Process

1. **Validation**: Checks if current directory is a valid project
2. **Version Check**: Shows current project version vs target version
3. **Backup**: Creates backup if requested
4. **Download**: Downloads latest template from npm
5. **Conflict Check**: Identifies files with conflicts
6. **Update**: Updates files while preserving project-specific settings
7. **Cleanup**: Removes temporary files

#### Example Output

```bash
🔄 Checking for template updates...
📦 Current project version: 1.1.26
📌 Updating to latest version
📦 Downloading latest template: @diagramers/api
✅ Template downloaded from npm: @diagramers/api
📝 Updating project files...
✅ Updated: src/core/config/index.ts
✅ Updated: scripts/env-debug.js
✅ Updated: package.json (version: 1.1.27)
✅ Project updated successfully!
📦 Template version: 1.1.27
📝 Review the changes and test your application
💡 Run "npm install" to update dependencies if needed
```

#### List Available Versions
```bash
diagramers versions [options]
```

**Options:**
- `-a, --all` - Show all versions (default: show last 10)

**Examples:**
```bash
# Show last 10 versions
diagramers versions

# Show all available versions
diagramers versions --all
```

### Module Management

#### Generate Module
```bash
diagramers extend --module <module-name> [options]
```

**Examples:**
```bash
# Generate basic module
diagramers extend --module products

# Generate module with CRUD operations
diagramers extend --module products --crud

# Generate module with custom fields
diagramers extend --module products --fields name,price,description --crud
```

### Table Management

#### Add Table to Module
```bash
diagramers extend --table <module:table> --fields <field1,field2,...>
```

**Examples:**
```bash
# Add categories table to products module
diagramers extend --table products:categories --fields name,description,slug

# Add products table to products module
diagramers extend --table products:products --fields name,price,category_id

# Add user profiles table to users module
diagramers extend --table users:profiles --fields bio,avatar,social_links
```

**Field Types (Auto-detected):**
- `name`, `title`, `description` → String
- `email`, `phone` → String
- `price`, `count`, `age` → Number
- `created_at`, `updated_at` → Date
- `is_active`, `verified` → Boolean
- `*_id` → ObjectId
- `status` → Number

### Endpoint Management

#### Add Endpoint to Module
```bash
diagramers extend --endpoint <module:endpoint> [options]
```

**Examples:**
```bash
# Add GET endpoint
diagramers extend --endpoint products:search --method GET

# Add POST endpoint
diagramers extend --endpoint users:reset-password --method POST

# Add endpoint with custom path
diagramers extend --endpoint products:featured --method GET --path /featured --description "Get featured products"
```

**Supported Methods:**
- `GET` - Retrieve data
- `POST` - Create data
- `PUT` - Update data
- `DELETE` - Delete data

### Relation Management

#### Create Relations Within Module
```bash
diagramers extend --relation <module:table1-table2[:type]>
```

**Examples:**
```bash
# One-to-many relation (default)
diagramers extend --relation products:category-product

# One-to-one relation
diagramers extend --relation users:user-profile:one-to-one

# Many-to-many relation
diagramers extend --relation products:product-tag:many-to-many
```

**Relation Types:**
- `one-to-one` - Single record relations
- `one-to-many` - Parent-child relations (default)
- `many-to-many` - Junction table relations

### Feature Management

#### List Available Features
```bash
diagramers extend --list
```

#### Add Feature
```bash
diagramers extend --feature <feature-name>
```

## 🎨 Admin Dashboard Management

The CLI provides comprehensive support for managing admin dashboard projects with modern frameworks and features.

### Admin Project Initialization

#### Initialize New Admin Project
```bash
diagramers admin init <template-type> <project-name> [options]
```

**Template Types:**
- `react-typescript` - React 18 + TypeScript + Tailwind CSS
- `vue-typescript` - Vue 3 + TypeScript + Tailwind CSS
- `angular` - Angular 17 + TypeScript + Tailwind CSS

**Options:**
- `-f, --framework <framework>` - Framework to use (react, vue, angular)
- `-t, --template <template>` - Template package name
- `-v, --version <version>` - Template version to use
- `-y, --yes` - Skip prompts and use defaults
- `--typescript` - Use TypeScript (default: true)
- `--tailwind` - Use Tailwind CSS (default: true)
- `--api-url <url>` - API URL for the backend
- `--socket-url <url>` - Socket.IO URL for real-time features

**Examples:**
```bash
# Create React admin project
diagramers admin init react-typescript my-admin-app

# Create Vue admin project with specific version
diagramers admin init vue-typescript my-vue-admin --version 1.0.0

# Create Angular admin project with custom API URL
diagramers admin init angular my-angular-admin --api-url http://localhost:3000

# Create with all options
diagramers admin init react-typescript my-admin-app \
  --framework react \
  --typescript \
  --tailwind \
  --api-url http://localhost:3000 \
  --socket-url http://localhost:3000
```

### Admin Project Extension

#### Extend Admin Project
```bash
diagramers admin extend [options]
```

**Options:**
- `-p, --page <name>` - Generate a new page
- `-c, --component <name>` - Generate a new component
- `-s, --service <name>` - Generate a new service
- `-h, --hook <name>` - Generate a new custom hook
- `-m, --module <name>` - Generate a complete module with CRUD
- `--crud` - Include CRUD operations for module
- `--api` - Include API integration for module
- `--socket` - Include Socket.IO integration for module
- `--table` - Include data table for module
- `--form` - Include form components for module
- `--chart` - Include chart components for module
- `--auth` - Include authentication for module
- `--path <path>` - Custom path for generated files

**Examples:**
```bash
# Generate a new module with CRUD operations
diagramers admin extend --module products --crud --api --table

# Generate a new page
diagramers admin extend --page analytics

# Generate a new component
diagramers admin extend --component ProductCard

# Generate a new service
diagramers admin extend --service orderService

# Generate a new custom hook
diagramers admin extend --hook useOrders

# Generate complete module with all features
diagramers admin extend --module orders --crud --api --socket --table --form --chart --auth
```

### Admin Project Updates

#### Update Admin Project
```bash
diagramers admin update [options]
```

**Options:**
- `-t, --template <template>` - Template to update
- `-v, --version <version>` - Version to update to
- `--force` - Force update even if conflicts exist
- `--backup` - Create backup before updating

**Examples:**
```bash
# Update to latest version
diagramers admin update

# Update to specific version
diagramers admin update --version 1.0.0

# Force update with backup
diagramers admin update --force --backup
```

### Admin Version Management

#### Check Admin Version
```bash
diagramers admin version [options]
```

**Options:**
- `-c, --check <version>` - Check if specific version exists

**Examples:**
```bash
# Show current version info
diagramers admin version

# Check specific version
diagramers admin version --check 1.0.0
```

#### List Available Admin Versions
```bash
diagramers admin versions [options]
```

**Options:**
- `-a, --all` - Show all versions (default: show last 10)

**Examples:**
```bash
# Show last 10 versions
diagramers admin versions

# Show all available versions
diagramers admin versions --all
```

### Admin Project Features

#### Available Templates
- **React TypeScript Admin** - React 18 + TypeScript + Tailwind CSS
- **Vue TypeScript Admin** - Vue 3 + TypeScript + Tailwind CSS  
- **Angular Admin** - Angular 17 + TypeScript + Tailwind CSS

#### Built-in Features
- **Authentication System** - Login, register, password reset, JWT management
- **Dashboard** - Analytics overview, metric cards, chart widgets
- **User Management** - User CRUD, profiles, role management, activity tracking
- **Real-time Updates** - Socket.IO integration, live notifications
- **Data Tables** - Advanced filtering, sorting, pagination, bulk actions
- **Charts & Analytics** - Line, bar, pie, area charts with real-time data
- **Form Builder** - Dynamic forms, validation, file uploads, multi-step forms
- **File Upload** - Drag & drop, progress tracking, file preview
- **Notifications** - Toast notifications, notification center, push notifications
- **Settings Panel** - Application settings, user preferences, theme customization

#### Project Structure
```
my-admin-app/
├── src/
│   ├── components/           # Reusable UI components
│   │   ├── ui/              # Base UI components
│   │   └── layout/          # Layout components
│   ├── features/            # Feature modules
│   │   ├── auth/           # Authentication
│   │   ├── dashboard/      # Dashboard
│   │   ├── users/          # User management
│   │   └── [modules]/      # Generated modules
│   ├── hooks/              # Custom React hooks
│   ├── services/           # API services
│   ├── lib/                # Utilities and configurations
│   ├── types/              # TypeScript type definitions
│   ├── styles/             # Global styles
│   └── assets/             # Static assets
├── public/                 # Public assets
├── package.json           # Dependencies and scripts
├── tsconfig.json          # TypeScript configuration
├── tailwind.config.js     # Tailwind CSS configuration
├── vite.config.ts         # Vite configuration
└── .env                   # Environment variables
```

### Email System Management

#### Generate Email Module
```bash
diagramers extend --module email --crud
```

#### Add Email Configuration Table
```bash
diagramers extend --table email:configs --fields provider,code,credentials,fromName,fromEmail,default
```

#### Add Email Templates Table
```bash
diagramers extend --table email:templates --fields name,subject,body,isActive,createdAt
```

#### Add Email Logs Table
```bash
diagramers extend --table email:logs --fields to,subject,status,provider,error,createdAt
```

#### Create Email Relations
```bash
# One-to-many: User to Email Configs
diagramers extend --relation email:user-config:one-to-many

# One-to-many: Email Config to Email Logs
diagramers extend --relation email:config-log:one-to-many
```

#### Add Email Endpoints
```bash
# Send email endpoint
diagramers extend --endpoint email:send --method POST --description "Send email using configured provider"

# Test email endpoint
diagramers extend --endpoint email:test --method POST --description "Test email configuration"

# Get email statistics
diagramers extend --endpoint email:stats --method GET --description "Get email sending statistics"
```

#### Email Provider Setup Commands
```bash
# Add Gmail SMTP configuration
diagramers extend --endpoint email:setup-gmail --method POST --description "Setup Gmail SMTP configuration"

# Add SendGrid configuration
diagramers extend --endpoint email:setup-sendgrid --method POST --description "Setup SendGrid configuration"

# Add AWS SES configuration
diagramers extend --endpoint email:setup-ses --method POST --description "Setup AWS SES configuration"
```

### User Management System

#### Generate User Module
```bash
diagramers extend --module users --crud
```

#### Add User Profile Table
```bash
diagramers extend --table users:profiles --fields bio,avatar,socialLinks,location,website,birthDate,preferences
```

#### Add User Sessions Table
```bash
diagramers extend --table users:sessions --fields userId,deviceInfo,ipAddress,userAgent,isActive,lastActivity
```

#### Add User Activity Table
```bash
diagramers extend --table users:activities --fields userId,action,details,ipAddress,userAgent,timestamp
```

#### Create User Relations
```bash
# One-to-one: User to Profile
diagramers extend --relation users:user-profile:one-to-one

# One-to-many: User to Sessions
diagramers extend --relation users:user-session:one-to-many

# One-to-many: User to Activities
diagramers extend --relation users:user-activity:one-to-many
```

#### Add User Endpoints
```bash
# User profile management
diagramers extend --endpoint users:profile --method GET --description "Get user profile"
diagramers extend --endpoint users:update-profile --method PUT --description "Update user profile"
diagramers extend --endpoint users:upload-avatar --method POST --description "Upload user avatar"

# User administration
diagramers extend --endpoint users:list --method GET --description "List all users (admin)"
diagramers extend --endpoint users:create --method POST --description "Create user (admin)"
diagramers extend --endpoint users:update --method PUT --description "Update user (admin)"
diagramers extend --endpoint users:delete --method DELETE --description "Delete user (admin)"

# User statistics
diagramers extend --endpoint users:stats --method GET --description "Get user statistics"
diagramers extend --endpoint users:activity --method GET --description "Get user activity"
```

## 🔧 Workflow Examples

### Complete Product Management System

```bash
# 1. Create new API project
diagramers init api ecommerce-api
cd ecommerce-api

# 2. Generate products module
diagramers extend --module products --crud

# 3. Add categories table
diagramers extend --table products:categories --fields name,description,slug

# 4. Add products table
diagramers extend --table products:products --fields name,price,description,category_id

# 5. Create category-product relation
diagramers extend --relation products:category-product:one-to-many

# 6. Add custom search endpoint
diagramers extend --endpoint products:search --method GET --description "Search products"

# 7. Install dependencies and start
npm install
npm start
```

### User Management with Profiles

```bash
# 1. Generate users module (if not exists)
diagramers extend --module users --crud

# 2. Add user profiles table
diagramers extend --table users:profiles --fields bio,avatar,social_links,birth_date

# 3. Create user-profile relation
diagramers extend --relation users:user-profile:one-to-one

# 4. Add profile endpoints
diagramers extend --endpoint users:update-profile --method PUT
diagramers extend --endpoint users:get-profile --method GET
```

### Complete Email System Setup

```bash
# 1. Generate email module with CRUD operations
diagramers extend --module email --crud

# 2. Add email configurations table
diagramers extend --table email:configs --fields provider,code,credentials,fromName,fromEmail,default

# 3. Add email templates table
diagramers extend --table email:templates --fields name,subject,body,isActive,createdAt

# 4. Add email logs table for tracking
diagramers extend --table email:logs --fields to,subject,status,provider,error,createdAt

# 5. Create relationships
diagramers extend --relation email:user-config:one-to-many
diagramers extend --relation email:config-log:one-to-many

# 6. Add email-specific endpoints
diagramers extend --endpoint email:send --method POST --description "Send email using configured provider"
diagramers extend --endpoint email:test --method POST --description "Test email configuration"
diagramers extend --endpoint email:stats --method GET --description "Get email sending statistics"

# 7. Add provider setup endpoints
diagramers extend --endpoint email:setup-gmail --method POST --description "Setup Gmail SMTP configuration"
diagramers extend --endpoint email:setup-sendgrid --method POST --description "Setup SendGrid configuration"

# 8. Install dependencies and start
npm install
npm start
```

### Complete User Management System Setup

```bash
# 1. Generate users module with CRUD operations
diagramers extend --module users --crud

# 2. Add user profiles table
diagramers extend --table users:profiles --fields bio,avatar,socialLinks,location,website,birthDate,preferences

# 3. Add user sessions table for tracking
diagramers extend --table users:sessions --fields userId,deviceInfo,ipAddress,userAgent,isActive,lastActivity

# 4. Add user activity table for audit
diagramers extend --table users:activities --fields userId,action,details,ipAddress,userAgent,timestamp

# 5. Create user relationships
diagramers extend --relation users:user-profile:one-to-one
diagramers extend --relation users:user-session:one-to-many
diagramers extend --relation users:user-activity:one-to-many

# 6. Add user profile endpoints
diagramers extend --endpoint users:profile --method GET --description "Get user profile"
diagramers extend --endpoint users:update-profile --method PUT --description "Update user profile"
diagramers extend --endpoint users:upload-avatar --method POST --description "Upload user avatar"

# 7. Add user administration endpoints
diagramers extend --endpoint users:list --method GET --description "List all users (admin)"
diagramers extend --endpoint users:create --method POST --description "Create user (admin)"
diagramers extend --endpoint users:update --method PUT --description "Update user (admin)"
diagramers extend --endpoint users:delete --method DELETE --description "Delete user (admin)"

# 8. Add user analytics endpoints
diagramers extend --endpoint users:stats --method GET --description "Get user statistics"
diagramers extend --endpoint users:activity --method GET --description "Get user activity"

# 9. Install dependencies and start
npm install
npm start
```

## 🛠️ Advanced Usage

### Database Seeding

All generated tables automatically include:
- **Sample data** - 3 sample records per table
- **Seeder integration** - Automatic database seeding
- **Development data** - Realistic test data

```bash
# Run database seeding
npm run seed

# Reset and reseed database
npm run seed --reset
```

### Template Updates

```bash
# Update project with latest template
diagramers update

# Force update with backup
diagramers update --force --backup
```

### Custom Field Types

The CLI automatically detects field types based on naming conventions:

```bash
# These fields will be auto-typed:
diagramers extend --table products:products --fields \
  name,description,price,stock_count,created_at,is_active,category_id
```

**Auto-detection:**
- `name`, `title`, `description` → String
- `price`, `count`, `stock_count` → Number
- `created_at`, `updated_at` → Date
- `is_active`, `verified` → Boolean
- `category_id`, `user_id` → ObjectId

## 📚 Project Structure

Generated projects follow this structure:

```
my-project/
├── src/
│   ├── modules/
│   │   ├── products/
│   │   │   ├── controllers/
│   │   │   ├── entities/
│   │   │   ├── schemas/
│   │   │   ├── services/
│   │   │   └── routes/
│   │   └── users/
│   ├── core/
│   │   ├── database/
│   │   ├── config/
│   │   └── server/
│   └── shared/
├── scripts/
└── package.json
```

## 🔍 Troubleshooting

### Common Issues

#### Module Not Found
```bash
❌ Module 'inventory' does not exist
```
**Solution:** Create the module first:
```bash
diagramers extend --module inventory
```

#### Table Already Exists
```bash
❌ Table 'products' already exists in module 'products'
```
**Solution:** Use a different table name or check existing tables

#### Invalid Relation
```bash
❌ Table 'categories' does not exist in module 'products'
```
**Solution:** Create both tables before creating relations:
```bash
diagramers extend --table products:categories --fields name,description
diagramers extend --table products:products --fields name,price
diagramers extend --relation products:category-product
```

### Getting Help

```bash
# General help
diagramers --help

# Command-specific help
diagramers init --help
diagramers extend --help
diagramers update --help
```

## 🤝 Contributing

We welcome contributions! Please see our [Contributing Guide](CONTRIBUTING.md) for details.

## 📄 License

MIT License - see [LICENSE](LICENSE) file for details.

## 🔗 Related Packages

- [@diagramers/api](https://npmjs.com/package/@diagramers/api) - API template package
- [@diagramers/admin](https://npmjs.com/package/@diagramers/admin) - Admin template package

## 📞 Support

- **Issues**: [GitHub Issues](https://github.com/diagramers/diagramers-cli/issues)
- **Documentation**: [Official Docs](https://docs.diagramers.com)
- **Community**: [Discord Server](https://discord.gg/diagramers) 