# Activity Log Integration - Spatie Laravel Activitylog

## 📦 Package Installation

```bash
composer require spatie/laravel-activitylog
php artisan vendor:publish --provider="Spatie\Activitylog\ActivitylogServiceProvider" --tag="activitylog-config"
```

## ✅ Integration Complete

### Activity Logging Added to Onboarding Flow

#### 1. Email Verification
**Location**: `app/Http/Controllers/Auth/VerificationController.php`

```php
activity()
    ->performedOn($user)
    ->causedBy($user)
    ->withProperties(['action' => 'email_verified'])
    ->log('Email address verified');
```

**Logged When**: User successfully verifies email with OTP

---

#### 2. Plan Selection
**Location**: `app/Http/Controllers/OnboardingController.php`

```php
activity()
    ->performedOn($organization)
    ->causedBy($user)
    ->withProperties([
        'plan' => $plan->name,
        'billing_cycle' => $request->billing_cycle,
        'with_trial' => $startWithTrial,
    ])
    ->log('Subscription plan selected during onboarding');
```

**Logged When**: User selects a subscription plan

---

#### 3. Trial Subscription Started
**Location**: `app/Http/Controllers/OnboardingController.php`

```php
activity()
    ->performedOn($organization)
    ->causedBy($user)
    ->withProperties(['plan' => $plan->name, 'trial' => true])
    ->log('Onboarding completed with trial subscription');
```

**Logged When**: User completes onboarding with trial subscription

---

#### 4. Paid Subscription Completed
**Location**: `app/Services/BillingService.php`

```php
activity()
    ->performedOn($organization)
    ->causedBy($orgAdmin)
    ->withProperties([
        'plan' => $subscription->plan->name,
        'amount' => $payment->amount,
        'payment_method' => $payment->payment_method,
    ])
    ->log('Onboarding completed after successful payment');
```

**Logged When**: Payment is successful and onboarding is completed

---

## 📊 Activity Log Structure

### Database Table: `activity_log`

| Column | Type | Description |
|--------|------|-------------|
| id | bigint | Primary key |
| log_name | string | Category/type of log |
| description | text | Activity description |
| subject_type | string | Model type (Organization, User) |
| subject_id | bigint | Model ID |
| causer_type | string | User model type |
| causer_id | bigint | User ID who performed action |
| properties | json | Additional data |
| event | string | Event type |
| batch_uuid | uuid | Batch identifier |
| created_at | timestamp | When logged |

---

## 🔍 Querying Activity Logs

### Get All Activities for an Organization
```php
$activities = Activity::forSubject($organization)->get();
```

### Get Activities by a Specific User
```php
$activities = Activity::causedBy($user)->get();
```

### Get Onboarding Activities
```php
$activities = Activity::where('description', 'like', '%onboarding%')->get();
```

### Get Recent Activities
```php
$activities = Activity::latest()->take(10)->get();
```

---

## 📈 Activity Log Dashboard (Future Enhancement)

### Suggested Features:
1. **Organization Activity Timeline**
   - Show all activities for an organization
   - Filter by date range
   - Filter by activity type

2. **User Activity History**
   - Show all activities by a user
   - Track onboarding progress
   - Monitor subscription changes

3. **System-wide Activity Feed**
   - Recent activities across all organizations
   - Filter by organization
   - Export to CSV

4. **Activity Analytics**
   - Onboarding completion rate
   - Average time to complete onboarding
   - Most popular subscription plans
   - Payment success rate

---

## 🎯 Onboarding Activities Tracked

| Activity | Description | Properties |
|----------|-------------|------------|
| Email Verified | User verifies email with OTP | action: email_verified |
| Plan Selected | User selects subscription plan | plan, billing_cycle, with_trial |
| Trial Started | Trial subscription created | plan, trial: true |
| Payment Completed | Paid subscription activated | plan, amount, payment_method |

---

## 🔧 Configuration

### Config File: `config/activitylog.php`

Key settings:
- `enabled` - Enable/disable activity logging
- `delete_records_older_than_days` - Auto-cleanup old logs
- `subject_returns_soft_deleted_models` - Include soft-deleted models
- `activity_model` - Custom activity model

---

## 📝 Best Practices

### 1. Always Include Context
```php
activity()
    ->performedOn($model)      // What was affected
    ->causedBy($user)          // Who did it
    ->withProperties([...])    // Additional context
    ->log('Description');      // What happened
```

### 2. Use Descriptive Messages
✅ Good: "Onboarding completed with trial subscription"  
❌ Bad: "Onboarding done"

### 3. Include Relevant Properties
```php
->withProperties([
    'plan' => $plan->name,
    'amount' => $payment->amount,
    'payment_method' => 'mpesa',
])
```

### 4. Log Important Events Only
Don't log every single action - focus on:
- Security events (login, verification)
- Business events (subscription, payment)
- Critical changes (plan upgrade, cancellation)

---

## 🚀 Future Enhancements

### Additional Events to Log:
1. **Subscription Management**
   - Plan upgrade/downgrade
   - Subscription cancellation
   - Subscription reactivation
   - Trial extension

2. **Payment Events**
   - Payment initiated
   - Payment failed
   - Payment refunded
   - Invoice generated

3. **User Management**
   - User invited
   - User role changed
   - User deactivated

4. **Organization Events**
   - Organization settings changed
   - Organization suspended
   - Organization reactivated

---

## 📊 Sample Queries

### Get Onboarding Timeline for Organization
```php
$timeline = Activity::forSubject($organization)
    ->where('description', 'like', '%onboarding%')
    ->orderBy('created_at')
    ->get()
    ->map(function($activity) {
        return [
            'event' => $activity->description,
            'user' => $activity->causer->name,
            'time' => $activity->created_at->diffForHumans(),
            'details' => $activity->properties,
        ];
    });
```

### Get Payment Activities
```php
$payments = Activity::where('description', 'like', '%payment%')
    ->with(['subject', 'causer'])
    ->latest()
    ->paginate(20);
```

### Export Activity Log
```php
$activities = Activity::whereBetween('created_at', [$startDate, $endDate])
    ->get()
    ->map(function($activity) {
        return [
            'Date' => $activity->created_at->format('Y-m-d H:i:s'),
            'Organization' => $activity->subject->name ?? 'N/A',
            'User' => $activity->causer->name ?? 'System',
            'Action' => $activity->description,
            'Details' => json_encode($activity->properties),
        ];
    });

// Export to CSV
Excel::download(new ActivityExport($activities), 'activity-log.csv');
```

---

## ✅ Integration Status

- [x] Package installed
- [x] Configuration published
- [x] Email verification logging
- [x] Plan selection logging
- [x] Trial subscription logging
- [x] Payment completion logging
- [ ] Activity log dashboard (future)
- [ ] Activity log export (future)
- [ ] Activity log analytics (future)

---

**Status**: ✅ COMPLETE  
**Date**: February 9, 2026  
**Version**: 1.0.0
