> ## Documentation Index
> Fetch the complete documentation index at: https://docs.reach.raysium.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Managing Campaigns

> Complete guide to managing campaigns, permissions, editing, and operations

## Campaign Management Overview

Campaign management involves viewing, editing, controlling execution, and monitoring performance. All operations respect organization context and role-based permissions.

## Viewing Campaigns

### Campaign List

The campaigns list displays all accessible campaigns based on view mode and permissions.

**View Modes:**

**My Campaigns (`view_mode=own`):**

* Shows only campaigns you created
* Default view for all users
* In organization mode: Shows your campaigns within organization
* In personal mode: Shows your personal campaigns

**All Organization Campaigns (`view_mode=all`):**

* Shows all campaigns in organization
* **Only available to Owner/Admin roles**
* Requires `admin_view_enabled = true` setting
* Members cannot access this view (falls back to "own")

**Personal Mode:**

* Shows campaigns with `organization_id = NULL`
* Complete isolation from organization data
* Only your own campaigns visible

### Campaign Details

Click campaign name to view detailed information:

**Overview Tab:**

* Campaign metadata (name, description, status)
* Telegram account information
* Creation and update timestamps
* Creator information (in org mode)

**Flow Tab:**

* Visual representation of flow
* Read-only view of nodes and edges
* Shows current flow configuration

**Contacts Tab:**

* List of all contacts in campaign
* Execution status per contact
* Add/remove contacts functionality
* Filter and search contacts

**Statistics Tab:**

* Real-time campaign metrics
* Execution breakdown by status
* Message statistics (sent, delivered, failed)
* Response rates and completion rates
* Recent activities (last 20 log entries)

**Logs Tab:**

* Complete audit trail of all executions
* Filter by execution, node type, status
* Search by contact name or message content
* Export logs for compliance

## Permissions

### View Permissions

**Own Campaigns:**

* All roles can view own campaigns
* Always accessible regardless of organization settings

**Other Members' Campaigns:**

* **Owner/Admin**: Can view if `admin_view_enabled = true`
* **Member**: Cannot view (even if `admin_view_enabled = true`)
* Campaign must belong to same organization

**Personal Mode:**

* Users can only view campaigns with `organization_id = NULL`
* Complete isolation from organization data

### Edit Permissions

**Own Campaigns:**

* All roles can edit own campaigns
* Subject to status-based restrictions (see below)

**Other Members' Campaigns:**

* **Owner**: Can edit any organization campaign (regardless of status)
* **Admin**: Can edit any organization campaign (regardless of status)
* **Member**: Cannot edit other members' campaigns

**Status-Based Restrictions:**

* `draft`, `paused`, `scheduled`: Can edit flow configuration
* `active`: Cannot edit flow (must pause first)
* `completed`, `cancelled`: Cannot edit (historical record)

**Note:** Basic metadata (name, description, Telegram account) can be updated even when flow is locked.

### Delete Permissions

**Own Campaigns:**

* All roles can delete own campaigns
* Soft delete: `deleted_at` timestamp set
* Statistics and logs preserved

**Other Members' Campaigns:**

* **Owner**: Can delete any organization campaign
* **Admin**: Can delete any organization campaign
* **Member**: Cannot delete other members' campaigns

## Campaign Actions

### Launch Campaign

Start a campaign to begin processing executions.

**Requirements:**

* Campaign status: `draft` or `paused`
* Campaign must be enabled (`enabled = true`)
* Telegram account must be connected and healthy
* At least one contact must be selected

**Launch Process:**

1. Status changes to `active` (or `scheduled` if scheduled)
2. Paused executions resume (status: `pending`)
3. Completed executions reset (status: `pending`, `current_node_id = null`)
4. `next_execution_at` set to `now()` for immediate processing
5. Worker picks up executions on next cycle

**Permissions:**

* Owner: Can launch own campaigns
* Admin: Can launch own campaigns
* Member: Can launch own campaigns
* Cannot launch other members' campaigns (even with view access)

### Pause Campaign

Temporarily stop an active campaign.

**Pause Process:**

1. Campaign status changes to `paused`
2. All active executions paused (status: `paused`)
3. `next_execution_at` preserved (resume from same point)
4. Flow configuration can be edited

**Resume:**

