# 🤖 Using Claude Code to Implement Workflow Schedule Module

## What is Claude Code?

Claude Code is a command-line tool that lets Claude work directly in your codebase, making changes, creating files, and implementing features autonomously.

---

## 🚀 Quick Setup

### Step 1: Install Claude Code

```bash
# Install Claude Code CLI
npm install -g @anthropic-ai/claude-code

# Or using brew (macOS)
brew install claude-code
```

### Step 2: Authenticate

```bash
claude-code auth
# Follow the prompts to authenticate with your Anthropic account
```

---

## 📋 Implementation with Claude Code

### Option 1: Automated Full Implementation

Navigate to your project and run:

```bash
cd /Users/debrajdas/WORKSPACE/001_RZ/PROJECTS/ETHER/250218_nodejs_core

# Start Claude Code session
claude-code
```

Then give Claude this prompt:

```
I need you to implement a complete workflow schedule module in my NestJS project.

Project path: /Users/debrajdas/WORKSPACE/001_RZ/PROJECTS/ETHER/250218_nodejs_core

Requirements:
1. Create a workflow-schedule module at: src/module/workflow-schedule/
2. Implement scheduled workflows using NestJS + Bull + Redis
3. Create the following structure:
   - workflow-schedule.module.ts (main module)
   - workflow-schedule.service.ts (9 methods for schedule management)
   - workflow-schedule.controller.ts (9 REST endpoints)
   - entities/ (ScheduledWorkflow, WorkflowExecutionLog)
   - dto/ (CreateScheduleDto, UpdateScheduleDto, GetExecutionLogsDto)
   - processors/schedule.processor.ts (Bull processor)
   - constants/schedule.constants.ts
   - interfaces/schedule-job-data.interface.ts

4. Create TypeORM migrations:
   - Add workflow_type column to workflows table
   - Create scheduled_workflows table
   - Create workflow_execution_logs table

5. Create config/bull.config.ts for Bull/Redis configuration

6. Update app.module.ts to import BullModule and WorkflowScheduleModule

Features needed:
- Schedule workflows with cron expressions
- Timezone support
- Pause/resume schedules
- Manual trigger execution
- Execution logging
- Retry with exponential backoff
- Batch processing (100 records/batch)
- Actions: send email, update records, create tasks, send notifications

Please implement all files with complete code, proper TypeScript types, validation, error handling, and documentation.
```

---

## Option 2: Step-by-Step Implementation

If you prefer more control, use Claude Code for specific tasks:

### Task 1: Create Module Structure

```bash
claude-code
```

Prompt:
```
Create the workflow-schedule module structure in src/module/workflow-schedule/ with these subdirectories:
- constants/
- dto/
- entities/
- interfaces/
- processors/
- tests/

Create empty index files in each subdirectory.
```

### Task 2: Create Entities

Prompt:
```
Create TypeORM entities in src/module/workflow-schedule/entities/:

1. scheduled-workflow.entity.ts with fields:
   - id, workflow_id, schedule_expression, timezone, is_active
   - last_executed_at, next_execution_at, execution_count
   - start_date, end_date, created_at, updated_at
   - Relation: ManyToOne with Workflow
   - Indexes: next_execution_at, workflow_id

2. workflow-execution-log.entity.ts with fields:
   - id, workflow_id, execution_type, status
   - started_at, completed_at, records_processed, records_failed
   - error_message, job_id, execution_data
   - Relation: ManyToOne with Workflow
   - Computed properties: durationMs, successRate
```

### Task 3: Create DTOs

Prompt:
```
Create validation DTOs in src/module/workflow-schedule/dto/:

1. create-schedule.dto.ts
   - workflowId (required, number)
   - scheduleExpression (required, string, cron format)
   - timezone (optional, string, IANA format, default: UTC)
   - startDate, endDate (optional, ISO date strings)
   - isActive (optional, boolean, default: true)

2. update-schedule.dto.ts
   - All fields optional from CreateScheduleDto

3. get-execution-logs.dto.ts
   - status (optional, enum filter)
   - executionType (optional, enum filter)
   - limit (optional, number, default: 50, max: 500)
   - offset (optional, number, default: 0)

Use class-validator decorators for all validation.
```

### Task 4: Create Service

