# Workflow Schedule Module - Installation Guide

## Quick Start

### Step 1: Install Dependencies

```bash
npm install @nestjs/bull bull redis cron-parser
npm install --save-dev @types/bull
```

**Note:** `cron-parser` includes its own TypeScript definitions, so no `@types` package is needed.

### Step 2: Setup Redis

#### Option A: Using Docker (Recommended)
```bash
docker run -d \
  --name redis-workflow \
  -p 6379:6379 \
  redis:latest
```

#### Option B: Local Installation
**macOS:**
```bash
brew install redis
brew services start redis
```

**Ubuntu/Debian:**
```bash
sudo apt-get install redis-server
sudo systemctl start redis-server
```

**Windows:**
Download from: https://redis.io/download

### Step 3: Configure Environment Variables

Add to your `.env` file:

```env
# Redis Configuration
REDIS_HOST=localhost
REDIS_PORT=6379
REDIS_PASSWORD=
REDIS_DB=0

# Existing Database Configuration (verify these)
DB_HOST=13.234.25.234
DB_PORT=3306
DB_USER=root
DB_PASS=Rezolut@123
DB_NAME=core
```

### Step 4: Verify Redis Connection

```bash
# Test Redis connection
redis-cli ping
# Should respond: PONG
```

### Step 5: Run Database Migrations

The module requires three migrations to be run:

```bash
# Using TypeORM CLI (recommended)
npx ts-node -r tsconfig-paths/register ./node_modules/typeorm/cli.js migration:run -d src/config/database.config.ts

# Or create a migration script in package.json:
# "migration:run": "typeorm migration:run -d src/config/database.config.ts"
# Then run:
npm run migration:run
```

**Migrations will create:**
1. ✅ `workflow_type` column in `cr_wf_master` table
2. ✅ `cr_wf_scheduled_workflow` table with indexes
3. ✅ `cr_wf_execution_log` table with indexes

### Step 6: Start Your Application

```bash
npm run start:dev
```

### Step 7: Verify Installation

Check the console logs for:
```
[Nest] INFO [BullModule] Bull queues registered
[Nest] INFO [WorkflowScheduleModule] Workflow Schedule Module initialized
```

## Quick Test

### Create Your First Schedule

```bash
curl -X POST http://localhost:3000/workflow-schedule/create \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer YOUR_JWT_TOKEN" \
  -d '{
    "workflow_id": 1,
    "name": "Test Schedule",
    "cron_expression": "*/5 * * * *",
    "timezone": "Asia/Kolkata",
    "actions": []
  }'
```

### List All Schedules

```bash
curl -X GET http://localhost:3000/workflow-schedule/list \
  -H "Authorization: Bearer YOUR_JWT_TOKEN"
```

## Troubleshooting

### Issue: Cannot connect to Redis

**Solution:**
```bash
# Check if Redis is running
redis-cli ping

# If not running, start Redis
docker start redis-workflow
# or
brew services start redis
```

### Issue: Migration fails with "Table already exists"

**Solution:**
Migrations check if tables exist before creating them. If you see this message, the tables are already present. You can safely ignore it.

### Issue: Jobs are not processing

**Checklist:**
- [ ] Redis is running and accessible
- [ ] Schedule status is `ACTIVE`
- [ ] Schedule `is_enabled` is `true`
- [ ] Cron expression is valid
- [ ] Application has restarted after creating the schedule

**Verify:**
```bash
# Check Redis keys
redis-cli KEYS "bull:workflow-schedule:*"

# Should show keys if jobs are queued
```

### Issue: TypeScript errors after installation

**Solution:**
```bash
# Clear node_modules and reinstall
rm -rf node_modules package-lock.json
npm install

# Restart your IDE/editor
```

## Verify Bull Queue Dashboard (Optional)

Install Bull Board for visual queue monitoring:

```bash
npm install @bull-board/express @bull-board/api
```

Add to your `main.ts`:
```typescript
import { createBullBoard } from '@bull-board/api';
import { BullAdapter } from '@bull-board/api/bullAdapter';
import { ExpressAdapter } from '@bull-board/express';

// Get queue from your app
const schedulerQueue = app.get('BullQueue_workflow-schedule');

const serverAdapter = new ExpressAdapter();
createBullBoard({
  queues: [new BullAdapter(schedulerQueue)],
  serverAdapter,
});

serverAdapter.setBasePath('/admin/queues');
app.use('/admin/queues', serverAdapter.getRouter());
```

Then access: `http://localhost:3000/admin/queues`

## Package Versions

Tested with:
```json
{
  "@nestjs/bull": "^10.0.0",
  "@nestjs/common": "^11.0.0",
  "@nestjs/core": "^11.0.0",
  "bull": "^4.12.0",
  "redis": "^4.6.0",
  "cron-parser": "^4.9.0"
}
```

## Production Checklist

Before deploying to production:

- [ ] Configure Redis with persistence
- [ ] Set up Redis password authentication
- [ ] Configure appropriate retry strategies
- [ ] Set up monitoring and alerting
- [ ] Configure log retention policies
- [ ] Test failover scenarios
- [ ] Set up backup for scheduled workflow configurations
- [ ] Document schedule ownership and purpose
- [ ] Configure rate limiting if needed
- [ ] Set up Redis clustering for high availability

## Next Steps

1. Read the full [README.md](./README.md) for API documentation
2. Test the 9 API endpoints
3. Create your first scheduled workflow
4. Monitor execution logs
5. Set up Bull Board for visual monitoring

## Support

If you encounter issues:
1. Check application logs
2. Verify Redis connectivity
3. Ensure migrations ran successfully
4. Review the [README.md](./README.md) troubleshooting section