* Launch campaign again to resume
* Executions continue from where they stopped
* No progress lost

**Permissions:**

* Owner: Can pause own campaigns
* Admin: Can pause own campaigns
* Member: Can pause own campaigns
* Cannot pause other members' campaigns

### Stop Campaign

Immediately stop a campaign and cancel all executions.

**Stop Process:**

1. Campaign status changes to `cancelled`
2. All active executions cancelled (status: `cancelled`)
3. `completed_at` timestamp set
4. `error_message`: "Campaign stopped by user"
5. Cannot be resumed (must duplicate to restart)

**Permissions:**

* Owner: Can stop own campaigns
* Admin: Can stop own campaigns
* Member: Can stop own campaigns
* Cannot stop other members' campaigns

### Edit Campaign

Modify campaign settings and flow configuration.

**What Can Be Edited:**

**Always Editable (regardless of status):**

* Campaign name
* Description
* Telegram account
* Timezone
* A/B test settings (if not active)
* Response handling settings

**Status-Dependent:**

* Flow configuration (nodes, edges): Only if `draft`, `paused`, or `scheduled`
* Cannot edit flow if `active`, `completed`, or `cancelled`

**Edit Restrictions:**

* Active campaigns: Must pause before editing flow
* Completed campaigns: Cannot edit (historical record)
* Cancelled campaigns: Cannot edit (historical record)

**Permissions:**

* Owner: Can edit own campaigns (subject to status)
* Admin: Can edit own campaigns (subject to status)
* Member: Can edit own campaigns (subject to status)
* Owner/Admin: Can edit other members' campaigns (subject to status)
* Member: Cannot edit other members' campaigns

### Duplicate Campaign

Create a copy of an existing campaign.

**Duplication Process:**

1. New campaign created with name: `"{original_name} (Copy)"`
2. Flow configuration copied (nodes, edges)
3. Settings copied (timezone, Telegram account, A/B test config)
4. Status set to `draft`
5. No contacts assigned (must add manually)

**Use Cases:**

* Create variations for A/B testing
* Test changes without affecting original
* Reuse successful campaign structure

**Permissions:**

* Owner: Can duplicate own campaigns
* Admin: Can duplicate own campaigns
* Member: Can duplicate own campaigns
* Owner/Admin: Can duplicate other members' campaigns (if can view)
* Member: Cannot duplicate other members' campaigns

### Delete Campaign

Permanently remove a campaign (soft delete).

**Delete Process:**

1. `deleted_at` timestamp set
2. Campaign hidden from list (soft delete)
3. Statistics and logs preserved
4. Executions preserved (for audit trail)
5. Can be restored (if needed)

**Permissions:**

* Owner: Can delete own campaigns
* Admin: Can delete own campaigns
* Member: Can delete own campaigns
* Owner/Admin: Can delete other members' campaigns
* Member: Cannot delete other members' campaigns

## Enable/Disable Campaign

### Enable Campaign

Enable a disabled campaign to allow launching.

**Enable Process:**

1. `enabled` flag set to `true`
2. Campaign can be launched
3. Previously cancelled executions remain cancelled
4. Does not automatically start campaign

**Use Cases:**

* Re-enable after maintenance
* Enable after fixing issues
* Prepare campaign for launch

### Disable Campaign

Disable a campaign to prevent launching and stop active executions.

**Disable Process:**

1. `enabled` flag set to `false`
2. Campaign cannot be launched
3. All active executions immediately cancelled
4. Status remains unchanged (can be `active`, `paused`, etc.)

**Use Cases:**

* Emergency stop without deleting
* Temporarily prevent launches
* Disable problematic campaigns

**Difference from Pause:**

* Pause: Temporarily stops, can resume
* Disable: Prevents launching, cancels executions
* Disabled campaigns cannot be launched until re-enabled

## Contact Management

### Adding Contacts

Add contacts to campaign (works for any status).

**During Campaign Creation:**

* Select contacts from available list
* Executions created when campaign saved

**After Campaign Creation:**

* Use "Add Contacts" button on campaign detail page
* Select contacts from available list
* Executions created with status `pending`
* For active campaigns: Executions processed immediately
* For completed campaigns: Campaign reactivated to `active`

**Execution Creation:**