Prompt:
```
Create workflow-schedule.service.ts in src/module/workflow-schedule/ with these methods:

1. scheduleWorkflow(createDto) - Create new schedule
2. updateSchedule(id, updateDto) - Update existing schedule
3. deleteSchedule(id) - Delete schedule
4. pauseSchedule(id) - Pause schedule
5. resumeSchedule(id) - Resume schedule
6. triggerSchedule(id) - Manually trigger execution
7. getExecutionLogs(scheduleId, query) - Get logs with filtering
8. getScheduledJobs() - Get all active schedules
9. getScheduleById(id) - Get schedule by ID

Include:
- Cron expression validation using cron-parser
- Timezone validation using moment-timezone
- Next execution calculation
- Bull queue management
- Error handling with proper exceptions
```

### Task 5: Create Bull Processor

Prompt:
```
Create schedule.processor.ts in src/module/workflow-schedule/processors/:

Implement a Bull processor that:
1. Processes scheduled workflow jobs
2. Queries records based on workflow criteria
3. Executes actions (sendEmail, updateRecord, createTask, sendNotification)
4. Handles batch processing (100 records per batch)
5. Logs execution results
6. Updates schedule after execution
7. Implements retry with exponential backoff
8. Handles template variable replacement ({{record.field}})

Include lifecycle hooks:
- @OnQueueActive()
- @OnQueueCompleted()
- @OnQueueFailed()
```

### Task 6: Create Controller

Prompt:
```
Create workflow-schedule.controller.ts with REST endpoints:

POST   /workflow-schedule           - Create schedule
GET    /workflow-schedule           - List all schedules  
GET    /workflow-schedule/:id       - Get by ID
PUT    /workflow-schedule/:id       - Update schedule
DELETE /workflow-schedule/:id       - Delete schedule
POST   /workflow-schedule/:id/pause - Pause
POST   /workflow-schedule/:id/resume - Resume
POST   /workflow-schedule/:id/trigger - Manual trigger
GET    /workflow-schedule/:id/logs  - Get execution logs

Add Swagger decorators (@ApiOperation, @ApiResponse, @ApiTags).
```

### Task 7: Create Migrations

Prompt:
```
Create TypeORM migrations in src/migrations/:

1. AddWorkflowTypeToWorkflows - Add workflow_type ENUM column to workflows table
2. CreateScheduledWorkflowsTable - Create scheduled_workflows table with all fields and indexes
3. CreateWorkflowExecutionLogsTable - Create workflow_execution_logs table with all fields and indexes

Use proper TypeORM migration format with up() and down() methods.
```

### Task 8: Create Configuration

Prompt:
```
Create src/config/bull.config.ts:

Export getBullConfig function that returns BullModuleOptions with:
- Redis connection config from environment variables
- Default job options (attempts: 3, exponential backoff)
- Queue settings (lock duration, stalled interval)
- Job retention policies

Support environment variables:
- REDIS_HOST, REDIS_PORT, REDIS_PASSWORD, REDIS_DB
```

### Task 9: Update App Module

Prompt:
```
Update src/app.module.ts:

1. Import BullModule from @nestjs/bull
2. Import WorkflowScheduleModule
3. Import getBullConfig from ./config/bull.config

4. Add to imports array:
   - BullModule.forRootAsync() with getBullConfig
   - WorkflowScheduleModule

Keep all existing imports and configuration.
```

### Task 10: Create Tests

Prompt:
```
Create unit tests in src/module/workflow-schedule/tests/workflow-schedule.service.spec.ts:

Test all service methods:
- scheduleWorkflow() - valid and invalid inputs
- updateSchedule() - success and not found cases
- deleteSchedule() - success and not found cases
- pauseSchedule() - verify isActive flag
- resumeSchedule() - verify queue management
- triggerSchedule() - verify manual execution
- getExecutionLogs() - verify filtering and pagination

Use Jest with mocked repositories and queue.
```

---

## 🎯 Complete Implementation Command

For a single-command implementation, use:

```bash
cd /Users/debrajdas/WORKSPACE/001_RZ/PROJECTS/ETHER/250218_nodejs_core

claude-code --prompt "Implement a complete workflow schedule module based on the attached implementation plan. Create all files in src/module/workflow-schedule/ with full TypeScript implementation, including module, service, controller, entities, DTOs, processor, migrations, and tests. Follow NestJS best practices and include proper error handling, validation, and documentation." --attach Schedule_Workflow_Implementation_Plan.md
```

---

## 📦 What Claude Code Will Create

Claude Code will create approximately 17 files:

