# Workflow Activity Logging Documentation

## Overview

The workflow system now includes comprehensive activity logging using Spatie ActivityLog. All workflow actions are automatically logged with detailed information about what happened, who performed the action, and relevant context.

## Features

### Automatic Logging
The `HasWorkflow` trait provides built-in logging methods that are automatically called by the `WorkflowActions` class:

- **Workflow Started**: Logged when a workflow is initiated
- **Step Approved**: Logged when a workflow step is approved/completed
- **Step Rejected**: Logged when a workflow step is rejected
- **Workflow Completed**: Logged when the entire workflow is finished
- **Custom Activities**: Support for logging custom workflow events

### Logged Information

Each activity log entry includes:
- **Performer**: Who performed the action (via `causedBy()`)
- **Subject**: The model the workflow is on (via `performedOn()`)
- **Event Type**: Categorized event name (workflow_started, workflow_step_approved, etc.)
- **Properties**: Detailed data about the action
- **Description**: Human-readable description of what happened

## Activity Types

### 1. Workflow Started
```php
// Triggered when: Starting a new workflow
$record->logWorkflowStarted($notes);

// Properties logged:
[
    'action' => 'started',
    'current_step' => 'Study Phase',
    'current_step_id' => 123,
    'notes' => 'Auto-initialized when viewing record',
    'workflow_id' => 456,
]

// Description: "Workflow started"
```

### 2. Step Approved
```php
// Triggered when: Approving/completing a workflow step
$record->logWorkflowStepApproved($fromStep, $toStep, $stepData, $notes);

// Properties logged:
[
    'action' => 'approved',
    'from_step' => 'Study Phase',
    'from_step_id' => 123,
    'to_step' => 'Approval Phase',
    'to_step_id' => 124,
    'step_data' => ['amount' => 50000, 'po_number' => 'PO-2024-001'],
    'notes' => 'All documents verified',
    'workflow_id' => 456,
]

// Description: "Step 'Study Phase' approved → 'Approval Phase'"
```

### 3. Step Rejected
```php
// Triggered when: Rejecting a workflow step
$record->logWorkflowStepRejected($step, $reason, $notes);

// Properties logged:
[
    'action' => 'rejected',
    'step' => 'Study Phase',
    'step_id' => 123,
    'reason' => 'Missing required documentation',
    'notes' => 'Additional notes',
    'workflow_id' => 456,
]

// Description: "Step 'Study Phase' rejected: Missing required documentation"
```

### 4. Workflow Completed
```php
// Triggered when: Workflow reaches final step
$record->logWorkflowCompleted($notes);

// Properties logged:
[
    'action' => 'completed',
    'notes' => 'Project approved and launched',
    'workflow_id' => 456,
]

// Description: "Workflow completed successfully"
```

### 5. Custom Activities
```php
// For custom workflow events
$record->logWorkflowActivity(
    'workflow_paused',
    'Workflow paused for additional review',
    ['reason' => 'Pending external approval'],
    'Waiting for ministry approval'
);
```

## Usage Examples

### Viewing Activity Logs
```php
// Get all activities for an order
$activities = $order->activities;

// Get workflow-specific activities
$workflowActivities = $order->activities()
    ->where('event', 'LIKE', 'workflow_%')
    ->get();

// Get activities by specific event
$approvals = $order->activities()
    ->where('event', 'workflow_step_approved')
    ->get();
```

### Activity Properties
```php
foreach ($order->activities as $activity) {
    echo "Action: " . $activity->description . "\n";
    echo "Performer: " . $activity->causer->name . "\n";
    echo "Date: " . $activity->created_at . "\n";
    echo "Properties: " . json_encode($activity->properties) . "\n";
}
```

### Filament Integration
You can display activity logs in Filament using the ActivityLog package:

```php
// In your Filament resource
use RalphJSmit\Filament\ActivityLog\RelationManagers\ActivitylogRelationManager;

public static function getRelations(): array
{
    return [
        ActivitylogRelationManager::class,
    ];
}
```

## Model Requirements

For models using workflow activity logging:

1. **Use both traits:**
```php
use App\Workflows\Traits\HasWorkflow;
use Spatie\Activitylog\Traits\LogsActivity;

class YourModel extends Model
{
    use HasWorkflow, LogsActivity;
}
```

2. **Configure activity log options:**
```php
public function getActivitylogOptions(): LogOptions
{
    return LogOptions::defaults()
        ->useLogName('your_model')
        ->logFillable()
        ->logOnlyDirty();
}
```

## Database Schema

The activity logs are stored in the `activity_log` table created by the Spatie ActivityLog package:

```sql
-- Key columns for workflow logging:
id              - Unique activity ID
log_name        - Log category (e.g., 'order')
description     - Human-readable description
subject_type    - Model class (e.g., 'App\Models\Order')
subject_id      - Model ID
causer_type     - User model class
causer_id       - User ID who performed action
event           - Event name (e.g., 'workflow_step_approved')
properties      - JSON data with detailed information
created_at      - When the activity occurred
```

## Benefits

1. **Audit Trail**: Complete history of all workflow actions
2. **Accountability**: Know who performed each action and when
3. **Debugging**: Detailed information for troubleshooting workflow issues
4. **Compliance**: Meet audit requirements for approval processes
5. **Analytics**: Analyze workflow performance and bottlenecks
6. **User Experience**: Show progress and history to users

## Configuration

Add your models to the activity log configuration if needed:

```php
// config/activitylog.php
'default_log_name' => 'default',
'default_auth_driver' => null,
'table_name' => 'activity_log',
'subject_returns_soft_deleted_models' => false,
'activity_model' => \Spatie\Activitylog\Models\Activity::class,
```

This comprehensive logging system ensures that all workflow activities are tracked and can be audited, providing transparency and accountability for all workflow operations.