* One execution per contact
* Status: `pending`
* `next_execution_at`: `now()` for immediate processing
* Context initialized with contact data
* Duplicate contacts skipped (execution already exists)

### Removing Contacts

Remove contacts from campaign.

**Remove Process:**

1. Select contacts to remove
2. Executions deleted (soft delete)
3. Progress lost for removed contacts
4. Campaign statistics updated

**Permissions:**

* Owner: Can remove contacts from own campaigns
* Admin: Can remove contacts from own campaigns
* Member: Can remove contacts from own campaigns
* Owner/Admin: Can remove contacts from other members' campaigns
* Member: Cannot remove contacts from other members' campaigns

## Campaign Statistics

### Real-Time Metrics

**Execution Metrics:**

* `total_contacts`: Total leads in campaign
* `contacts_started`: Executions that began processing
* `contacts_completed`: Executions that finished successfully
* `contacts_failed`: Executions that failed
* `contacts_active`: Currently processing executions
* `contacts_responded`: Leads who replied

**Message Metrics:**

* `messages_sent`: Total messages sent
* `messages_failed`: Failed send attempts
* `messages_delivered`: Confirmed deliveries
* `messages_not_sent`: Pending sends

**Rates:**

* `completion_rate`: (completed / total) × 100
* `response_rate`: (responded / delivered) × 100
* `delivery_rate`: (delivered / sent) × 100

### Statistics Calculation

**Database Function:**

* Statistics computed by `get_campaign_statistics()` function
* Aggregates data from executions, logs, and messages
* Cached for performance (refreshed every 5 minutes)

**Real-Time Updates:**

* Statistics update as executions progress
* Refresh button available for manual update
* Auto-refresh every 30 seconds on statistics page

**Access:**

* Available via `/campaign-flows/{id}/statistics` endpoint
* Displayed on campaign detail page
* Used for performance monitoring

### Recent Activities

**Activity Feed:**

* Last 20 log entries from all executions
* Shows node executions, message sends, responses
* Filtered by importance (sendMessage, delivery, response, etc.)
* Sorted by `executed_at` (newest first)

**Activity Types:**

* `message_sent`: Message sent to lead
* `campaign_activity`: Other node executions
* `response_detected`: Lead replied
* `delivery_confirmed`: Message delivered

## Troubleshooting

### Campaign Not Sending

**Check:**

1. Campaign status is `active`
2. Campaign is enabled (`enabled = true`)
3. Telegram account is connected and healthy
4. Contacts are selected and executions exist
5. Rate limits not exceeded
6. Flow configuration is valid

**Common Issues:**

* Account disconnected: Reconnect Telegram account
* Rate limit exceeded: Wait for cooldown or adjust limits
* No executions: Add contacts to campaign
* Invalid flow: Check flow configuration for errors

### Campaign Stuck

**Symptoms:**

* Executions remain in `pending` or `running` status
* No progress for extended period

**Check:**

1. Worker is running (check worker logs)
2. Executions have valid `next_execution_at`
3. Rate limits not blocking execution
4. Telegram account is healthy

**Solutions:**

* Pause and resume campaign
* Check worker logs for errors
* Verify rate limit configuration
* Restart worker if needed

### Cannot Edit Campaign

**Check:**

1. Campaign status allows editing (`draft`, `paused`, `scheduled`)
2. You have edit permissions (owner or admin)
3. Campaign is not locked by another process

**Solutions:**

* Pause campaign before editing flow
* Check your role and permissions
* Refresh page and try again
* Contact support if issue persists

### Statistics Not Updating

**Check:**

1. Statistics cache (refreshes every 5 minutes)
2. Executions are actually progressing
3. Database function is working

**Solutions:**

* Click refresh button
* Wait for cache refresh (5 minutes)
* Check execution logs for activity
* Contact support if issue persists

## Best Practices

1. **Monitor Regularly**: Check campaign progress and statistics frequently
2. **Use Pause**: Pause instead of stop when temporarily halting
3. **Review Logs**: Check audit logs for debugging and compliance
4. **Test First**: Test campaigns with small audience before full launch
5. **Respect Permissions**: Understand role-based access controls
6. **Document Changes**: Use description field to note changes
7. **Monitor Rate Limits**: Watch account health and rate limit usage
8. **Optimize Based on Data**: Use statistics to improve campaigns