```
src/
├── config/
│   └── bull.config.ts
├── migrations/
│   ├── [timestamp]-AddWorkflowTypeToWorkflows.ts
│   ├── [timestamp]-CreateScheduledWorkflowsTable.ts
│   └── [timestamp]-CreateWorkflowExecutionLogsTable.ts
└── module/
    └── workflow-schedule/
        ├── workflow-schedule.module.ts
        ├── workflow-schedule.service.ts
        ├── workflow-schedule.controller.ts
        ├── constants/
        │   └── schedule.constants.ts
        ├── dto/
        │   ├── create-schedule.dto.ts
        │   ├── update-schedule.dto.ts
        │   └── get-execution-logs.dto.ts
        ├── entities/
        │   ├── scheduled-workflow.entity.ts
        │   └── workflow-execution-log.entity.ts
        ├── interfaces/
        │   └── schedule-job-data.interface.ts
        ├── processors/
        │   └── schedule.processor.ts
        └── tests/
            └── workflow-schedule.service.spec.ts
```

---

## ✅ After Implementation

Once Claude Code finishes, you'll need to:

### 1. Install Dependencies

```bash
npm install @nestjs/bull bull ioredis cron-parser moment-timezone
npm install --save-dev @types/bull @types/cron
```

### 2. Setup Redis

```bash
docker run -d -p 6379:6379 --name redis redis:alpine
```

### 3. Update .env

```env
REDIS_HOST=localhost
REDIS_PORT=6379
REDIS_PASSWORD=
REDIS_DB=0
```

### 4. Run Migrations

```bash
npm run migration:run
```

### 5. Start Application

```bash
npm run start:dev
```

---

## 🔍 Monitoring Progress

Claude Code will show you:
- ✅ Files being created
- 📝 Code being written
- 🔧 Changes being made
- ⚠️ Any errors encountered

You can review each change before accepting it.

---

## 💡 Pro Tips

### 1. **Use Context Files**

Provide Claude Code with your implementation plan:

```bash
claude-code --attach /path/to/Schedule_Workflow_Implementation_Plan.md
```

### 2. **Iterative Refinement**

If something isn't perfect, ask Claude Code to refine:

```
"The service needs better error messages. Update all error handling to include detailed context."
```

### 3. **Add Tests as You Go**

```
"After creating the service, generate comprehensive unit tests for all methods."
```

### 4. **Review Changes**

Claude Code shows diffs before applying. Review carefully!

---

## 🚨 Important Notes

1. **Backup First**: Always commit your current code before using Claude Code
   ```bash
   git add .
   git commit -m "Before workflow-schedule implementation"
   ```

2. **Review Generated Code**: Claude Code is powerful but always review the changes

3. **Test Thoroughly**: Run tests after implementation
   ```bash
   npm run test
   npm run test:e2e
   ```

---

## 📚 Claude Code Commands Reference

```bash
# Start interactive session
claude-code

# Run with specific prompt
claude-code --prompt "Your prompt here"

# Attach context files
claude-code --attach file1.md --attach file2.ts

# Run in specific directory
claude-code --dir /path/to/project

# Show help
claude-code --help

# Check version
claude-code --version
```

---

## 🎬 Example Session

```bash
$ cd /Users/debrajdas/WORKSPACE/001_RZ/PROJECTS/ETHER/250218_nodejs_core
$ claude-code

Claude Code> Implement the workflow schedule module based on the plan in /mnt/project/Schedule_Workflow_Implementation_Plan.md

🤖 Claude: I'll implement the workflow schedule module for you. Let me start by creating the directory structure...

✅ Created: src/module/workflow-schedule/
✅ Created: src/module/workflow-schedule/entities/
✅ Created: src/module/workflow-schedule/dto/
...
[Claude creates all files]
...
✅ Implementation complete!

📋 Next steps:
1. Install dependencies: npm install @nestjs/bull bull ioredis cron-parser moment-timezone
2. Setup Redis: docker run -d -p 6379:6379 --name redis redis:alpine
3. Update .env with Redis configuration
4. Run migrations: npm run migration:run
5. Start application: npm run start:dev

Claude Code> exit
```

---

## 🎉 Benefits of Using Claude Code

✅ **Faster**: Complete implementation in minutes  
✅ **Consistent**: Follows best practices automatically  
✅ **Interactive**: Can ask questions and refine  
✅ **Safe**: Shows diffs before applying changes  
✅ **Smart**: Understands your project structure  

---

## 📞 Need Help?

If you encounter issues with Claude Code:

1. Check Claude Code documentation: https://docs.claude.com/claude-code
2. Use `--verbose` flag for detailed logging
3. Start with small tasks to test
4. Always review changes before accepting

---

**Ready to use Claude Code? Start with the complete implementation command above!** 🚀
